From 6e5ce3faf115fea423ae5da079b4d3911c76c4ad Mon Sep 17 00:00:00 2001 From: Jose Date: Thu, 4 Jan 2024 17:02:13 +0100 Subject: [PATCH] Port IceGrid, IceStorm, and IceXML to C++17 (#1629) Co-authored-by: Joe George Co-authored-by: Bernard Normier Co-authored-by: Austin Henriksen Co-authored-by: Benoit Foucher --- .github/workflows/ci.yml | 6 +- cpp/config/Make.rules | 31 +- cpp/doxygen/config-cpp11 | 1 - cpp/include/IcePatch2/ClientUtil.h | 29 +- cpp/msbuild/ice.cpp.props | 1 + cpp/msbuild/ice.test.sln | 458 +++++---- cpp/msbuild/ice.v143.sln | 125 +-- .../msbuild/iceboxadmin/iceboxadmin.vcxproj | 1 + cpp/src/IceBridge/IceBridge.cpp | 468 ++++----- cpp/src/IceBridge/msbuild/icebridge.vcxproj | 21 +- cpp/src/IceDB/IceDB.cpp | 40 +- cpp/src/IceDB/IceDB.h | 26 +- cpp/src/IceDB/msbuild/icedb.vcxproj | 3 +- cpp/src/IceGrid/Activator.cpp | 152 +-- cpp/src/IceGrid/Activator.h | 41 +- cpp/src/IceGrid/AdapterCache.cpp | 330 +++---- cpp/src/IceGrid/AdapterCache.h | 225 +++-- cpp/src/IceGrid/AdminCallbackRouter.cpp | 60 +- cpp/src/IceGrid/AdminCallbackRouter.h | 21 +- cpp/src/IceGrid/AdminI.cpp | 656 ++++++------- cpp/src/IceGrid/AdminI.h | 150 +-- cpp/src/IceGrid/AdminRouter.cpp | 126 ++- cpp/src/IceGrid/AdminRouter.h | 9 +- cpp/src/IceGrid/AdminSessionI.cpp | 309 +++--- cpp/src/IceGrid/AdminSessionI.h | 121 +-- cpp/src/IceGrid/Allocatable.cpp | 148 ++- cpp/src/IceGrid/Allocatable.h | 74 +- cpp/src/IceGrid/AllocatableObjectCache.cpp | 112 ++- cpp/src/IceGrid/AllocatableObjectCache.h | 71 +- cpp/src/IceGrid/Cache.h | 60 +- cpp/src/IceGrid/Client.cpp | 149 ++- cpp/src/IceGrid/Database.cpp | 610 ++++++------ cpp/src/IceGrid/Database.h | 175 ++-- cpp/src/IceGrid/DescriptorBuilder.cpp | 52 +- cpp/src/IceGrid/DescriptorBuilder.h | 67 +- cpp/src/IceGrid/DescriptorHelper.cpp | 434 ++++----- cpp/src/IceGrid/DescriptorHelper.h | 135 ++- cpp/src/IceGrid/DescriptorParser.cpp | 70 +- cpp/src/IceGrid/DescriptorParser.h | 17 +- cpp/src/IceGrid/FileCache.cpp | 6 +- cpp/src/IceGrid/FileCache.h | 10 +- cpp/src/IceGrid/FileParserI.cpp | 6 +- cpp/src/IceGrid/FileParserI.h | 11 +- cpp/src/IceGrid/FileUserAccountMapperI.cpp | 4 +- cpp/src/IceGrid/FileUserAccountMapperI.h | 2 +- cpp/src/IceGrid/IceGridNode.cpp | 135 ++- cpp/src/IceGrid/IceGridRegistry.cpp | 31 +- cpp/src/IceGrid/Internal.ice | 24 +- cpp/src/IceGrid/InternalRegistryI.cpp | 78 +- cpp/src/IceGrid/InternalRegistryI.h | 59 +- cpp/src/IceGrid/LocatorI.cpp | 573 +++++------ cpp/src/IceGrid/LocatorI.h | 68 +- cpp/src/IceGrid/LocatorRegistryI.cpp | 381 ++++---- cpp/src/IceGrid/LocatorRegistryI.h | 51 +- cpp/src/IceGrid/NodeAdminRouter.cpp | 19 +- cpp/src/IceGrid/NodeAdminRouter.h | 13 +- cpp/src/IceGrid/NodeCache.cpp | 780 +++++++-------- cpp/src/IceGrid/NodeCache.h | 83 +- cpp/src/IceGrid/NodeI.cpp | 566 ++++------- cpp/src/IceGrid/NodeI.h | 219 +++-- cpp/src/IceGrid/NodeSessionI.cpp | 252 ++--- cpp/src/IceGrid/NodeSessionI.h | 94 +- cpp/src/IceGrid/NodeSessionManager.cpp | 224 ++--- cpp/src/IceGrid/NodeSessionManager.h | 69 +- cpp/src/IceGrid/ObjectCache.cpp | 68 +- cpp/src/IceGrid/ObjectCache.h | 26 +- cpp/src/IceGrid/Parser.cpp | 244 +++-- cpp/src/IceGrid/Parser.h | 24 +- cpp/src/IceGrid/PlatformInfo.cpp | 123 +-- cpp/src/IceGrid/PlatformInfo.h | 28 +- cpp/src/IceGrid/PluginFacadeI.cpp | 88 +- cpp/src/IceGrid/PluginFacadeI.h | 51 +- cpp/src/IceGrid/QueryI.cpp | 47 +- cpp/src/IceGrid/QueryI.h | 22 +- cpp/src/IceGrid/ReapThread.cpp | 167 ++-- cpp/src/IceGrid/ReapThread.h | 74 +- cpp/src/IceGrid/RegistryAdminRouter.cpp | 75 +- cpp/src/IceGrid/RegistryAdminRouter.h | 40 +- cpp/src/IceGrid/RegistryI.cpp | 472 +++++---- cpp/src/IceGrid/RegistryI.h | 120 ++- cpp/src/IceGrid/ReplicaCache.cpp | 102 +- cpp/src/IceGrid/ReplicaCache.h | 52 +- cpp/src/IceGrid/ReplicaSessionI.cpp | 137 +-- cpp/src/IceGrid/ReplicaSessionI.h | 80 +- cpp/src/IceGrid/ReplicaSessionManager.cpp | 233 +++-- cpp/src/IceGrid/ReplicaSessionManager.h | 63 +- cpp/src/IceGrid/Scanner.cpp | 39 +- cpp/src/IceGrid/Scanner.l | 10 - cpp/src/IceGrid/ServerAdapterI.cpp | 67 +- cpp/src/IceGrid/ServerAdapterI.h | 32 +- cpp/src/IceGrid/ServerCache.cpp | 435 ++++----- cpp/src/IceGrid/ServerCache.h | 123 ++- cpp/src/IceGrid/ServerI.cpp | 899 +++++++++--------- cpp/src/IceGrid/ServerI.h | 211 ++-- cpp/src/IceGrid/SessionI.cpp | 198 ++-- cpp/src/IceGrid/SessionI.h | 125 ++- cpp/src/IceGrid/SessionManager.cpp | 83 +- cpp/src/IceGrid/SessionManager.h | 166 ++-- cpp/src/IceGrid/SessionServantManager.cpp | 96 +- cpp/src/IceGrid/SessionServantManager.h | 77 +- cpp/src/IceGrid/Topics.cpp | 381 ++++---- cpp/src/IceGrid/Topics.h | 116 ++- cpp/src/IceGrid/TraceLevels.cpp | 32 +- cpp/src/IceGrid/TraceLevels.h | 34 +- cpp/src/IceGrid/Util.cpp | 16 +- cpp/src/IceGrid/Util.h | 142 ++- cpp/src/IceGrid/WaitQueue.cpp | 175 ---- cpp/src/IceGrid/WaitQueue.h | 57 -- cpp/src/IceGrid/WellKnownObjectsManager.cpp | 46 +- cpp/src/IceGrid/WellKnownObjectsManager.h | 24 +- .../msbuild/icegridadmin/icegridadmin.vcxproj | 3 +- .../msbuild/icegridnode/icegridnode.vcxproj | 3 +- .../icegridregistry/icegridregistry.vcxproj | 3 +- cpp/src/IcePatch2Lib/ClientUtil.cpp | 261 ++++- cpp/src/IcePatch2Lib/Util.cpp | 22 +- .../icepatch2++11/icepatch2++11.vcxproj | 226 +++++ .../icepatch2++11.vcxproj.filters | 143 +++ .../{ => icepatch2++11}/packages.config | 0 .../msbuild/{ => icepatch2}/icepatch2.vcxproj | 82 +- .../{ => icepatch2}/icepatch2.vcxproj.filters | 70 +- .../msbuild/icepatch2/packages.config | 5 + cpp/src/IceStorm/Admin.cpp | 53 +- cpp/src/IceStorm/IceStormDB.cpp | 33 +- cpp/src/IceStorm/IceStormInternal.ice | 4 +- cpp/src/IceStorm/Instance.cpp | 220 +++-- cpp/src/IceStorm/Instance.h | 116 ++- cpp/src/IceStorm/InstrumentationI.cpp | 54 +- cpp/src/IceStorm/InstrumentationI.h | 50 +- cpp/src/IceStorm/Makefile.mk | 6 +- cpp/src/IceStorm/NodeI.cpp | 358 ++++--- cpp/src/IceStorm/NodeI.h | 84 +- cpp/src/IceStorm/Observers.cpp | 80 +- cpp/src/IceStorm/Observers.h | 29 +- cpp/src/IceStorm/Parser.cpp | 218 ++--- cpp/src/IceStorm/Parser.h | 29 +- cpp/src/IceStorm/Replica.h | 26 +- cpp/src/IceStorm/Scanner.cpp | 8 +- cpp/src/IceStorm/Service.cpp | 185 ++-- cpp/src/IceStorm/Service.h | 27 +- cpp/src/IceStorm/Subscriber.cpp | 617 +++++------- cpp/src/IceStorm/Subscriber.h | 32 +- cpp/src/IceStorm/TopicI.cpp | 466 +++++---- cpp/src/IceStorm/TopicI.h | 46 +- cpp/src/IceStorm/TopicManagerI.cpp | 328 ++++--- cpp/src/IceStorm/TopicManagerI.h | 59 +- cpp/src/IceStorm/TraceLevels.cpp | 10 +- cpp/src/IceStorm/TraceLevels.h | 13 +- cpp/src/IceStorm/TransientTopicI.cpp | 297 ++---- cpp/src/IceStorm/TransientTopicI.h | 50 +- cpp/src/IceStorm/TransientTopicManagerI.cpp | 68 +- cpp/src/IceStorm/TransientTopicManagerI.h | 32 +- cpp/src/IceStorm/Util.cpp | 14 +- cpp/src/IceStorm/Util.h | 13 +- .../icestormadmin/icestormadmin.vcxproj | 3 +- .../msbuild/icestormdb/icestormdb.vcxproj | 3 +- .../icestormservice/icestormservice.vcxproj | 3 +- cpp/src/IceXML/Parser.cpp | 68 +- cpp/src/IceXML/Parser.h | 73 +- cpp/src/IceXML/msbuild/icexml.vcxproj | 3 +- cpp/src/icegriddb/IceGridDB.cpp | 42 +- cpp/src/icegriddb/msbuild/icegriddb.vcxproj | 3 +- cpp/test/Glacier2/attack/BackendI.h | 4 +- cpp/test/Glacier2/attack/Client.cpp | 37 +- cpp/test/Glacier2/attack/Server.cpp | 35 +- cpp/test/Glacier2/dynamicFiltering/BackendI.h | 6 +- cpp/test/Glacier2/dynamicFiltering/Client.cpp | 34 +- cpp/test/Glacier2/dynamicFiltering/Server.cpp | 113 +-- .../Glacier2/dynamicFiltering/SessionI.cpp | 27 +- cpp/test/Glacier2/dynamicFiltering/SessionI.h | 23 +- .../dynamicFiltering/TestControllerI.cpp | 44 +- .../dynamicFiltering/TestControllerI.h | 60 +- cpp/test/Glacier2/override/CallbackI.cpp | 156 +-- cpp/test/Glacier2/override/CallbackI.h | 41 +- cpp/test/Glacier2/override/Client.cpp | 88 +- cpp/test/Glacier2/override/Server.cpp | 10 +- cpp/test/Glacier2/router/CallbackI.cpp | 254 ++--- cpp/test/Glacier2/router/CallbackI.h | 74 +- cpp/test/Glacier2/router/Client.cpp | 390 ++++---- cpp/test/Glacier2/router/Server.cpp | 16 +- cpp/test/Glacier2/sessionControl/Client.cpp | 20 +- cpp/test/Glacier2/sessionControl/Server.cpp | 8 +- cpp/test/Glacier2/sessionControl/SessionI.cpp | 47 +- cpp/test/Glacier2/sessionControl/SessionI.h | 18 +- cpp/test/Glacier2/sessionHelper/Client.cpp | 281 +++--- cpp/test/Glacier2/sessionHelper/Server.cpp | 22 +- cpp/test/Glacier2/ssl/Client.cpp | 24 +- cpp/test/Glacier2/ssl/Server.cpp | 62 +- cpp/test/Glacier2/staticFiltering/BackendI.h | 4 +- cpp/test/Glacier2/staticFiltering/Client.cpp | 40 +- cpp/test/Glacier2/staticFiltering/Server.cpp | 105 +- cpp/test/IceBridge/simple/AllTests.cpp | 123 +-- cpp/test/IceBridge/simple/Client.cpp | 8 +- cpp/test/IceBridge/simple/Server.cpp | 20 +- cpp/test/IceBridge/simple/TestI.cpp | 232 ++--- cpp/test/IceBridge/simple/TestI.h | 54 +- cpp/test/IceGrid/activation/AllTests.cpp | 374 +++++--- cpp/test/IceGrid/activation/TestI.h | 2 +- cpp/test/IceGrid/allocation/AllTests.cpp | 552 +++++------ .../allocation/PermissionsVerifier.cpp | 26 +- cpp/test/IceGrid/allocation/Server.cpp | 26 +- cpp/test/IceGrid/allocation/TestI.cpp | 6 +- cpp/test/IceGrid/allocation/TestI.h | 10 +- cpp/test/IceGrid/deployer/AllTests.cpp | 175 ++-- cpp/test/IceGrid/deployer/Server.cpp | 3 +- cpp/test/IceGrid/deployer/Service.cpp | 7 +- cpp/test/IceGrid/deployer/TestI.cpp | 2 +- cpp/test/IceGrid/deployer/TestI.h | 2 +- cpp/test/IceGrid/distribution/AllTests.cpp | 28 +- cpp/test/IceGrid/distribution/Server.cpp | 3 +- cpp/test/IceGrid/distribution/TestI.cpp | 4 +- cpp/test/IceGrid/distribution/TestI.h | 4 +- cpp/test/IceGrid/noRestartUpdate/AllTests.cpp | 150 ++- cpp/test/IceGrid/noRestartUpdate/Client.cpp | 4 +- cpp/test/IceGrid/noRestartUpdate/Server.cpp | 9 +- cpp/test/IceGrid/noRestartUpdate/Service.cpp | 32 +- cpp/test/IceGrid/noRestartUpdate/TestI.cpp | 8 +- cpp/test/IceGrid/noRestartUpdate/TestI.h | 12 +- cpp/test/IceGrid/replicaGroup/AllTests.cpp | 134 +-- .../IceGrid/replicaGroup/RegistryPlugin.cpp | 84 +- cpp/test/IceGrid/replicaGroup/Server.cpp | 6 +- cpp/test/IceGrid/replicaGroup/Service.cpp | 29 +- cpp/test/IceGrid/replication/AllTests.cpp | 355 +++---- cpp/test/IceGrid/replication/Client.cpp | 12 +- cpp/test/IceGrid/replication/Server.cpp | 12 +- cpp/test/IceGrid/replication/TestI.h | 2 +- cpp/test/IceGrid/session/AllTests.cpp | 832 +++++++--------- cpp/test/IceGrid/session/Client.cpp | 8 +- .../IceGrid/session/PermissionsVerifier.cpp | 20 +- cpp/test/IceGrid/session/Server.cpp | 31 +- cpp/test/IceGrid/simple/AllTests.cpp | 8 +- cpp/test/IceGrid/simple/Client.cpp | 3 +- cpp/test/IceGrid/update/AllTests.cpp | 50 +- cpp/test/IceGrid/update/Server.cpp | 2 +- cpp/test/IceGrid/update/TestI.cpp | 2 +- cpp/test/IceGrid/update/TestI.h | 2 +- cpp/test/IceStorm/federation/Publisher.cpp | 28 +- cpp/test/IceStorm/federation/Subscriber.cpp | 68 +- cpp/test/IceStorm/federation2/Publisher.cpp | 22 +- cpp/test/IceStorm/federation2/Subscriber.cpp | 57 +- cpp/test/IceStorm/persistent/Client.cpp | 18 +- cpp/test/IceStorm/rep1/Publisher.cpp | 31 +- cpp/test/IceStorm/rep1/Sub.cpp | 26 +- cpp/test/IceStorm/rep1/Subscriber.cpp | 49 +- cpp/test/IceStorm/repgrid/Client.cpp | 47 +- cpp/test/IceStorm/repstress/Control.cpp | 6 +- cpp/test/IceStorm/repstress/Publisher.cpp | 50 +- cpp/test/IceStorm/repstress/Subscriber.cpp | 41 +- cpp/test/IceStorm/single/Publisher.cpp | 12 +- cpp/test/IceStorm/single/Subscriber.cpp | 83 +- cpp/test/IceStorm/stress/Publisher.cpp | 21 +- cpp/test/IceStorm/stress/Subscriber.cpp | 232 ++--- scripts/Component.py | 15 +- scripts/IceBridgeUtil.py | 2 +- scripts/IceGridUtil.py | 7 +- scripts/IceStormUtil.py | 4 +- slice/IceStorm/IceStorm.ice | 4 +- 256 files changed, 12110 insertions(+), 14127 deletions(-) delete mode 100644 cpp/src/IceGrid/WaitQueue.cpp delete mode 100644 cpp/src/IceGrid/WaitQueue.h create mode 100644 cpp/src/IcePatch2Lib/msbuild/icepatch2++11/icepatch2++11.vcxproj create mode 100644 cpp/src/IcePatch2Lib/msbuild/icepatch2++11/icepatch2++11.vcxproj.filters rename cpp/src/IcePatch2Lib/msbuild/{ => icepatch2++11}/packages.config (100%) rename cpp/src/IcePatch2Lib/msbuild/{ => icepatch2}/icepatch2.vcxproj (72%) rename cpp/src/IcePatch2Lib/msbuild/{ => icepatch2}/icepatch2.vcxproj.filters (78%) create mode 100644 cpp/src/IcePatch2Lib/msbuild/icepatch2/packages.config diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 207c748e22e..d0f0c38d435 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,5 +18,7 @@ jobs: uses: actions/checkout@v3 - name: Build run: make -j8 V=1 CONFIGS="shared cpp98-shared cpp11-shared" - - name: Test - run: ./allTests.py --workers=4 + - name: Tests + run: ./allTests.py --workers=4 --config=cpp11-shared + - name: C++98 Tests + run: ./allTests.py --workers=4 --config=cpp98-shared --languages=cpp diff --git a/cpp/config/Make.rules b/cpp/config/Make.rules index 4e53238f3b3..a66ac5e491a 100644 --- a/cpp/config/Make.rules +++ b/cpp/config/Make.rules @@ -62,12 +62,28 @@ static_excludes = test/Ice/library test/Ice/plugin # Components and projects which are built with C++98 # cpp98_projects = % -cpp98_excludes = glacier2router +cpp98_excludes = glacier2router \ + icebridge \ + icegridnode icegridregistry icegridadmin icegriddb \ + IceStormService icestormadmin icestormdb \ + IceXML \ + IceDB \ + test/Glacier2/% \ + test/IceBridge/% \ + test/IceGrid/% \ + test/IceStorm/% # # Components and projects which are built with C++11 # -cpp11_components = $(coreandstub_components) glacier2router Glacier2CryptPermissionsVerifier icebox +cpp11_components = $(coreandstub_components) \ + glacier2router Glacier2CryptPermissionsVerifier \ + icebox icebridge \ + IceDB \ + IceXML \ + icegridnode icegridregistry icegridadmin icegriddb \ + IceStormService icestormadmin icestormdb \ + cpp11_projects = test/Common \ test/IceUtil/% \ test/Slice/% \ @@ -75,12 +91,13 @@ cpp11_projects = test/Common \ test/IceSSL/% \ test/IceDiscovery/% \ test/IceBox/% \ - test/Glacier2/application \ - test/Glacier2/sessionHelper \ - test/IceGrid/simple + test/IceGrid/% \ + test/IceStorm/% \ + test/Glacier2/% \ + test/IceGrid/% \ + test/IceBridge/simple -cpp11_excludes = IcePatch2 \ - test/Ice/gc +cpp11_excludes = test/Ice/gc # # If building on a Linux multilib platform, we restrict what we build for diff --git a/cpp/doxygen/config-cpp11 b/cpp/doxygen/config-cpp11 index 3bf9cfb4f3d..02f5513a596 100644 --- a/cpp/doxygen/config-cpp11 +++ b/cpp/doxygen/config-cpp11 @@ -933,7 +933,6 @@ EXCLUDE_PATTERNS = EXCLUDE_SYMBOLS = IceInternal \ IceUtilInternal \ Glacier2Internal \ - IcePatch2 \ std # The EXAMPLE_PATH tag can be used to specify one or more files or directories diff --git a/cpp/include/IcePatch2/ClientUtil.h b/cpp/include/IcePatch2/ClientUtil.h index c733e867d08..d8f193a5b7c 100644 --- a/cpp/include/IcePatch2/ClientUtil.h +++ b/cpp/include/IcePatch2/ClientUtil.h @@ -19,7 +19,10 @@ namespace IcePatch2 // allow the user to interact with the patching and report progress // on the patching. // -class ICEPATCH2_API PatcherFeedback : public IceUtil::Shared +class ICEPATCH2_API PatcherFeedback +#ifndef ICE_CPP11_MAPPING + : public IceUtil::Shared +#endif // !ICE_CPP11_MAPPING { public: @@ -65,13 +68,19 @@ class ICEPATCH2_API PatcherFeedback : public IceUtil::Shared virtual bool patchProgress(Ice::Long, Ice::Long, Ice::Long, Ice::Long) = 0; virtual bool patchEnd() = 0; }; +#ifdef ICE_CPP11_MAPPING +typedef std::shared_ptr PatcherFeedbackPtr; +#else typedef IceUtil::Handle PatcherFeedbackPtr; - +#endif // // IcePatch2 clients instantiate the IcePatch2::Patcher class to patch // a given local data directory. // -class ICEPATCH2_API Patcher : public IceUtil::Shared +class ICEPATCH2_API Patcher +#ifndef ICE_CPP11_MAPPING + : public IceUtil::Shared +#endif { public: @@ -106,13 +115,23 @@ class ICEPATCH2_API Patcher : public IceUtil::Shared // virtual void finish() = 0; }; + +#ifdef ICE_CPP11_MAPPING +typedef std::shared_ptr PatcherPtr; +#else typedef IceUtil::Handle PatcherPtr; +#endif // ICE_CPP11_MAPPING + + // // IcePatch2 clients instantiate the IcePatch2::Patcher class // using the patcher factory. // -class ICEPATCH2_API PatcherFactory : public IceUtil::noncopyable +class ICEPATCH2_API PatcherFactory +#ifndef ICE_CPP11_MAPPING + : public IceUtil::noncopyable +#endif // !ICE_CPP11_MAPPING { public: @@ -135,7 +154,7 @@ class ICEPATCH2_API PatcherFactory : public IceUtil::noncopyable // Create a patcher with the given parameters. These parameters // are equivalent to the configuration properties described above. // - static PatcherPtr create(const FileServerPrx&, const PatcherFeedbackPtr&, const std::string&, bool, Ice::Int, Ice::Int); + static PatcherPtr create(const FileServerPrxPtr&, const PatcherFeedbackPtr&, const std::string&, bool, Ice::Int, Ice::Int); }; } diff --git a/cpp/msbuild/ice.cpp.props b/cpp/msbuild/ice.cpp.props index 860b4d9be04..1b89fd52c3f 100644 --- a/cpp/msbuild/ice.cpp.props +++ b/cpp/msbuild/ice.cpp.props @@ -76,6 +76,7 @@ ProgramDatabase $(IntDir)$(TargetName)-objs.pdb + stdcpp17 diff --git a/cpp/msbuild/ice.test.sln b/cpp/msbuild/ice.test.sln index da065766f50..2679c905002 100644 --- a/cpp/msbuild/ice.test.sln +++ b/cpp/msbuild/ice.test.sln @@ -2662,125 +2662,125 @@ Global {74127AED-9D17-4789-8B2F-9CCD660E7204}.Release|x64.ActiveCfg = Release|x64 {74127AED-9D17-4789-8B2F-9CCD660E7204}.Release|x64.Build.0 = Release|x64 {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Debug|Win32.ActiveCfg = Debug|Win32 {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Debug|Win32.Build.0 = Debug|Win32 {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Debug|x64.ActiveCfg = Debug|x64 - {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Debug|x64.Build.0 = Debug|x64 {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Release|Win32.ActiveCfg = Release|Win32 - {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Release|Win32.Build.0 = Release|Win32 {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Release|x64.ActiveCfg = Release|x64 - {DE360450-9BF9-42FB-98FD-3D29C5CAF6DA}.Release|x64.Build.0 = Release|x64 {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Debug|Win32.ActiveCfg = Debug|Win32 - {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Debug|Win32.Build.0 = Debug|Win32 {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Debug|x64.ActiveCfg = Debug|x64 - {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Debug|x64.Build.0 = Debug|x64 {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Release|Win32.ActiveCfg = Release|Win32 - {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Release|Win32.Build.0 = Release|Win32 {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Release|x64.ActiveCfg = Release|x64 - {D6C3E453-ED0B-41CA-84E6-7D07D8867A2D}.Release|x64.Build.0 = Release|x64 {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Debug|Win32.ActiveCfg = Debug|Win32 {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Debug|Win32.Build.0 = Debug|Win32 {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Debug|x64.ActiveCfg = Debug|x64 - {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Debug|x64.Build.0 = Debug|x64 {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Release|Win32.ActiveCfg = Release|Win32 - {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Release|Win32.Build.0 = Release|Win32 {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Release|x64.ActiveCfg = Release|x64 - {14C78FC0-F80C-425F-A504-1DD264BCDD01}.Release|x64.Build.0 = Release|x64 {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Debug|Win32.ActiveCfg = Debug|Win32 - {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Debug|Win32.Build.0 = Debug|Win32 {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Debug|x64.ActiveCfg = Debug|x64 - {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Debug|x64.Build.0 = Debug|x64 {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Release|Win32.ActiveCfg = Release|Win32 - {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Release|Win32.Build.0 = Release|Win32 {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Release|x64.ActiveCfg = Release|x64 - {814690FE-2C4F-4EF4-82CB-720BC4C8FF9B}.Release|x64.Build.0 = Release|x64 {3C394401-8E95-475B-8B35-B90A7CCAE578}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {3C394401-8E95-475B-8B35-B90A7CCAE578}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {3C394401-8E95-475B-8B35-B90A7CCAE578}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {3C394401-8E95-475B-8B35-B90A7CCAE578}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {3C394401-8E95-475B-8B35-B90A7CCAE578}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 {3C394401-8E95-475B-8B35-B90A7CCAE578}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {3C394401-8E95-475B-8B35-B90A7CCAE578}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {3C394401-8E95-475B-8B35-B90A7CCAE578}.Debug|Win32.ActiveCfg = Debug|Win32 {3C394401-8E95-475B-8B35-B90A7CCAE578}.Debug|Win32.Build.0 = Debug|Win32 {3C394401-8E95-475B-8B35-B90A7CCAE578}.Debug|x64.ActiveCfg = Debug|x64 - {3C394401-8E95-475B-8B35-B90A7CCAE578}.Debug|x64.Build.0 = Debug|x64 {3C394401-8E95-475B-8B35-B90A7CCAE578}.Release|Win32.ActiveCfg = Release|Win32 - {3C394401-8E95-475B-8B35-B90A7CCAE578}.Release|Win32.Build.0 = Release|Win32 {3C394401-8E95-475B-8B35-B90A7CCAE578}.Release|x64.ActiveCfg = Release|x64 - {3C394401-8E95-475B-8B35-B90A7CCAE578}.Release|x64.Build.0 = Release|x64 {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Debug|Win32.ActiveCfg = Debug|Win32 - {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Debug|Win32.Build.0 = Debug|Win32 {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Debug|x64.ActiveCfg = Debug|x64 - {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Debug|x64.Build.0 = Debug|x64 {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Release|Win32.ActiveCfg = Release|Win32 - {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Release|Win32.Build.0 = Release|Win32 {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Release|x64.ActiveCfg = Release|x64 - {E1510790-AF0B-4FFE-B6AA-B75119793AFC}.Release|x64.Build.0 = Release|x64 {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Debug|Win32.ActiveCfg = Debug|Win32 {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Debug|Win32.Build.0 = Debug|Win32 {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Debug|x64.ActiveCfg = Debug|x64 - {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Debug|x64.Build.0 = Debug|x64 {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Release|Win32.ActiveCfg = Release|Win32 - {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Release|Win32.Build.0 = Release|Win32 {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Release|x64.ActiveCfg = Release|x64 - {7CB05069-58C9-4C7D-A6A6-DBFB1CE7C58C}.Release|x64.Build.0 = Release|x64 {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Debug|Win32.ActiveCfg = Debug|Win32 - {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Debug|Win32.Build.0 = Debug|Win32 {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Debug|x64.ActiveCfg = Debug|x64 - {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Debug|x64.Build.0 = Debug|x64 {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Release|Win32.ActiveCfg = Release|Win32 - {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Release|Win32.Build.0 = Release|Win32 {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Release|x64.ActiveCfg = Release|x64 - {3BD0D95D-8DC6-4A07-B4D9-72EC85C4C97A}.Release|x64.Build.0 = Release|x64 {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Debug|Win32.ActiveCfg = Debug|Win32 {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Debug|Win32.Build.0 = Debug|Win32 {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Debug|x64.ActiveCfg = Debug|x64 - {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Debug|x64.Build.0 = Debug|x64 {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Release|Win32.ActiveCfg = Release|Win32 - {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Release|Win32.Build.0 = Release|Win32 {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Release|x64.ActiveCfg = Release|x64 - {8CCBFE0A-E0EE-40B7-A78A-C36B7615618A}.Release|x64.Build.0 = Release|x64 {40C0ABA8-A839-4988-AC60-04F649B44C54}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {40C0ABA8-A839-4988-AC60-04F649B44C54}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {40C0ABA8-A839-4988-AC60-04F649B44C54}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {40C0ABA8-A839-4988-AC60-04F649B44C54}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {40C0ABA8-A839-4988-AC60-04F649B44C54}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {40C0ABA8-A839-4988-AC60-04F649B44C54}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {40C0ABA8-A839-4988-AC60-04F649B44C54}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {40C0ABA8-A839-4988-AC60-04F649B44C54}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {40C0ABA8-A839-4988-AC60-04F649B44C54}.Debug|Win32.ActiveCfg = Debug|Win32 - {40C0ABA8-A839-4988-AC60-04F649B44C54}.Debug|Win32.Build.0 = Debug|Win32 {40C0ABA8-A839-4988-AC60-04F649B44C54}.Debug|x64.ActiveCfg = Debug|x64 - {40C0ABA8-A839-4988-AC60-04F649B44C54}.Debug|x64.Build.0 = Debug|x64 {40C0ABA8-A839-4988-AC60-04F649B44C54}.Release|Win32.ActiveCfg = Release|Win32 - {40C0ABA8-A839-4988-AC60-04F649B44C54}.Release|Win32.Build.0 = Release|Win32 {40C0ABA8-A839-4988-AC60-04F649B44C54}.Release|x64.ActiveCfg = Release|x64 - {40C0ABA8-A839-4988-AC60-04F649B44C54}.Release|x64.Build.0 = Release|x64 {BF42E24D-954E-47A6-8699-B2F764939757}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 {BF42E24D-954E-47A6-8699-B2F764939757}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {BF42E24D-954E-47A6-8699-B2F764939757}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 @@ -2792,11 +2792,8 @@ Global {BF42E24D-954E-47A6-8699-B2F764939757}.Debug|Win32.ActiveCfg = Debug|Win32 {BF42E24D-954E-47A6-8699-B2F764939757}.Debug|Win32.Build.0 = Debug|Win32 {BF42E24D-954E-47A6-8699-B2F764939757}.Debug|x64.ActiveCfg = Debug|x64 - {BF42E24D-954E-47A6-8699-B2F764939757}.Debug|x64.Build.0 = Debug|x64 {BF42E24D-954E-47A6-8699-B2F764939757}.Release|Win32.ActiveCfg = Release|Win32 - {BF42E24D-954E-47A6-8699-B2F764939757}.Release|Win32.Build.0 = Release|Win32 {BF42E24D-954E-47A6-8699-B2F764939757}.Release|x64.ActiveCfg = Release|x64 - {BF42E24D-954E-47A6-8699-B2F764939757}.Release|x64.Build.0 = Release|x64 {D3978518-2640-48BE-9D42-F664742BCB45}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 {D3978518-2640-48BE-9D42-F664742BCB45}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {D3978518-2640-48BE-9D42-F664742BCB45}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 @@ -2806,61 +2803,57 @@ Global {D3978518-2640-48BE-9D42-F664742BCB45}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 {D3978518-2640-48BE-9D42-F664742BCB45}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {D3978518-2640-48BE-9D42-F664742BCB45}.Debug|Win32.ActiveCfg = Debug|Win32 - {D3978518-2640-48BE-9D42-F664742BCB45}.Debug|Win32.Build.0 = Debug|Win32 {D3978518-2640-48BE-9D42-F664742BCB45}.Debug|x64.ActiveCfg = Debug|x64 - {D3978518-2640-48BE-9D42-F664742BCB45}.Debug|x64.Build.0 = Debug|x64 {D3978518-2640-48BE-9D42-F664742BCB45}.Release|Win32.ActiveCfg = Release|Win32 - {D3978518-2640-48BE-9D42-F664742BCB45}.Release|Win32.Build.0 = Release|Win32 {D3978518-2640-48BE-9D42-F664742BCB45}.Release|x64.ActiveCfg = Release|x64 - {D3978518-2640-48BE-9D42-F664742BCB45}.Release|x64.Build.0 = Release|x64 {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Debug|Win32.ActiveCfg = Debug|Win32 {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Debug|Win32.Build.0 = Debug|Win32 {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Debug|x64.ActiveCfg = Debug|x64 - {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Debug|x64.Build.0 = Debug|x64 {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Release|Win32.ActiveCfg = Release|Win32 - {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Release|Win32.Build.0 = Release|Win32 {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Release|x64.ActiveCfg = Release|x64 - {F0F9CA32-65BC-4F71-9901-E231FD485CDA}.Release|x64.Build.0 = Release|x64 {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Debug|Win32.ActiveCfg = Debug|Win32 - {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Debug|Win32.Build.0 = Debug|Win32 {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Debug|x64.ActiveCfg = Debug|x64 - {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Debug|x64.Build.0 = Debug|x64 {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Release|Win32.ActiveCfg = Release|Win32 - {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Release|Win32.Build.0 = Release|Win32 {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Release|x64.ActiveCfg = Release|x64 - {5579253D-24F6-4001-BF9E-D0D6DA3EF928}.Release|x64.Build.0 = Release|x64 {C02402BC-608E-4E46-B432-3C0C39E3B346}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {C02402BC-608E-4E46-B432-3C0C39E3B346}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {C02402BC-608E-4E46-B432-3C0C39E3B346}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {C02402BC-608E-4E46-B432-3C0C39E3B346}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {C02402BC-608E-4E46-B432-3C0C39E3B346}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 {C02402BC-608E-4E46-B432-3C0C39E3B346}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {C02402BC-608E-4E46-B432-3C0C39E3B346}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {C02402BC-608E-4E46-B432-3C0C39E3B346}.Debug|Win32.ActiveCfg = Debug|Win32 {C02402BC-608E-4E46-B432-3C0C39E3B346}.Debug|Win32.Build.0 = Debug|Win32 {C02402BC-608E-4E46-B432-3C0C39E3B346}.Debug|x64.ActiveCfg = Debug|x64 - {C02402BC-608E-4E46-B432-3C0C39E3B346}.Debug|x64.Build.0 = Debug|x64 {C02402BC-608E-4E46-B432-3C0C39E3B346}.Release|Win32.ActiveCfg = Release|Win32 - {C02402BC-608E-4E46-B432-3C0C39E3B346}.Release|Win32.Build.0 = Release|Win32 {C02402BC-608E-4E46-B432-3C0C39E3B346}.Release|x64.ActiveCfg = Release|x64 - {C02402BC-608E-4E46-B432-3C0C39E3B346}.Release|x64.Build.0 = Release|x64 {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Debug|Win32.ActiveCfg = Debug|Win32 - {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Debug|Win32.Build.0 = Debug|Win32 {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Debug|x64.ActiveCfg = Debug|x64 - {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Debug|x64.Build.0 = Debug|x64 {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Release|Win32.ActiveCfg = Release|Win32 - {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Release|Win32.Build.0 = Release|Win32 {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Release|x64.ActiveCfg = Release|x64 - {5ED6FC18-EAED-4833-8CE8-FA19F5CD713B}.Release|x64.Build.0 = Release|x64 {0AF7FE2E-9C7F-4F87-A999-D397D39CE752}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 {0AF7FE2E-9C7F-4F87-A999-D397D39CE752}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {0AF7FE2E-9C7F-4F87-A999-D397D39CE752}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 @@ -2990,137 +2983,142 @@ Global {8A420B3E-C5C5-403B-874A-6D2A5A51783B}.Release|x64.ActiveCfg = Release|x64 {8A420B3E-C5C5-403B-874A-6D2A5A51783B}.Release|x64.Build.0 = Release|x64 {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Debug|Win32.ActiveCfg = Debug|Win32 {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Debug|Win32.Build.0 = Debug|Win32 {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Debug|x64.ActiveCfg = Debug|x64 - {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Debug|x64.Build.0 = Debug|x64 {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Release|Win32.ActiveCfg = Release|Win32 - {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Release|Win32.Build.0 = Release|Win32 {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Release|x64.ActiveCfg = Release|x64 - {F2FC008C-2972-481A-9E30-2D194E1DBAD7}.Release|x64.Build.0 = Release|x64 {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Debug|Win32.ActiveCfg = Debug|Win32 - {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Debug|Win32.Build.0 = Debug|Win32 {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Debug|x64.ActiveCfg = Debug|x64 - {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Debug|x64.Build.0 = Debug|x64 {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Release|Win32.ActiveCfg = Release|Win32 - {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Release|Win32.Build.0 = Release|Win32 {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Release|x64.ActiveCfg = Release|x64 - {5150E36B-EDF1-410B-A7D7-7B0D75AB92C4}.Release|x64.Build.0 = Release|x64 {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Debug|Win32.ActiveCfg = Debug|Win32 {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Debug|Win32.Build.0 = Debug|Win32 {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Debug|x64.ActiveCfg = Debug|x64 - {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Debug|x64.Build.0 = Debug|x64 {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Release|Win32.ActiveCfg = Release|Win32 - {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Release|Win32.Build.0 = Release|Win32 {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Release|x64.ActiveCfg = Release|x64 - {FA05E973-3F45-4C5A-8226-BBDAD8F9DE4F}.Release|x64.Build.0 = Release|x64 {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Debug|Win32.ActiveCfg = Debug|Win32 - {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Debug|Win32.Build.0 = Debug|Win32 {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Debug|x64.ActiveCfg = Debug|x64 - {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Debug|x64.Build.0 = Debug|x64 {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Release|Win32.ActiveCfg = Release|Win32 - {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Release|Win32.Build.0 = Release|Win32 {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Release|x64.ActiveCfg = Release|x64 - {E879E538-6746-4EEE-8D70-0FC80B8A2FAC}.Release|x64.Build.0 = Release|x64 {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Debug|Win32.ActiveCfg = Debug|Win32 {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Debug|Win32.Build.0 = Debug|Win32 {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Debug|x64.ActiveCfg = Debug|x64 - {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Debug|x64.Build.0 = Debug|x64 {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Release|Win32.ActiveCfg = Release|Win32 - {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Release|Win32.Build.0 = Release|Win32 {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Release|x64.ActiveCfg = Release|x64 - {58B8CF53-AC7C-4FE5-ABA1-A356034BFE10}.Release|x64.Build.0 = Release|x64 {CB22725D-1669-4945-83D3-81CA767F0B56}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {CB22725D-1669-4945-83D3-81CA767F0B56}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {CB22725D-1669-4945-83D3-81CA767F0B56}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {CB22725D-1669-4945-83D3-81CA767F0B56}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {CB22725D-1669-4945-83D3-81CA767F0B56}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {CB22725D-1669-4945-83D3-81CA767F0B56}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {CB22725D-1669-4945-83D3-81CA767F0B56}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {CB22725D-1669-4945-83D3-81CA767F0B56}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {CB22725D-1669-4945-83D3-81CA767F0B56}.Debug|Win32.ActiveCfg = Debug|Win32 - {CB22725D-1669-4945-83D3-81CA767F0B56}.Debug|Win32.Build.0 = Debug|Win32 {CB22725D-1669-4945-83D3-81CA767F0B56}.Debug|x64.ActiveCfg = Debug|x64 - {CB22725D-1669-4945-83D3-81CA767F0B56}.Debug|x64.Build.0 = Debug|x64 {CB22725D-1669-4945-83D3-81CA767F0B56}.Release|Win32.ActiveCfg = Release|Win32 - {CB22725D-1669-4945-83D3-81CA767F0B56}.Release|Win32.Build.0 = Release|Win32 {CB22725D-1669-4945-83D3-81CA767F0B56}.Release|x64.ActiveCfg = Release|x64 - {CB22725D-1669-4945-83D3-81CA767F0B56}.Release|x64.Build.0 = Release|x64 {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Debug|Win32.ActiveCfg = Debug|Win32 - {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Debug|Win32.Build.0 = Debug|Win32 {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Debug|x64.ActiveCfg = Debug|x64 - {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Debug|x64.Build.0 = Debug|x64 {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Release|Win32.ActiveCfg = Release|Win32 - {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Release|Win32.Build.0 = Release|Win32 {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Release|x64.ActiveCfg = Release|x64 - {E6690528-7BB9-4B8E-8F15-4F3C58A736B9}.Release|x64.Build.0 = Release|x64 {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Debug|Win32.ActiveCfg = Debug|Win32 {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Debug|Win32.Build.0 = Debug|Win32 {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Debug|x64.ActiveCfg = Debug|x64 - {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Debug|x64.Build.0 = Debug|x64 {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Release|Win32.ActiveCfg = Release|Win32 - {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Release|Win32.Build.0 = Release|Win32 {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Release|x64.ActiveCfg = Release|x64 - {C988F9AD-ED3C-4796-A7F5-CE7678FD689A}.Release|x64.Build.0 = Release|x64 {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Debug|Win32.ActiveCfg = Debug|Win32 {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Debug|Win32.Build.0 = Debug|Win32 {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Debug|x64.ActiveCfg = Debug|x64 - {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Debug|x64.Build.0 = Debug|x64 {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Release|Win32.ActiveCfg = Release|Win32 - {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Release|Win32.Build.0 = Release|Win32 {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Release|x64.ActiveCfg = Release|x64 - {7C5AB509-3BB9-43F7-B4BA-D8D57BDED7BA}.Release|x64.Build.0 = Release|x64 {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Debug|Win32.ActiveCfg = Debug|Win32 - {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Debug|Win32.Build.0 = Debug|Win32 {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Debug|x64.ActiveCfg = Debug|x64 - {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Debug|x64.Build.0 = Debug|x64 {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Release|Win32.ActiveCfg = Release|Win32 - {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Release|Win32.Build.0 = Release|Win32 {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Release|x64.ActiveCfg = Release|x64 - {A6F10BA0-D8BC-4CE6-A6B0-E9C556F4FCC0}.Release|x64.Build.0 = Release|x64 {6020F924-5846-452A-B704-BA762AC106DD}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {6020F924-5846-452A-B704-BA762AC106DD}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {6020F924-5846-452A-B704-BA762AC106DD}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {6020F924-5846-452A-B704-BA762AC106DD}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {6020F924-5846-452A-B704-BA762AC106DD}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {6020F924-5846-452A-B704-BA762AC106DD}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {6020F924-5846-452A-B704-BA762AC106DD}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {6020F924-5846-452A-B704-BA762AC106DD}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {6020F924-5846-452A-B704-BA762AC106DD}.Debug|Win32.ActiveCfg = Debug|Win32 - {6020F924-5846-452A-B704-BA762AC106DD}.Debug|Win32.Build.0 = Debug|Win32 {6020F924-5846-452A-B704-BA762AC106DD}.Debug|x64.ActiveCfg = Debug|x64 - {6020F924-5846-452A-B704-BA762AC106DD}.Debug|x64.Build.0 = Debug|x64 {6020F924-5846-452A-B704-BA762AC106DD}.Release|Win32.ActiveCfg = Release|Win32 - {6020F924-5846-452A-B704-BA762AC106DD}.Release|Win32.Build.0 = Release|Win32 {6020F924-5846-452A-B704-BA762AC106DD}.Release|x64.ActiveCfg = Release|x64 - {6020F924-5846-452A-B704-BA762AC106DD}.Release|x64.Build.0 = Release|x64 {076446BE-553C-4938-9CF8-BC7DEB1BF235}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 {076446BE-553C-4938-9CF8-BC7DEB1BF235}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {076446BE-553C-4938-9CF8-BC7DEB1BF235}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 @@ -3454,329 +3452,329 @@ Global {948059F3-CD57-4ACC-9EA5-C4550D06CB19}.Release|x64.ActiveCfg = Release|x64 {948059F3-CD57-4ACC-9EA5-C4550D06CB19}.Release|x64.Build.0 = Release|x64 {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Debug|Win32.ActiveCfg = Debug|Win32 - {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Debug|Win32.Build.0 = Debug|Win32 {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Debug|x64.ActiveCfg = Debug|x64 - {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Debug|x64.Build.0 = Debug|x64 {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Release|Win32.ActiveCfg = Release|Win32 - {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Release|Win32.Build.0 = Release|Win32 {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Release|x64.ActiveCfg = Release|x64 - {83801760-CFF3-4B11-9CA5-4598C0DBC442}.Release|x64.Build.0 = Release|x64 {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Debug|Win32.ActiveCfg = Debug|Win32 - {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Debug|Win32.Build.0 = Debug|Win32 {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Debug|x64.ActiveCfg = Debug|x64 - {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Debug|x64.Build.0 = Debug|x64 {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Release|Win32.ActiveCfg = Release|Win32 - {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Release|Win32.Build.0 = Release|Win32 {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Release|x64.ActiveCfg = Release|x64 - {7186CBA9-18FE-4868-8A2F-2CF50F66132A}.Release|x64.Build.0 = Release|x64 {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Debug|Win32.ActiveCfg = Debug|Win32 - {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Debug|Win32.Build.0 = Debug|Win32 {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Debug|x64.ActiveCfg = Debug|x64 - {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Debug|x64.Build.0 = Debug|x64 {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Release|Win32.ActiveCfg = Release|Win32 - {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Release|Win32.Build.0 = Release|Win32 {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Release|x64.ActiveCfg = Release|x64 - {1F040862-DAB3-4F65-893D-0023BD2BD0E4}.Release|x64.Build.0 = Release|x64 {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Debug|Win32.ActiveCfg = Debug|Win32 - {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Debug|Win32.Build.0 = Debug|Win32 {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Debug|x64.ActiveCfg = Debug|x64 - {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Debug|x64.Build.0 = Debug|x64 {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Release|Win32.ActiveCfg = Release|Win32 - {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Release|Win32.Build.0 = Release|Win32 {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Release|x64.ActiveCfg = Release|x64 - {529BDB9A-7714-4CC6-A116-189159D8CC4A}.Release|x64.Build.0 = Release|x64 {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Debug|Win32.ActiveCfg = Debug|Win32 - {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Debug|Win32.Build.0 = Debug|Win32 {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Debug|x64.ActiveCfg = Debug|x64 - {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Debug|x64.Build.0 = Debug|x64 {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Release|Win32.ActiveCfg = Release|Win32 - {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Release|Win32.Build.0 = Release|Win32 {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Release|x64.ActiveCfg = Release|x64 - {F0DEFABC-1F27-4CDB-835A-1AF2958C3F9B}.Release|x64.Build.0 = Release|x64 {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Debug|Win32.ActiveCfg = Debug|Win32 - {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Debug|Win32.Build.0 = Debug|Win32 {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Debug|x64.ActiveCfg = Debug|x64 - {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Debug|x64.Build.0 = Debug|x64 {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Release|Win32.ActiveCfg = Release|Win32 - {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Release|Win32.Build.0 = Release|Win32 {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Release|x64.ActiveCfg = Release|x64 - {C00984F2-B825-45AF-86EC-A4FEF70B02C8}.Release|x64.Build.0 = Release|x64 {2CF45619-1C69-4072-B869-817D7954CABF}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {2CF45619-1C69-4072-B869-817D7954CABF}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {2CF45619-1C69-4072-B869-817D7954CABF}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {2CF45619-1C69-4072-B869-817D7954CABF}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {2CF45619-1C69-4072-B869-817D7954CABF}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {2CF45619-1C69-4072-B869-817D7954CABF}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {2CF45619-1C69-4072-B869-817D7954CABF}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {2CF45619-1C69-4072-B869-817D7954CABF}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {2CF45619-1C69-4072-B869-817D7954CABF}.Debug|Win32.ActiveCfg = Debug|Win32 - {2CF45619-1C69-4072-B869-817D7954CABF}.Debug|Win32.Build.0 = Debug|Win32 {2CF45619-1C69-4072-B869-817D7954CABF}.Debug|x64.ActiveCfg = Debug|x64 - {2CF45619-1C69-4072-B869-817D7954CABF}.Debug|x64.Build.0 = Debug|x64 {2CF45619-1C69-4072-B869-817D7954CABF}.Release|Win32.ActiveCfg = Release|Win32 - {2CF45619-1C69-4072-B869-817D7954CABF}.Release|Win32.Build.0 = Release|Win32 {2CF45619-1C69-4072-B869-817D7954CABF}.Release|x64.ActiveCfg = Release|x64 - {2CF45619-1C69-4072-B869-817D7954CABF}.Release|x64.Build.0 = Release|x64 {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Debug|Win32.ActiveCfg = Debug|Win32 - {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Debug|Win32.Build.0 = Debug|Win32 {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Debug|x64.ActiveCfg = Debug|x64 - {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Debug|x64.Build.0 = Debug|x64 {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Release|Win32.ActiveCfg = Release|Win32 - {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Release|Win32.Build.0 = Release|Win32 {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Release|x64.ActiveCfg = Release|x64 - {0FC21E44-5EF6-4725-8B9E-CC3C91552BDE}.Release|x64.Build.0 = Release|x64 {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Debug|Win32.ActiveCfg = Debug|Win32 - {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Debug|Win32.Build.0 = Debug|Win32 {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Debug|x64.ActiveCfg = Debug|x64 - {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Debug|x64.Build.0 = Debug|x64 {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Release|Win32.ActiveCfg = Release|Win32 - {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Release|Win32.Build.0 = Release|Win32 {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Release|x64.ActiveCfg = Release|x64 - {5DBA95DD-954C-4B77-A2D1-42E959B27C36}.Release|x64.Build.0 = Release|x64 {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Debug|Win32.ActiveCfg = Debug|Win32 - {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Debug|Win32.Build.0 = Debug|Win32 {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Debug|x64.ActiveCfg = Debug|x64 - {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Debug|x64.Build.0 = Debug|x64 {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Release|Win32.ActiveCfg = Release|Win32 - {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Release|Win32.Build.0 = Release|Win32 {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Release|x64.ActiveCfg = Release|x64 - {9EA751B7-04D5-484C-89EF-03AA2782B1D6}.Release|x64.Build.0 = Release|x64 {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Debug|Win32.ActiveCfg = Debug|Win32 - {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Debug|Win32.Build.0 = Debug|Win32 {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Debug|x64.ActiveCfg = Debug|x64 - {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Debug|x64.Build.0 = Debug|x64 {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Release|Win32.ActiveCfg = Release|Win32 - {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Release|Win32.Build.0 = Release|Win32 {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Release|x64.ActiveCfg = Release|x64 - {3DF7D787-3F9C-48E9-BECE-B9E7030E01A7}.Release|x64.Build.0 = Release|x64 {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Debug|Win32.ActiveCfg = Debug|Win32 - {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Debug|Win32.Build.0 = Debug|Win32 {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Debug|x64.ActiveCfg = Debug|x64 - {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Debug|x64.Build.0 = Debug|x64 {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Release|Win32.ActiveCfg = Release|Win32 - {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Release|Win32.Build.0 = Release|Win32 {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Release|x64.ActiveCfg = Release|x64 - {727351F3-D1CC-42C5-9AA2-5840AD3F7A1A}.Release|x64.Build.0 = Release|x64 {C3955110-CB5E-484A-938C-D7861E08D43B}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {C3955110-CB5E-484A-938C-D7861E08D43B}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {C3955110-CB5E-484A-938C-D7861E08D43B}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {C3955110-CB5E-484A-938C-D7861E08D43B}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {C3955110-CB5E-484A-938C-D7861E08D43B}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {C3955110-CB5E-484A-938C-D7861E08D43B}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {C3955110-CB5E-484A-938C-D7861E08D43B}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {C3955110-CB5E-484A-938C-D7861E08D43B}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {C3955110-CB5E-484A-938C-D7861E08D43B}.Debug|Win32.ActiveCfg = Debug|Win32 - {C3955110-CB5E-484A-938C-D7861E08D43B}.Debug|Win32.Build.0 = Debug|Win32 {C3955110-CB5E-484A-938C-D7861E08D43B}.Debug|x64.ActiveCfg = Debug|x64 - {C3955110-CB5E-484A-938C-D7861E08D43B}.Debug|x64.Build.0 = Debug|x64 {C3955110-CB5E-484A-938C-D7861E08D43B}.Release|Win32.ActiveCfg = Release|Win32 - {C3955110-CB5E-484A-938C-D7861E08D43B}.Release|Win32.Build.0 = Release|Win32 {C3955110-CB5E-484A-938C-D7861E08D43B}.Release|x64.ActiveCfg = Release|x64 - {C3955110-CB5E-484A-938C-D7861E08D43B}.Release|x64.Build.0 = Release|x64 {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Debug|Win32.ActiveCfg = Debug|Win32 - {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Debug|Win32.Build.0 = Debug|Win32 {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Debug|x64.ActiveCfg = Debug|x64 - {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Debug|x64.Build.0 = Debug|x64 {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Release|Win32.ActiveCfg = Release|Win32 - {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Release|Win32.Build.0 = Release|Win32 {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Release|x64.ActiveCfg = Release|x64 - {DFDF7BA0-4F61-4060-B919-7C8B2D40172E}.Release|x64.Build.0 = Release|x64 {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Debug|Win32.ActiveCfg = Debug|Win32 - {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Debug|Win32.Build.0 = Debug|Win32 {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Debug|x64.ActiveCfg = Debug|x64 - {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Debug|x64.Build.0 = Debug|x64 {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Release|Win32.ActiveCfg = Release|Win32 - {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Release|Win32.Build.0 = Release|Win32 {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Release|x64.ActiveCfg = Release|x64 - {E4DC9D1E-8282-491F-A1FA-AF497EB1FF9C}.Release|x64.Build.0 = Release|x64 {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Debug|Win32.ActiveCfg = Debug|Win32 - {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Debug|Win32.Build.0 = Debug|Win32 {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Debug|x64.ActiveCfg = Debug|x64 - {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Debug|x64.Build.0 = Debug|x64 {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Release|Win32.ActiveCfg = Release|Win32 - {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Release|Win32.Build.0 = Release|Win32 {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Release|x64.ActiveCfg = Release|x64 - {D7F18F42-AD57-4F5C-B66E-FA0061BEB54F}.Release|x64.Build.0 = Release|x64 {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Debug|Win32.ActiveCfg = Debug|Win32 - {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Debug|Win32.Build.0 = Debug|Win32 {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Debug|x64.ActiveCfg = Debug|x64 - {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Debug|x64.Build.0 = Debug|x64 {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Release|Win32.ActiveCfg = Release|Win32 - {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Release|Win32.Build.0 = Release|Win32 {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Release|x64.ActiveCfg = Release|x64 - {8680F272-78C1-41E2-AE78-10E37BFC6F53}.Release|x64.Build.0 = Release|x64 {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Debug|Win32.ActiveCfg = Debug|Win32 - {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Debug|Win32.Build.0 = Debug|Win32 {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Debug|x64.ActiveCfg = Debug|x64 - {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Debug|x64.Build.0 = Debug|x64 {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Release|Win32.ActiveCfg = Release|Win32 - {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Release|Win32.Build.0 = Release|Win32 {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Release|x64.ActiveCfg = Release|x64 - {6D4BA8B0-63B8-47D8-8B37-0A56A464BD4D}.Release|x64.Build.0 = Release|x64 {849F83BA-7817-419C-93E5-9F92541F773F}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {849F83BA-7817-419C-93E5-9F92541F773F}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {849F83BA-7817-419C-93E5-9F92541F773F}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {849F83BA-7817-419C-93E5-9F92541F773F}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {849F83BA-7817-419C-93E5-9F92541F773F}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {849F83BA-7817-419C-93E5-9F92541F773F}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {849F83BA-7817-419C-93E5-9F92541F773F}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {849F83BA-7817-419C-93E5-9F92541F773F}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {849F83BA-7817-419C-93E5-9F92541F773F}.Debug|Win32.ActiveCfg = Debug|Win32 - {849F83BA-7817-419C-93E5-9F92541F773F}.Debug|Win32.Build.0 = Debug|Win32 {849F83BA-7817-419C-93E5-9F92541F773F}.Debug|x64.ActiveCfg = Debug|x64 - {849F83BA-7817-419C-93E5-9F92541F773F}.Debug|x64.Build.0 = Debug|x64 {849F83BA-7817-419C-93E5-9F92541F773F}.Release|Win32.ActiveCfg = Release|Win32 - {849F83BA-7817-419C-93E5-9F92541F773F}.Release|Win32.Build.0 = Release|Win32 {849F83BA-7817-419C-93E5-9F92541F773F}.Release|x64.ActiveCfg = Release|x64 - {849F83BA-7817-419C-93E5-9F92541F773F}.Release|x64.Build.0 = Release|x64 {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Debug|Win32.ActiveCfg = Debug|Win32 - {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Debug|Win32.Build.0 = Debug|Win32 {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Debug|x64.ActiveCfg = Debug|x64 - {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Debug|x64.Build.0 = Debug|x64 {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Release|Win32.ActiveCfg = Release|Win32 - {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Release|Win32.Build.0 = Release|Win32 {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Release|x64.ActiveCfg = Release|x64 - {DA51489E-AC9D-4D59-89FC-1F103449CC5A}.Release|x64.Build.0 = Release|x64 {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Debug|Win32.ActiveCfg = Debug|Win32 - {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Debug|Win32.Build.0 = Debug|Win32 {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Debug|x64.ActiveCfg = Debug|x64 - {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Debug|x64.Build.0 = Debug|x64 {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Release|Win32.ActiveCfg = Release|Win32 - {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Release|Win32.Build.0 = Release|Win32 {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Release|x64.ActiveCfg = Release|x64 - {299B54D9-A682-40D5-B87B-A0C21BF1E839}.Release|x64.Build.0 = Release|x64 {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Debug|Win32.ActiveCfg = Debug|Win32 - {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Debug|Win32.Build.0 = Debug|Win32 {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Debug|x64.ActiveCfg = Debug|x64 - {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Debug|x64.Build.0 = Debug|x64 {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Release|Win32.ActiveCfg = Release|Win32 - {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Release|Win32.Build.0 = Release|Win32 {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Release|x64.ActiveCfg = Release|x64 - {77CB36FD-F130-4416-B6B7-C24EFD83630E}.Release|x64.Build.0 = Release|x64 {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Debug|Win32.ActiveCfg = Debug|Win32 - {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Debug|Win32.Build.0 = Debug|Win32 {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Debug|x64.ActiveCfg = Debug|x64 - {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Debug|x64.Build.0 = Debug|x64 {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Release|Win32.ActiveCfg = Release|Win32 - {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Release|Win32.Build.0 = Release|Win32 {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Release|x64.ActiveCfg = Release|x64 - {D306ADCE-34A1-4599-BD50-8598BB92B47F}.Release|x64.Build.0 = Release|x64 {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Debug|Win32.ActiveCfg = Debug|Win32 - {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Debug|Win32.Build.0 = Debug|Win32 {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Debug|x64.ActiveCfg = Debug|x64 - {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Debug|x64.Build.0 = Debug|x64 {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Release|Win32.ActiveCfg = Release|Win32 - {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Release|Win32.Build.0 = Release|Win32 {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Release|x64.ActiveCfg = Release|x64 - {3A517759-2BC3-4110-97AA-E5E7E45EA3D8}.Release|x64.Build.0 = Release|x64 {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Debug|Win32.ActiveCfg = Debug|Win32 - {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Debug|Win32.Build.0 = Debug|Win32 {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Debug|x64.ActiveCfg = Debug|x64 - {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Debug|x64.Build.0 = Debug|x64 {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Release|Win32.ActiveCfg = Release|Win32 - {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Release|Win32.Build.0 = Release|Win32 {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Release|x64.ActiveCfg = Release|x64 - {8EBD7C12-5623-467F-B80D-CFBB4C695771}.Release|x64.Build.0 = Release|x64 {00000035-0000-0000-0000-000000000000}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {00000035-0000-0000-0000-000000000000}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {00000035-0000-0000-0000-000000000000}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {00000035-0000-0000-0000-000000000000}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {00000035-0000-0000-0000-000000000000}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {00000035-0000-0000-0000-000000000000}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {00000035-0000-0000-0000-000000000000}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {00000035-0000-0000-0000-000000000000}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {00000035-0000-0000-0000-000000000000}.Debug|Win32.ActiveCfg = Debug|Win32 - {00000035-0000-0000-0000-000000000000}.Debug|Win32.Build.0 = Debug|Win32 {00000035-0000-0000-0000-000000000000}.Debug|x64.ActiveCfg = Debug|x64 - {00000035-0000-0000-0000-000000000000}.Debug|x64.Build.0 = Debug|x64 {00000035-0000-0000-0000-000000000000}.Release|Win32.ActiveCfg = Release|Win32 - {00000035-0000-0000-0000-000000000000}.Release|Win32.Build.0 = Release|Win32 {00000035-0000-0000-0000-000000000000}.Release|x64.ActiveCfg = Release|x64 - {00000035-0000-0000-0000-000000000000}.Release|x64.Build.0 = Release|x64 {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Debug|Win32.ActiveCfg = Debug|Win32 - {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Debug|Win32.Build.0 = Debug|Win32 {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Debug|x64.ActiveCfg = Debug|x64 - {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Debug|x64.Build.0 = Debug|x64 {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Release|Win32.ActiveCfg = Release|Win32 - {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Release|Win32.Build.0 = Release|Win32 {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Release|x64.ActiveCfg = Release|x64 - {16EED45E-8D20-40EF-BB30-9DDD5A11B352}.Release|x64.Build.0 = Release|x64 {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 @@ -3786,13 +3784,9 @@ Global {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Debug|Win32.ActiveCfg = Debug|Win32 - {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Debug|Win32.Build.0 = Debug|Win32 {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Debug|x64.ActiveCfg = Debug|x64 - {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Debug|x64.Build.0 = Debug|x64 {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Release|Win32.ActiveCfg = Release|Win32 - {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Release|Win32.Build.0 = Release|Win32 {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Release|x64.ActiveCfg = Release|x64 - {2B721A85-96F1-4B92-BB31-1BCEF6ACFC8E}.Release|x64.Build.0 = Release|x64 {C5606B09-9FB7-4337-A490-2024CDCE4036}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 {C5606B09-9FB7-4337-A490-2024CDCE4036}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {C5606B09-9FB7-4337-A490-2024CDCE4036}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 @@ -3802,37 +3796,33 @@ Global {C5606B09-9FB7-4337-A490-2024CDCE4036}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 {C5606B09-9FB7-4337-A490-2024CDCE4036}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {C5606B09-9FB7-4337-A490-2024CDCE4036}.Debug|Win32.ActiveCfg = Debug|Win32 - {C5606B09-9FB7-4337-A490-2024CDCE4036}.Debug|Win32.Build.0 = Debug|Win32 {C5606B09-9FB7-4337-A490-2024CDCE4036}.Debug|x64.ActiveCfg = Debug|x64 - {C5606B09-9FB7-4337-A490-2024CDCE4036}.Debug|x64.Build.0 = Debug|x64 {C5606B09-9FB7-4337-A490-2024CDCE4036}.Release|Win32.ActiveCfg = Release|Win32 - {C5606B09-9FB7-4337-A490-2024CDCE4036}.Release|Win32.Build.0 = Release|Win32 {C5606B09-9FB7-4337-A490-2024CDCE4036}.Release|x64.ActiveCfg = Release|x64 - {C5606B09-9FB7-4337-A490-2024CDCE4036}.Release|x64.Build.0 = Release|x64 {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Debug|Win32.ActiveCfg = Debug|Win32 - {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Debug|Win32.Build.0 = Debug|Win32 {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Debug|x64.ActiveCfg = Debug|x64 - {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Debug|x64.Build.0 = Debug|x64 {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Release|Win32.ActiveCfg = Release|Win32 - {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Release|Win32.Build.0 = Release|Win32 {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Release|x64.ActiveCfg = Release|x64 - {12405F8D-7361-450D-8AFE-85BFD3AEEFD7}.Release|x64.Build.0 = Release|x64 {D7224A94-13EF-4253-B3EA-801295D5966B}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {D7224A94-13EF-4253-B3EA-801295D5966B}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {D7224A94-13EF-4253-B3EA-801295D5966B}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {D7224A94-13EF-4253-B3EA-801295D5966B}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {D7224A94-13EF-4253-B3EA-801295D5966B}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {D7224A94-13EF-4253-B3EA-801295D5966B}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {D7224A94-13EF-4253-B3EA-801295D5966B}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {D7224A94-13EF-4253-B3EA-801295D5966B}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {D7224A94-13EF-4253-B3EA-801295D5966B}.Debug|Win32.ActiveCfg = Debug|Win32 - {D7224A94-13EF-4253-B3EA-801295D5966B}.Debug|Win32.Build.0 = Debug|Win32 {D7224A94-13EF-4253-B3EA-801295D5966B}.Debug|x64.ActiveCfg = Debug|x64 - {D7224A94-13EF-4253-B3EA-801295D5966B}.Debug|x64.Build.0 = Debug|x64 {D7224A94-13EF-4253-B3EA-801295D5966B}.Release|Win32.ActiveCfg = Release|Win32 - {D7224A94-13EF-4253-B3EA-801295D5966B}.Release|Win32.Build.0 = Release|Win32 {D7224A94-13EF-4253-B3EA-801295D5966B}.Release|x64.ActiveCfg = Release|x64 - {D7224A94-13EF-4253-B3EA-801295D5966B}.Release|x64.Build.0 = Release|x64 {4FA5930A-77B1-46D8-B1F0-EF3D00C2E0A3}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 {4FA5930A-77B1-46D8-B1F0-EF3D00C2E0A3}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {4FA5930A-77B1-46D8-B1F0-EF3D00C2E0A3}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 @@ -4020,11 +4010,8 @@ Global {24916CD9-F28F-436C-8F20-B22BE0555601}.Debug|Win32.ActiveCfg = Debug|Win32 {24916CD9-F28F-436C-8F20-B22BE0555601}.Debug|Win32.Build.0 = Debug|Win32 {24916CD9-F28F-436C-8F20-B22BE0555601}.Debug|x64.ActiveCfg = Debug|x64 - {24916CD9-F28F-436C-8F20-B22BE0555601}.Debug|x64.Build.0 = Debug|x64 {24916CD9-F28F-436C-8F20-B22BE0555601}.Release|Win32.ActiveCfg = Release|Win32 - {24916CD9-F28F-436C-8F20-B22BE0555601}.Release|Win32.Build.0 = Release|Win32 {24916CD9-F28F-436C-8F20-B22BE0555601}.Release|x64.ActiveCfg = Release|x64 - {24916CD9-F28F-436C-8F20-B22BE0555601}.Release|x64.Build.0 = Release|x64 {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 @@ -4034,13 +4021,9 @@ Global {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Debug|Win32.ActiveCfg = Debug|Win32 - {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Debug|Win32.Build.0 = Debug|Win32 {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Debug|x64.ActiveCfg = Debug|x64 - {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Debug|x64.Build.0 = Debug|x64 {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Release|Win32.ActiveCfg = Release|Win32 - {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Release|Win32.Build.0 = Release|Win32 {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Release|x64.ActiveCfg = Release|x64 - {E17093DB-4940-4EB4-A7BB-6958A96475E2}.Release|x64.Build.0 = Release|x64 {806A4720-1E5E-4479-A92B-07D3253E72ED}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 {806A4720-1E5E-4479-A92B-07D3253E72ED}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {806A4720-1E5E-4479-A92B-07D3253E72ED}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 @@ -4058,29 +4041,29 @@ Global {806A4720-1E5E-4479-A92B-07D3253E72ED}.Release|x64.ActiveCfg = Release|x64 {806A4720-1E5E-4479-A92B-07D3253E72ED}.Release|x64.Build.0 = Release|x64 {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Debug|Win32.ActiveCfg = Debug|Win32 - {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Debug|Win32.Build.0 = Debug|Win32 {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Debug|x64.ActiveCfg = Debug|x64 - {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Debug|x64.Build.0 = Debug|x64 {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Release|Win32.ActiveCfg = Release|Win32 - {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Release|Win32.Build.0 = Release|Win32 {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Release|x64.ActiveCfg = Release|x64 - {86FA255C-ED2F-44E3-989B-F9291165D3E1}.Release|x64.Build.0 = Release|x64 {4D76D578-E858-485E-8498-9FC604B3B069}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {4D76D578-E858-485E-8498-9FC604B3B069}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {4D76D578-E858-485E-8498-9FC604B3B069}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {4D76D578-E858-485E-8498-9FC604B3B069}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {4D76D578-E858-485E-8498-9FC604B3B069}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {4D76D578-E858-485E-8498-9FC604B3B069}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {4D76D578-E858-485E-8498-9FC604B3B069}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {4D76D578-E858-485E-8498-9FC604B3B069}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {4D76D578-E858-485E-8498-9FC604B3B069}.Debug|Win32.ActiveCfg = Debug|Win32 - {4D76D578-E858-485E-8498-9FC604B3B069}.Debug|Win32.Build.0 = Debug|Win32 {4D76D578-E858-485E-8498-9FC604B3B069}.Debug|x64.ActiveCfg = Debug|x64 - {4D76D578-E858-485E-8498-9FC604B3B069}.Debug|x64.Build.0 = Debug|x64 {4D76D578-E858-485E-8498-9FC604B3B069}.Release|Win32.ActiveCfg = Release|Win32 - {4D76D578-E858-485E-8498-9FC604B3B069}.Release|Win32.Build.0 = Release|Win32 {4D76D578-E858-485E-8498-9FC604B3B069}.Release|x64.ActiveCfg = Release|x64 - {4D76D578-E858-485E-8498-9FC604B3B069}.Release|x64.Build.0 = Release|x64 {A19DC61B-84AE-4983-9B4C-4F4A338178C5}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 {A19DC61B-84AE-4983-9B4C-4F4A338178C5}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {A19DC61B-84AE-4983-9B4C-4F4A338178C5}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 @@ -4114,17 +4097,18 @@ Global {0DDD44E0-E425-47BE-8DAA-06CA0E8704D2}.Release|x64.ActiveCfg = Release|x64 {0DDD44E0-E425-47BE-8DAA-06CA0E8704D2}.Release|x64.Build.0 = Release|x64 {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 + {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 + {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Cpp11-Debug|x64.Build.0 = Cpp11-Debug|x64 {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Cpp11-Release|Win32.ActiveCfg = Cpp11-Release|Win32 + {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Cpp11-Release|Win32.Build.0 = Cpp11-Release|Win32 {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Cpp11-Release|x64.ActiveCfg = Cpp11-Release|x64 + {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Cpp11-Release|x64.Build.0 = Cpp11-Release|x64 {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Debug|Win32.ActiveCfg = Debug|Win32 {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Debug|Win32.Build.0 = Debug|Win32 {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Debug|x64.ActiveCfg = Debug|x64 - {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Debug|x64.Build.0 = Debug|x64 {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Release|Win32.ActiveCfg = Release|Win32 - {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Release|Win32.Build.0 = Release|Win32 {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Release|x64.ActiveCfg = Release|x64 - {7D48DD81-247D-467E-B94C-D23EC94BDAB0}.Release|x64.Build.0 = Release|x64 {B1C09F91-405B-448C-84FE-1BB4E29CA620}.Cpp11-Debug|Win32.ActiveCfg = Cpp11-Debug|Win32 {B1C09F91-405B-448C-84FE-1BB4E29CA620}.Cpp11-Debug|Win32.Build.0 = Cpp11-Debug|Win32 {B1C09F91-405B-448C-84FE-1BB4E29CA620}.Cpp11-Debug|x64.ActiveCfg = Cpp11-Debug|x64 diff --git a/cpp/msbuild/ice.v143.sln b/cpp/msbuild/ice.v143.sln index 8331d3685a5..b8c9ceb815b 100644 --- a/cpp/msbuild/ice.v143.sln +++ b/cpp/msbuild/ice.v143.sln @@ -50,9 +50,9 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ice++11", "..\src\Ice\msbui {763F88BB-37FD-4BCC-9D13-A7103596EA06} = {763F88BB-37FD-4BCC-9D13-A7103596EA06} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icexml", "..\src\IceXML\msbuild\icexml.vcxproj", "{90EC26E8-AFFA-4E44-B068-AB5849A96FDD}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icexml++11", "..\src\IceXML\msbuild\icexml.vcxproj", "{90EC26E8-AFFA-4E44-B068-AB5849A96FDD}" ProjectSection(ProjectDependencies) = postProject - {6485EC94-6B47-428D-B42D-AAA11F08DB59} = {6485EC94-6B47-428D-B42D-AAA11F08DB59} + {3AB9772C-6113-4F1C-90FB-5368E7486C11} = {3AB9772C-6113-4F1C-90FB-5368E7486C11} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ice", "..\src\Ice\msbuild\ice\ice.vcxproj", "{6485EC94-6B47-428D-B42D-AAA11F08DB59}" @@ -66,9 +66,9 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glacier2++11", "..\src\Glac {3AB9772C-6113-4F1C-90FB-5368E7486C11} = {3AB9772C-6113-4F1C-90FB-5368E7486C11} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icedb", "..\src\IceDB\msbuild\icedb.vcxproj", "{E8ACC848-F7DA-4B29-B52F-81D66E7D397E}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icedb++11", "..\src\IceDB\msbuild\icedb.vcxproj", "{E8ACC848-F7DA-4B29-B52F-81D66E7D397E}" ProjectSection(ProjectDependencies) = postProject - {6485EC94-6B47-428D-B42D-AAA11F08DB59} = {6485EC94-6B47-428D-B42D-AAA11F08DB59} + {3AB9772C-6113-4F1C-90FB-5368E7486C11} = {3AB9772C-6113-4F1C-90FB-5368E7486C11} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icestorm", "..\src\IceStormLib\msbuild\icestorm\icestorm.vcxproj", "{E6864F0D-B2ED-406A-B98C-F3668A680005}" @@ -81,7 +81,7 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icestorm++11", "..\src\IceS {3AB9772C-6113-4F1C-90FB-5368E7486C11} = {3AB9772C-6113-4F1C-90FB-5368E7486C11} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icepatch2", "..\src\IcePatch2Lib\msbuild\icepatch2.vcxproj", "{994ADD25-20A0-4715-A3EC-9F86AFD481D0}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icepatch2", "..\src\IcePatch2Lib\msbuild\icepatch2\icepatch2.vcxproj", "{994ADD25-20A0-4715-A3EC-9F86AFD481D0}" ProjectSection(ProjectDependencies) = postProject {6485EC94-6B47-428D-B42D-AAA11F08DB59} = {6485EC94-6B47-428D-B42D-AAA11F08DB59} EndProjectSection @@ -158,53 +158,53 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "iceserviceinstall", "..\src {6485EC94-6B47-428D-B42D-AAA11F08DB59} = {6485EC94-6B47-428D-B42D-AAA11F08DB59} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icestormdb", "..\src\IceStorm\msbuild\icestormdb\icestormdb.vcxproj", "{F0B74B00-F252-4D38-A352-ED379CB196E9}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icestormdb++11", "..\src\IceStorm\msbuild\icestormdb\icestormdb.vcxproj", "{F0B74B00-F252-4D38-A352-ED379CB196E9}" ProjectSection(ProjectDependencies) = postProject - {18BF13D3-85D3-43A5-8C96-E52EB0672F72} = {18BF13D3-85D3-43A5-8C96-E52EB0672F72} - {588F90CA-62AC-4101-83FC-19AB9DB6B509} = {588F90CA-62AC-4101-83FC-19AB9DB6B509} + {142A9562-8DEC-4B1B-9B15-2CAD8304447B} = {142A9562-8DEC-4B1B-9B15-2CAD8304447B} + {2940A3C2-A9BA-44AA-AF65-00479C783407} = {2940A3C2-A9BA-44AA-AF65-00479C783407} + {4F8DD63C-3359-42F2-A6A8-80F7D55593AC} = {4F8DD63C-3359-42F2-A6A8-80F7D55593AC} {994ADD25-20A0-4715-A3EC-9F86AFD481D0} = {994ADD25-20A0-4715-A3EC-9F86AFD481D0} - {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} = {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} - {E6864F0D-B2ED-406A-B98C-F3668A680005} = {E6864F0D-B2ED-406A-B98C-F3668A680005} + {A28E5839-97F3-4874-BB77-E425787CF2ED} = {A28E5839-97F3-4874-BB77-E425787CF2ED} {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} = {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icestormservice", "..\src\IceStorm\msbuild\icestormservice\icestormservice.vcxproj", "{9E13C4B5-5DA9-43C1-9304-AEAC035E854D}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icestormservice++11", "..\src\IceStorm\msbuild\icestormservice\icestormservice.vcxproj", "{9E13C4B5-5DA9-43C1-9304-AEAC035E854D}" ProjectSection(ProjectDependencies) = postProject - {18BF13D3-85D3-43A5-8C96-E52EB0672F72} = {18BF13D3-85D3-43A5-8C96-E52EB0672F72} - {588F90CA-62AC-4101-83FC-19AB9DB6B509} = {588F90CA-62AC-4101-83FC-19AB9DB6B509} - {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} = {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} - {E6864F0D-B2ED-406A-B98C-F3668A680005} = {E6864F0D-B2ED-406A-B98C-F3668A680005} + {142A9562-8DEC-4B1B-9B15-2CAD8304447B} = {142A9562-8DEC-4B1B-9B15-2CAD8304447B} + {2940A3C2-A9BA-44AA-AF65-00479C783407} = {2940A3C2-A9BA-44AA-AF65-00479C783407} + {4F8DD63C-3359-42F2-A6A8-80F7D55593AC} = {4F8DD63C-3359-42F2-A6A8-80F7D55593AC} + {A28E5839-97F3-4874-BB77-E425787CF2ED} = {A28E5839-97F3-4874-BB77-E425787CF2ED} {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} = {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icestormadmin", "..\src\IceStorm\msbuild\icestormadmin\icestormadmin.vcxproj", "{8F1A1F99-DBE0-408D-99F7-D59142BD008C}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icestormadmin++11", "..\src\IceStorm\msbuild\icestormadmin\icestormadmin.vcxproj", "{8F1A1F99-DBE0-408D-99F7-D59142BD008C}" ProjectSection(ProjectDependencies) = postProject - {18BF13D3-85D3-43A5-8C96-E52EB0672F72} = {18BF13D3-85D3-43A5-8C96-E52EB0672F72} - {588F90CA-62AC-4101-83FC-19AB9DB6B509} = {588F90CA-62AC-4101-83FC-19AB9DB6B509} - {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} = {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} - {E6864F0D-B2ED-406A-B98C-F3668A680005} = {E6864F0D-B2ED-406A-B98C-F3668A680005} + {142A9562-8DEC-4B1B-9B15-2CAD8304447B} = {142A9562-8DEC-4B1B-9B15-2CAD8304447B} + {2940A3C2-A9BA-44AA-AF65-00479C783407} = {2940A3C2-A9BA-44AA-AF65-00479C783407} + {4F8DD63C-3359-42F2-A6A8-80F7D55593AC} = {4F8DD63C-3359-42F2-A6A8-80F7D55593AC} + {A28E5839-97F3-4874-BB77-E425787CF2ED} = {A28E5839-97F3-4874-BB77-E425787CF2ED} {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} = {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icegridadmin", "..\src\IceGrid\msbuild\icegridadmin\icegridadmin.vcxproj", "{1F4CA1BE-B405-400F-912E-F0CC7E369D59}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icegridadmin++11", "..\src\IceGrid\msbuild\icegridadmin\icegridadmin.vcxproj", "{1F4CA1BE-B405-400F-912E-F0CC7E369D59}" ProjectSection(ProjectDependencies) = postProject - {18BF13D3-85D3-43A5-8C96-E52EB0672F72} = {18BF13D3-85D3-43A5-8C96-E52EB0672F72} - {5A8CEAB6-9F57-495C-B554-F93F842A0A28} = {5A8CEAB6-9F57-495C-B554-F93F842A0A28} - {81C8FC6A-CAC3-4B6D-AE4D-5DEAD29726C5} = {81C8FC6A-CAC3-4B6D-AE4D-5DEAD29726C5} + {142A9562-8DEC-4B1B-9B15-2CAD8304447B} = {142A9562-8DEC-4B1B-9B15-2CAD8304447B} + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5} = {18F381D8-BA61-4E6A-B877-9F6BC28C07E5} {90EC26E8-AFFA-4E44-B068-AB5849A96FDD} = {90EC26E8-AFFA-4E44-B068-AB5849A96FDD} - {994ADD25-20A0-4715-A3EC-9F86AFD481D0} = {994ADD25-20A0-4715-A3EC-9F86AFD481D0} + {96161748-CE5E-4548-BC1D-AFD2F137A1DC} = {96161748-CE5E-4548-BC1D-AFD2F137A1DC} + {C694B856-3393-41B4-B3DC-3A5AD9A92A3D} = {C694B856-3393-41B4-B3DC-3A5AD9A92A3D} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icegridnode", "..\src\IceGrid\msbuild\icegridnode\icegridnode.vcxproj", "{48EF9416-336F-4FA5-A376-FDFB7726ADBA}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icegridnode++11", "..\src\IceGrid\msbuild\icegridnode\icegridnode.vcxproj", "{48EF9416-336F-4FA5-A376-FDFB7726ADBA}" ProjectSection(ProjectDependencies) = postProject - {18BF13D3-85D3-43A5-8C96-E52EB0672F72} = {18BF13D3-85D3-43A5-8C96-E52EB0672F72} - {588F90CA-62AC-4101-83FC-19AB9DB6B509} = {588F90CA-62AC-4101-83FC-19AB9DB6B509} - {72FA68A9-49B6-4AB6-94AE-34BB03770A51} = {72FA68A9-49B6-4AB6-94AE-34BB03770A51} + {142A9562-8DEC-4B1B-9B15-2CAD8304447B} = {142A9562-8DEC-4B1B-9B15-2CAD8304447B} + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5} = {18F381D8-BA61-4E6A-B877-9F6BC28C07E5} + {2940A3C2-A9BA-44AA-AF65-00479C783407} = {2940A3C2-A9BA-44AA-AF65-00479C783407} + {4F8DD63C-3359-42F2-A6A8-80F7D55593AC} = {4F8DD63C-3359-42F2-A6A8-80F7D55593AC} + {5923B17D-2873-4245-87A7-FB8F4BE12501} = {5923B17D-2873-4245-87A7-FB8F4BE12501} {90EC26E8-AFFA-4E44-B068-AB5849A96FDD} = {90EC26E8-AFFA-4E44-B068-AB5849A96FDD} - {994ADD25-20A0-4715-A3EC-9F86AFD481D0} = {994ADD25-20A0-4715-A3EC-9F86AFD481D0} {9E13C4B5-5DA9-43C1-9304-AEAC035E854D} = {9E13C4B5-5DA9-43C1-9304-AEAC035E854D} - {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} = {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} - {E6864F0D-B2ED-406A-B98C-F3668A680005} = {E6864F0D-B2ED-406A-B98C-F3668A680005} + {A28E5839-97F3-4874-BB77-E425787CF2ED} = {A28E5839-97F3-4874-BB77-E425787CF2ED} {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} = {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} EndProjectSection EndProject @@ -213,16 +213,16 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icessl", "..\src\IceSSL\msb {6485EC94-6B47-428D-B42D-AAA11F08DB59} = {6485EC94-6B47-428D-B42D-AAA11F08DB59} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icegridregistry", "..\src\IceGrid\msbuild\icegridregistry\icegridregistry.vcxproj", "{64490115-464B-4DC3-B7C6-D0AF1B68B6F9}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icegridregistry++11", "..\src\IceGrid\msbuild\icegridregistry\icegridregistry.vcxproj", "{64490115-464B-4DC3-B7C6-D0AF1B68B6F9}" ProjectSection(ProjectDependencies) = postProject - {18BF13D3-85D3-43A5-8C96-E52EB0672F72} = {18BF13D3-85D3-43A5-8C96-E52EB0672F72} - {588F90CA-62AC-4101-83FC-19AB9DB6B509} = {588F90CA-62AC-4101-83FC-19AB9DB6B509} - {72FA68A9-49B6-4AB6-94AE-34BB03770A51} = {72FA68A9-49B6-4AB6-94AE-34BB03770A51} + {142A9562-8DEC-4B1B-9B15-2CAD8304447B} = {142A9562-8DEC-4B1B-9B15-2CAD8304447B} + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5} = {18F381D8-BA61-4E6A-B877-9F6BC28C07E5} + {2940A3C2-A9BA-44AA-AF65-00479C783407} = {2940A3C2-A9BA-44AA-AF65-00479C783407} + {4F8DD63C-3359-42F2-A6A8-80F7D55593AC} = {4F8DD63C-3359-42F2-A6A8-80F7D55593AC} + {5923B17D-2873-4245-87A7-FB8F4BE12501} = {5923B17D-2873-4245-87A7-FB8F4BE12501} {90EC26E8-AFFA-4E44-B068-AB5849A96FDD} = {90EC26E8-AFFA-4E44-B068-AB5849A96FDD} - {994ADD25-20A0-4715-A3EC-9F86AFD481D0} = {994ADD25-20A0-4715-A3EC-9F86AFD481D0} {9E13C4B5-5DA9-43C1-9304-AEAC035E854D} = {9E13C4B5-5DA9-43C1-9304-AEAC035E854D} - {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} = {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} - {E6864F0D-B2ED-406A-B98C-F3668A680005} = {E6864F0D-B2ED-406A-B98C-F3668A680005} + {A28E5839-97F3-4874-BB77-E425787CF2ED} = {A28E5839-97F3-4874-BB77-E425787CF2ED} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icessl++11", "..\src\IceSSL\msbuild\icessl++11\icessl++11.vcxproj", "{5923B17D-2873-4245-87A7-FB8F4BE12501}" @@ -251,16 +251,16 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glacier2router++11", "..\sr {5923B17D-2873-4245-87A7-FB8F4BE12501} = {5923B17D-2873-4245-87A7-FB8F4BE12501} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icegriddb", "..\src\icegriddb\msbuild\icegriddb.vcxproj", "{369524F4-D374-44F4-BCFD-408934595701}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icegriddb++11", "..\src\icegriddb\msbuild\icegriddb.vcxproj", "{369524F4-D374-44F4-BCFD-408934595701}" ProjectSection(ProjectDependencies) = postProject - {18BF13D3-85D3-43A5-8C96-E52EB0672F72} = {18BF13D3-85D3-43A5-8C96-E52EB0672F72} - {6485EC94-6B47-428D-B42D-AAA11F08DB59} = {6485EC94-6B47-428D-B42D-AAA11F08DB59} + {142A9562-8DEC-4B1B-9B15-2CAD8304447B} = {142A9562-8DEC-4B1B-9B15-2CAD8304447B} + {3AB9772C-6113-4F1C-90FB-5368E7486C11} = {3AB9772C-6113-4F1C-90FB-5368E7486C11} {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} = {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icebridge", "..\src\IceBridge\msbuild\icebridge.vcxproj", "{1D6E8807-7C28-421F-B49E-BCB482FCB21D}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icebridge++11", "..\src\IceBridge\msbuild\icebridge.vcxproj", "{1D6E8807-7C28-421F-B49E-BCB482FCB21D}" ProjectSection(ProjectDependencies) = postProject - {6485EC94-6B47-428D-B42D-AAA11F08DB59} = {6485EC94-6B47-428D-B42D-AAA11F08DB59} + {3AB9772C-6113-4F1C-90FB-5368E7486C11} = {3AB9772C-6113-4F1C-90FB-5368E7486C11} EndProjectSection EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "slice2rb", "..\src\slice2rb\msbuild\slice2rb.vcxproj", "{A79E9EB0-878C-4EDB-9804-2D262D6008DB}" @@ -281,14 +281,16 @@ Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ice2slice", "..\src\ice2sli EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glacier2cryptpermissionsverifier", "..\src\Glacier2CryptPermissionsVerifier\msbuild\glacier2cryptpermissionsverifier\glacier2cryptpermissionsverifier.vcxproj", "{519CB7EF-8E49-4BC1-B3DB-181BEF5AC3B3}" ProjectSection(ProjectDependencies) = postProject - {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} = {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} + {2940A3C2-A9BA-44AA-AF65-00479C783407} = {2940A3C2-A9BA-44AA-AF65-00479C783407} EndProjectSection EndProject -Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glacier2cryptpermissionsverifier++11", "..\src\Glacier2CryptPermissionsVerifier\msbuild\glacier2cryptpermissionsverifier++11\glacier2cryptpermissionsverifier++11.vcxproj", "{BF2077E4-D837-486B-9356-24FA5F659808}" +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "icepatch2++11", "..\src\IcePatch2Lib\msbuild\icepatch2++11\icepatch2++11.vcxproj", "{18F381D8-BA61-4E6A-B877-9F6BC28C07E5}" ProjectSection(ProjectDependencies) = postProject - {2940A3C2-A9BA-44AA-AF65-00479C783407} = {2940A3C2-A9BA-44AA-AF65-00479C783407} + {3AB9772C-6113-4F1C-90FB-5368E7486C11} = {3AB9772C-6113-4F1C-90FB-5368E7486C11} EndProjectSection EndProject +Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "glacier2cryptpermissionsverifier++11", "..\src\Glacier2CryptPermissionsVerifier\msbuild\glacier2cryptpermissionsverifier++11\glacier2cryptpermissionsverifier++11.vcxproj", "{BF2077E4-D837-486B-9356-24FA5F659808}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 @@ -697,6 +699,14 @@ Global {519CB7EF-8E49-4BC1-B3DB-181BEF5AC3B3}.Release|Win32.Build.0 = Release|Win32 {519CB7EF-8E49-4BC1-B3DB-181BEF5AC3B3}.Release|x64.ActiveCfg = Release|x64 {519CB7EF-8E49-4BC1-B3DB-181BEF5AC3B3}.Release|x64.Build.0 = Release|x64 + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5}.Debug|Win32.ActiveCfg = Debug|Win32 + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5}.Debug|Win32.Build.0 = Debug|Win32 + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5}.Debug|x64.ActiveCfg = Debug|x64 + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5}.Debug|x64.Build.0 = Debug|x64 + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5}.Release|Win32.ActiveCfg = Release|Win32 + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5}.Release|Win32.Build.0 = Release|Win32 + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5}.Release|x64.ActiveCfg = Release|x64 + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5}.Release|x64.Build.0 = Release|x64 {BF2077E4-D837-486B-9356-24FA5F659808}.Debug|Win32.ActiveCfg = Debug|Win32 {BF2077E4-D837-486B-9356-24FA5F659808}.Debug|Win32.Build.0 = Debug|Win32 {BF2077E4-D837-486B-9356-24FA5F659808}.Debug|x64.ActiveCfg = Debug|x64 @@ -720,10 +730,10 @@ Global {55A6E595-EFE4-47B9-957C-E4CFF2E75FD6} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {ACAF39D3-B4BD-426B-98DE-D95944B0D3F6} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {3AB9772C-6113-4F1C-90FB-5368E7486C11} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} - {90EC26E8-AFFA-4E44-B068-AB5849A96FDD} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} + {90EC26E8-AFFA-4E44-B068-AB5849A96FDD} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} {6485EC94-6B47-428D-B42D-AAA11F08DB59} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {2940A3C2-A9BA-44AA-AF65-00479C783407} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} - {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} + {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} {E6864F0D-B2ED-406A-B98C-F3668A680005} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {A28E5839-97F3-4874-BB77-E425787CF2ED} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} {994ADD25-20A0-4715-A3EC-9F86AFD481D0} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} @@ -741,25 +751,26 @@ Global {43D54B43-526E-40CE-9945-81420C54A415} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {8BCB4793-C004-459D-9605-272470D53A40} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {0E22B627-F1A6-4771-89DE-9E45FD51F124} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} - {F0B74B00-F252-4D38-A352-ED379CB196E9} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} - {9E13C4B5-5DA9-43C1-9304-AEAC035E854D} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} - {8F1A1F99-DBE0-408D-99F7-D59142BD008C} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} - {1F4CA1BE-B405-400F-912E-F0CC7E369D59} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} - {48EF9416-336F-4FA5-A376-FDFB7726ADBA} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} + {F0B74B00-F252-4D38-A352-ED379CB196E9} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} + {9E13C4B5-5DA9-43C1-9304-AEAC035E854D} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} + {8F1A1F99-DBE0-408D-99F7-D59142BD008C} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} + {1F4CA1BE-B405-400F-912E-F0CC7E369D59} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} + {48EF9416-336F-4FA5-A376-FDFB7726ADBA} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} {72FA68A9-49B6-4AB6-94AE-34BB03770A51} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} - {64490115-464B-4DC3-B7C6-D0AF1B68B6F9} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} + {64490115-464B-4DC3-B7C6-D0AF1B68B6F9} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} {5923B17D-2873-4245-87A7-FB8F4BE12501} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} {3850C9C9-BA92-4EE6-9E77-E5BAE2A9BC81} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {C7223CC8-0AAA-470B-ACB3-12B9DE75525C} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {541CF1D6-95FD-4499-AB02-75CCCEE660B0} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} - {369524F4-D374-44F4-BCFD-408934595701} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} - {1D6E8807-7C28-421F-B49E-BCB482FCB21D} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} + {369524F4-D374-44F4-BCFD-408934595701} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} + {1D6E8807-7C28-421F-B49E-BCB482FCB21D} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} {A79E9EB0-878C-4EDB-9804-2D262D6008DB} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {D64AAD99-11C7-4C69-BD27-9FA9C71A36AC} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {D0DC2305-37FE-4D03-BE05-AC8912678DC8} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} {0D08F6B8-39C0-413B-84CE-D73230BCC740} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {773EA63E-40AE-45B8-82B4-82B54CF309F8} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} {519CB7EF-8E49-4BC1-B3DB-181BEF5AC3B3} = {2DC2B270-B7AE-48CF-8FB0-41A55A9747E9} + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} {BF2077E4-D837-486B-9356-24FA5F659808} = {F48CC091-6F26-4EC8-A2FB-485975E7C908} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution diff --git a/cpp/src/IceBox/msbuild/iceboxadmin/iceboxadmin.vcxproj b/cpp/src/IceBox/msbuild/iceboxadmin/iceboxadmin.vcxproj index d26907b4cf8..b03c9a76c67 100644 --- a/cpp/src/IceBox/msbuild/iceboxadmin/iceboxadmin.vcxproj +++ b/cpp/src/IceBox/msbuild/iceboxadmin/iceboxadmin.vcxproj @@ -21,6 +21,7 @@ {1B745EA3-C97A-41BB-8E6F-64AAE992BE55} IceBox + iceboxadmin diff --git a/cpp/src/IceBridge/IceBridge.cpp b/cpp/src/IceBridge/IceBridge.cpp index 5619360615d..0292c7482ca 100644 --- a/cpp/src/IceBridge/IceBridge.cpp +++ b/cpp/src/IceBridge/IceBridge.cpp @@ -13,124 +13,49 @@ using namespace Ice; namespace { - -// -// Represents a pending invocation. -// -class Invocation : public IceUtil::Shared -{ -public: - - Invocation(const AMD_Object_ice_invokePtr& cb) : - _cb(cb) - { - } - - void success(bool ok, const pair& results) - { - _cb->ice_response(ok, results); - } - - void exception(const Exception& ex) - { - _cb->ice_exception(ex); - } - - void sent(bool) - { - _cb->ice_response(true, vector()); // For oneway invocations - } - -private: - - const AMD_Object_ice_invokePtr _cb; -}; -typedef IceUtil::Handle InvocationPtr; - // -// Holds information about an incoming invocation that's been queued until an outgoing connection has +// Holds information about an incoming dispatch that's been queued until an outgoing connection has // been established. // -struct QueuedInvocation : public IceUtil::Shared +struct QueuedDispatch final { // - // The pointers in paramData refer to the Ice marshaling buffer and won't remain valid after - // ice_invoke_async completes, so we have to make a copy of the parameter data. + // The pointers in p refer to the Ice marshaling buffer and won't remain valid after + // ice_invokeAsync completes, so we have to make a copy of the in parameters // - QueuedInvocation(const AMD_Object_ice_invokePtr& c, const pair& p, const Current& curr) : - cb(c), paramData(p.first, p.second), current(curr) + QueuedDispatch(pair p, + function&)>&& r, + function&& e, + const Current& c) : + inParams(p.first, p.second), response(std::move(r)), error(std::move(e)), current(c) { } - const AMD_Object_ice_invokePtr cb; - const vector paramData; - const Current current; -}; -typedef IceUtil::Handle QueuedInvocationPtr; + QueuedDispatch(QueuedDispatch&&) = default; -// -// Relays heartbeat messages. -// -class HeartbeatCallbackI : public HeartbeatCallback -{ -public: - - HeartbeatCallbackI(const ConnectionPtr&); - - virtual void heartbeat(const ConnectionPtr&); - -private: - - const ConnectionPtr _connection; -}; - -class BridgeI; -typedef IceUtil::Handle BridgeIPtr; - -class BridgeConnection; -typedef IceUtil::Handle BridgeConnectionPtr; - -class CloseCallbackI : public CloseCallback -{ -public: - - CloseCallbackI(const BridgeIPtr&); - - virtual void closed(const ConnectionPtr&); - -private: - - const BridgeIPtr _bridge; -}; - -class GetConnectionCallback : public IceUtil::Shared -{ -public: - - GetConnectionCallback(const BridgeIPtr&, const BridgeConnectionPtr&); - void success(const ConnectionPtr&); - void exception(const Exception&); - -private: + // Make sure we don't copy this struct by accident + QueuedDispatch(const QueuedDispatch&) = delete; - const BridgeIPtr _bridge; - const BridgeConnectionPtr _bc; + const vector inParams; + function&)> response; + function error; + const Current current; }; // // Allows the bridge to be used as an Ice router. // -class RouterI : public Router +class RouterI final : public Router { public: - virtual ObjectPrx getClientProxy(IceUtil::Optional& hasRoutingTable, const Current&) const + shared_ptr getClientProxy(Ice::optional& hasRoutingTable, const Current&) const override { hasRoutingTable = false; // We don't maintain a routing table, no need to call addProxies on this impl. - return 0; + return nullptr; } - virtual ObjectPrx getServerProxy(const Current& current) const + shared_ptr getServerProxy(const Current& current) const override { // // We return a non-nil dummy proxy here so that a client is able to configure its @@ -139,107 +64,107 @@ class RouterI : public Router return current.adapter->getCommunicator()->stringToProxy("dummy"); } - virtual ObjectProxySeq addProxies(const ObjectProxySeq&, const Current&) + ObjectProxySeq addProxies(ObjectProxySeq, const Current&) override { return ObjectProxySeq(); } }; -class FinderI : public RouterFinder +class FinderI final : public RouterFinder { public: - FinderI(const RouterPrx& router) : - _router(router) + FinderI(shared_ptr router) : + _router(std::move(router)) { } - virtual RouterPrx getRouter(const Current&) + shared_ptr getRouter(const Current&) override { return _router; } private: - const RouterPrx _router; + const shared_ptr _router; }; // -// Represents a pair of bridged connections. +// Represents a pair of connections (shared object) // -class BridgeConnection : public IceUtil::Shared +class BridgeConnection final { public: - BridgeConnection(const ObjectAdapterPtr&, const ObjectPrx&, const ConnectionPtr&); - - void outgoingSuccess(const ConnectionPtr&); - void outgoingException(const Exception&); + BridgeConnection(shared_ptr, shared_ptr, shared_ptr); - void closed(const ConnectionPtr&); - void dispatch(const AMD_Object_ice_invokePtr&, const pair&, const Current&); + void outgoingSuccess(shared_ptr); + void outgoingException(exception_ptr); + void closed(const shared_ptr&); + void dispatch(pair, + function&)>, + function, + const Current&); private: - void send(const ConnectionPtr&, - const AMD_Object_ice_invokePtr&, - const pair&, - const Current&); + void send(const shared_ptr&, + pair, + function&)>, + function, + const Current& current); - const ObjectAdapterPtr _adapter; - const ObjectPrx _target; - const ConnectionPtr _incoming; + const shared_ptr _adapter; + const shared_ptr _target; + const shared_ptr _incoming; - IceUtil::Mutex _lock; - ConnectionPtr _outgoing; - IceInternal::UniquePtr _exception; + std::mutex _lock; + shared_ptr _outgoing; + exception_ptr _exception; // - // We maintain our own queue for invocations that arrive on the incoming connection before the outgoing + // We maintain our own queue for dispatches that arrive on the incoming connection before the outgoing // connection has been established. We don't want to forward these to proxies and let the proxies handle // the queuing because then the invocations could be sent out of order (e.g., when invocations are split // among twoway/oneway/datagram proxies). // - vector _queue; + vector _queue; }; // // The main bridge servant. // -class BridgeI : public Ice::BlobjectArrayAsync +class BridgeI final : public Ice::BlobjectArrayAsync, public enable_shared_from_this { public: - BridgeI(const ObjectAdapterPtr& adapter, const ObjectPrx& target); + BridgeI(shared_ptr adapter, shared_ptr target); - virtual void ice_invoke_async(const AMD_Object_ice_invokePtr&, - const std::pair&, - const Current&); + void ice_invokeAsync(pair inEncaps, + function&)> response, + function error, + const Current& current) override; - void closed(const ConnectionPtr&); - void outgoingSuccess(const BridgeConnectionPtr&, const ConnectionPtr&); - void outgoingException(const BridgeConnectionPtr&, const Exception&); + void closed(const shared_ptr&); + void outgoingSuccess(const shared_ptr&, shared_ptr); + void outgoingException(const shared_ptr&, exception_ptr); private: - const ObjectAdapterPtr _adapter; - const ObjectPrx _target; + const shared_ptr _adapter; + const shared_ptr _target; - IceUtil::Mutex _lock; - map _connections; + std::mutex _lock; + map, shared_ptr> _connections; }; -class BridgeService : public Service +class BridgeService final : public Service { -public: - - BridgeService(); - protected: - virtual bool start(int, char*[], int&); - virtual bool stop(); - virtual CommunicatorPtr initializeCommunicator(int&, char*[], const InitializationData&, int); + bool start(int, char*[], int&) override; + bool stop() override; + shared_ptr initializeCommunicator(int&, char*[], const InitializationData&, int) override; private: @@ -248,63 +173,17 @@ class BridgeService : public Service } -HeartbeatCallbackI::HeartbeatCallbackI(const ConnectionPtr& con) : - _connection(con) -{ -} - -void -HeartbeatCallbackI::heartbeat(const ConnectionPtr&) -{ - // - // When a connection receives a heartbeat message, we send one over its corresponding connection. - // - try - { - _connection->begin_heartbeat(); - } - catch(...) - { - } -} - -CloseCallbackI::CloseCallbackI(const BridgeIPtr& bridge) : - _bridge(bridge) -{ -} - -void -CloseCallbackI::closed(const ConnectionPtr& con) -{ - _bridge->closed(con); -} - -GetConnectionCallback::GetConnectionCallback(const BridgeIPtr& bridge, const BridgeConnectionPtr& bc) : - _bridge(bridge), _bc(bc) -{ -} - -void -GetConnectionCallback::success(const ConnectionPtr& outgoing) +BridgeConnection::BridgeConnection(shared_ptr adapter, + shared_ptr target, + shared_ptr inc) : + _adapter(std::move(adapter)), _target(std::move(target)), _incoming(std::move(inc)) { - _bridge->outgoingSuccess(_bc, outgoing); } void -GetConnectionCallback::exception(const Exception& ex) +BridgeConnection::outgoingSuccess(shared_ptr outgoing) { - _bridge->outgoingException(_bc, ex); -} - -BridgeConnection::BridgeConnection(const ObjectAdapterPtr& adapter, const ObjectPrx& target, const ConnectionPtr& inc) : - _adapter(adapter), _target(target), _incoming(inc) -{ -} - -void -BridgeConnection::outgoingSuccess(const ConnectionPtr& outgoing) -{ - IceUtil::Mutex::Lock lock(_lock); + lock_guard lg(_lock); assert(!_outgoing && outgoing); if(_exception) { @@ -312,17 +191,36 @@ BridgeConnection::outgoingSuccess(const ConnectionPtr& outgoing) // The incoming connection is already closed. There's no point in leaving the outgoing // connection open. // - outgoing->close(ICE_SCOPED_ENUM(ConnectionClose, Gracefully)); + outgoing->close(ConnectionClose::Gracefully); return; } - _outgoing = outgoing; + _outgoing = std::move(outgoing); // // Register hearbeat callbacks on both connections. // - _incoming->setHeartbeatCallback(new HeartbeatCallbackI(_outgoing)); - _outgoing->setHeartbeatCallback(new HeartbeatCallbackI(_incoming)); + _incoming->setHeartbeatCallback([con = _outgoing](const auto&) + { + try + { + con->heartbeatAsync(nullptr); + } + catch(...) + { + } + }); + + _outgoing->setHeartbeatCallback([con = _incoming](const auto&) + { + try + { + con->heartbeatAsync(nullptr); + } + catch(...) + { + } + }); // // Configure the outgoing connection for bidirectional requests. @@ -330,90 +228,92 @@ BridgeConnection::outgoingSuccess(const ConnectionPtr& outgoing) _outgoing->setAdapter(_adapter); // - // Flush any queued invocations. + // Flush any queued dispatches // - for(vector::const_iterator p = _queue.begin(); p != _queue.end(); ++p) + for(auto& p : _queue) { - pair paramData(&(*p)->paramData[0], &(*p)->paramData[0] + (*p)->paramData.size()); - send(outgoing, (*p)->cb, paramData, (*p)->current); + auto inParams = make_pair(p.inParams.data(), p.inParams.data() + p.inParams.size()); + send(_outgoing, inParams, std::move(p.response), std::move(p.error), p.current); } _queue.clear(); } void -BridgeConnection::outgoingException(const Exception& ex) +BridgeConnection::outgoingException(exception_ptr ex) { - IceUtil::Mutex::Lock lock(_lock); + lock_guard lg(_lock); if(_exception) { return; } - _exception.reset(ex.ice_clone()); + _exception = ex; // // The outgoing connection failed so we close the incoming connection. closed() will eventually // be called for it when the connection's dispatch count reaches zero. // - _incoming->close(ICE_SCOPED_ENUM(ConnectionClose, Gracefully)); + _incoming->close(ConnectionClose::Gracefully); // - // Complete the queued incoming invocations, otherwise the incoming connection will never + // Complete the queued incoming dispatch, otherwise the incoming connection will never // complete its graceful closure. This is only necessary on the server side. // // The client will receive an UnknownLocalException whose reason member contains information // about the failure. // - for(vector::iterator p = _queue.begin(); p != _queue.end(); ++p) + for(const auto& p : _queue) { - (*p)->cb->ice_exception(ex); + p.error(ex); } _queue.clear(); } void -BridgeConnection::closed(const ConnectionPtr& con) +BridgeConnection::closed(const shared_ptr& con) { - IceUtil::Mutex::Lock lock(_lock); + lock_guard lg(_lock); if(_exception) { return; // Nothing to do if the exception is already set, both connections have been closed already. } - ConnectionPtr toBeClosed = con == _incoming ? _outgoing : _incoming; + auto toBeClosed = con == _incoming ? _outgoing : _incoming; try { con->throwException(); } - catch(const Ice::CloseConnectionException& ex) + catch(const Ice::CloseConnectionException&) { - _exception.reset(ex.ice_clone()); + _exception = current_exception(); if(toBeClosed) { - toBeClosed->close(ICE_SCOPED_ENUM(ConnectionClose, Gracefully)); + toBeClosed->close(ConnectionClose::Gracefully); } } - catch(const Ice::Exception& ex) + catch(const std::exception&) { - _exception.reset(ex.ice_clone()); + _exception = current_exception(); if(toBeClosed) { - toBeClosed->close(ICE_SCOPED_ENUM(ConnectionClose, Forcefully)); + toBeClosed->close(ConnectionClose::Forcefully); } } // - // Even though the connection is already closed, we still need to "complete" the pending invocations so + // Even though the connection is already closed, we still need to "complete" the pending dispatches so // that the connection's dispatch count is updated correctly. // - for(vector::iterator p = _queue.begin(); p != _queue.end(); ++p) + for(const auto& p : _queue) { - (*p)->cb->ice_exception(*_exception.get()); + p.error(_exception); } _queue.clear(); } void -BridgeConnection::dispatch(const AMD_Object_ice_invokePtr& cb, const pair& paramData, +BridgeConnection::dispatch(pair inParams, + function&)> response, + function error, const Current& current) { // @@ -421,10 +321,10 @@ BridgeConnection::dispatch(const AMD_Object_ice_invokePtr& cb, const pair lg(_lock); if(_exception) { - cb->ice_exception(*_exception.get()); + error(_exception); } else if(!_outgoing) { @@ -432,18 +332,19 @@ BridgeConnection::dispatch(const AMD_Object_ice_invokePtr& cb, const pair& paramData, +BridgeConnection::send(const shared_ptr& dest, + pair inParams, + function&)> response, + function error, const Current& current) { try @@ -451,60 +352,60 @@ BridgeConnection::send(const ConnectionPtr& dest, // // Create a proxy having the same identity as the request. // - ObjectPrx prx = dest->createProxy(current.id); + auto prx = dest->createProxy(current.id); - // - // Examine the request to determine whether it should be forwarded as a oneway or a twoway. - // - Callback_Object_ice_invokePtr d; if(!current.requestId) { + // Oneway request if(prx->ice_isTwoway()) { prx = prx->ice_oneway(); } - d = newCallback_Object_ice_invoke(new Invocation(cb), &Invocation::exception, &Invocation::sent); + prx->ice_invokeAsync(current.operation, current.mode, inParams, nullptr, error, + [response = std::move(response)](bool){ response(true, {nullptr, nullptr}); }, + current.ctx); } else { - d = newCallback_Object_ice_invoke(new Invocation(cb), &Invocation::success, &Invocation::exception); + // Twoway request + prx->ice_invokeAsync(current.operation, current.mode, inParams, std::move(response), error, + nullptr, current.ctx); } - prx->begin_ice_invoke(current.operation, current.mode, paramData, current.ctx, d); } - catch(const std::exception& ex) + catch(const std::exception&) { - cb->ice_exception(ex); + // can't move error parameter above since we need it here + error(current_exception()); } } -BridgeI::BridgeI(const ObjectAdapterPtr& adapter, const ObjectPrx& target) : - _adapter(adapter), _target(target) +BridgeI::BridgeI(shared_ptr adapter, shared_ptr target) : + _adapter(std::move(adapter)), _target(std::move(target)) { } void -BridgeI::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, - const std::pair& paramData, - const Current& current) +BridgeI::ice_invokeAsync(pair inParams, + function&)> response, + function error, + const Current& current) { - BridgeConnectionPtr bc; - + shared_ptr bc; { - IceUtil::Mutex::Lock lock(_lock); + lock_guard lg(_lock); - map::iterator p = _connections.find(current.con); + auto p = _connections.find(current.con); if(p == _connections.end()) { // // The connection is unknown to us, it must be a new incoming connection. // - - EndpointInfoPtr info = current.con->getEndpoint()->getInfo(); + auto info = current.con->getEndpoint()->getInfo(); // // Create a target proxy that matches the configuration of the incoming connection. // - ObjectPrx target; + shared_ptr target; if(info->datagram()) { target = _target->ice_datagram(); @@ -523,12 +424,14 @@ BridgeI::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, // target = target->ice_connectionId(Ice::generateUUID()); - bc = new BridgeConnection(_adapter, target, current.con); - _connections.insert(make_pair(current.con, bc)); - current.con->setCloseCallback(new CloseCallbackI(this)); + bc = make_shared(_adapter, target, current.con); + _connections.emplace(current.con, bc); + + auto self = shared_from_this(); + current.con->setCloseCallback([self](const auto& con) { self->closed(con); }); // - // Try to establish the outgoing connection. + // Try to establish the outgoing connection asynchronously // try { @@ -536,15 +439,13 @@ BridgeI::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, // Begin the connection establishment process asynchronously. This can take a while to complete, // especially when using Bluetooth. // - Callback_Object_ice_getConnectionPtr d = - newCallback_Object_ice_getConnection(new GetConnectionCallback(this, bc), - &GetConnectionCallback::success, - &GetConnectionCallback::exception); - target->begin_ice_getConnection(d); + target->ice_getConnectionAsync( + [self, bc](auto outgoing) { self->outgoingSuccess(bc, std::move(outgoing)); }, + [self, bc](auto ex) { self->outgoingException(bc, ex); }); } - catch(const Exception& ex) + catch(const std::exception&) { - cb->ice_exception(ex); + error(current_exception()); return; } } @@ -557,19 +458,19 @@ BridgeI::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, // // Delegate the invocation to the BridgeConnection object. // - bc->dispatch(cb, paramData, current); + bc->dispatch(inParams, std::move(response), std::move(error), current); } void -BridgeI::closed(const ConnectionPtr& con) +BridgeI::closed(const shared_ptr& con) { // // Notify the BridgeConnection that a connection has closed. We also need to remove it from our map. // - BridgeConnectionPtr bc; + shared_ptr bc; { - IceUtil::Mutex::Lock lock(_lock); - map::iterator p = _connections.find(con); + lock_guard lg(_lock); + auto p = _connections.find(con); assert(p != _connections.end()); bc = p->second; _connections.erase(p); @@ -579,21 +480,21 @@ BridgeI::closed(const ConnectionPtr& con) } void -BridgeI::outgoingSuccess(const BridgeConnectionPtr& bc, const ConnectionPtr& outgoing) +BridgeI::outgoingSuccess(const shared_ptr& bc, shared_ptr outgoing) { // // An outgoing connection was established. Notify the BridgeConnection object. // { - IceUtil::Mutex::Lock lock(_lock); - _connections.insert(make_pair(outgoing, bc)); - outgoing->setCloseCallback(new CloseCallbackI(this)); + lock_guard lg(_lock); + _connections.emplace(outgoing, bc); + outgoing->setCloseCallback([self = shared_from_this()](const auto& con) { self->closed(con); }); } - bc->outgoingSuccess(outgoing); + bc->outgoingSuccess(std::move(outgoing)); } void -BridgeI::outgoingException(const BridgeConnectionPtr& bc, const Exception& ex) +BridgeI::outgoingException(const shared_ptr& bc, exception_ptr ex) { // // An outgoing connection attempt failed. Notify the BridgeConnection object. @@ -601,10 +502,6 @@ BridgeI::outgoingException(const BridgeConnectionPtr& bc, const Exception& ex) bc->outgoingException(ex); } -BridgeService::BridgeService() -{ -} - bool BridgeService::start(int argc, char* argv[], int& status) { @@ -644,7 +541,7 @@ BridgeService::start(int argc, char* argv[], int& status) return false; } - PropertiesPtr properties = communicator()->getProperties(); + auto properties = communicator()->getProperties(); const string targetProperty = "IceBridge.Target.Endpoints"; const string targetEndpoints = properties->getProperty(targetProperty); @@ -654,7 +551,7 @@ BridgeService::start(int argc, char* argv[], int& status) return false; } - Ice::ObjectPrx target; + shared_ptr target; try { @@ -677,13 +574,14 @@ BridgeService::start(int argc, char* argv[], int& status) return false; } - ObjectAdapterPtr adapter = communicator()->createObjectAdapter("IceBridge.Source"); + auto adapter = communicator()->createObjectAdapter("IceBridge.Source"); - adapter->addDefaultServant(new BridgeI(adapter, target), ""); + adapter->addDefaultServant(make_shared(adapter, std::move(target)), ""); string instanceName = properties->getPropertyWithDefault("IceBridge.InstanceName", "IceBridge"); - RouterPrx router = RouterPrx::uncheckedCast(adapter->add(new RouterI, stringToIdentity(instanceName + "/router"))); - adapter->add(new FinderI(router), stringToIdentity("Ice/RouterFinder")); + auto router = uncheckedCast(adapter->add(make_shared(), + stringToIdentity(instanceName + "/router"))); + adapter->add(make_shared(router), stringToIdentity("Ice/RouterFinder")); try { @@ -709,7 +607,7 @@ BridgeService::stop() return true; } -CommunicatorPtr +shared_ptr BridgeService::initializeCommunicator(int& argc, char* argv[], const InitializationData& initializationData, int version) { @@ -750,15 +648,11 @@ BridgeService::usage(const string& appName) } #ifdef _WIN32 - int wmain(int argc, wchar_t* argv[]) - #else - int main(int argc, char* argv[]) - #endif { BridgeService svc; diff --git a/cpp/src/IceBridge/msbuild/icebridge.vcxproj b/cpp/src/IceBridge/msbuild/icebridge.vcxproj index 079d64b73dc..37c62c453fe 100644 --- a/cpp/src/IceBridge/msbuild/icebridge.vcxproj +++ b/cpp/src/IceBridge/msbuild/icebridge.vcxproj @@ -21,6 +21,7 @@ {1D6E8807-7C28-421F-B49E-BCB482FCB21D} + icebridge++11 @@ -44,7 +45,7 @@ $(DefaultPlatformToolset) - + @@ -68,24 +69,16 @@ - - $(Platform)\$(Configuration)\;%(AdditionalIncludeDirectories) - + - - $(Platform)\$(Configuration)\;%(AdditionalIncludeDirectories) - + - - $(Platform)\$(Configuration)\;%(AdditionalIncludeDirectories) - + - - $(Platform)\$(Configuration)\;%(AdditionalIncludeDirectories) - + @@ -105,4 +98,4 @@ - \ No newline at end of file + diff --git a/cpp/src/IceDB/IceDB.cpp b/cpp/src/IceDB/IceDB.cpp index e10ab81bcb8..55284d813b5 100644 --- a/cpp/src/IceDB/IceDB.cpp +++ b/cpp/src/IceDB/IceDB.cpp @@ -16,12 +16,6 @@ LMDBException::LMDBException(const char* file, int line, int err) : { } -#ifndef ICE_CPP11_COMPILER -LMDBException::~LMDBException() throw() -{ -} -#endif - string LMDBException::ice_id() const { @@ -35,13 +29,11 @@ LMDBException::ice_print(ostream& out) const out << ": " << mdb_strerror(_error); } -#ifndef ICE_CPP11_MAPPING -LMDBException* -LMDBException::ice_clone() const +IceUtil::Exception* +LMDBException::ice_cloneImpl() const { return new LMDBException(*this); } -#endif void LMDBException::ice_throw() const @@ -61,12 +53,6 @@ KeyTooLongException::KeyTooLongException(const char* file, int line, size_t size { } -#ifndef ICE_CPP11_COMPILER -KeyTooLongException::~KeyTooLongException() throw() -{ -} -#endif - string KeyTooLongException::ice_id() const { @@ -85,13 +71,11 @@ KeyTooLongException::ice_print(ostream& out) const out << "Max size = " << maxKeySize; } -#ifndef ICE_CPP11_MAPPING -KeyTooLongException* -KeyTooLongException::ice_clone() const +IceUtil::Exception* +KeyTooLongException::ice_cloneImpl() const { return new KeyTooLongException(*this); } -#endif void KeyTooLongException::ice_throw() const @@ -105,12 +89,6 @@ BadEnvException::BadEnvException(const char* file, int line, size_t size) : { } -#ifndef ICE_CPP11_COMPILER -BadEnvException::~BadEnvException() throw() -{ -} -#endif - string BadEnvException::ice_id() const { @@ -125,13 +103,11 @@ BadEnvException::ice_print(ostream& out) const out << ", IceDB max key size = " << maxKeySize; } -#ifndef ICE_CPP11_MAPPING -BadEnvException* -BadEnvException::ice_clone() const +IceUtil::Exception* +BadEnvException::ice_cloneImpl() const { return new BadEnvException(*this); } -#endif void BadEnvException::ice_throw() const @@ -322,10 +298,6 @@ DbiBase::DbiBase() : { } -DbiBase::~DbiBase() -{ -} - void DbiBase::clear(const ReadWriteTxn& txn) { diff --git a/cpp/src/IceDB/IceDB.h b/cpp/src/IceDB/IceDB.h index e7a183c7a23..e32be7e22a1 100644 --- a/cpp/src/IceDB/IceDB.h +++ b/cpp/src/IceDB/IceDB.h @@ -48,15 +48,10 @@ class ICE_DB_API LMDBException : public IceUtil::Exception public: LMDBException(const char*, int, int); -#ifndef ICE_CPP11_COMPILER - virtual ~LMDBException() throw(); -#endif virtual std::string ice_id() const; virtual void ice_print(std::ostream&) const; -#ifndef ICE_CPP11_MAPPING - virtual LMDBException* ice_clone() const; -#endif + virtual IceUtil::Exception* ice_cloneImpl() const; virtual void ice_throw() const; int error() const; @@ -76,15 +71,10 @@ class ICE_DB_API KeyTooLongException : public IceUtil::Exception public: KeyTooLongException(const char*, int, size_t); -#ifndef ICE_CPP11_COMPILER - virtual ~KeyTooLongException() throw(); -#endif virtual std::string ice_id() const; virtual void ice_print(std::ostream&) const; -#ifndef ICE_CPP11_MAPPING - virtual KeyTooLongException* ice_clone() const; -#endif + virtual IceUtil::Exception* ice_cloneImpl() const; virtual void ice_throw() const; private: @@ -102,15 +92,10 @@ class ICE_DB_API BadEnvException : public IceUtil::Exception public: BadEnvException(const char*, int, size_t); -#ifndef ICE_CPP11_COMPILER - virtual ~BadEnvException() throw(); -#endif virtual std::string ice_id() const; virtual void ice_print(std::ostream&) const; -#ifndef ICE_CPP11_MAPPING - virtual BadEnvException* ice_clone() const; -#endif + virtual IceUtil::Exception* ice_cloneImpl() const; virtual void ice_throw() const; private: @@ -221,7 +206,6 @@ class ICE_DB_API DbiBase DbiBase(const Txn&, const std::string&, unsigned int, MDB_cmp_func*); DbiBase(); - ~DbiBase(); // default copy ctor and assignment operator are OK @@ -250,10 +234,6 @@ class Dbi : public DbiBase { } - ~Dbi() - { - } - bool get(const Txn& txn, const K& key, D& data) const { unsigned char kbuf[maxKeySize]; diff --git a/cpp/src/IceDB/msbuild/icedb.vcxproj b/cpp/src/IceDB/msbuild/icedb.vcxproj index dfdfe76ffc3..f1665dc4526 100644 --- a/cpp/src/IceDB/msbuild/icedb.vcxproj +++ b/cpp/src/IceDB/msbuild/icedb.vcxproj @@ -21,6 +21,7 @@ {E8ACC848-F7DA-4B29-B52F-81D66E7D397E} IceDB + icedb++11 @@ -44,7 +45,7 @@ $(DefaultPlatformToolset) - + diff --git a/cpp/src/IceGrid/Activator.cpp b/cpp/src/IceGrid/Activator.cpp index fcffb15c1cd..1317def1d9a 100644 --- a/cpp/src/IceGrid/Activator.cpp +++ b/cpp/src/IceGrid/Activator.cpp @@ -46,33 +46,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) { // // Send any errors to the parent process, using the write @@ -303,19 +282,19 @@ extern "C" void CALLBACK activatorWaitCallback(PVOID data, BOOLEAN) } #endif -Activator::Activator(const TraceLevelsPtr& traceLevels) : +Activator::Activator(const shared_ptr& 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()); @@ -337,10 +316,8 @@ Activator::Activator(const TraceLevelsPtr& traceLevels) : Activator::~Activator() { - assert(!_thread); - #ifdef _WIN32 - if(_hIntr != ICE_NULLPTR) + if(_hIntr != nullptr) { CloseHandle(_hIntr); } @@ -360,9 +337,9 @@ Activator::activate(const string& name, #endif const Ice::StringSeq& options, const Ice::StringSeq& envs, - const ServerIPtr& server) + const shared_ptr& server) { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); if(_deactivating) { @@ -585,10 +562,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 @@ -811,7 +788,7 @@ Activator::activate(const string& name, int maxFd = static_cast(sysconf(_SC_OPEN_MAX)); if(maxFd <= 0) { - maxFd = INT_MAX; + maxFd = numeric_limits::max(); } for(int fd = 3; fd < maxFd; ++fd) @@ -932,42 +909,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& process) { #ifdef _WIN32 Ice::Int pid = getServerPid(name); @@ -990,8 +933,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; } @@ -1087,18 +1046,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::const_iterator p = _processes.find(name); + auto p = _processes.find(name); if(p == _processes.end()) { return 0; } - return static_cast(p->second.pid); + return static_cast(p->second.pid); } void @@ -1107,24 +1066,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; @@ -1138,7 +1093,7 @@ Activator::shutdown() // _deactivating = true; setInterrupt(); - notifyAll(); + _condVar.notify_all(); } void @@ -1146,7 +1101,7 @@ Activator::destroy() { map processes; { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); assert(_deactivating); processes = _processes; } @@ -1154,7 +1109,7 @@ Activator::destroy() // // Stop all active processes. // - for(map::iterator p = processes.begin(); p != processes.end(); ++p) + for(const auto& [name, proc] : processes) { // // Stop the server. The listener thread should detect the @@ -1163,7 +1118,7 @@ Activator::destroy() // try { - p->second.server->stop_async(0, Ice::emptyCurrent); + proc.server->stopAsync(nullptr, nullptr, Ice::emptyCurrent); } catch(const ServerStopException&) { @@ -1178,7 +1133,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; } } @@ -1187,18 +1142,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; } @@ -1247,7 +1198,7 @@ Activator::terminationListener() vector terminated; bool deactivated = false; { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); for(vector::const_iterator q = _terminated.begin(); q != _terminated.end(); ++q) { for(map::iterator p = _processes.begin(); p != _processes.end(); ++p) @@ -1309,7 +1260,7 @@ Activator::terminationListener() FD_SET(_fdIntrRead, &fdSet); { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); for(map::iterator p = _processes.begin(); p != _processes.end(); ++p) { @@ -1346,7 +1297,7 @@ Activator::terminationListener() vector terminated; bool deactivated = false; { - IceUtil::Monitor< IceUtil::Mutex>::Lock sync(*this); + lock_guard lock(_mutex); if(FD_ISSET(_fdIntrRead, &fdSet)) { @@ -1463,8 +1414,7 @@ Activator::clearInterrupt() ResetEvent(_hIntr); #else char c; - while(read(_fdIntrRead, &c, 1) == 1) - ; + while(read(_fdIntrRead, &c, 1) == 1); #endif } @@ -1536,7 +1486,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 #include #ifndef _WIN32 @@ -16,14 +15,11 @@ namespace IceGrid { class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; - class ServerI; -typedef IceUtil::Handle ServerIPtr; std::string signalToString(int); -class Activator : public IceUtil::Monitor< IceUtil::Mutex>, public IceUtil::Shared +class Activator final : public std::enable_shared_from_this { public: @@ -39,27 +35,27 @@ class Activator : public IceUtil::Monitor< IceUtil::Mutex>, public IceUtil::Shar int pipeFd; std::string msg; #endif - ServerIPtr server; + std::shared_ptr server; }; - Activator(const TraceLevelsPtr&); - virtual ~Activator(); + Activator(const std::shared_ptr&); + ~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&); + void deactivate(const std::string&, const std::shared_ptr&); + 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 @@ class Activator : public IceUtil::Monitor< IceUtil::Mutex>, public IceUtil::Shar int waitPid(pid_t); #endif - TraceLevelsPtr _traceLevels; + std::shared_ptr _traceLevels; std::map _processes; bool _deactivating; @@ -92,9 +88,10 @@ class Activator : public IceUtil::Monitor< IceUtil::Mutex>, public IceUtil::Shar int _fdIntrWrite; #endif - IceUtil::ThreadPtr _thread; + std::mutex _mutex; + std::condition_variable _condVar; + std::thread _thread; }; -typedef IceUtil::Handle ActivatorPtr; } diff --git a/cpp/src/IceGrid/AdapterCache.cpp b/cpp/src/IceGrid/AdapterCache.cpp index 87046d4d8b0..45dc7a6aef2 100644 --- a/cpp/src/IceGrid/AdapterCache.cpp +++ b/cpp/src/IceGrid/AdapterCache.cpp @@ -22,51 +22,11 @@ using namespace IceGrid; namespace IceGrid { -struct ReplicaLoadComp -{ - bool operator()(const pair& lhs, const pair& rhs) - { - return lhs.first < rhs.first; - } -}; - -struct ReplicaPriorityComp -{ - bool operator()(const ServerAdapterEntryPtr& lhs, const ServerAdapterEntryPtr& rhs) - { - return lhs->getPriority() < rhs->getPriority(); - } -}; - -struct TransformToReplicaLoad +class ReplicaGroupSyncCallback final : public SynchronizationCallback { public: - TransformToReplicaLoad(LoadSample loadSample) : _loadSample(loadSample) { } - - pair - operator()(const ServerAdapterEntryPtr& value) - { - return make_pair(value->getLeastLoadedNodeLoad(_loadSample), value); - } - - LoadSample _loadSample; -}; - -struct TransformToReplica -{ - ServerAdapterEntryPtr - operator()(const pair& value) - { - return value.second; - } -}; - -class ReplicaGroupSyncCallback : public SynchronizationCallback, public IceUtil::Mutex -{ -public: - - ReplicaGroupSyncCallback(const SynchronizationCallbackPtr& callback, int count, int nReplicas) : + ReplicaGroupSyncCallback(const shared_ptr& callback, int count, int nReplicas) : _callback(callback), _responseCalled(false), _synchronizeCount(count), @@ -78,20 +38,20 @@ class ReplicaGroupSyncCallback : public SynchronizationCallback, public IceUtil: 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; @@ -100,9 +60,9 @@ class ReplicaGroupSyncCallback : public SynchronizationCallback, public IceUtil: void synchronized() { - SynchronizationCallbackPtr callback; + shared_ptr callback; { - Lock sync(*this); + lock_guard lock(_mutex); ++_synchronizedCount; --_synchronizeCount; @@ -117,7 +77,7 @@ class ReplicaGroupSyncCallback : public SynchronizationCallback, public IceUtil: } callback = _callback; - _callback = 0; + _callback = nullptr; } if(callback) @@ -127,14 +87,14 @@ class ReplicaGroupSyncCallback : public SynchronizationCallback, public IceUtil: } void - synchronized(const Ice::Exception& ex) + synchronized(exception_ptr ex) { - SynchronizationCallbackPtr callback; + shared_ptr callback; { - Lock sync(*this); - if(!_exception.get()) + lock_guard lock(_mutex); + if(!_exception) { - _exception.reset(ex.ice_clone()); + _exception = ex; } --_synchronizeCount; @@ -160,19 +120,20 @@ class ReplicaGroupSyncCallback : public SynchronizationCallback, public IceUtil: private: - SynchronizationCallbackPtr _callback; + shared_ptr _callback; bool _responseCalled; int _synchronizeCount; int _synchronizedCount; int _nReplicas; - IceInternal::UniquePtr _exception; + exception_ptr _exception; + + mutex _mutex; }; -typedef IceUtil::Handle ReplicaGroupSyncCallbackPtr; } void -GetAdapterInfoResult::add(const ServerAdapterEntryPtr& adapter) +GetAdapterInfoResult::add(const ServerAdapterEntry* adapter) { AdapterInfo info; info.id = adapter->getId(); @@ -180,15 +141,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); } } @@ -196,13 +157,13 @@ AdapterInfoSeq GetAdapterInfoResult::get() { vector::iterator q = _adapters.begin(); - for(vector::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((*p)->get()); } } catch(const Ice::Exception&) @@ -212,14 +173,14 @@ GetAdapterInfoResult::get() return _adapters; } -AdapterCache::AdapterCache(const Ice::CommunicatorPtr& communicator) : _communicator(communicator) +AdapterCache::AdapterCache(const shared_ptr& communicator) : _communicator(communicator) { } void -AdapterCache::addServerAdapter(const AdapterDescriptor& desc, const ServerEntryPtr& server, const string& app) +AdapterCache::addServerAdapter(const AdapterDescriptor& desc, const shared_ptr& server, const string& app) { - Lock sync(*this); + lock_guard lock(_mutex); if(getImpl(desc.id)) { Ice::Error out(_communicator->getLogger()); @@ -227,23 +188,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(*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(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(*this, desc.replicaGroupId, "", + make_shared("0"), ""); addImpl(desc.replicaGroupId, repEntry); } repEntry->addReplica(desc.id, entry); @@ -253,8 +220,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(getImpl(desc.id)); if(repEntry) { // @@ -272,14 +239,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(*this, desc.id, app, desc.loadBalancing, desc.filter)); } -AdapterEntryPtr +shared_ptr 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); @@ -290,9 +258,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(getImpl(id)); if(!entry) { Ice::Error out(_communicator->getLogger()); @@ -304,7 +272,7 @@ AdapterCache::removeServerAdapter(const string& id) string replicaGroupId = entry->getReplicaGroupId(); if(!replicaGroupId.empty()) { - ReplicaGroupEntryPtr repEntry = ReplicaGroupEntryPtr::dynamicCast(getImpl(replicaGroupId)); + auto repEntry = dynamic_pointer_cast(getImpl(replicaGroupId)); if(!repEntry) { Ice::Error out(_communicator->getLogger()); @@ -326,8 +294,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(getImpl(id)); if(!entry) { Ice::Error out(_communicator->getLogger()); @@ -337,8 +306,8 @@ AdapterCache::removeReplicaGroup(const string& id) removeImpl(id); } -AdapterEntryPtr -AdapterCache::addImpl(const string& id, const AdapterEntryPtr& entry) +shared_ptr +AdapterCache::addImpl(const string& id, const shared_ptr& entry) { if(_traceLevels && _traceLevels->adapter > 0) { @@ -389,7 +358,7 @@ ServerAdapterEntry::ServerAdapterEntry(AdapterCache& cache, const string& application, const string& replicaGroupId, int priority, - const ServerEntryPtr& server) : + const shared_ptr& server) : AdapterEntry(cache, id, application), _replicaGroupId(replicaGroupId), _priority(priority), @@ -398,7 +367,7 @@ ServerAdapterEntry::ServerAdapterEntry(AdapterCache& cache, } bool -ServerAdapterEntry::addSyncCallback(const SynchronizationCallbackPtr& callback, const set&) +ServerAdapterEntry::addSyncCallback(const shared_ptr& callback, const set&) { try { @@ -449,23 +418,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 ServerAdapterEntry::getAdapterInfoAsync() const { - GetAdapterInfoResultPtr result = new GetAdapterInfoResult(); - result->add(const_cast(this)); + auto result = make_shared(); + result->add(this); return result; } -AdapterPrx +shared_ptr ServerAdapterEntry::getProxy(const string& replicaGroupId, bool upToDate) const { if(replicaGroupId.empty()) @@ -485,9 +449,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, std::move(proxy), activationTimeout, deactivationTimeout }; adapters.push_back(info); } @@ -519,7 +484,7 @@ ServerAdapterEntry::getNodeName() const ReplicaGroupEntry::ReplicaGroupEntry(AdapterCache& cache, const string& id, const string& application, - const LoadBalancingPolicyPtr& policy, + const shared_ptr& policy, const string& filter) : AdapterEntry(cache, id, application), _lastReplica(0), @@ -529,26 +494,27 @@ ReplicaGroupEntry::ReplicaGroupEntry(AdapterCache& cache, } bool -ReplicaGroupEntry::addSyncCallback(const SynchronizationCallbackPtr& callback, const set& excludes) +ReplicaGroupEntry::addSyncCallback(const shared_ptr& callback, const set& excludes) { - vector replicas; + vector> replicas; int nReplicas; - int roundRobin = false; + bool roundRobin = false; { - Lock sync(*this); + lock_guard lock(_mutex); + nReplicas = _loadBalancingNReplicas > 0 ? _loadBalancingNReplicas : static_cast(_replicas.size()); - roundRobin = RoundRobinLoadBalancingPolicyPtr::dynamicCast(_loadBalancing); + roundRobin = dynamic_pointer_cast(_loadBalancing) != nullptr; if(!roundRobin) { replicas = _replicas; } else { - for(vector::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); } } } @@ -559,39 +525,37 @@ ReplicaGroupEntry::addSyncCallback(const SynchronizationCallbackPtr& callback, c } } - ReplicaGroupSyncCallbackPtr cb = new ReplicaGroupSyncCallback(callback, - static_cast(replicas.size()), - nReplicas); + auto cb = make_shared(callback, static_cast(replicas.size()), nReplicas); set emptyExcludes; - for(vector::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& adapter) { - Lock sync(*this); + lock_guard lock(_mutex); _replicas.push_back(adapter); } bool ReplicaGroupEntry::removeReplica(const string& replicaId) { - Lock sync(*this); - for(vector::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()) { @@ -607,37 +571,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& 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(_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; } } } @@ -646,11 +617,11 @@ void ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& nReplicas, bool& replicaGroup, bool& roundRobin, string& filter, const set& excludes) { - vector replicas; + vector> replicas; bool adaptive = false; - LoadSample loadSample = LoadSample1; + LoadSample loadSample = LoadSample::LoadSample1; { - Lock sync(*this); + unique_lock lock(_mutex); replicaGroup = true; roundRobin = false; filter = _filter; @@ -662,13 +633,10 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n } replicas.reserve(_replicas.size()); - if(RoundRobinLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) + if(dynamic_pointer_cast(_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) { @@ -677,19 +645,23 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n _lastReplica = (_lastReplica + 1) % static_cast(_replicas.size()); roundRobin = true; } - else if(AdaptiveLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) + else if(dynamic_pointer_cast(_loadBalancing)) { replicas = _replicas; IceUtilInternal::shuffle(replicas.begin(), replicas.end()); loadSample = _loadSample; adaptive = true; } - else if(OrderedLoadBalancingPolicyPtr::dynamicCast(_loadBalancing)) + else if(dynamic_pointer_cast(_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(_loadBalancing)) { replicas = _replicas; IceUtilInternal::shuffle(replicas.begin(), replicas.end()); @@ -704,16 +676,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 > rl; - transform(replicas.begin(), replicas.end(), back_inserter(rl), TransformToReplicaLoad(loadSample)); - sort(rl.begin(), rl.end(), ReplicaLoadComp()); + vector>> rl; + transform(replicas.begin(), replicas.end(), back_inserter(rl), + [loadSample](const auto& value) -> pair> + { + 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; }); } // @@ -723,13 +699,13 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n // set emptyExcludes; bool firstUnreachable = true; - for(vector::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&) @@ -746,24 +722,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(_replicas.size()); @@ -779,9 +755,9 @@ ReplicaGroupEntry::getLocatorAdapterInfo(LocatorAdapterInfoSeq& adapters, int& n float ReplicaGroupEntry::getLeastLoadedNodeLoad(LoadSample loadSample) const { - vector replicas; + vector> replicas; { - Lock sync(*this); + lock_guard lock(_mutex); replicas = _replicas; } @@ -796,9 +772,17 @@ ReplicaGroupEntry::getLeastLoadedNodeLoad(LoadSample loadSample) const else { IceUtilInternal::shuffle(replicas.begin(), replicas.end()); - vector > rl; - transform(replicas.begin(), replicas.end(), back_inserter(rl), TransformToReplicaLoad(loadSample)); - return min_element(rl.begin(), rl.end(), ReplicaLoadComp())->first; + vector>> rl; + transform(replicas.begin(), replicas.end(), back_inserter(rl), + [loadSample] (const auto& value) -> pair> + { + return { value->getLeastLoadedNodeLoad(loadSample), value }; + }); + return min_element(rl.begin(), rl.end(), + [](const auto& lhs, const auto& rhs) + { + return lhs.first < rhs.first; + })->first; } } @@ -809,34 +793,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 replicas; + vector> replicas; { - Lock sync(*this); + lock_guard lock(_mutex); replicas = _replicas; } AdapterInfoSeq infos; - for(vector::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 ReplicaGroupEntry::getAdapterInfoAsync() const { - GetAdapterInfoResultPtr result = new GetAdapterInfoResult(); - vector replicas; + auto result = make_shared(); + vector> replicas; { - Lock sync(*this); + lock_guard lock(_mutex); replicas = _replicas; } - for(vector::const_iterator p = replicas.begin(); p != replicas.end(); ++p) + for(const auto& replica : replicas) { - result->add(*p); + result->add(replica.get()); } return result; } @@ -844,16 +828,16 @@ ReplicaGroupEntry::getAdapterInfoAsync() const bool ReplicaGroupEntry::hasAdaptersFromOtherApplications() const { - vector replicas; + vector> replicas; { - Lock sync(*this); + lock_guard lock(_mutex); replicas = _replicas; } AdapterInfoSeq infos; - for(vector::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..06936659161 100644 --- a/cpp/src/IceGrid/AdapterCache.h +++ b/cpp/src/IceGrid/AdapterCache.h @@ -5,174 +5,165 @@ #ifndef ICE_GRID_ADAPTERCACHE_H #define ICE_GRID_ADAPTERCACHE_H -#include -#include #include #include #include +#include #include namespace IceGrid { -class AdapterCache; + class AdapterCache; + class AdapterEntry; + class ServerAdapterEntry; + class ServerEntry; + class SynchronizationCallback; -class SynchronizationCallback; -typedef IceUtil::Handle SynchronizationCallbackPtr; + using ServerEntrySeq = std::vector>; -class ServerEntry; -typedef IceUtil::Handle ServerEntryPtr; -typedef std::vector ServerEntrySeq; + struct LocatorAdapterInfo + { + std::string id; + std::shared_ptr proxy; + std::chrono::seconds activationTimeout; + std::chrono::seconds deactivationTimeout; + }; + using LocatorAdapterInfoSeq = std::vector; -class AdapterEntry; -typedef IceUtil::Handle AdapterEntryPtr; + class GetAdapterInfoResult + { + public: -class ServerAdapterEntry; -typedef IceUtil::Handle ServerAdapterEntryPtr; + void add(const ServerAdapterEntry*); + AdapterInfoSeq get(); -struct LocatorAdapterInfo -{ - std::string id; - AdapterPrx proxy; - int activationTimeout; - int deactivationTimeout; -}; -typedef std::vector LocatorAdapterInfoSeq; - -class GetAdapterInfoResult : public IceUtil::Shared -{ -public: + private: - void add(const ServerAdapterEntryPtr&); - AdapterInfoSeq get(); + AdapterInfoSeq _adapters; + std::vector>>> _results; + }; -private: + class AdapterEntry + { + public: - AdapterInfoSeq _adapters; - std::vector _results; -}; -typedef IceUtil::Handle GetAdapterInfoResultPtr; - -class AdapterEntry : public virtual IceUtil::Shared -{ -public: + AdapterEntry(AdapterCache&, const std::string&, const std::string&); - AdapterEntry(AdapterCache&, const std::string&, const std::string&); + virtual bool addSyncCallback(const std::shared_ptr&, const std::set&) = 0; - virtual bool addSyncCallback(const SynchronizationCallbackPtr&, const std::set&) = 0; + virtual void getLocatorAdapterInfo(LocatorAdapterInfoSeq&, int&, bool&, bool&, std::string&, + const std::set&) = 0; + virtual float getLeastLoadedNodeLoad(LoadSample) const = 0; + virtual AdapterInfoSeq getAdapterInfoNoEndpoints() const = 0; + virtual std::shared_ptr getAdapterInfoAsync() const = 0; + virtual std::shared_ptr getProxy(const std::string&, bool) const = 0; - virtual void getLocatorAdapterInfo(LocatorAdapterInfoSeq&, int&, bool&, bool&, std::string&, - const std::set&) = 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 bool canRemove(); - virtual bool canRemove(); + std::string getId() const; + std::string getApplication() const; - std::string getId() const; - std::string getApplication() const; + protected: -protected: + AdapterCache& _cache; + const std::string _id; + std::string _application; + }; - AdapterCache& _cache; - const std::string _id; - std::string _application; -}; -typedef IceUtil::Handle AdapterEntryPtr; + class ServerAdapterEntry final : public AdapterEntry + { + public: -class ServerAdapterEntry : public AdapterEntry -{ -public: + ServerAdapterEntry(AdapterCache&, const std::string&, const std::string&, const std::string&, int, + const std::shared_ptr&); - ServerAdapterEntry(AdapterCache&, const std::string&, const std::string&, const std::string&, int, - const ServerEntryPtr&); + bool addSyncCallback(const std::shared_ptr&, const std::set&) override; - virtual bool addSyncCallback(const SynchronizationCallbackPtr&, const std::set&); + void getLocatorAdapterInfo(LocatorAdapterInfoSeq&, int&, bool&, bool&, std::string&, + const std::set&) override; - virtual void getLocatorAdapterInfo(LocatorAdapterInfoSeq&, int&, bool&, bool&, std::string&, - const std::set&); + float getLeastLoadedNodeLoad(LoadSample) const override; + AdapterInfoSeq getAdapterInfoNoEndpoints() const override; + std::shared_ptr getAdapterInfoAsync() const override; + std::shared_ptr getProxy(const std::string&, bool) const override; - virtual float getLeastLoadedNodeLoad(LoadSample) const; - virtual AdapterInfoSeq getAdapterInfoNoEndpoints() const; - virtual GetAdapterInfoResultPtr getAdapterInfoAsync() const; - virtual AdapterPrx getProxy(const std::string&, bool) const; + void getLocatorAdapterInfo(LocatorAdapterInfoSeq&) const; + const std::string& getReplicaGroupId() const { return _replicaGroupId; } + int getPriority() const; - void getLocatorAdapterInfo(LocatorAdapterInfoSeq&) const; - const std::string& getReplicaGroupId() const { return _replicaGroupId; } - int getPriority() const; + std::string getServerId() const; + std::string getNodeName() const; - std::string getServerId() const; - std::string getNodeName() const; + private: -private: + const std::string _replicaGroupId; + const int _priority; + const std::shared_ptr _server; + }; - const std::string _replicaGroupId; - const int _priority; - const ServerEntryPtr _server; -}; -typedef IceUtil::Handle ServerAdapterEntryPtr; + class ReplicaGroupEntry final : public AdapterEntry + { + public: -class ReplicaGroupEntry : public AdapterEntry, public IceUtil::Monitor -{ -public: + ReplicaGroupEntry(AdapterCache&, const std::string&, const std::string&, const std::shared_ptr&, + const std::string&); - ReplicaGroupEntry(AdapterCache&, const std::string&, const std::string&, const LoadBalancingPolicyPtr&, - const std::string&); + virtual bool addSyncCallback(const std::shared_ptr&, const std::set&); - virtual bool addSyncCallback(const SynchronizationCallbackPtr&, const std::set&); + virtual void getLocatorAdapterInfo(LocatorAdapterInfoSeq&, int&, bool&, bool&, std::string&, + const std::set&); + virtual float getLeastLoadedNodeLoad(LoadSample) const; + virtual AdapterInfoSeq getAdapterInfoNoEndpoints() const; + virtual std::shared_ptr getAdapterInfoAsync() const; + virtual std::shared_ptr getProxy(const std::string&, bool) const { return nullptr; } - virtual void getLocatorAdapterInfo(LocatorAdapterInfoSeq&, int&, bool&, bool&, std::string&, - const std::set&); - virtual float getLeastLoadedNodeLoad(LoadSample) const; - virtual AdapterInfoSeq getAdapterInfoNoEndpoints() const; - virtual GetAdapterInfoResultPtr getAdapterInfoAsync() const; - virtual AdapterPrx getProxy(const std::string&, bool) const { return 0; } + void addReplica(const std::string&, const std::shared_ptr&); + bool removeReplica(const std::string&); - void addReplica(const std::string&, const ServerAdapterEntryPtr&); - bool removeReplica(const std::string&); + void update(const std::string&, const std::shared_ptr&, const std::string&); + bool hasAdaptersFromOtherApplications() const; - void update(const std::string&, const LoadBalancingPolicyPtr&, const std::string&); - bool hasAdaptersFromOtherApplications() const; + const std::string& getFilter() const { return _filter; } - const std::string& getFilter() const { return _filter; } + private: -private: + std::shared_ptr _loadBalancing; + int _loadBalancingNReplicas; + LoadSample _loadSample; + std::string _filter; + std::vector> _replicas; + int _lastReplica; + bool _requestInProgress; - LoadBalancingPolicyPtr _loadBalancing; - int _loadBalancingNReplicas; - LoadSample _loadSample; - std::string _filter; - std::vector _replicas; - int _lastReplica; - bool _requestInProgress; -}; -typedef IceUtil::Handle ReplicaGroupEntryPtr; + mutable std::mutex _mutex; + std::condition_variable _condVar; + }; -class AdapterCache : public CacheByString -{ -public: + class AdapterCache : public CacheByString + { + public: - AdapterCache(const Ice::CommunicatorPtr&); + AdapterCache(const std::shared_ptr&); - void addServerAdapter(const AdapterDescriptor&, const ServerEntryPtr&, const std::string&); - void addReplicaGroup(const ReplicaGroupDescriptor&, const std::string&); + void addServerAdapter(const AdapterDescriptor&, const std::shared_ptr&, const std::string&); + void addReplicaGroup(const ReplicaGroupDescriptor&, const std::string&); - AdapterEntryPtr get(const std::string&) const; + std::shared_ptr get(const std::string&) const; - void removeServerAdapter(const std::string&); - void removeReplicaGroup(const std::string&); + void removeServerAdapter(const std::string&); + void removeReplicaGroup(const std::string&); -protected: + protected: - virtual AdapterEntryPtr addImpl(const std::string&, const AdapterEntryPtr&); - virtual void removeImpl(const std::string&); + virtual std::shared_ptr addImpl(const std::string&, const std::shared_ptr&); + virtual void removeImpl(const std::string&); -private: + private: - const Ice::CommunicatorPtr _communicator; -}; + const std::shared_ptr _communicator; + }; }; diff --git a/cpp/src/IceGrid/AdminCallbackRouter.cpp b/cpp/src/IceGrid/AdminCallbackRouter.cpp index 3d58311845c..f5e439c7185 100644 --- a/cpp/src/IceGrid/AdminCallbackRouter.cpp +++ b/cpp/src/IceGrid/AdminCallbackRouter.cpp @@ -4,42 +4,26 @@ #include -using namespace Ice; using namespace std; +using namespace IceGrid; void -IceGrid::AdminCallbackRouter::invokeResponse(bool ok, - const std::pair& outParams, - const AMD_Object_ice_invokePtr& amdCB) +AdminCallbackRouter::addMapping(const string& category, const shared_ptr& 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::value_type(category, con)); + _categoryToConnection.insert({ category, con }); #else - bool inserted = - _categoryToConnection.insert(map::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& inParams, - const Current& current) +AdminCallbackRouter::ice_invokeAsync(pair inParams, + function&)> response, + function exception, + const Ice::Current& current) { - ConnectionPtr con; + shared_ptr con; { - IceUtil::Mutex::Lock sync(_mutex); - map::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, + std::move(response), + [exception = std::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&); void removeMapping(const std::string&); - virtual void invokeResponse(bool, - const std::pair&, - 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::Current&); + void ice_invokeAsync(std::pair, + std::function&)>, + std::function, + const Ice::Current& current) override; private: - IceUtil::Mutex _mutex; - std::map _categoryToConnection; + std::mutex _mutex; + std::map> _categoryToConnection; }; -typedef IceUtil::Handle AdminCallbackRouterPtr; } + #endif diff --git a/cpp/src/IceGrid/AdminI.cpp b/cpp/src/IceGrid/AdminI.cpp index b2c1b2a5112..34dc93125a9 100644 --- a/cpp/src/IceGrid/AdminI.cpp +++ b/cpp/src/IceGrid/AdminI.cpp @@ -20,134 +20,166 @@ #include "SynchronizationException.h" using namespace std; +using namespace std::chrono; using namespace Ice; using namespace IceGrid; -namespace IceGrid -{ - -class ServerProxyWrapper +namespace { -public: - ServerProxyWrapper(const DatabasePtr& database, const string& id) : _id(id) + class ServerProxyWrapper { - try - { - _proxy = database->getServer(_id)->getProxy(_activationTimeout, _deactivationTimeout, _node, false, 5); - } - catch(const SynchronizationException&) + public: + + ServerProxyWrapper(const shared_ptr& database, const string& id) : _id(id) { - throw DeploymentException("server is being updated"); + try + { + _proxy = database->getServer(_id)->getProxy(_activationTimeout, _deactivationTimeout, _node, false, 5s); + } + catch (const SynchronizationException&) + { + throw DeploymentException("server is being updated"); + } } - } - - ServerProxyWrapper(const ServerProxyWrapper& wrapper) : - _id(wrapper._id), - _proxy(wrapper._proxy), - _activationTimeout(wrapper._activationTimeout), - _deactivationTimeout(wrapper._deactivationTimeout), - _node(wrapper._node) - { - } - void - useActivationTimeout() - { - _proxy = ServerPrx::uncheckedCast(_proxy->ice_invocationTimeout(_activationTimeout * 1000)); - } - - void - useDeactivationTimeout() - { - _proxy = ServerPrx::uncheckedCast(_proxy->ice_invocationTimeout(_deactivationTimeout * 1000)); - } + ServerProxyWrapper(const ServerProxyWrapper& wrapper) = default; - IceProxy::IceGrid::Server* - operator->() const - { - return _proxy.get(); - } + template + auto invoke(Func&& f, Args&&... args) + { + try + { + return std::invoke(std::forward(f), _proxy, std::forward(args)..., ::Ice::noExplicitContext); + } + catch (const Ice::Exception&) + { + handleException(current_exception()); + throw; // keep compiler happy + } + } - void - handleException(const Ice::Exception& ex) const - { - try + template + auto invokeAsync(Func&& f, function response, function exception) { - ex.ice_throw(); + auto exceptionWrapper = [this, exception = std::move(exception)](exception_ptr ex) + { + try + { + handleException(ex); + } + catch (const std::exception&) + { + exception(current_exception()); + } + }; + return std::invoke(std::forward(f), _proxy, std::move(response), std::move(exceptionWrapper), nullptr, Ice::noExplicitContext); } - catch(const Ice::UserException&) + + void useActivationTimeout() { - throw; + auto timeout = secondsToInt(_activationTimeout) * 1000; + _proxy = _proxy->ice_invocationTimeout(timeout); } - catch(const Ice::ObjectNotExistException&) + + void useDeactivationTimeout() { - throw ServerNotExistException(_id); + auto timeout = secondsToInt(_deactivationTimeout) * 1000; + _proxy = _proxy->ice_invocationTimeout(timeout); } - catch(const Ice::LocalException& e) + + ServerPrx* operator->() const { - ostringstream os; - os << e; - throw NodeUnreachableException(_node, os.str()); + return _proxy.get(); } - } -private: + void handleException(exception_ptr ex) const + { + try + { + rethrow_exception(ex); + } + catch (const Ice::UserException&) + { + throw; + } + catch (const Ice::ObjectNotExistException&) + { + throw ServerNotExistException(_id); + } + catch (const Ice::LocalException& e) + { + throw NodeUnreachableException(_node, e.what()); + } + } - string _id; - ServerPrx _proxy; - int _activationTimeout; - int _deactivationTimeout; - string _node; -}; + private: + + string _id; + shared_ptr _proxy; + chrono::seconds _activationTimeout; + chrono::seconds _deactivationTimeout; + string _node; + }; + + class AMDPatcherFeedbackAggregator : public PatcherFeedbackAggregator + { + public: + + AMDPatcherFeedbackAggregator( + function response, + function exception, + Ice::Identity id, + const shared_ptr& traceLevels, + const string& type, + const string& name, + int nodeCount) : + PatcherFeedbackAggregator(id, traceLevels, type, name, nodeCount), + _response(std::move(response)), + _exception(std::move(exception)) + { + } -template -class AMDPatcherFeedbackAggregator : public PatcherFeedbackAggregator -{ -public: + private: - AMDPatcherFeedbackAggregator(const AmdCB& cb, - Ice::Identity id, - const TraceLevelsPtr& traceLevels, - const string& type, - const string& name, - int nodeCount) : - PatcherFeedbackAggregator(id, traceLevels, type, name, nodeCount), - _cb(cb) - { - } + void response() + { + _response(); + } -private: + void exception(exception_ptr ex) + { + _exception(ex); + } - void - response() - { - _cb->ice_response(); - } + function _response; + function _exception; + }; - void - exception(const Ice::Exception& ex) + shared_ptr + static newPatcherFeedback( + function response, + function exception, + Ice::Identity id, + const shared_ptr& traceLevels, + const string& type, + const string& name, + int nodeCount) { - _cb->ice_exception(ex); + return make_shared( + response, + exception, + id, + traceLevels, + type, + name, + nodeCount); } - const AmdCB _cb; -}; - -template PatcherFeedbackAggregatorPtr -static newPatcherFeedback(const AmdCB& cb, - Ice::Identity id, - const TraceLevelsPtr& traceLevels, - const string& type, - const string& name, - int nodeCount) -{ - return new AMDPatcherFeedbackAggregator(cb, id, traceLevels, type, name, nodeCount); } -} - -AdminI::AdminI(const DatabasePtr& database, const RegistryIPtr& registry, const AdminSessionIPtr& session) : +AdminI::AdminI(const shared_ptr& database, const shared_ptr& registry, + const shared_ptr& session) : _database(database), _registry(registry), _traceLevels(_database->getTraceLevels()), @@ -155,17 +187,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(system_clock::now().time_since_epoch()).count(); info.createUser = info.updateUser = _session->getId(); info.descriptor = descriptor; info.revision = 1; @@ -175,19 +203,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(system_clock::now().time_since_epoch()).count(); update.updateUser = _session->getId(); update.descriptor = descriptor; update.revision = -1; // The database will set it. @@ -195,19 +223,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(system_clock::now().time_since_epoch()).count(); update.updateUser = _session->getId(); update.descriptor = descriptor; update.revision = -1; // The database will set it. @@ -215,24 +243,26 @@ 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(std::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(std::move(app), std::move(node), std::move(desc), _session.get()); } void -AdminI::patchApplication_async(const AMD_Admin_patchApplicationPtr& amdCB, - const string& name, - bool shutdown, - const Current& current) +AdminI::patchApplicationAsync( + string name, + bool shutdown, + function response, + function exception, + const Current& current) { ApplicationHelper helper(current.adapter->getCommunicator(), _database->getApplicationInfo(name).descriptor); DistributionDescriptor appDistrib; @@ -241,7 +271,7 @@ AdminI::patchApplication_async(const AMD_Admin_patchApplicationPtr& amdCB, if(nodes.empty()) { - amdCB->ice_response(); + response(); return; } @@ -249,8 +279,15 @@ AdminI::patchApplication_async(const AMD_Admin_patchApplicationPtr& amdCB, id.category = current.id.category; id.name = Ice::generateUUID(); - PatcherFeedbackAggregatorPtr feedback = - newPatcherFeedback(amdCB, id, _traceLevels, "application", name, static_cast(nodes.size())); + shared_ptr feedback = + newPatcherFeedback( + response, + exception, + id, + _traceLevels, + "application", + name, + static_cast(nodes.size())); for(vector::const_iterator p = nodes.begin(); p != nodes.end(); ++p) { @@ -262,11 +299,10 @@ AdminI::patchApplication_async(const AMD_Admin_patchApplicationPtr& amdCB, out << "started patching of application `" << name << "' on node `" << *p << "'"; } - NodeEntryPtr node = _database->getNode(*p); + shared_ptr node = _database->getNode(*p); Resolver resolve(node->getInfo(), _database->getCommunicator()); DistributionDescriptor desc = resolve(appDistrib); - InternalDistributionDescriptorPtr intAppDistrib = new InternalDistributionDescriptor(desc.icepatch, - desc.directories); + auto intAppDistrib = make_shared(desc.icepatch, desc.directories); node->getSession()->patch(feedback, name, "", intAppDistrib, shutdown); } catch(const NodeNotExistException&) @@ -287,20 +323,20 @@ AdminI::patchApplication_async(const AMD_Admin_patchApplicationPtr& amdCB, } ApplicationInfo -AdminI::getApplicationInfo(const string& name, const Current&) const +AdminI::getApplicationInfo(string name, const Current&) const { - return _database->getApplicationInfo(name); + return _database->getApplicationInfo(std::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()) + if (path.empty()) { throw DeploymentException("no default templates configured, you need to set " - "IceGrid.Registry.DefaultTemplates in the IceGrid registry configuration."); + "IceGrid.Registry.DefaultTemplates in the IceGrid registry configuration."); } ApplicationDescriptor desc; @@ -308,12 +344,12 @@ AdminI::getDefaultApplicationDescriptor(const Current& current) const { desc = DescriptorParser::parseDescriptor(path, current.adapter->getCommunicator()); } - catch(const IceXML::ParserException& ex) + catch (const IceXML::ParserException& ex) { throw DeploymentException("can't parse default templates:\n" + ex.reason()); } desc.name = ""; - if(!desc.nodes.empty()) + if (!desc.nodes.empty()) { Ice::Warning warn(_traceLevels->logger); warn << "default application descriptor:\nnode definitions are not allowed."; @@ -325,19 +361,19 @@ AdminI::getDefaultApplicationDescriptor(const Current& current) const warn << "default application descriptor:\ndistribution is not allowed."; desc.distrib = DistributionDescriptor(); } - if(!desc.replicaGroups.empty()) + if (!desc.replicaGroups.empty()) { Ice::Warning warn(_traceLevels->logger); warn << "default application descriptor:\nreplica group definitions are not allowed."; desc.replicaGroups.clear(); } - if(!desc.description.empty()) + if (!desc.description.empty()) { Ice::Warning warn(_traceLevels->logger); warn << "default application descriptor:\ndescription is not allowed."; desc.description = ""; } - if(!desc.variables.empty()) + if (!desc.variables.empty()) { Ice::Warning warn(_traceLevels->logger); warn << "default application descriptor:\nvariable definitions are not allowed."; @@ -353,39 +389,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(std::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, std::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, std::move(id)); + return proxy.invoke(&ServerPrx::getPid); } string @@ -394,115 +414,25 @@ AdminI::getServerAdminCategory(const Current&) const return _registry->getServerAdminCategory(); } -ObjectPrx -AdminI::getServerAdmin(const string& id, const Current& current) const +shared_ptr +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 response, function exception, const Current&) { - ServerProxyWrapper proxy(_database, id); + ServerProxyWrapper proxy(_database, std::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...); }, std::move(response), std::move(exception)); } void -AdminI::stopServer_async(const AMD_Admin_stopServerPtr& amdCB, const string& id, const Current&) +AdminI::stopServerAsync(string id, function response, function exception, const Current&) { ServerProxyWrapper proxy(_database, id); proxy.useDeactivationTimeout(); @@ -510,14 +440,31 @@ 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 = std::move(exception)](exception_ptr ex) { + try + { + rethrow_exception(ex); + } + catch (const Ice::TimeoutException&) + { + response(); + } + catch (const Ice::Exception&) + { + exception(current_exception()); + } + }); } void -AdminI::patchServer_async(const AMD_Admin_patchServerPtr& amdCB, const string& id, bool shutdown, - const Current& current) +AdminI::patchServerAsync( + string id, + bool shutdown, + function response, + function exception, + const Current& current) { ServerInfo info = _database->getServer(id)->getInfo(); ApplicationInfo appInfo = _database->getApplicationInfo(info.application); @@ -528,7 +475,7 @@ AdminI::patchServer_async(const AMD_Admin_patchServerPtr& amdCB, const string& i if(appDistrib.icepatch.empty() && nodes.empty()) { - amdCB->ice_response(); + response(); return; } @@ -538,8 +485,15 @@ AdminI::patchServer_async(const AMD_Admin_patchServerPtr& amdCB, const string& i identity.category = current.id.category; identity.name = Ice::generateUUID(); - PatcherFeedbackAggregatorPtr feedback = - newPatcherFeedback(amdCB, identity, _traceLevels, "server", id, static_cast(nodes.size())); + shared_ptr feedback = + newPatcherFeedback( + response, + exception, + identity, + _traceLevels, + "server", + id, + static_cast(nodes.size())); vector::const_iterator p = nodes.begin(); try @@ -550,11 +504,11 @@ AdminI::patchServer_async(const AMD_Admin_patchServerPtr& amdCB, const string& i out << "started patching of server `" << id << "' on node `" << *p << "'"; } - NodeEntryPtr node = _database->getNode(*p); + shared_ptr node = _database->getNode(*p); Resolver resolve(node->getInfo(), _database->getCommunicator()); DistributionDescriptor desc = resolve(appDistrib); - InternalDistributionDescriptorPtr intAppDistrib = new InternalDistributionDescriptor(desc.icepatch, - desc.directories); + shared_ptr intAppDistrib = + make_shared(desc.icepatch, desc.directories); node->getSession()->patch(feedback, info.application, id, intAppDistrib, shutdown); } catch(const NodeNotExistException&) @@ -574,17 +528,10 @@ AdminI::patchServer_async(const AMD_Admin_patchServerPtr& amdCB, const string& i } 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, std::move(id)); + proxy.invoke(&ServerPrx::sendSignal, std::move(signal)); } StringSeq @@ -594,42 +541,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, std::move(id)); + proxy.invoke(&ServerPrx::setEnabled, std::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, std::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); @@ -642,11 +574,11 @@ AdminI::getAllAdapterIds(const Current&) const } void -AdminI::addObject(const Ice::ObjectPrx& proxy, const ::Ice::Current& current) +AdminI::addObject(shared_ptr proxy, const ::Ice::Current& current) { checkIsReadOnly(); - if(!proxy) + if (!proxy) { throw DeploymentException("proxy is null"); } @@ -655,51 +587,51 @@ AdminI::addObject(const Ice::ObjectPrx& proxy, const ::Ice::Current& current) { addObjectWithType(proxy, proxy->ice_id(), current); } - catch(const Ice::LocalException& ex) + catch (const Ice::LocalException& ex) { ostringstream os; os << "failed to invoke ice_id() on proxy `" + current.adapter->getCommunicator()->proxyToString(proxy) - << "':\n" << ex; + << "':\n" << ex; throw DeploymentException(os.str()); } } void -AdminI::updateObject(const Ice::ObjectPrx& proxy, const ::Ice::Current&) +AdminI::updateObject(shared_ptr proxy, const ::Ice::Current&) { checkIsReadOnly(); - if(!proxy) + if (!proxy) { throw DeploymentException("proxy is null"); } const Ice::Identity id = proxy->ice_getIdentity(); - if(id.category == _database->getInstanceName()) + if (id.category == _database->getInstanceName()) { throw DeploymentException("updating object `" + _database->getCommunicator()->identityToString(id) + - "' is not allowed:\nobjects with identity category `" + id.category + - "' are managed by IceGrid"); + "' is not allowed:\nobjects with identity category `" + id.category + + "' are managed by IceGrid"); } _database->updateObject(proxy); } void -AdminI::addObjectWithType(const Ice::ObjectPrx& proxy, const string& type, const ::Ice::Current&) +AdminI::addObjectWithType(shared_ptr proxy, string type, const ::Ice::Current&) { checkIsReadOnly(); - if(!proxy) + if (!proxy) { throw DeploymentException("proxy is null"); } const Ice::Identity id = proxy->ice_getIdentity(); - if(id.category == _database->getInstanceName()) + if (id.category == _database->getInstanceName()) { throw DeploymentException("adding object `" + _database->getCommunicator()->identityToString(id) + - "' is not allowed:\nobjects with identity category `" + id.category + - "' are managed by IceGrid"); + "' is not allowed:\nobjects with identity category `" + id.category + + "' are managed by IceGrid"); } ObjectInfo info; @@ -709,90 +641,87 @@ 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()) + if (id.category == _database->getInstanceName()) { throw DeploymentException("removing object `" + _database->getCommunicator()->identityToString(id) + - "' is not allowed:\nobjects with identity category `" + id.category + - "' are managed by IceGrid"); + "' is not allowed:\nobjects with identity category `" + id.category + + "' are managed by IceGrid"); } _database->removeObject(id); } 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(std::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(std::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(std::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 +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 { _database->getNode(name)->getProxy()->ice_ping(); return true; } - catch(const NodeUnreachableException&) + catch (const NodeUnreachableException&) { return false; } - catch(const Ice::ObjectNotExistException&) + catch (const Ice::ObjectNotExistException&) { throw NodeNotExistException(); } - catch(const Ice::LocalException&) + catch (const Ice::LocalException&) { return false; } } LoadInfo -AdminI::getNodeLoad(const string& name, const Current&) const +AdminI::getNodeLoad(string name, const Current&) const { try { return _database->getNode(name)->getProxy()->getLoad(); } - catch(const Ice::ObjectNotExistException&) + catch (const Ice::ObjectNotExistException&) { throw NodeNotExistException(); } - catch(const Ice::LocalException& ex) + catch (const Ice::LocalException& ex) { ostringstream os; os << ex; @@ -801,22 +730,22 @@ 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 { return _database->getNode(name)->getProxy()->getProcessorSocketCount(); } - catch(const Ice::OperationNotExistException&) + catch (const Ice::OperationNotExistException&) { return 0; // Not supported. } - catch(const Ice::ObjectNotExistException&) + catch (const Ice::ObjectNotExistException&) { throw NodeNotExistException(name); return 0; } - catch(const Ice::LocalException& ex) + catch (const Ice::LocalException& ex) { ostringstream os; os << ex; @@ -826,17 +755,17 @@ AdminI::getNodeProcessorSocketCount(const string& name, const Current&) const } void -AdminI::shutdownNode(const string& name, const Current&) +AdminI::shutdownNode(string name, const Current&) { try { _database->getNode(name)->getProxy()->shutdown(); } - catch(const Ice::ObjectNotExistException&) + catch (const Ice::ObjectNotExistException&) { throw NodeNotExistException(name); } - catch(const Ice::LocalException& ex) + catch (const Ice::LocalException& ex) { ostringstream os; os << ex; @@ -845,17 +774,17 @@ AdminI::shutdownNode(const string& name, const Current&) } string -AdminI::getNodeHostname(const string& name, const Current&) const +AdminI::getNodeHostname(string name, const Current&) const { try { return _database->getNode(name)->getInfo()->hostname; } - catch(const Ice::ObjectNotExistException&) + catch (const Ice::ObjectNotExistException&) { throw NodeNotExistException(name); } - catch(const Ice::LocalException& ex) + catch (const Ice::LocalException& ex) { ostringstream os; os << ex; @@ -870,9 +799,9 @@ 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()) + if (name == _registry->getName()) { return _registry->getInfo(); } @@ -882,10 +811,10 @@ AdminI::getRegistryInfo(const string& name, const Ice::Current&) const } } -ObjectPrx -AdminI::getRegistryAdmin(const string& name, const Current& current) const +shared_ptr +AdminI::getRegistryAdmin(string name, const Current& current) const { - if(name != _registry->getName()) + if (name != _registry->getName()) { // // Check if the replica exists @@ -893,16 +822,13 @@ 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()) + if (name == _registry->getName()) { return true; } @@ -912,20 +838,20 @@ AdminI::pingRegistry(const string& name, const Current&) const _database->getReplica(name)->getProxy()->ice_ping(); return true; } - catch(const Ice::ObjectNotExistException&) + catch (const Ice::ObjectNotExistException&) { throw RegistryNotExistException(); } - catch(const Ice::LocalException&) + catch (const Ice::LocalException&) { return false; } } void -AdminI::shutdownRegistry(const string& name, const Current&) +AdminI::shutdownRegistry(string name, const Current&) { - if(name == _registry->getName()) + if (name == _registry->getName()) { _registry->shutdown(); return; @@ -935,11 +861,11 @@ AdminI::shutdownRegistry(const string& name, const Current&) { _database->getReplica(name)->getProxy()->shutdown(); } - catch(const Ice::ObjectNotExistException&) + catch (const Ice::ObjectNotExistException&) { throw RegistryNotExistException(name); } - catch(const Ice::LocalException& ex) + catch (const Ice::LocalException& ex) { ostringstream os; os << ex; @@ -964,7 +890,7 @@ AdminI::shutdown(const Current&) void AdminI::checkIsReadOnly() const { - if(_database->isReadOnly()) + if (_database->isReadOnly()) { throw DeploymentException("this operation is not allowed on a slave or read-only master registry."); } diff --git a/cpp/src/IceGrid/AdminI.h b/cpp/src/IceGrid/AdminI.h index a73ce089155..c7781abd0e1 100644 --- a/cpp/src/IceGrid/AdminI.h +++ b/cpp/src/IceGrid/AdminI.h @@ -10,92 +10,96 @@ namespace IceGrid { +class AdminSessionI; class Database; -typedef IceUtil::Handle DatabasePtr; - -class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; - class RegistryI; -typedef IceUtil::Handle RegistryIPtr; - -class AdminSessionI; -typedef IceUtil::Handle 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 void patchApplication_async(const AMD_Admin_patchApplicationPtr&, const std::string&, bool, - 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 patchServer_async(const AMD_Admin_patchServerPtr&, const ::std::string&, bool, 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&, const std::shared_ptr&, const std::shared_ptr&); + + 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 patchApplicationAsync( + std::string, + bool, + std::function, + std::function, + 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 getServerAdmin(std::string, const Ice::Current&) const override; + void startServerAsync(std::string, std::function, std::function, + const Ice::Current&) override; + void stopServerAsync(std::string, std::function, std::function, + const Ice::Current&) override; + + void patchServerAsync( + std::string, + bool, + std::function, + std::function, + 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, const ::Ice::Current&) override; + void updateObject(std::shared_ptr, const ::Ice::Current&) override; + void addObjectWithType(std::shared_ptr, 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 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 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; + const std::shared_ptr _registry; + const std::shared_ptr _traceLevels; + const std::shared_ptr _session; + + std::mutex _mutex; }; -typedef IceUtil::Handle AdminIPtr; } diff --git a/cpp/src/IceGrid/AdminRouter.cpp b/cpp/src/IceGrid/AdminRouter.cpp index 27c0fa9c0ae..02704b1a4ff 100644 --- a/cpp/src/IceGrid/AdminRouter.cpp +++ b/cpp/src/IceGrid/AdminRouter.cpp @@ -4,89 +4,73 @@ #include -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& 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) { } void -IceGrid::AdminRouter::invokeOnTarget(const Ice::ObjectPrx& target, - const AMD_Object_ice_invokePtr& cb, - const pair& inParams, - const Current& current) +IceGrid::AdminRouter::invokeOnTarget(const shared_ptr& target, + const pair& inParams, + function&)>&& response, + function&& 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(std::move(ok), std::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&); - void invokeOnTarget(const Ice::ObjectPrx&, - const Ice::AMD_Object_ice_invokePtr&, + void invokeOnTarget(const std::shared_ptr&, const std::pair&, + std::function&)>&&, + std::function&&, const Ice::Current&); - const TraceLevelsPtr _traceLevels; + const std::shared_ptr _traceLevels; }; } diff --git a/cpp/src/IceGrid/AdminSessionI.cpp b/cpp/src/IceGrid/AdminSessionI.cpp index f34fd25335f..69511aa20f0 100644 --- a/cpp/src/IceGrid/AdminSessionI.cpp +++ b/cpp/src/IceGrid/AdminSessionI.cpp @@ -21,61 +21,39 @@ 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& 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& proxy) : + _proxy(proxy) { } - virtual void - ice_invoke_async(const Ice::AMD_Object_ice_invokePtr& amdCB, - const pair& inParams, - const Ice::Current& current) + void + ice_invokeAsync(pair inParams, + function&)> response, + function 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, + std::move(response), + [exception = std::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 _proxy; }; } -FileIteratorI::FileIteratorI(const AdminSessionIPtr& session, - const FileReaderPrx& reader, +FileIteratorI::FileIteratorI(const shared_ptr& session, + const shared_ptr& reader, const string& filename, - Ice::Long offset, + long long offset, int messageSizeMax) : _session(session), _reader(reader), @@ -92,11 +70,9 @@ FileIteratorI::read(int size, Ice::StringSeq& lines, const Ice::Current&) { return _reader->read(_filename, _offset, size > _messageSizeMax ? _messageSizeMax : 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()); } } @@ -106,7 +82,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& db, chrono::seconds timeout, + const shared_ptr& registry) : BaseSessionI(id, "admin", db), _timeout(timeout), _replicaName(registry->getName()), @@ -114,12 +91,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 +AdminSessionI::_register(const shared_ptr& servantManager, + const shared_ptr& con) { // // This is supposed to be called after creation only, no need to synchronize. @@ -139,117 +113,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(shared_from_this()); + + auto session = _servantManager->addSession(self, con, category); - _admin = AdminPrx::uncheckedCast(_servantManager->add(new AdminI(_database, _registry, this), this)); + _admin = Ice::uncheckedCast(_servantManager->add(make_shared(_database, _registry, self), self)); return session; } -AdminPrx +shared_ptr AdminSessionI::getAdmin(const Ice::Current&) const { return _admin; } -Ice::ObjectPrx +shared_ptr 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 registryObserver, + shared_ptr nodeObserver, + shared_ptr appObserver, + shared_ptr adapterObserver, + shared_ptr 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, "", ""); @@ -262,7 +242,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, "", ""); @@ -277,12 +258,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 +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(std::move(id))->getProxy(false, 5s), "#" + std::move(path), nLines, current); } catch(const SynchronizationException&) { @@ -290,12 +271,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 +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(std::move(id))->getProxy(false, 5s), "stdout", nLines, current); } catch(const SynchronizationException&) { @@ -303,12 +284,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 +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(std::move(id))->getProxy(false, 5s), "stderr", nLines, current); } catch(const SynchronizationException&) { @@ -316,44 +297,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 +AdminSessionI::openNodeStdOut(string name, int nLines, const Ice::Current& current) { - return addFileIterator(_database->getNode(name)->getProxy(), "stdout", nLines, current); + return addFileIterator(_database->getNode(std::move(name))->getProxy(), "stdout", nLines, current); } -FileIteratorPrx -AdminSessionI::openNodeStdErr(const string& name, int nLines, const Ice::Current& current) +shared_ptr +AdminSessionI::openNodeStdErr(string name, int nLines, const Ice::Current& current) { - return addFileIterator(_database->getNode(name)->getProxy(), "stderr", nLines, current); + return addFileIterator(_database->getNode(std::move(name))->getProxy(), "stderr", nLines, current); } -FileIteratorPrx -AdminSessionI::openRegistryStdOut(const string& name, int nLines, const Ice::Current& current) +shared_ptr +AdminSessionI::openRegistryStdOut(string name, int nLines, const Ice::Current& current) { - FileReaderPrx reader; + shared_ptr reader; if(name == _replicaName) { reader = _database->getReplicaCache().getInternalRegistry(); } else { - reader = _database->getReplica(name)->getProxy(); + reader = _database->getReplica(std::move(name))->getProxy(); } return addFileIterator(reader, "stdout", nLines, current); } -FileIteratorPrx -AdminSessionI::openRegistryStdErr(const string& name, int nLines, const Ice::Current& current) +shared_ptr +AdminSessionI::openRegistryStdErr(string name, int nLines, const Ice::Current& current) { - FileReaderPrx reader; + shared_ptr reader; if(name == _replicaName) { reader = _database->getReplicaCache().getInternalRegistry(); } else { - reader = _database->getReplica(name)->getProxy(); + reader = _database->getReplica(std::move(name))->getProxy(); } return addFileIterator(reader, "stderr", nLines, current); } @@ -365,7 +346,7 @@ AdminSessionI::destroy(const Ice::Current&) } void -AdminSessionI::setupObserverSubscription(TopicName name, const Ice::ObjectPrx& observer, bool forwarder) +AdminSessionI::setupObserverSubscription(TopicName name, const shared_ptr& observer, bool forwarder) { if(_observers.find(name) != _observers.end() && _observers[name].first != observer) { @@ -392,27 +373,28 @@ AdminSessionI::setupObserverSubscription(TopicName name, const Ice::ObjectPrx& o } } -Ice::ObjectPrx +shared_ptr 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 +AdminSessionI::addForwarder(const shared_ptr& prx) { - return _registry->getRegistryAdapter()->addWithUUID(new SubscriberForwarderI(prx)); + return _registry->getRegistryAdapter()->addWithUUID(make_shared(prx)); } -FileIteratorPrx -AdminSessionI::addFileIterator(const FileReaderPrx& reader, const string& filename, int nLines, +shared_ptr +AdminSessionI::addFileIterator(const shared_ptr& 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, "", ""); @@ -422,29 +404,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(); + auto properties = reader->ice_getCommunicator()->getProperties(); int messageSizeMax = properties->getPropertyAsIntWithDefault("Ice.MessageSizeMax", 1024) * 1024; - Ice::ObjectPrx obj = _servantManager->add(new FileIteratorI(this, reader, filename, offset, messageSizeMax), this); - return FileIteratorPrx::uncheckedCast(obj); + auto self = static_pointer_cast(shared_from_this()); + auto obj = _servantManager->add(make_shared(self, reader, filename, offset, messageSizeMax), self); + return Ice::uncheckedCast(obj); } void AdminSessionI::removeFileIterator(const Ice::Identity& id, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); + _servantManager->remove(id); } @@ -453,7 +435,7 @@ AdminSessionI::destroyImpl(bool shutdown) { BaseSessionI::destroyImpl(shutdown); - _servantManager->removeSession(this); + _servantManager->removeSession(shared_from_this()); try { @@ -468,18 +450,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& servantManager, + const shared_ptr& database, + const shared_ptr& reaper, + const shared_ptr& registry) : _servantManager(servantManager), _database(database), _timeout(registry->getSessionTimeout(Ice::emptyCurrent)), @@ -489,35 +471,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(_filters) = props->getPropertyAsIntWithDefault("IceGrid.Registry.AdminSessionFilters", 0) > 0; } } -Glacier2::SessionPrx -AdminSessionFactory::createGlacier2Session(const string& sessionId, const Glacier2::SessionControlPrx& ctl) +shared_ptr +AdminSessionFactory::createGlacier2Session(const string& sessionId, const shared_ptr& 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) { @@ -530,39 +506,40 @@ AdminSessionFactory::createGlacier2Session(const string& sessionId, const Glacie } } - _reaper->add(new SessionReapable(_database->getTraceLevels()->logger, session), timeout); - return Glacier2::SessionPrx::uncheckedCast(proxy); + _reaper->add(make_shared>(_database->getTraceLevels()->logger, session), timeout); + return Ice::uncheckedCast(proxy); } -AdminSessionIPtr +shared_ptr AdminSessionFactory::createSessionServant(const string& id) { - return new AdminSessionI(id, _database, _timeout, _registry); + return make_shared(id, _database, _timeout, _registry); } -const TraceLevelsPtr& +const shared_ptr& AdminSessionFactory::getTraceLevels() const { return _database->getTraceLevels(); } -AdminSessionManagerI::AdminSessionManagerI(const AdminSessionFactoryPtr& factory) : _factory(factory) +AdminSessionManagerI::AdminSessionManagerI(const shared_ptr& factory) : _factory(factory) { } -Glacier2::SessionPrx -AdminSessionManagerI::create(const string& userId, const Glacier2::SessionControlPrx& ctl, const Ice::Current&) +shared_ptr +AdminSessionManagerI::create(string userId, shared_ptr ctl, + const Ice::Current&) { - return _factory->createGlacier2Session(userId, ctl); + return _factory->createGlacier2Session(std::move(userId), std::move(ctl)); } -AdminSSLSessionManagerI::AdminSSLSessionManagerI(const AdminSessionFactoryPtr& factory) : _factory(factory) +AdminSSLSessionManagerI::AdminSSLSessionManagerI(const shared_ptr& factory) : _factory(factory) { } -Glacier2::SessionPrx -AdminSSLSessionManagerI::create(const Glacier2::SSLInfo& info, - const Glacier2::SessionControlPrx& ctl, +shared_ptr +AdminSSLSessionManagerI::create(Glacier2::SSLInfo info, + shared_ptr ctl, const Ice::Current&) { string userDN; @@ -570,7 +547,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) @@ -582,5 +559,5 @@ AdminSSLSessionManagerI::create(const Glacier2::SSLInfo& info, } } - return _factory->createGlacier2Session(userDN, ctl); + return _factory->createGlacier2Session(std::move(userDN), std::move(ctl)); } diff --git a/cpp/src/IceGrid/AdminSessionI.h b/cpp/src/IceGrid/AdminSessionI.h index ee1d9c909d8..c910882cdaf 100644 --- a/cpp/src/IceGrid/AdminSessionI.h +++ b/cpp/src/IceGrid/AdminSessionI.h @@ -14,131 +14,134 @@ namespace IceGrid { class RegistryI; -typedef IceUtil::Handle RegistryIPtr; - class FileIteratorI; -typedef IceUtil::Handle 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&, + std::chrono::seconds, const std::shared_ptr&); - Ice::ObjectPrx _register(const SessionServantManagerPtr&, const Ice::ConnectionPtr&); + std::shared_ptr _register(const std::shared_ptr&, + const std::shared_ptr&); - 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 getAdmin(const Ice::Current&) const override; + std::shared_ptr 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, std::shared_ptr, + std::shared_ptr, std::shared_ptr, + std::shared_ptr, 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 openServerLog(std::string, std::string, int, const Ice::Current&) override; + std::shared_ptr openServerStdOut(std::string, int, const Ice::Current&) override; + std::shared_ptr 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 openNodeStdOut(std::string, int, const Ice::Current&) override; + std::shared_ptr 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 openRegistryStdOut(std::string, int, const Ice::Current&) override; + std::shared_ptr 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&, bool = false); + std::shared_ptr addForwarder(const Ice::Identity&, const Ice::Current&); + std::shared_ptr addForwarder(const std::shared_ptr&); + std::shared_ptr addFileIterator(const std::shared_ptr&, 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 > _observers; - RegistryIPtr _registry; - Ice::ObjectPrx _adminCallbackTemplate; + std::shared_ptr _admin; + std::map, bool>> _observers; + std::shared_ptr _registry; + std::shared_ptr _adminCallbackTemplate; }; -typedef IceUtil::Handle AdminSessionIPtr; -class AdminSessionFactory : public virtual IceUtil::Shared +class AdminSessionFactory { public: - AdminSessionFactory(const SessionServantManagerPtr&, const DatabasePtr&, const ReapThreadPtr&, const RegistryIPtr&); + AdminSessionFactory(const std::shared_ptr&, const std::shared_ptr&, + const std::shared_ptr&, const std::shared_ptr&); - Glacier2::SessionPrx createGlacier2Session(const std::string&, const Glacier2::SessionControlPrx&); - AdminSessionIPtr createSessionServant(const std::string&); + std::shared_ptr createGlacier2Session(const std::string&, + const std::shared_ptr&); + std::shared_ptr createSessionServant(const std::string&); - const TraceLevelsPtr& getTraceLevels() const; + const std::shared_ptr& getTraceLevels() const; private: - const SessionServantManagerPtr _servantManager; - const DatabasePtr _database; - const int _timeout; - const ReapThreadPtr _reaper; - const RegistryIPtr _registry; + const std::shared_ptr _servantManager; + const std::shared_ptr _database; + const std::chrono::seconds _timeout; + const std::shared_ptr _reaper; + const std::shared_ptr _registry; const bool _filters; }; -typedef IceUtil::Handle AdminSessionFactoryPtr; -class AdminSessionManagerI : public virtual Glacier2::SessionManager +class AdminSessionManagerI : public Glacier2::SessionManager { public: - AdminSessionManagerI(const AdminSessionFactoryPtr&); + AdminSessionManagerI(const std::shared_ptr&); - virtual Glacier2::SessionPrx create(const std::string&, const Glacier2::SessionControlPrx&, const Ice::Current&); + std::shared_ptr create(std::string, std::shared_ptr, + const Ice::Current&) override; private: - const AdminSessionFactoryPtr _factory; + const std::shared_ptr _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&); + + std::shared_ptr create(Glacier2::SSLInfo, std::shared_ptr, + const Ice::Current&) override; private: - const AdminSessionFactoryPtr _factory; + const std::shared_ptr _factory; }; class FileIteratorI : public FileIterator { public: - FileIteratorI(const AdminSessionIPtr&, const FileReaderPrx&, const std::string&, Ice::Long, int); + FileIteratorI(const std::shared_ptr&, const std::shared_ptr&, 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 _session; + const std::shared_ptr _reader; const std::string _filename; - Ice::Long _offset; + long long _offset; const int _messageSizeMax; }; 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&, const shared_ptr& 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& 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& 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(_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& 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& 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& 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 request; + shared_ptr 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 >::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 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, + const shared_ptr& 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) { 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::dequeueAllocationAttempt(shared_ptr& request) { if(_requests.empty()) { - return 0; + return nullptr; } - pair 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& 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& request, + const shared_ptr& 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 -#include -#include -#include #include #include @@ -19,35 +15,33 @@ namespace IceGrid { -class SessionI; -typedef IceUtil::Handle SessionIPtr; - class Allocatable; -typedef IceUtil::Handle AllocatablePtr; +class SessionI; -class AllocationRequest : public IceUtil::Mutex, public IceUtil::TimerTask +class AllocationRequest : public IceUtil::TimerTask, public std::enable_shared_from_this { 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&, const std::shared_ptr&) = 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&, const std::shared_ptr&); + void cancel(std::exception_ptr); + + void runTimerTask() override; int getTimeout() const { return _timeout; } - const SessionIPtr& getSession() const { return _session; } + const std::shared_ptr& getSession() const { return _session; } bool isCanceled() const; bool operator<(const AllocationRequest&) const; protected: - AllocationRequest(const SessionIPtr&); + AllocationRequest(const std::shared_ptr&); private: @@ -59,53 +53,57 @@ class AllocationRequest : public IceUtil::Mutex, public IceUtil::TimerTask Allocated }; - const SessionIPtr _session; + const std::shared_ptr _session; const int _timeout; State _state; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle AllocationRequestPtr; -class Allocatable : public virtual IceUtil::Shared, public IceUtil::Monitor +class Allocatable: public virtual std::enable_shared_from_this { public: - Allocatable(bool, const AllocatablePtr&); - virtual ~Allocatable(); + Allocatable(bool, const std::shared_ptr&); + 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&, bool = false); + virtual bool tryAllocate(const std::shared_ptr&, bool = false); + virtual void release(const std::shared_ptr&, bool = false); bool isAllocatable() const { return _allocatable; } - SessionIPtr getSession() const; + std::shared_ptr 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&) = 0; + virtual void released(const std::shared_ptr&) = 0; virtual bool canTryAllocate() { return false; } - virtual void allocatedNoSync(const SessionIPtr&) { ; } - virtual void releasedNoSync(const SessionIPtr&) { ; } + virtual void allocatedNoSync(const std::shared_ptr&) {} + virtual void releasedNoSync(const std::shared_ptr&) {} 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&, bool, bool); + void queueAllocationAttemptFromChild(const std::shared_ptr&); + bool allocateFromChild(const std::shared_ptr&, const std::shared_ptr&, bool, bool); - void queueAllocationAttempt(const AllocatablePtr&, const AllocationRequestPtr&, bool); - AllocatablePtr dequeueAllocationAttempt(AllocationRequestPtr&); + void queueAllocationAttempt(const std::shared_ptr&, const std::shared_ptr&, bool); + std::shared_ptr dequeueAllocationAttempt(std::shared_ptr&); bool _allocatable; - const AllocatablePtr _parent; + const std::shared_ptr _parent; - std::list > _requests; - SessionIPtr _session; + std::list, std::shared_ptr>> _requests; + std::shared_ptr _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 5ec7256f437..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 +bool compareAllocatableObjectEntry(const shared_ptr& lhs, + const shared_ptr& 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& 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& obj) { // // No mutex protection here, this is called with the cache locked. // - vector::iterator q; - q = lower_bound(_objects.begin(), _objects.end(), obj, AllocatableObjectEntryCI()); + vector>::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::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& 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& entry, bool fromRelease) { // // No mutex protection here, this is called with the cache locked. // - list::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& communicator) : _communicator(communicator) { } void -AllocatableObjectCache::add(const ObjectInfo& info, const ServerEntryPtr& parent) +AllocatableObjectCache::add(const ObjectInfo& info, const shared_ptr& 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(*this, info, parent); addImpl(id, entry); map::iterator p = _types.find(entry->getType()); @@ -151,11 +144,12 @@ AllocatableObjectCache::add(const ObjectInfo& info, const ServerEntryPtr& parent } } -AllocatableObjectEntryPtr +shared_ptr 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 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::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& request) { - Lock sync(*this); - map::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 objects = p->second.getObjects(); + vector> objects = p->second.getObjects(); IceUtilInternal::shuffle(objects.begin(), objects.end()); // TODO: OPTIMIZE int allocatable = 0; try { - for(vector::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& entry) { // // Notify the type entry that an object was released. // - Lock sync(*this); - map::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& parent) : Allocatable(true, parent), _cache(cache), _info(info), @@ -265,7 +261,7 @@ AllocatableObjectEntry::AllocatableObjectEntry(AllocatableObjectCache& cache, assert(_server); } -Ice::ObjectPrx +shared_ptr AllocatableObjectEntry::getProxy() const { return _info.proxy; @@ -290,15 +286,15 @@ AllocatableObjectEntry::isEnabled() const } void -AllocatableObjectEntry::allocated(const SessionIPtr& session) +AllocatableObjectEntry::allocated(const shared_ptr& 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& 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 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(shared_from_this())); } diff --git a/cpp/src/IceGrid/AllocatableObjectCache.h b/cpp/src/IceGrid/AllocatableObjectCache.h index a1bb3a66b70..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 #include #include #include @@ -14,77 +13,73 @@ namespace IceGrid { -class ServerEntry; -typedef IceUtil::Handle 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&); + std::shared_ptr 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&) override; + void released(const std::shared_ptr&) override; + bool canTryAllocate() override; - void destroy(); - virtual void checkAllocatable(); + void destroy(); + void checkAllocatable() override; private: AllocatableObjectCache& _cache; const ObjectInfo _info; - ServerEntryPtr _server; + std::shared_ptr _server; bool _destroyed; }; -typedef IceUtil::Handle AllocatableObjectEntryPtr; class ObjectAllocationRequest : public AllocationRequest { public: - ObjectAllocationRequest(const SessionIPtr& session) : AllocationRequest(session) { } + ObjectAllocationRequest(const std::shared_ptr& session) : AllocationRequest(session) + { + } - virtual void response(const Ice::ObjectPrx&) = 0; - virtual void exception(const Ice::UserException&) = 0; + virtual void response(const std::shared_ptr&) = 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, const std::shared_ptr&) override { - response(AllocatableObjectEntryPtr::dynamicCast(allocatable)->getProxy()); + response(std::dynamic_pointer_cast(allocatable)->getProxy()); } - virtual void canceled(const Ice::UserException& ex) + void canceled(std::exception_ptr ex) override { exception(ex); } }; -typedef IceUtil::Handle ObjectAllocationRequestPtr; - -class AdapterCache; class AllocatableObjectCache : public Cache { public: - AllocatableObjectCache(const Ice::CommunicatorPtr&); + AllocatableObjectCache(const std::shared_ptr&); - void add(const ObjectInfo&, const ServerEntryPtr&); - AllocatableObjectEntryPtr get(const Ice::Identity&) const; + void add(const ObjectInfo&, const std::shared_ptr&); + std::shared_ptr 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&); + bool canTryAllocate(const std::shared_ptr&); - const Ice::CommunicatorPtr& getCommunicator() const { return _communicator; } + const std::shared_ptr& getCommunicator() const { return _communicator; } private: @@ -92,23 +87,21 @@ class AllocatableObjectCache : public Cache&); + bool remove(const std::shared_ptr&); - void addAllocationRequest(const ObjectAllocationRequestPtr&); - bool canTryAllocate(const AllocatableObjectEntryPtr&, bool); + void addAllocationRequest(const std::shared_ptr&); + bool canTryAllocate(const std::shared_ptr&, bool); - const std::vector& getObjects() const { return _objects; } + const std::vector>& getObjects() const { return _objects; } private: - std::vector _objects; - std::list _requests; + std::vector> _objects; + std::list> _requests; }; - const Ice::CommunicatorPtr _communicator; + const std::shared_ptr _communicator; std::map _types; std::map > _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 -#include #include #include +#include + 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 SynchronizationCallbackPtr; template -class Cache : public IceUtil::Monitor +class Cache { - typedef IceUtil::Handle ValuePtr; - typedef std::map ValueMap; + using ValueType = std::shared_ptr; + using ValueMap = std::map; public: @@ -35,39 +32,36 @@ class Cache : public IceUtil::Monitor { } - virtual - ~Cache() - { - } + virtual ~Cache() = default; bool has(const Key& key) const { - Lock sync(*this); - return getImpl(key); + std::lock_guard lock(_mutex); + return getImpl(key) != nullptr; } void remove(const Key& key) { - Lock sync(*this); + std::lock_guard lock(_mutex); removeImpl(key); } void - setTraceLevels(const TraceLevelsPtr& traceLevels) + setTraceLevels(const std::shared_ptr& traceLevels) { _traceLevels = traceLevels; } - const TraceLevelsPtr& getTraceLevels() const { return _traceLevels; } + const std::shared_ptr& getTraceLevels() const { return _traceLevels; } protected: - virtual ValuePtr + virtual ValueType getImpl(const Key& key) const { - typename ValueMap::iterator p = const_cast(_entries).end(); + auto p = const_cast(_entries).end(); if(_entriesHint != p) { if(_entriesHint->first == key) @@ -88,22 +82,21 @@ class Cache : public IceUtil::Monitor } 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 @@ class Cache : public IceUtil::Monitor } } - TraceLevelsPtr _traceLevels; + std::shared_ptr _traceLevels; ValueMap _entries; typename ValueMap::iterator _entriesHint; + + mutable std::mutex _mutex; + std::condition_variable _condVar; }; template class CacheByString : public Cache { - typedef IceUtil::Handle TPtr; - public: - virtual std::vector + std::vector getAll(const std::string& expr) { - IceUtil::Monitor::Lock sync(*this); - return getMatchingKeys >(Cache::_entries, expr); + std::lock_guard lock(Cache::_mutex); + return getMatchingKeys>>(Cache::_entries, expr); } }; diff --git a/cpp/src/IceGrid/Client.cpp b/cpp/src/IceGrid/Client.cpp index 627cb87e95d..c92eeb867c5 100644 --- a/cpp/src/IceGrid/Client.cpp +++ b/cpp/src/IceGrid/Client.cpp @@ -4,12 +4,9 @@ #include #include -#include #include #include #include -#include -#include #include #include #include @@ -37,90 +34,46 @@ class Client; namespace { -IceUtil::Mutex* _staticMutex = 0; -Ice::CommunicatorPtr communicator; -IceGrid::ParserPtr parser; +mutex staticMutex; +shared_ptr communicator; +shared_ptr 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 proxy) : _clientProxy(std::move(proxy)) { } - virtual Ice::ObjectPrx - getClientProxy(IceUtil::Optional& hasRoutingTable, const Ice::Current&) const + shared_ptr + getClientProxy(IceUtil::Optional& 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 + 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 _clientProxy; }; int run(const Ice::StringSeq&); -// -// Callback for CtrlCHandler -// -static void -interruptCallback(int /*signal*/) -{ - IceUtilInternal::MutexPtrLock 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,8 +91,8 @@ main(int argc, char* argv[]) try { - Ice::CtrlCHandler ctrlCHandler; - Ice::PropertiesPtr defaultProps = Ice::createProperties(); + IceUtil::CtrlCHandler ctrlCHandler; + auto defaultProps = Ice::createProperties(); defaultProps->setProperty("IceGridAdmin.Server.Endpoints", "tcp -h localhost"); Ice::InitializationData id; id.properties = createProperties(args, defaultProps); @@ -147,7 +100,21 @@ main(int argc, char* argv[]) 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 +191,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&, const string&, const Ice::StringSeq&); int run(const Ice::StringSeq& args) @@ -275,9 +242,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(), Ice::stringToIdentity("FileParser")); consoleOut << proxy << endl; communicator->waitForShutdown(); @@ -286,10 +253,9 @@ run(const Ice::StringSeq& args) if(opts.isSet("e")) { - vector optargs = opts.argVec("e"); - for(vector::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 +300,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 router; + shared_ptr session; int status = 0; try { @@ -356,7 +322,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(communicator->stringToProxy(os.str())); try { communicator->setDefaultLocator(finder->getLocator()); @@ -381,18 +347,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 pluginObj(createIceLocatorDiscovery(communicator, "IceGridAdmin.Discovery", + Ice::StringSeq())); + auto plugin = dynamic_pointer_cast(pluginObj); plugin->initialize(); - vector 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::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 +407,7 @@ run(const Ice::StringSeq& args) try { // Use SSL if available. - router = Glacier2::RouterPrx::checkedCast(communicator->getDefaultRouter()->ice_preferSecure(true)); + router = Ice::checkedCast(communicator->getDefaultRouter()->ice_preferSecure(true)); if(!router) { consoleErr << args[0] << ": configured router is not a Glacier2 router" << endl; @@ -455,7 +422,7 @@ run(const Ice::StringSeq& args) if(ssl) { - session = IceGrid::AdminSessionPrx::uncheckedCast(router->createSessionFromSecureConnection()); + session = Ice::uncheckedCast(router->createSessionFromSecureConnection()); if(!session) { consoleErr << args[0] @@ -488,7 +455,7 @@ run(const Ice::StringSeq& args) #endif } - session = IceGrid::AdminSessionPrx::uncheckedCast(router->createSession(id, password)); + session = Ice::uncheckedCast(router->createSession(id, password)); fill(password.begin(), password.end(), '\0'); // Zero the password string. if(!session) @@ -528,11 +495,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 locator; + shared_ptr localRegistry; try { - locator = IceGrid::LocatorPrx::checkedCast(communicator->getDefaultLocator()); + locator = Ice::checkedCast(communicator->getDefaultLocator()); if(!locator) { consoleErr << args[0] << ": configured locator is not an IceGrid locator" << endl; @@ -546,7 +513,7 @@ run(const Ice::StringSeq& args) return 1; } - IceGrid::RegistryPrx registry; + shared_ptr registry; if(localRegistry->ice_getIdentity() == registryId) { registry = localRegistry; @@ -559,7 +526,7 @@ run(const Ice::StringSeq& args) try { - registry = IceGrid::RegistryPrx::checkedCast(locator->findObjectById(registryId)); + registry = Ice::checkedCast(locator->findObjectById(registryId)); if(!registry) { consoleErr << args[0] << ": could not contact an IceGrid registry" << endl; @@ -603,9 +570,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( + colloc->addWithUUID(make_shared(locator)))); registry = registry->ice_router(communicator->getDefaultRouter()); } @@ -667,8 +634,8 @@ run(const Ice::StringSeq& args) } { - IceUtilInternal::MutexPtrLock lock(_staticMutex); - parser = IceGrid::Parser::createParser(communicator, session, session->getAdmin(), commands.empty()); + lock_guard lock(staticMutex); + parser = make_shared(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 1552c823117..3a3c5de714e 100644 --- a/cpp/src/IceGrid/Database.cpp +++ b/cpp/src/IceGrid/Database.cpp @@ -25,11 +25,11 @@ using namespace std; using namespace IceGrid; -typedef IceDB::ReadWriteCursor ApplicationMapRWCursor; -typedef IceDB::ReadOnlyCursor AdapterMapROCursor; -typedef IceDB::Cursor AdaptersByGroupMapCursor; -typedef IceDB::ReadOnlyCursor ObjectsByTypeMapROCursor; -typedef IceDB::ReadOnlyCursor ObjectsMapROCursor; +using ApplicationMapRWCursor = IceDB::ReadWriteCursor; +using AdapterMapROCursor = IceDB::ReadOnlyCursor; +using AdaptersByGroupMapCursor = IceDB::Cursor; +using ObjectsByTypeMapROCursor = IceDB::ReadOnlyCursor; +using ObjectsMapROCursor = IceDB::ReadOnlyCursor; namespace { @@ -43,14 +43,6 @@ const string internalObjectsDbName = "internal-objects"; const string internalObjectsByTypeDbName = "internal-objectsByType"; const string serialsDbName = "serials"; -struct ObjectLoadCI -{ - bool operator()(const pair& lhs, const pair& rhs) - { - return lhs.second < rhs.second; - } -}; - template vector toVector(const IceDB::ReadOnlyTxn& txn, const IceDB::Dbi& m) { @@ -82,7 +74,7 @@ toMap(const IceDB::Txn& txn, const IceDB::Dbi& d) } void -logError(const Ice::CommunicatorPtr& com, const IceDB::LMDBException& ex) +logError(const shared_ptr& com, const IceDB::LMDBException& ex) { Ice::Error error(com->getLogger()); error << "LMDB error: " << ex; @@ -91,8 +83,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& pluginFacade, + const shared_ptr& con, const Ice::Context& ctx, AdapterInfoSeq& infos) { @@ -101,7 +93,7 @@ filterAdapterInfos(const string& filter, return; } - vector filters = pluginFacade->getReplicaGroupFilters(filter); + auto filters = pluginFacade->getReplicaGroupFilters(filter); if(filters.empty()) { return; @@ -109,25 +101,25 @@ filterAdapterInfos(const string& filter, Ice::StringSeq adapterIds; adapterIds.reserve(infos.size()); - for(vector::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::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 filteredAdpts; filteredAdpts.reserve(infos.size()); - for(Ice::StringSeq::const_iterator q = adapterIds.begin(); q != adapterIds.end(); ++q) + for(const auto& id : adapterIds) { - for(vector::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 +179,25 @@ findByType(const IceDB::ReadOnlyTxn& txn, } -Database::Database(const Ice::ObjectAdapterPtr& registryAdapter, - const IceStorm::TopicManagerPrx& topicManager, +shared_ptr +Database::create(const shared_ptr& registryAdapter, + const shared_ptr& topicManager, + const string& instanceName, + const shared_ptr& traceLevels, + const RegistryInfo& info, + bool readonly) +{ + shared_ptr db(new Database(registryAdapter, topicManager, instanceName, traceLevels, info, readonly)); + + db->_pluginFacade->setDatabase(db); + + return db; +} + +Database::Database(const shared_ptr& registryAdapter, + const shared_ptr& topicManager, const string& instanceName, - const TraceLevelsPtr& traceLevels, + const shared_ptr& traceLevels, const RegistryInfo& info, bool readonly) : _communicator(registryAdapter->getCommunicator()), @@ -209,8 +216,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(getRegistryPluginFacade())), + _lock(nullptr) { IceDB::ReadWriteTxn txn(_env); @@ -257,13 +264,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(_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 +284,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(_topicManager, toMap(txn, _applications), + getSerial(txn, applicationsDbName)); + _adapterObserverTopic = make_shared(_topicManager, toMap(txn, _adapters), + getSerial(txn, adaptersDbName)); + _objectObserverTopic = make_shared(_topicManager, toMap(txn, _objects), + getSerial(txn, objectsDbName)); txn.commit(); _registryObserverTopic->registryUp(info); - - _pluginFacade->setDatabase(this); } std::string @@ -300,7 +305,7 @@ Database::getInstanceName() const void Database::destroy() { - _pluginFacade->setDatabase(0); + _pluginFacade->setDatabase(nullptr); _registryObserverTopic->destroy(); _nodeObserverTopic->destroy(); @@ -309,31 +314,31 @@ Database::destroy() _objectObserverTopic->destroy(); } -ObserverTopicPtr +shared_ptr 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 +347,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 +364,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 oldApplications; try @@ -433,11 +439,11 @@ Database::syncApplications(const ApplicationInfoSeq& newApplications, Ice::Long } } -#ifdef ICE_CPP11_COMPILER - for_each(entries.begin(), entries.end(), [](const ServerEntryPtr& it) {it->sync(); }); -#else - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); -#endif + for(const auto& entry : entries) + { + entry->sync(); + } + if(_traceLevels->application > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->applicationCat); @@ -450,21 +456,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); @@ -492,21 +498,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); @@ -530,7 +536,7 @@ Database::syncObjects(const ObjectInfoSeq& objects, Ice::Long dbSerial) } ApplicationInfoSeq -Database::getApplications(Ice::Long& serial) +Database::getApplications(long long& serial) { try { @@ -547,7 +553,7 @@ Database::getApplications(Ice::Long& serial) } AdapterInfoSeq -Database::getAdapters(Ice::Long& serial) +Database::getAdapters(long long& serial) { try { @@ -564,7 +570,7 @@ Database::getAdapters(Ice::Long& serial) } ObjectInfoSeq -Database::getObjects(Ice::Long& serial) +Database::getObjects(long long& serial) { try { @@ -588,7 +594,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); @@ -596,10 +602,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); @@ -617,11 +623,10 @@ Database::addApplication(const ApplicationInfo& info, AdminSessionI* session, Ic load(helper, entries, info.uuid, info.revision); startUpdating(info.descriptor.name, info.uuid, info.revision); -#ifdef ICE_CPP11_COMPILER - for_each(entries.begin(), entries.end(), [](const ServerEntryPtr& it) { it->sync(); }); -#else - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); -#endif + for(const auto& entry : entries) + { + entry->sync(); + } serial = _applicationObserverTopic->applicationAdded(dbSerial, info); } catch(const IceDB::KeyTooLongException& ex) @@ -641,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::iterator p = find(_updating.begin(), _updating.end(), info.descriptor.name); assert(p != _updating.end()); p->markUpdated(); @@ -667,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); @@ -675,11 +681,11 @@ Database::addApplication(const ApplicationInfo& info, AdminSessionI* session, Ic dbSerial = removeApplication(info.descriptor.name, txn); txn.commit(); -#ifdef ICE_CPP11_COMPILER - for_each(entries.begin(), entries.end(), [](const ServerEntryPtr& it) { it->sync(); }); -#else - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); -#endif + for(const auto& entry : entries) + { + entry->sync(); + } + serial = _applicationObserverTopic->applicationRemoved(dbSerial, info.descriptor.name); } catch(const DeploymentException& ex) @@ -693,11 +699,10 @@ Database::addApplication(const ApplicationInfo& info, AdminSessionI* session, Ic } _applicationObserverTopic->waitForSyncedSubscribers(serial); -#ifdef ICE_CPP11_COMPILER - for_each(entries.begin(), entries.end(), [](const ServerEntryPtr& it) { it->waitForSyncNoThrow(); }); -#else - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::waitForSyncNoThrow)); -#endif + for(const auto& entry : entries) + { + entry->waitForSyncNoThrow(); + } finishUpdating(info.descriptor.name); throw; } @@ -719,14 +724,14 @@ Database::updateApplication(const ApplicationUpdateInfo& updt, bool noRestart, A ApplicationInfo oldApp; ApplicationUpdateInfo update = updt; - IceInternal::UniquePtr previous; - IceInternal::UniquePtr helper; + unique_ptr previous; + unique_ptr helper; try { - Lock sync(*this); + unique_lock lock(_mutex); checkSessionLock(session); - waitForUpdate(update.descriptor.name); + waitForUpdate(lock, update.descriptor.name); IceDB::ReadOnlyTxn txn(_env); @@ -740,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(_communicator, oldApp.descriptor); + helper = make_unique(_communicator, previous->update(update.descriptor), true); startUpdating(update.descriptor.name, oldApp.uuid, oldApp.revision + 1); } @@ -751,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 @@ -761,14 +766,14 @@ Database::syncApplicationDescriptor(const ApplicationDescriptor& newDesc, bool n ApplicationUpdateInfo update; ApplicationInfo oldApp; - IceInternal::UniquePtr previous; - IceInternal::UniquePtr helper; + unique_ptr previous; + unique_ptr helper; try { - Lock sync(*this); + unique_lock lock(_mutex); checkSessionLock(session); - waitForUpdate(newDesc.name); + waitForUpdate(lock, newDesc.name); IceDB::ReadOnlyTxn txn(_env); @@ -777,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(_communicator, oldApp.descriptor); + helper = make_unique(_communicator, newDesc, true); update.updateTime = IceUtil::Time::now().toMilliSeconds(); update.updateUser = _lockUserId; @@ -793,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 @@ -806,15 +811,15 @@ Database::instantiateServer(const string& application, ApplicationUpdateInfo update; ApplicationInfo oldApp; - IceInternal::UniquePtr previous; - IceInternal::UniquePtr helper; + unique_ptr previous; + unique_ptr helper; try { - Lock sync(*this); + unique_lock lock(_mutex); checkSessionLock(session); - waitForUpdate(application); + waitForUpdate(lock, application); IceDB::ReadOnlyTxn txn(_env); @@ -823,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(_communicator, oldApp.descriptor); + helper = make_unique(_communicator, previous->instantiateServer(node, instance), true); update.updateTime = IceUtil::Time::now().toMilliSeconds(); update.updateUser = _lockUserId; @@ -839,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 @@ -851,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; @@ -885,11 +890,11 @@ Database::removeApplication(const string& name, AdminSessionI* session, Ice::Lon txn.commit(); startUpdating(name, appInfo.uuid, appInfo.revision); -#ifdef ICE_CPP11_COMPILER - for_each(entries.begin(), entries.end(), [](const ServerEntryPtr& it) { it->sync(); }); -#else - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); -#endif + + for(const auto& entry : entries) + { + entry->sync(); + } serial = _applicationObserverTopic->applicationRemoved(dbSerial, name); } catch(const IceDB::LMDBException& ex) @@ -902,11 +907,10 @@ Database::removeApplication(const string& name, AdminSessionI* session, Ice::Lon if(_master) { -#ifdef ICE_CPP11_COMPILER - for_each(entries.begin(), entries.end(), [](const auto& it) { it->waitForSyncNoThrow(); }); -#else - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::waitForSyncNoThrow)); -#endif + for(const auto& entry : entries) + { + entry->waitForSyncNoThrow(); + } } if(_traceLevels->application > 0) @@ -939,20 +943,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 response, function exception) { - Lock sync(*this); + lock_guard lock(_mutex); vector::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(); } } @@ -962,7 +966,7 @@ Database::getNodeCache() return _nodeCache; } -NodeEntryPtr +shared_ptr Database::getNode(const string& name, bool create) const { return _nodeCache.get(name, create); @@ -974,7 +978,7 @@ Database::getReplicaCache() return _replicaCache; } -ReplicaEntryPtr +shared_ptr Database::getReplica(const string& name) const { return _replicaCache.get(name); @@ -986,7 +990,7 @@ Database::getServerCache() return _serverCache; } -ServerEntryPtr +shared_ptr Database::getServer(const string& id) const { return _serverCache.get(id); @@ -998,21 +1002,21 @@ Database::getAllocatableObjectCache() return _allocatableObjectCache; } -AllocatableObjectEntryPtr +shared_ptr 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& 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); @@ -1025,10 +1029,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 @@ -1099,8 +1100,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 +Database::getAdapterDirectProxy(const string& id, const Ice::EncodingVersion& encoding, + const shared_ptr& con, const Ice::Context& ctx) { IceDB::ReadOnlyTxn txn(_env); @@ -1141,10 +1143,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() + "'"); @@ -1210,16 +1212,16 @@ Database::removeAdapter(const string& adapterId) _adapterObserverTopic->waitForSyncedSubscribers(serial); } -AdapterPrx +shared_ptr 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& connection, const Ice::Context& context, LocatorAdapterInfoSeq& adpts, int& count, @@ -1229,13 +1231,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 filters = _pluginFacade->getReplicaGroupFilters(filter); + auto filters = _pluginFacade->getReplicaGroupFilters(filter); if(!filters.empty()) { Ice::StringSeq adapterIds; @@ -1244,9 +1246,9 @@ Database::getLocatorAdapterInfo(const string& id, adapterIds.push_back(q->id); } - for(vector::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; @@ -1269,10 +1271,10 @@ Database::getLocatorAdapterInfo(const string& id, bool Database::addAdapterSyncCallback(const string& id, - const SynchronizationCallbackPtr& callback, + const shared_ptr& callback, const std::set& 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); } @@ -1284,10 +1286,10 @@ Database::getAdapterInfo(const string& id) // server, if that's the case we get the adapter proxy from the // server. // - GetAdapterInfoResultPtr result; + shared_ptr 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&) @@ -1326,7 +1328,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& con, const Ice::Context& ctx) { // // First we check if the given adapter id is associated to a @@ -1336,13 +1338,13 @@ Database::getFilteredAdapterInfo(const string& id, const Ice::ConnectionPtr& con try { AdapterInfoSeq infos; - ReplicaGroupEntryPtr replicaGroup; + shared_ptr 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(entry); } if(replicaGroup) { @@ -1387,8 +1389,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(_adapterCache.get(id)); if(adapter) { return adapter->getServerId(); @@ -1405,7 +1407,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&) @@ -1419,8 +1421,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(_adapterCache.get(id)); if(adapter) { return adapter->getNodeName(); @@ -1435,7 +1437,7 @@ Database::getAdapterNode(const string& id) const Ice::StringSeq Database::getAllAdapters(const string& expression) { - Lock sync(*this); + lock_guard lock(_mutex); vector result; vector ids = _adapterCache.getAll(expression); result.swap(ids); @@ -1478,7 +1480,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)) @@ -1486,7 +1488,7 @@ Database::addObject(const ObjectInfo& info) throw ObjectExistsException(id); } - Ice::Long dbSerial = 0; + long long dbSerial = 0; try { IceDB::ReadWriteTxn txn(_env); @@ -1518,13 +1520,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)) @@ -1574,13 +1576,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" @@ -1620,13 +1622,13 @@ Database::removeObject(const Ice::Identity& id, Ice::Long dbSerial) } void -Database::updateObject(const Ice::ObjectPrx& proxy) +Database::updateObject(const shared_ptr& proxy) { assert(_master); int serial = 0; { - Lock sync(*this); + lock_guard lock(_mutex); const Ice::Identity id = proxy->ice_getIdentity(); if(_objectCache.has(id)) @@ -1671,19 +1673,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(); } @@ -1699,13 +1701,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)) { @@ -1723,7 +1725,7 @@ Database::removeRegistryWellKnownObjects(const ObjectInfoSeq& objects) return _objectObserverTopic->wellKnownObjectsRemoved(objects); } -Ice::ObjectPrx +shared_ptr Database::getObjectProxy(const Ice::Identity& id) { try @@ -1746,8 +1748,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 +Database::getObjectByType(const string& type, const shared_ptr& con, const Ice::Context& ctx) { Ice::ObjectProxySeq objs = getObjectsByType(type, con, ctx); if(objs.empty()) @@ -1757,9 +1759,9 @@ Database::getObjectByType(const string& type, const Ice::ConnectionPtr& con, con return objs[IceUtilInternal::random(static_cast(objs.size()))]; } -Ice::ObjectPrx -Database::getObjectByTypeOnLeastLoadedNode(const string& type, LoadSample sample, const Ice::ConnectionPtr& con, - const Ice::Context& ctx) +shared_ptr +Database::getObjectByTypeOnLeastLoadedNode(const string& type, LoadSample sample, + const shared_ptr& con, const Ice::Context& ctx) { Ice::ObjectProxySeq objs = getObjectsByType(type, con, ctx); if(objs.empty()) @@ -1768,55 +1770,59 @@ Database::getObjectByTypeOnLeastLoadedNode(const string& type, LoadSample sample } IceUtilInternal::shuffle(objs.begin(), objs.end()); - vector > objectsWithLoad; + vector, 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& con, const Ice::Context& ctx) { Ice::ObjectProxySeq proxies; - vector objects = _objectCache.getObjectsByType(type); - for(vector::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 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 filters = _pluginFacade->getTypeFilters(type); + auto filters = _pluginFacade->getTypeFilters(type); if(!filters.empty()) { - for(vector::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); } } } @@ -1828,8 +1834,7 @@ Database::getObjectInfo(const Ice::Identity& id) { try { - ObjectEntryPtr object = _objectCache.get(id); - return object->getObjectInfo(); + return _objectCache.get(id)->getObjectInfo(); } catch(const ObjectNotRegisteredException&) { @@ -1881,7 +1886,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 @@ -1911,7 +1916,7 @@ Database::addInternalObject(const ObjectInfo& info, bool replace) void Database::removeInternalObject(const Ice::Identity& id) { - Lock sync(*this); + lock_guard lock(_mutex); try { @@ -1956,7 +1961,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::const_iterator p = adapterIds.begin(); p != adapterIds.end(); ++p) @@ -1975,7 +1984,10 @@ Database::checkForAddition(const ApplicationHelper& app, const IceDB::ReadWriteT set repGrps; set adptRepGrps; app.getReplicaGroups(repGrps, adptRepGrps); - for_each(adptRepGrps.begin(), adptRepGrps.end(), objFunc(*this, &Database::checkReplicaGroupExists)); + for(const auto& repGrp : adptRepGrps) + { + checkReplicaGroupExists(repGrp); + } } void @@ -1992,15 +2004,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); } } @@ -2008,9 +2023,9 @@ Database::checkForUpdate(const ApplicationHelper& origApp, set_difference(newObjs.begin(), newObjs.end(), oldObjs.begin(), oldObjs.end(), back_inserter(addedObjs)); if(!addedObjs.empty()) { - for(vector::const_iterator p = addedObjs.begin(); p != addedObjs.end(); ++p) + for(const auto& obj : addedObjs) { - checkObjectForAddition(*p, txn); + checkObjectForAddition(obj, txn); } } @@ -2021,12 +2036,18 @@ Database::checkForUpdate(const ApplicationHelper& origApp, set 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 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 invalidAdptRepGrps; set_intersection(rmRepGrps.begin(), rmRepGrps.end(), newAdptRepGrps.begin(), newAdptRepGrps.end(), @@ -2043,7 +2064,11 @@ Database::checkForRemove(const ApplicationHelper& app) set replicaGroups; set adapterReplicaGroups; app.getReplicaGroups(replicaGroups, adapterReplicaGroups); - for_each(replicaGroups.begin(), replicaGroups.end(), objFunc(*this, &Database::checkReplicaGroupForRemove)); + + for(const auto& replicaGroup : replicaGroups) + { + checkReplicaGroupForRemove(replicaGroup); + } } void @@ -2110,10 +2135,10 @@ Database::checkObjectForAddition(const Ice::Identity& objectId, void Database::checkReplicaGroupExists(const string& replicaGroup) { - ReplicaGroupEntryPtr entry; + shared_ptr entry; try { - entry = ReplicaGroupEntryPtr::dynamicCast(_adapterCache.get(replicaGroup)); + entry = dynamic_pointer_cast(_adapterCache.get(replicaGroup)); } catch(const AdapterNotExistException&) { @@ -2128,10 +2153,10 @@ Database::checkReplicaGroupExists(const string& replicaGroup) void Database::checkReplicaGroupForRemove(const string& replicaGroup) { - ReplicaGroupEntryPtr entry; + shared_ptr entry; try { - entry = ReplicaGroupEntryPtr::dynamicCast(_adapterCache.get(replicaGroup)); + entry = dynamic_pointer_cast(_adapterCache.get(replicaGroup)); } catch(const AdapterNotExistException&) { @@ -2159,53 +2184,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 servers = app.getServerInfos(uuid, revision); - for(map::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 servers = app.getServerInfos("", 0); - for(map::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); } } @@ -2222,8 +2244,8 @@ Database::reload(const ApplicationHelper& oldApp, // // Remove destroyed servers. // - map oldServers = oldApp.getServerInfos(uuid, revision); - map newServers = newApp.getServerInfos(uuid, revision); + auto oldServers = oldApp.getServerInfos(uuid, revision); + auto newServers = newApp.getServerInfos(uuid, revision); vector > load; for(map::const_iterator p = newServers.begin(); p != newServers.end(); ++p) { @@ -2239,7 +2261,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); } @@ -2303,7 +2325,7 @@ Database::reload(const ApplicationHelper& oldApp, { try { - ReplicaGroupEntryPtr entry = ReplicaGroupEntryPtr::dynamicCast(_adapterCache.get(r->id)); + auto entry = dynamic_pointer_cast(_adapterCache.get(r->id)); assert(entry); entry->update(application, r->loadBalancing, r->filter); } @@ -2334,16 +2356,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); @@ -2365,21 +2387,21 @@ Database::checkUpdate(const ApplicationHelper& oldApp, map::const_iterator p; vector servers; vector reasons; - vector results; + vector> results; set unreachableNodes; if(noRestart) { for(p = oldServers.begin(); p != oldServers.end(); ++p) { - map::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); @@ -2400,7 +2422,7 @@ Database::checkUpdate(const ApplicationHelper& oldApp, for(p = newServers.begin(); p != newServers.end(); ++p) { - map::const_iterator q = oldServers.find(p->first); + auto q = oldServers.find(p->first); if(q != oldServers.end() && isServerUpdated(p->second, q->second)) { if(noRestart && @@ -2422,7 +2444,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); @@ -2441,11 +2463,11 @@ Database::checkUpdate(const ApplicationHelper& oldApp, } } - for(vector::const_iterator q = results.begin(); q != results.end(); ++q) + for(const auto& result : results) { try { - (*q)->getResult(); + result->getResult(); } catch(const NodeUnreachableException& ex) { @@ -2453,7 +2475,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); } } @@ -2468,15 +2490,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::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"; @@ -2563,18 +2579,18 @@ 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); -#ifdef ICE_CPP11_COMPILER - for_each(entries.begin(), entries.end(), [](const ServerEntryPtr& it) { it->sync(); }); -#else - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); -#endif + for(const auto& entry : entries) + { + entry->sync(); + } + ApplicationInfo info = oldApp; info.updateTime = update.updateTime; info.updateUser = update.updateUser; @@ -2604,8 +2620,8 @@ Database::finishApplicationUpdate(const ApplicationUpdateInfo& update, // for the nodes to start servers. // { - Lock sync(*this); - vector::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(); } @@ -2630,7 +2646,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); @@ -2660,19 +2676,20 @@ Database::finishApplicationUpdate(const ApplicationUpdateInfo& update, assert(p != _updating.end()); p->unmarkUpdated(); -#ifdef ICE_CPP11_COMPILER - for_each(entries.begin(), entries.end(), [](const ServerEntryPtr& it) { it->sync(); }); -#else - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::sync)); -#endif + for(const auto& entry : entries) + { + entry->sync(); + } + serial = _applicationObserverTopic->applicationUpdated(dbSerial, newUpdate); } _applicationObserverTopic->waitForSyncedSubscribers(serial); // Wait for subscriber to be updated. -#ifdef ICE_CPP11_COMPILER - for_each(entries.begin(), entries.end(), [](const ServerEntryPtr& it) { it->waitForSyncNoThrow(); }); -#else - for_each(entries.begin(), entries.end(), IceUtil::voidMemFun(&ServerEntry::waitForSyncNoThrow)); -#endif + + for(const auto& entry : entries) + { + entry->waitForSyncNoThrow(); + } + finishUpdating(newDesc.name); throw; } @@ -2687,12 +2704,9 @@ Database::finishApplicationUpdate(const ApplicationUpdateInfo& update, } void -Database::waitForUpdate(const string& name) +Database::waitForUpdate(unique_lock& 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 @@ -2706,25 +2720,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::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 -#include #include #include #include @@ -25,126 +23,117 @@ namespace IceGrid { -class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; - +class AdminSessionI; +class ApplicationHelper; class NodeSessionI; -typedef IceUtil::Handle NodeSessionIPtr; - class ReplicaSessionI; -typedef IceUtil::Handle ReplicaSessionIPtr; - -class AdminSessionI; - class ServerEntry; -typedef IceUtil::Handle ServerEntryPtr; - -class ApplicationHelper; - -typedef IceDB::Dbi - StringApplicationInfoMap; - -typedef IceDB::Dbi IdentityObjectInfoMap; -typedef IceDB::Dbi StringIdentityMap; - -typedef IceDB::Dbi StringAdapterInfoMap; -typedef IceDB::Dbi StringStringMap; - -typedef IceDB::Dbi StringLongMap; +class TraceLevels; -class Database : public IceUtil::Shared, public IceUtil::Monitor +using StringApplicationInfoMap = IceDB::Dbi; +using IdentityObjectInfoMap = IceDB::Dbi; +using StringIdentityMap = IceDB::Dbi; +using StringAdapterInfoMap = IceDB::Dbi; +using StringStringMap = IceDB::Dbi; +using StringLongMap = IceDB::Dbi; + +class Database final { public: -#ifdef __SUNPRO_CC - using IceUtil::Monitor::lock; - using IceUtil::Monitor::unlock; -#endif - - Database(const Ice::ObjectAdapterPtr&, const IceStorm::TopicManagerPrx&, const std::string&, const TraceLevelsPtr&, - const RegistryInfo&, bool); + static std::shared_ptr + create(const std::shared_ptr&, const std::shared_ptr&, + const std::string&, const std::shared_ptr&, 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& getTraceLevels() const { return _traceLevels; } + const std::shared_ptr& getCommunicator() const { return _communicator; } + const std::shared_ptr& getInternalAdapter() { return _internalAdapter; } void destroy(); - ObserverTopicPtr getObserverTopic(TopicName) const; + std::shared_ptr 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, + std::function); NodeCache& getNodeCache(); - NodeEntryPtr getNode(const std::string&, bool = false) const; + std::shared_ptr getNode(const std::string&, bool = false) const; ReplicaCache& getReplicaCache(); - ReplicaEntryPtr getReplica(const std::string&) const; + std::shared_ptr getReplica(const std::string&) const; ServerCache& getServerCache(); - ServerEntryPtr getServer(const std::string&) const; + std::shared_ptr getServer(const std::string&) const; AllocatableObjectCache& getAllocatableObjectCache(); - AllocatableObjectEntryPtr getAllocatableObject(const Ice::Identity&) const; + std::shared_ptr 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&, + long long = 0); + std::shared_ptr getAdapterDirectProxy(const std::string&, const Ice::EncodingVersion&, + const std::shared_ptr&, + 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 getAdapterProxy(const std::string&, const std::string&, bool); + void getLocatorAdapterInfo(const std::string&, const std::shared_ptr&, const Ice::Context&, LocatorAdapterInfoSeq&, int&, bool&, bool&, const std::set& = std::set()); - bool addAdapterSyncCallback(const std::string&, const SynchronizationCallbackPtr&, + bool addAdapterSyncCallback(const std::string&, const std::shared_ptr&, const std::set& = std::set()); - std::vector > getAdapters(const std::string&, int&, bool&); + std::vector>> 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&, 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&); 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 getObjectProxy(const Ice::Identity&); + std::shared_ptr getObjectByType(const std::string&, + const std::shared_ptr& = nullptr, const Ice::Context& = Ice::Context()); + std::shared_ptr getObjectByTypeOnLeastLoadedNode(const std::string&, LoadSample, + const std::shared_ptr& = nullptr, + const Ice::Context& = Ice::Context()); Ice::ObjectProxySeq getObjectsByType(const std::string&, - const Ice::ConnectionPtr& = Ice::ConnectionPtr(), + const std::shared_ptr& = nullptr, const Ice::Context& = Ice::Context()); ObjectInfo getObjectInfo(const Ice::Identity&); ObjectInfoSeq getObjectInfosByType(const std::string&); @@ -156,6 +145,9 @@ class Database : public IceUtil::Shared, public IceUtil::Monitor private: + Database(const std::shared_ptr&, const std::shared_ptr&, + const std::string&, const std::shared_ptr&, 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 @@ class Database : public IceUtil::Shared, public IceUtil::Monitor 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&, 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 @@ class Database : public IceUtil::Shared, public IceUtil::Monitor 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 _communicator; + const std::shared_ptr _internalAdapter; + const std::shared_ptr _topicManager; const std::string _instanceName; - const TraceLevelsPtr _traceLevels; + const std::shared_ptr _traceLevels; const bool _master; const bool _readonly; @@ -216,11 +208,11 @@ class Database : public IceUtil::Shared, public IceUtil::Monitor AllocatableObjectCache _allocatableObjectCache; ServerCache _serverCache; - RegistryObserverTopicPtr _registryObserverTopic; - NodeObserverTopicPtr _nodeObserverTopic; - ApplicationObserverTopicPtr _applicationObserverTopic; - AdapterObserverTopicPtr _adapterObserverTopic; - ObjectObserverTopicPtr _objectObserverTopic; + std::shared_ptr _registryObserverTopic; + std::shared_ptr _nodeObserverTopic; + std::shared_ptr _applicationObserverTopic; + std::shared_ptr _adapterObserverTopic; + std::shared_ptr _objectObserverTopic; IceUtilInternal::FileLock _dbLock; IceDB::Env _env; @@ -238,7 +230,7 @@ class Database : public IceUtil::Shared, public IceUtil::Monitor StringLongMap _serials; - RegistryPluginFacadeIPtr _pluginFacade; + std::shared_ptr _pluginFacade; AdminSessionI* _lock; std::string _lockUserId; @@ -248,7 +240,7 @@ class Database : public IceUtil::Shared, public IceUtil::Monitor std::string name; std::string uuid; int revision; - std::vector cbs; + std::vector, std::function>> cbs; bool updated; UpdateInfo(const std::string& n, const std::string& u, int r) : @@ -268,10 +260,9 @@ class Database : public IceUtil::Shared, public IceUtil::Monitor void markUpdated() { updated = true; - std::vector::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 @@ class Database : public IceUtil::Shared, public IceUtil::Monitor } }; std::vector _updating; -}; -typedef IceUtil::Handle 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 8d94d61baea..040bf0d5fbf 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& 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& communicator, const XmlAttributesHelper& attrs, const map& 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& communicator, const ApplicationDescriptor& app, const XmlAttributesHelper& attrs, const map& overrides) : @@ -264,7 +264,7 @@ ApplicationDescriptorBuilder::finishReplicaGroup() { if(!_descriptor.replicaGroups.back().loadBalancing) { - _descriptor.replicaGroups.back().loadBalancing = new RandomLoadBalancingPolicy(); + _descriptor.replicaGroups.back().loadBalancing = make_shared(); _descriptor.replicaGroups.back().loadBalancing->nReplicas = "0"; } } @@ -272,23 +272,23 @@ ApplicationDescriptorBuilder::finishReplicaGroup() void ApplicationDescriptorBuilder::setLoadBalancing(const XmlAttributesHelper& attrs) { - LoadBalancingPolicyPtr policy; + shared_ptr policy; string type = attrs("type"); if(type == "random") { - policy = new RandomLoadBalancingPolicy(); + policy = make_shared(); } else if(type == "ordered") { - policy = new OrderedLoadBalancingPolicy(); + policy = make_shared(); } else if(type == "round-robin") { - policy = new RoundRobinLoadBalancingPolicy(); + policy = make_shared(); } else if(type == "adaptive") { - AdaptiveLoadBalancingPolicyPtr alb = new AdaptiveLoadBalancingPolicy(); + auto alb = make_shared(); alb->loadSample = attrs("load-sample", "1"); policy = alb; } @@ -510,7 +510,7 @@ NodeDescriptorBuilder::addServerInstance(const ServerInstanceDescriptor& desc) } void -NodeDescriptorBuilder::addServer(const ServerDescriptorPtr& server) +NodeDescriptorBuilder::addServer(const shared_ptr& server) { _descriptor.servers.push_back(server); } @@ -556,7 +556,7 @@ TemplateDescriptorBuilder::addParameter(const XmlAttributesHelper& attrs) } void -TemplateDescriptorBuilder::setDescriptor(const CommunicatorDescriptorPtr& desc) +TemplateDescriptorBuilder::setDescriptor(const shared_ptr& desc) { _descriptor.descriptor = desc; } @@ -591,13 +591,13 @@ TemplateDescriptorBuilder::createService(const XmlAttributesHelper& attrs) return new ServiceDescriptorBuilder(_application.getCommunicator(), attrs); } -CommunicatorDescriptorBuilder::CommunicatorDescriptorBuilder(const Ice::CommunicatorPtr& communicator) : +CommunicatorDescriptorBuilder::CommunicatorDescriptorBuilder(const shared_ptr& communicator) : _communicator(communicator) { } void -CommunicatorDescriptorBuilder::init(const CommunicatorDescriptorPtr& desc, const XmlAttributesHelper&) +CommunicatorDescriptorBuilder::init(const shared_ptr& desc, const XmlAttributesHelper&) { _descriptor = desc; } @@ -656,7 +656,7 @@ CommunicatorDescriptorBuilder::addAdapter(const XmlAttributesHelper& attrs) else { string fqn = "${server}"; - if(ServiceDescriptorPtr::dynamicCast(_descriptor)) + if(dynamic_pointer_cast(_descriptor)) { fqn += ".${service}"; } @@ -756,20 +756,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& communicator, const XmlAttributesHelper& attrs) : CommunicatorDescriptorBuilder(communicator) { - init(new ServerDescriptor(), attrs); + init(make_shared(), attrs); } -ServerDescriptorBuilder::ServerDescriptorBuilder(const Ice::CommunicatorPtr& communicator) : +ServerDescriptorBuilder::ServerDescriptorBuilder(const shared_ptr& communicator) : CommunicatorDescriptorBuilder(communicator) { } void -ServerDescriptorBuilder::init(const ServerDescriptorPtr& desc, const XmlAttributesHelper& attrs) +ServerDescriptorBuilder::init(const shared_ptr& desc, const XmlAttributesHelper& attrs) { CommunicatorDescriptorBuilder::init(desc, attrs); _descriptor = desc; @@ -810,7 +810,7 @@ ServerDescriptorBuilder::addEnv(const string& v) } void -ServerDescriptorBuilder::addService(const ServiceDescriptorPtr& /*desc*/) +ServerDescriptorBuilder::addService(const shared_ptr& /*desc*/) { assert(false); } @@ -833,15 +833,15 @@ ServerDescriptorBuilder::addDistributionDirectory(const string& directory) _descriptor->distrib.directories.push_back(directory); } -IceBoxDescriptorBuilder::IceBoxDescriptorBuilder(const Ice::CommunicatorPtr& communicator, +IceBoxDescriptorBuilder::IceBoxDescriptorBuilder(const shared_ptr& communicator, const XmlAttributesHelper& attrs) : ServerDescriptorBuilder(communicator) { - init(new IceBoxDescriptor(), attrs); + init(make_shared(), attrs); } void -IceBoxDescriptorBuilder::init(const IceBoxDescriptorPtr& desc, const XmlAttributesHelper& attrs) +IceBoxDescriptorBuilder::init(const shared_ptr& desc, const XmlAttributesHelper& attrs) { ServerDescriptorBuilder::init(desc, attrs); _descriptor = desc; @@ -872,7 +872,7 @@ IceBoxDescriptorBuilder::addServiceInstance(const ServiceInstanceDescriptor& des } void -IceBoxDescriptorBuilder::addService(const ServiceDescriptorPtr& desc) +IceBoxDescriptorBuilder::addService(const shared_ptr& desc) { ServiceInstanceDescriptor instance; assert(desc); @@ -880,15 +880,15 @@ IceBoxDescriptorBuilder::addService(const ServiceDescriptorPtr& desc) _descriptor->services.push_back(instance); } -ServiceDescriptorBuilder::ServiceDescriptorBuilder(const Ice::CommunicatorPtr& communicator, +ServiceDescriptorBuilder::ServiceDescriptorBuilder(const shared_ptr& communicator, const XmlAttributesHelper& attrs) : CommunicatorDescriptorBuilder(communicator) { - init(new ServiceDescriptor(), attrs); + init(make_shared(), attrs); } void -ServiceDescriptorBuilder::init(const ServiceDescriptorPtr& desc, const XmlAttributesHelper& attrs) +ServiceDescriptorBuilder::init(const shared_ptr& 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 bc85441beaf..96a36097bac 100644 --- a/cpp/src/IceGrid/DescriptorBuilder.h +++ b/cpp/src/IceGrid/DescriptorBuilder.h @@ -10,13 +10,6 @@ #include #include -#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&, const std::string&, int); void checkUnknownAttributes(); bool contains(const std::string&) const; @@ -39,7 +32,7 @@ class XmlAttributesHelper private: const IceXML::Attributes& _attributes; - const Ice::LoggerPtr _logger; + const std::shared_ptr _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&); - ApplicationDescriptorBuilder(const Ice::CommunicatorPtr&, const ApplicationDescriptor&, const XmlAttributesHelper&, + ApplicationDescriptorBuilder(const std::shared_ptr&, const XmlAttributesHelper&, const std::map&); + ApplicationDescriptorBuilder(const std::shared_ptr&, const ApplicationDescriptor&, + const XmlAttributesHelper&, const std::map&); const ApplicationDescriptor& getDescriptor() const; @@ -120,11 +113,11 @@ class ApplicationDescriptorBuilder : public DescriptorBuilder bool isOverride(const std::string&); - const Ice::CommunicatorPtr& getCommunicator() const { return _communicator; } + const std::shared_ptr& getCommunicator() const { return _communicator; } private: - Ice::CommunicatorPtr _communicator; + std::shared_ptr _communicator; ApplicationDescriptor _descriptor; std::map _overrides; }; @@ -160,7 +153,7 @@ class NodeDescriptorBuilder : public DescriptorBuilder virtual PropertySetDescriptorBuilder* createPropertySet(const XmlAttributesHelper&) const; void addVariable(const XmlAttributesHelper&); - void addServer(const ServerDescriptorPtr&); + void addServer(const std::shared_ptr&); void addServerInstance(const ServerInstanceDescriptor&); void addPropertySet(const std::string&, const PropertySetDescriptor&); void setDescription(const std::string&); @@ -188,7 +181,7 @@ class TemplateDescriptorBuilder : public DescriptorBuilder virtual ServiceDescriptorBuilder* createService(const XmlAttributesHelper&); void addParameter(const XmlAttributesHelper&); - void setDescriptor(const CommunicatorDescriptorPtr&); + void setDescriptor(const std::shared_ptr&); const std::string& getId() const { return _id; } const TemplateDescriptor& getDescriptor() const { return _descriptor; } @@ -205,9 +198,9 @@ class CommunicatorDescriptorBuilder : public DescriptorBuilder { public: - CommunicatorDescriptorBuilder(const Ice::CommunicatorPtr&); + CommunicatorDescriptorBuilder(const std::shared_ptr&); - void init(const CommunicatorDescriptorPtr&, const XmlAttributesHelper&); + void init(const std::shared_ptr&, const XmlAttributesHelper&); virtual void finish(); virtual void setDescription(const std::string&); @@ -226,11 +219,11 @@ class CommunicatorDescriptorBuilder : public DescriptorBuilder void addProperty(PropertyDescriptorSeq&, const std::string&, const std::string&); PropertyDescriptorSeq _hiddenProperties; - Ice::CommunicatorPtr _communicator; + std::shared_ptr _communicator; private: - CommunicatorDescriptorPtr _descriptor; + std::shared_ptr _descriptor; }; class ServiceInstanceDescriptorBuilder : public DescriptorBuilder @@ -252,66 +245,62 @@ class ServerDescriptorBuilder : public CommunicatorDescriptorBuilder { public: - ServerDescriptorBuilder(const Ice::CommunicatorPtr&, const XmlAttributesHelper&); - ServerDescriptorBuilder(const Ice::CommunicatorPtr&); + ServerDescriptorBuilder(const std::shared_ptr&, const XmlAttributesHelper&); + ServerDescriptorBuilder(const std::shared_ptr&); - void init(const ServerDescriptorPtr&, const XmlAttributesHelper&); + void init(const std::shared_ptr&, 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&); virtual void addServiceInstance(const ServiceInstanceDescriptor&); virtual void addDistribution(const XmlAttributesHelper&); virtual void addDistributionDirectory(const std::string&); - const ServerDescriptorPtr& getDescriptor() const { return _descriptor; } + const std::shared_ptr& getDescriptor() const { return _descriptor; } private: - ServerDescriptorPtr _descriptor; + std::shared_ptr _descriptor; }; class IceBoxDescriptorBuilder : public ServerDescriptorBuilder { public: - IceBoxDescriptorBuilder(const Ice::CommunicatorPtr&, const XmlAttributesHelper&); + IceBoxDescriptorBuilder(const std::shared_ptr&, const XmlAttributesHelper&); - void init(const IceBoxDescriptorPtr&, const XmlAttributesHelper&); + void init(const std::shared_ptr&, const XmlAttributesHelper&); virtual ServiceDescriptorBuilder* createService(const XmlAttributesHelper&); virtual ServiceInstanceDescriptorBuilder* createServiceInstance(const XmlAttributesHelper&); virtual void addAdapter(const XmlAttributesHelper&); virtual void addServiceInstance(const ServiceInstanceDescriptor&); - virtual void addService(const ServiceDescriptorPtr&); + virtual void addService(const std::shared_ptr&); private: - IceBoxDescriptorPtr _descriptor; + std::shared_ptr _descriptor; }; class ServiceDescriptorBuilder : public CommunicatorDescriptorBuilder { public: - ServiceDescriptorBuilder(const Ice::CommunicatorPtr&, const XmlAttributesHelper&); - void init(const ServiceDescriptorPtr&, const XmlAttributesHelper&); + ServiceDescriptorBuilder(const std::shared_ptr&, const XmlAttributesHelper&); + void init(const std::shared_ptr&, const XmlAttributesHelper&); - const ServiceDescriptorPtr& getDescriptor() const { return _descriptor; } + const std::shared_ptr& getDescriptor() const { return _descriptor; } private: - ServiceDescriptorPtr _descriptor; + std::shared_ptr _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 cb85f7a00da..6f0205204c2 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 +const string& getReplicaGroupId(const ReplicaGroupDescriptor& desc) { - const string& - operator()(const ReplicaGroupDescriptor& desc) - { - return desc.id; - } -}; + return desc.id; +} -struct GetAdapterId +const string& getAdapterId(const AdapterDescriptor& desc) { - const string& - operator()(const AdapterDescriptor& desc) - { - return desc.id; - } -}; + return desc.id; +} -struct GetObjectId +const Ice::Identity& getObjectId(const ObjectDescriptor& desc) { - const Ice::Identity& - operator()(const ObjectDescriptor& desc) - { - return desc.id; - } -}; + return desc.id; +} template bool isSeqEqual(const Seq& lseq, const Seq& rseq, GetKeyFunc func, EqFunc eq = equal_to()) @@ -76,162 +57,147 @@ isSeqEqual(const Seq& lseq, const Seq& rseq, GetKeyFunc func, EqFunc eq = equal_ return true; } -struct TemplateDescriptorEqual +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(lhs.descriptor); + auto srhs = dynamic_pointer_cast(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(lhs.descriptor); + auto srhs = dynamic_pointer_cast(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(lhs.descriptor); + auto srhs = dynamic_pointer_cast(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 + 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 +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 +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(lhs.loadBalancing); + auto arhs = dynamic_pointer_cast(rhs.loadBalancing); + if(alhs && arhs && alhs->loadSample != arhs->loadSample) { return false; } - - return true; } -}; + else if(lhs.loadBalancing || rhs.loadBalancing) + { + return false; + } + + return true; +} template Seq getSeqUpdatedElts(const Seq& lseq, const Seq& rseq, GetKeyFunc func) @@ -383,7 +349,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& communicator, bool enableWarning) : _application(&app), _communicator(communicator), _escape(false), @@ -508,7 +474,7 @@ Resolver::Resolver(const Resolver& resolve, } } -Resolver::Resolver(const InternalNodeInfoPtr& info, const Ice::CommunicatorPtr& com) : +Resolver::Resolver(const shared_ptr& info, const shared_ptr& com) : _application(0), _communicator(com), _escape(true), @@ -1060,7 +1026,7 @@ Resolver::checkDeprecated(const string& name) const } } -CommunicatorHelper::CommunicatorHelper(const CommunicatorDescriptorPtr& desc, bool ignoreProps) : +CommunicatorHelper::CommunicatorHelper(const shared_ptr& desc, bool ignoreProps) : _desc(desc), _ignoreProps(ignoreProps) { } @@ -1078,7 +1044,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; } @@ -1148,7 +1114,7 @@ CommunicatorHelper::getReplicaGroups(set& replicaGroups) const } void -CommunicatorHelper::instantiateImpl(const CommunicatorDescriptorPtr& instance, const Resolver& resolve) const +CommunicatorHelper::instantiateImpl(const shared_ptr& instance, const Resolver& resolve) const { instance->description = resolve(_desc->description, "description"); instance->propertySet = resolve(_desc->propertySet); @@ -1212,7 +1178,7 @@ CommunicatorHelper::instantiateImpl(const CommunicatorDescriptorPtr& instance, c } void -CommunicatorHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) const +CommunicatorHelper::print(const shared_ptr& communicator, Output& out) const { if(!_desc->description.empty()) { @@ -1258,7 +1224,7 @@ CommunicatorHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) } void -CommunicatorHelper::printObjectAdapter(const Ice::CommunicatorPtr& communicator, +CommunicatorHelper::printObjectAdapter(const shared_ptr& communicator, Output& out, const AdapterDescriptor& adapter) const { @@ -1332,7 +1298,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& descriptor, bool ignoreProps) : CommunicatorHelper(descriptor, ignoreProps), _desc(descriptor) { @@ -1360,29 +1326,23 @@ ServiceHelper::operator==(const CommunicatorHelper& h) const return true; } -bool -ServiceHelper::operator!=(const CommunicatorHelper& helper) const -{ - return !operator==(helper); -} - -ServiceDescriptorPtr +shared_ptr ServiceHelper::getDescriptor() const { return _desc; } -ServiceDescriptorPtr +shared_ptr ServiceHelper::instantiate(const Resolver& resolver, const PropertyDescriptorSeq& props, const PropertySetDescriptorDict& serviceProps) const { - ServiceDescriptorPtr service = new ServiceDescriptor(); + auto service = make_shared(); instantiateImpl(service, resolver, props, serviceProps); return service; } void -ServiceHelper::instantiateImpl(const ServiceDescriptorPtr& instance, +ServiceHelper::instantiateImpl(const shared_ptr& instance, const Resolver& resolve, const PropertyDescriptorSeq& props, const PropertySetDescriptorDict& serviceProps) const @@ -1401,7 +1361,7 @@ ServiceHelper::instantiateImpl(const ServiceDescriptorPtr& instance, } void -ServiceHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) const +ServiceHelper::print(const shared_ptr& communicator, Output& out) const { out << "service `" + _desc->name + "'"; out << sb; @@ -1410,7 +1370,7 @@ ServiceHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) cons out << eb; } -ServerHelper::ServerHelper(const ServerDescriptorPtr& descriptor, bool ignoreProps) : +ServerHelper::ServerHelper(const shared_ptr& descriptor, bool ignoreProps) : CommunicatorHelper(descriptor, ignoreProps), _desc(descriptor) { @@ -1490,19 +1450,13 @@ ServerHelper::operator==(const CommunicatorHelper& h) const return true; } -bool -ServerHelper::operator!=(const CommunicatorHelper& helper) const -{ - return !operator==(helper); -} - -ServerDescriptorPtr +shared_ptr ServerHelper::getDescriptor() const { return _desc; } -ServerDescriptorPtr +shared_ptr ServerHelper::instantiate(const Resolver& resolver, const PropertyDescriptorSeq& props, const PropertySetDescriptorDict& serviceProps) const @@ -1512,19 +1466,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(); instantiateImpl(server, resolver, props); return server; } void -ServerHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) const +ServerHelper::print(const shared_ptr& 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& communicator, Output& out, const ServerInfo& info) const { out << "server `" + _desc->id + "'"; out << sb; @@ -1533,7 +1487,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& communicator, Output& out, const ServerInfo& info) const { if(!info.application.empty()) { @@ -1600,7 +1554,7 @@ ServerHelper::printImpl(const Ice::CommunicatorPtr& communicator, Output& out, c } void -ServerHelper::instantiateImpl(const ServerDescriptorPtr& instance, +ServerHelper::instantiateImpl(const shared_ptr& instance, const Resolver& resolve, const PropertyDescriptorSeq& props) const { @@ -1630,7 +1584,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& descriptor, bool ignoreProps) : ServerHelper(descriptor, ignoreProps), _desc(descriptor) { @@ -1657,18 +1611,12 @@ IceBoxHelper::operator==(const CommunicatorHelper& h) const return true; } -bool -IceBoxHelper::operator!=(const CommunicatorHelper& helper) const -{ - return !operator==(helper); -} - -ServerDescriptorPtr +shared_ptr IceBoxHelper::instantiate(const Resolver& resolver, const PropertyDescriptorSeq& props, const PropertySetDescriptorDict& serviceProps) const { - IceBoxDescriptorPtr iceBox = new IceBoxDescriptor(); + auto iceBox = make_shared(); instantiateImpl(iceBox, resolver, props, serviceProps); return iceBox; } @@ -1694,13 +1642,13 @@ IceBoxHelper::getReplicaGroups(set& replicaGroups) const } void -IceBoxHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) const +IceBoxHelper::print(const shared_ptr& 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& communicator, Output& out, const ServerInfo& info) const { out << "icebox `" + _desc->id + "'"; out << sb; @@ -1720,7 +1668,7 @@ IceBoxHelper::print(const Ice::CommunicatorPtr& communicator, Output& out, const } void -IceBoxHelper::instantiateImpl(const IceBoxDescriptorPtr& instance, +IceBoxHelper::instantiateImpl(const shared_ptr& instance, const Resolver& resolver, const PropertyDescriptorSeq& props, const PropertySetDescriptorDict& serviceProps) const @@ -1846,7 +1794,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(tmpl.descriptor)); parameterValues = instantiateParams(resolve, _def._cpp_template, _def.parameterValues, @@ -1893,7 +1841,7 @@ ServiceInstanceHelper::getReplicaGroups(set& replicaGroups) const } void -ServiceInstanceHelper::print(const Ice::CommunicatorPtr& communicator, Output& out) const +ServiceInstanceHelper::print(const shared_ptr& communicator, Output& out) const { if(_service.getDescriptor()) { @@ -1924,7 +1872,7 @@ ServerInstanceHelper::ServerInstanceHelper(const ServerInstanceDescriptor& desc, init(0, resolve, instantiate); } -ServerInstanceHelper::ServerInstanceHelper(const ServerDescriptorPtr& definition, +ServerInstanceHelper::ServerInstanceHelper(const shared_ptr& definition, const Resolver& resolve, bool instantiate) : _def(ServerInstanceDescriptor()) @@ -1933,12 +1881,12 @@ ServerInstanceHelper::ServerInstanceHelper(const ServerDescriptorPtr& definition } void -ServerInstanceHelper::init(const ServerDescriptorPtr& definition, const Resolver& resolve, bool instantiate) +ServerInstanceHelper::init(const shared_ptr& definition, const Resolver& resolve, bool instantiate) { // // Get the server definition if it's not provided. // - ServerDescriptorPtr def = definition; + auto def = definition; std::map parameterValues; if(!def) { @@ -1951,7 +1899,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(tmpl.descriptor); parameterValues = instantiateParams(resolve, _def._cpp_template, _def.parameterValues, @@ -2007,8 +1955,8 @@ ServerInstanceHelper::init(const ServerDescriptorPtr& definition, const Resolver // // Instantiate the server definition. // - ServerDescriptorPtr inst = _serverDefinition->instantiate(svrResolve, _instance.propertySet.properties, - _instance.servicePropertySets); + shared_ptr inst = _serverDefinition->instantiate(svrResolve, _instance.propertySet.properties, + _instance.servicePropertySets); _serverInstance = createHelper(inst); } @@ -2054,14 +2002,14 @@ ServerInstanceHelper::getInstance() const return _instance; } -ServerDescriptorPtr +shared_ptr ServerInstanceHelper::getServerDefinition() const { assert(_def._cpp_template.empty()); return _serverDefinition->getDescriptor(); } -ServerDescriptorPtr +shared_ptr ServerInstanceHelper::getServerInstance() const { assert(_serverInstance); @@ -2196,12 +2144,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(_def.loadFactor); } if(_def.description != helper._def.description) { - update.description = new BoxedString(_def.description); + update.description = make_shared(_def.description); } update.variables = getDictUpdatedElts(helper._def.variables, _def.variables); @@ -2598,7 +2546,7 @@ NodeHelper::printDiff(Output& out, const NodeHelper& helper) const out << eb; } -ApplicationHelper::ApplicationHelper(const Ice::CommunicatorPtr& communicator, +ApplicationHelper::ApplicationHelper(const shared_ptr& communicator, const ApplicationDescriptor& appDesc, bool enableWarning, bool instantiate) : @@ -2638,7 +2586,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(r->loadBalancing->ice_clone()); desc.loadBalancing->nReplicas = resolve.asInt(r->loadBalancing->nReplicas, "replica group number of replicas"); if(desc.loadBalancing->nReplicas.empty()) @@ -2649,7 +2597,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(desc.loadBalancing); if(al) { al->loadSample = resolve(al->loadSample, "replica group load sample"); @@ -2746,7 +2694,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(_def.description); } updt.variables = getDictUpdatedElts(helper._def.variables, _def.variables); @@ -2757,18 +2705,15 @@ ApplicationHelper::diff(const ApplicationHelper& helper) const if(_def.distrib != helper._def.distrib) { - updt.distrib = new BoxedDistributionDescriptor(_def.distrib); + updt.distrib = make_shared(_def.distrib); } - 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); @@ -2783,8 +2728,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(node.loadFactor); + nodeUpdate.description = make_shared(node.description); updt.nodes.push_back(nodeUpdate); } else @@ -2801,12 +2746,11 @@ 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.distrib = updt.distrib ? updt.distrib->value : _def.distrib; - 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); @@ -3052,19 +2996,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(p->loadBalancing)) { out << "random"; } - else if(OrderedLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) - { - out << "ordered"; - } - else if(RoundRobinLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) + else if(dynamic_pointer_cast(p->loadBalancing)) { out << "round-robin"; } - else if(AdaptiveLoadBalancingPolicyPtr::dynamicCast(p->loadBalancing)) + else if(dynamic_pointer_cast(p->loadBalancing)) { out << "adaptive" ; } @@ -3147,11 +3087,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"; @@ -3187,9 +3125,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()) { @@ -3217,9 +3154,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()) { @@ -3280,10 +3216,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& lhs, const shared_ptr& rhs, bool ignoreProps) { - IceBoxDescriptorPtr lhsIceBox = IceBoxDescriptorPtr::dynamicCast(lhs); - IceBoxDescriptorPtr rhsIceBox = IceBoxDescriptorPtr::dynamicCast(rhs); + auto lhsIceBox = dynamic_pointer_cast(lhs); + auto rhsIceBox = dynamic_pointer_cast(rhs); if(lhsIceBox && rhsIceBox) { return IceBoxHelper(lhsIceBox, ignoreProps) == IceBoxHelper(rhsIceBox, ignoreProps); @@ -3298,17 +3234,17 @@ IceGrid::descriptorEqual(const ServerDescriptorPtr& lhs, const ServerDescriptorP } } -ServerHelperPtr -IceGrid::createHelper(const ServerDescriptorPtr& desc) +shared_ptr +IceGrid::createHelper(const shared_ptr& desc) { - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(desc); + auto iceBox = dynamic_pointer_cast(desc); if(iceBox) { - return new IceBoxHelper(iceBox); + return make_shared(iceBox); } else { - return new ServerHelper(desc); + return make_shared(desc); } } diff --git a/cpp/src/IceGrid/DescriptorHelper.h b/cpp/src/IceGrid/DescriptorHelper.h index 66a657a9a5d..7a0e483c7a7 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&, bool); Resolver(const Resolver&, const std::map&, bool); - Resolver(const InternalNodeInfoPtr&, const Ice::CommunicatorPtr&); + Resolver(const std::shared_ptr&, const std::shared_ptr&); std::string operator()(const std::string&, const std::string& = std::string(), bool = true) const; Ice::StringSeq operator()(const Ice::StringSeq&, const std::string&) const; @@ -52,7 +52,7 @@ class Resolver TemplateDescriptor getServiceTemplate(const std::string&) const; bool hasReplicaGroup(const std::string&) const; - Ice::CommunicatorPtr getCommunicator() const { return _communicator; } + std::shared_ptr getCommunicator() const { return _communicator; } bool warningEnabled() const { return _enableWarning; } private: @@ -66,7 +66,7 @@ class Resolver void checkDeprecated(const std::string&) const; const ApplicationDescriptor* _application; - const Ice::CommunicatorPtr _communicator; + const std::shared_ptr _communicator; const bool _escape; const bool _enableWarning; std::string _context; @@ -83,89 +83,86 @@ class CommunicatorHelper { public: - CommunicatorHelper(const CommunicatorDescriptorPtr&, bool = false); CommunicatorHelper() : _ignoreProps(false) { } - virtual ~CommunicatorHelper() { } + CommunicatorHelper(const std::shared_ptr&, 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::multiset&) const; virtual void getReplicaGroups(std::set&) const; - void print(const Ice::CommunicatorPtr&, IceUtilInternal::Output&) const; + void print(const std::shared_ptr&, IceUtilInternal::Output&) const; protected: - void printObjectAdapter(const Ice::CommunicatorPtr&, IceUtilInternal::Output&, const AdapterDescriptor&) const; + void printObjectAdapter(const std::shared_ptr&, 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&, const Resolver&) const; private: - CommunicatorDescriptorPtr _desc; + std::shared_ptr _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&, 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 getDescriptor() const; + std::shared_ptr instantiate(const Resolver&, const PropertyDescriptorSeq&, + const PropertySetDescriptorDict&) const; - void print(const Ice::CommunicatorPtr&, IceUtilInternal::Output&) const; + void print(const std::shared_ptr&, IceUtilInternal::Output&) const; protected: using CommunicatorHelper::instantiateImpl; - void instantiateImpl(const ServiceDescriptorPtr&, const Resolver&, const PropertyDescriptorSeq&, + void instantiateImpl(const std::shared_ptr&, const Resolver&, const PropertyDescriptorSeq&, const PropertySetDescriptorDict&) const; private: - ServiceDescriptorPtr _desc; + std::shared_ptr _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&, 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 getDescriptor() const; + virtual std::shared_ptr 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&, IceUtilInternal::Output&) const; + void print(const std::shared_ptr&, 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&, IceUtilInternal::Output&, const ServerInfo&) const; + void instantiateImpl(const std::shared_ptr&, const Resolver&, const PropertyDescriptorSeq&) const; private: - ServerDescriptorPtr _desc; + std::shared_ptr _desc; }; -typedef IceUtil::Handle ServerHelperPtr; class InstanceHelper { @@ -178,7 +175,7 @@ class InstanceHelper const std::map&) const; }; -class ServiceInstanceHelper : public InstanceHelper +class ServiceInstanceHelper final : public InstanceHelper { public: @@ -191,7 +188,7 @@ class ServiceInstanceHelper : public InstanceHelper void getIds(std::multiset&, std::multiset&) const; void getReplicaGroups(std::set&) const; - void print(const Ice::CommunicatorPtr&, IceUtilInternal::Output&) const; + void print(const std::shared_ptr&, IceUtilInternal::Output&) const; private: @@ -199,47 +196,42 @@ class ServiceInstanceHelper : public InstanceHelper 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&, 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 instantiate(const Resolver&, const PropertyDescriptorSeq&, + const PropertySetDescriptorDict&) const override; - virtual void getIds(std::multiset&, std::multiset&) const; - virtual void getReplicaGroups(std::set&) const; + void getIds(std::multiset&, std::multiset&) const override; + void getReplicaGroups(std::set&) 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&, IceUtilInternal::Output&) const; + void print(const std::shared_ptr&, 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&, const Resolver&, const PropertyDescriptorSeq&, const PropertySetDescriptorDict&) const; private: - IceBoxDescriptorPtr _desc; + std::shared_ptr _desc; std::vector _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&, const Resolver&, bool); bool operator==(const ServerInstanceHelper&) const; bool operator!=(const ServerInstanceHelper&) const; @@ -248,33 +240,32 @@ class ServerInstanceHelper : public InstanceHelper ServerInstanceDescriptor getDefinition() const; ServerInstanceDescriptor getInstance() const; - ServerDescriptorPtr getServerDefinition() const; - ServerDescriptorPtr getServerInstance() const; + std::shared_ptr getServerDefinition() const; + std::shared_ptr getServerInstance() const; void getIds(std::multiset&, std::multiset&) const; void getReplicaGroups(std::set&) const; private: - void init(const ServerDescriptorPtr&, const Resolver&, bool); + void init(const std::shared_ptr&, const Resolver&, bool); ServerInstanceDescriptor _def; std::string _id; ServerInstanceDescriptor _instance; - ServerHelperPtr _serverDefinition; - ServerHelperPtr _serverInstance; + std::shared_ptr _serverDefinition; + std::shared_ptr _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; @@ -304,11 +295,11 @@ class NodeHelper ServerInstanceHelperDict _servers; }; -class ApplicationHelper +class ApplicationHelper final { public: - ApplicationHelper(const Ice::CommunicatorPtr&, const ApplicationDescriptor&, bool = false, bool = true); + ApplicationHelper(const std::shared_ptr&, const ApplicationDescriptor&, bool = false, bool = true); ApplicationUpdateDescriptor diff(const ApplicationHelper&) const; ApplicationDescriptor update(const ApplicationUpdateDescriptor&) const; @@ -326,16 +317,16 @@ class ApplicationHelper private: - Ice::CommunicatorPtr _communicator; + std::shared_ptr _communicator; ApplicationDescriptor _def; ApplicationDescriptor _instance; - typedef std::map NodeHelperDict; + using NodeHelperDict = std::map; NodeHelperDict _nodes; }; -bool descriptorEqual(const ServerDescriptorPtr&, const ServerDescriptorPtr&, bool = false); -ServerHelperPtr createHelper(const ServerDescriptorPtr&); +bool descriptorEqual(const std::shared_ptr&, const std::shared_ptr&, bool = false); +std::shared_ptr createHelper(const std::shared_ptr&); bool isServerUpdated(const ServerInfo&, const ServerInfo&, bool = false); } diff --git a/cpp/src/IceGrid/DescriptorParser.cpp b/cpp/src/IceGrid/DescriptorParser.cpp index 2db3506aaee..0a322d33666 100644 --- a/cpp/src/IceGrid/DescriptorParser.cpp +++ b/cpp/src/IceGrid/DescriptorParser.cpp @@ -17,22 +17,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&); - void setAdmin(const IceGrid::AdminPrx&); + void setAdmin(const shared_ptr&); void setVariables(const map&, const vector&); - 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; @@ -44,8 +44,8 @@ class DescriptorHandler : public IceXML::Handler void error(const string&) const; bool isTargetDeployable(const string&) const; - const Ice::CommunicatorPtr _communicator; - IceGrid::AdminPrx _admin; + const shared_ptr _communicator; + shared_ptr _admin; string _filename; map _overrides; vector _targets; @@ -56,15 +56,15 @@ class DescriptorHandler : public IceXML::Handler int _line; int _column; - IceInternal::UniquePtr _currentApplication; - IceInternal::UniquePtr _currentNode; - IceInternal::UniquePtr _currentTemplate; - IceInternal::UniquePtr _currentServerInstance; - IceInternal::UniquePtr _currentServiceInstance; - IceInternal::UniquePtr _currentServer; - IceInternal::UniquePtr _currentService; + unique_ptr _currentApplication; + unique_ptr _currentNode; + unique_ptr _currentTemplate; + unique_ptr _currentServerInstance; + unique_ptr _currentServiceInstance; + unique_ptr _currentServer; + unique_ptr _currentService; CommunicatorDescriptorBuilder* _currentCommunicator; - IceInternal::UniquePtr _currentPropertySet; + unique_ptr _currentPropertySet; bool _isTopLevel; bool _inAdapter; @@ -72,13 +72,11 @@ class DescriptorHandler : public IceXML::Handler bool _inDistrib; }; -} - -DescriptorHandler::DescriptorHandler(const string& filename, const Ice::CommunicatorPtr& communicator) : +DescriptorHandler::DescriptorHandler(const string& filename, const shared_ptr& communicator) : _communicator(communicator), _filename(filename), _isCurrentTargetDeployable(true), - _currentCommunicator(0), + _currentCommunicator(nullptr), _isTopLevel(true), _inAdapter(false), _inReplicaGroup(false) @@ -86,7 +84,7 @@ DescriptorHandler::DescriptorHandler(const string& filename, const Ice::Communic } void -DescriptorHandler::setAdmin(const AdminPrx& admin) +DescriptorHandler::setAdmin(const shared_ptr& admin) { _admin = admin; } @@ -489,7 +487,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") { @@ -504,14 +502,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") { @@ -525,26 +523,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") { @@ -578,7 +576,7 @@ DescriptorHandler::endElement(const string& name, int line, int column) { assert(false); } - _currentPropertySet.reset(0); + _currentPropertySet.reset(nullptr); } } else if(name == "description") @@ -822,12 +820,14 @@ DescriptorHandler::isTargetDeployable(const string& target) const return false; } +} + ApplicationDescriptor DescriptorParser::parseDescriptor(const string& descriptor, const Ice::StringSeq& targets, const map& variables, - const Ice::CommunicatorPtr& communicator, - const IceGrid::AdminPrx& admin) + const shared_ptr& communicator, + const shared_ptr& admin) { string filename = IcePatch2Internal::simplify(descriptor); DescriptorHandler handler(filename, communicator); @@ -838,7 +838,7 @@ DescriptorParser::parseDescriptor(const string& descriptor, } ApplicationDescriptor -DescriptorParser::parseDescriptor(const string& descriptor, const Ice::CommunicatorPtr& communicator) +DescriptorParser::parseDescriptor(const string& descriptor, const shared_ptr& communicator) { string filename = IcePatch2Internal::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&, - const Ice::CommunicatorPtr&, - const IceGrid::AdminPrx&); +ApplicationDescriptor parseDescriptor(const std::string&, + const Ice::StringSeq&, + const std::map&, + const std::shared_ptr&, + const std::shared_ptr&); - static ApplicationDescriptor parseDescriptor(const std::string&, const Ice::CommunicatorPtr&); +ApplicationDescriptor parseDescriptor(const std::string&, const std::shared_ptr&); -}; +} } diff --git a/cpp/src/IceGrid/FileCache.cpp b/cpp/src/IceGrid/FileCache.cpp index 628e54ca989..8ec3ca39adb 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) : +FileCache::FileCache(const shared_ptr& com) : _messageSizeMax(com->getProperties()->getPropertyAsIntWithDefault("Ice.MessageSizeMax", 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 @@ -122,7 +122,7 @@ 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); diff --git a/cpp/src/IceGrid/FileCache.h b/cpp/src/IceGrid/FileCache.h index 12751665402..a6a6b441918 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 #include #include namespace IceGrid { -class FileCache : public IceUtil::Shared +class FileCache { public: - FileCache(const Ice::CommunicatorPtr&); + FileCache(const std::shared_ptr&); - 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; }; -typedef IceUtil::Handle FileCachePtr; }; diff --git a/cpp/src/IceGrid/FileParserI.cpp b/cpp/src/IceGrid/FileParserI.cpp index fefe366a693..9de1845173b 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 admin, const Ice::Current& current) { try { - return DescriptorParser::parseDescriptor(file, Ice::StringSeq(), map(), - current.adapter->getCommunicator(), admin); + return DescriptorParser::parseDescriptor(std::move(file), Ice::StringSeq(), map(), + current.adapter->getCommunicator(), std::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 -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 admin, const Ice::Current&) override; }; +} + #endif diff --git a/cpp/src/IceGrid/FileUserAccountMapperI.cpp b/cpp/src/IceGrid/FileUserAccountMapperI.cpp index a9a1ef6dd77..a57e5aa0def 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::const_iterator p = _accounts.find(user); + map::const_iterator p = _accounts.find(std::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 @@ class FileUserAccountMapperI : public UserAccountMapper 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/IceGridNode.cpp b/cpp/src/IceGrid/IceGridNode.cpp index bbbc33ed72e..d685fc53f17 100644 --- a/cpp/src/IceGrid/IceGridNode.cpp +++ b/cpp/src/IceGrid/IceGridNode.cpp @@ -35,60 +35,58 @@ using namespace IceGrid; namespace { -class ProcessI : public Process +class ProcessI final : public Process { public: - ProcessI(const ActivatorPtr&, const ProcessPtr&); + ProcessI(const shared_ptr&, const shared_ptr&); - 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; + shared_ptr _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 initializeCommunicator(int&, char*[], const InitializationData&, int) override; private: void usage(const std::string&); - ActivatorPtr _activator; + shared_ptr _activator; IceUtil::TimerPtr _timer; - RegistryIPtr _registry; - NodeIPtr _node; - IceInternal::UniquePtr _sessions; - Ice::ObjectAdapterPtr _adapter; + shared_ptr _registry; + shared_ptr _node; + unique_ptr _sessions; + shared_ptr _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&, const shared_ptr&, bool, bool, const std::string&, + const std::string&); + void shutdown() override; private: - ActivatorPtr _activator; + shared_ptr _activator; }; #ifdef _WIN32 @@ -110,13 +108,13 @@ setNoIndexingAttribute(const string& path) } -CollocatedRegistry::CollocatedRegistry(const CommunicatorPtr& com, - const ActivatorPtr& activator, +CollocatedRegistry::CollocatedRegistry(const shared_ptr& com, + const shared_ptr& 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(com, "IceGrid.Registry"), nowarn, readonly, initFromReplica, nodeName), _activator(activator) { } @@ -127,7 +125,7 @@ CollocatedRegistry::shutdown() _activator->shutdown(); } -ProcessI::ProcessI(const ActivatorPtr& activator, const ProcessPtr& origProcess) : +ProcessI::ProcessI(const shared_ptr& activator, const shared_ptr& origProcess) : _activator(activator), _origProcess(origProcess) { @@ -140,17 +138,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(std::move(message), std::move(fd), current); } bool @@ -257,7 +247,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()) @@ -292,15 +282,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(communicator(), "IceGrid.Node"); + _activator = make_shared(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(communicator(), _activator, nowarn, readonly, initFromReplica, name); if(!_registry->start()) { return false; @@ -399,12 +389,12 @@ NodeService::startImpl(int argc, char* argv[], int& status) // string mapperProperty = "IceGrid.Node.UserAccountMapper"; string mapperPropertyValue = properties->getProperty(mapperProperty); - UserAccountMapperPrx mapper; + shared_ptr mapper; if(!mapperPropertyValue.empty()) { try { - mapper = UserAccountMapperPrx::uncheckedCast(communicator()->propertyToProxy(mapperProperty)); + mapper = uncheckedCast(communicator()->propertyToProxy(mapperProperty)); } catch(const std::exception& ex) { @@ -420,8 +410,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(userAccountFileProperty)); + mapper = uncheckedCast(object); } catch(const exception& ex) { @@ -434,7 +424,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. @@ -453,7 +443,7 @@ NodeService::startImpl(int argc, char* argv[], int& status) instanceName = "IceGrid"; } - _sessions.reset(new NodeSessionManager(communicator(), instanceName)); + _sessions = make_unique(communicator(), instanceName); // // Create the server factory. The server factory creates persistent objects @@ -461,18 +451,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(_adapter->createProxy(id)); + _node = make_shared(_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(_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(_node), instanceName + "-NodeRouter"); // // Start the platform info thread if needed. @@ -508,13 +499,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(communicator()->removeAdminFacet("Process")); + communicator()->addAdminFacet(make_shared(_activator, origProcess), "Process"); + communicator()->createAdmin(_adapter, { "NodeAdmin-" + name, instanceName }); } // @@ -555,11 +542,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(communicator()->getDefaultLocator()->findObjectById(regId)); if(!registry) { throw runtime_error("invalid registry"); @@ -567,7 +552,7 @@ NodeService::startImpl(int argc, char* argv[], int& status) registry = registry->ice_preferSecure(true); // Use SSL if available. - IceGrid::AdminSessionPrx session; + shared_ptr session; if(communicator()->getProperties()->getPropertyAsInt("IceGridAdmin.AuthenticateUsingSSL")) { session = registry->createAdminSessionFromSecureConnection(); @@ -594,9 +579,9 @@ NodeService::startImpl(int argc, char* argv[], int& status) } assert(session); - AdminPrx admin = session->getAdmin(); + auto admin = session->getAdmin(); map vars; - ApplicationDescriptor app = DescriptorParser::parseDescriptor(desc, targets, vars, communicator(), admin); + auto app = DescriptorParser::parseDescriptor(desc, targets, vars, communicator(), admin); try { @@ -675,7 +660,7 @@ NodeService::stop() { assert(false); } - _timer = 0; + _timer = nullptr; } // @@ -686,7 +671,7 @@ NodeService::stop() try { _adapter->deactivate(); - _adapter = 0; + _adapter = nullptr; } catch(const std::exception& ex) { @@ -731,7 +716,7 @@ NodeService::stop() if(_node) { _node->shutdown(); - _node = 0; + _node = nullptr; } // @@ -740,13 +725,13 @@ NodeService::stop() if(_registry) { _registry->stop(); - _registry = 0; + _registry = nullptr; } return true; } -CommunicatorPtr +shared_ptr NodeService::initializeCommunicator(int& argc, char* argv[], const InitializationData& initializationData, int version) @@ -762,20 +747,20 @@ NodeService::initializeCommunicator(int& argc, char* argv[], vTypes.push_back(""); vTypes.push_back("Admin"); - for(vector::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 initializeCommunicator(int&, char*[], const InitializationData&, int) override; private: void usage(const std::string&); - RegistryIPtr _registry; + shared_ptr _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(communicator(), "IceGrid.Registry"); - _registry = new RegistryI(communicator(), traceLevels, nowarn, readonly, initFromReplica, ""); + _registry = make_shared(communicator(), traceLevels, nowarn, readonly, initFromReplica, ""); if(!_registry->start()) { return false; @@ -153,7 +142,7 @@ RegistryService::stop() return true; } -CommunicatorPtr +shared_ptr 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 5e32a02570d..da37691f9ef 100644 --- a/cpp/src/IceGrid/Internal.ice +++ b/cpp/src/IceGrid/Internal.ice @@ -8,8 +8,7 @@ #include #include -#include - +#include #include #include #include @@ -266,11 +265,12 @@ interface Node extends FileReader, ReplicaObserver /// Patch application and server distributions. If some servers using a distribution directory to patch are active, /// this method will raise a PatchException unless shutdown is set to true. In which case the servers will be /// shutdown. - ["amd"] idempotent void patch(PatcherFeedback* feedback, - string application, - string server, - InternalDistributionDescriptor appDistrib, - bool shutdown); + ["amd"] idempotent void patch( + PatcherFeedback* feedback, + string application, + string server, + InternalDistributionDescriptor appDistrib, + bool shutdown); /// Establish a session to the given replica, this method only returns once the registration was attempted (unlike /// replicaAdded below). @@ -336,11 +336,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..b9ae61dea7d 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& registry, + const shared_ptr& database, + const shared_ptr& reaper, + const shared_ptr& wellKnownObjects, ReplicaSessionManager& session) : _registry(registry), _database(database), _reaper(reaper), _wellKnownObjects(wellKnownObjects), - _fileCache(new FileCache(database->getCommunicator())), + _fileCache(make_shared(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 +InternalRegistryI::registerNode(shared_ptr info, shared_ptr 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(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(logger, session), _nodeSessionTimeout); + auto session = NodeSessionI::create(_database, node, info, _nodeSessionTimeout, load); + _reaper->add(make_shared>(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 +InternalRegistryI::registerReplica(shared_ptr info, + shared_ptr 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(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(logger, s), _replicaSessionTimeout); + auto s = ReplicaSessionI::create(_database, _wellKnownObjects, info, prx, _replicaSessionTimeout); + _reaper->add(make_shared>(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 replica, const Ice::Current&) { - _session.create(replica); + _session.create(std::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(*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(*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 DatabasePtr; - class FileCache; -typedef IceUtil::Handle FileCachePtr; - -class WellKnownObjectsManager; -typedef IceUtil::Handle WellKnownObjectsManagerPtr; - class ReapThread; -typedef IceUtil::Handle ReapThreadPtr; - class RegistryI; -typedef IceUtil::Handle 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&, const std::shared_ptr&, + const std::shared_ptr&, const std::shared_ptr&, + 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 registerNode(std::shared_ptr, std::shared_ptr, LoadInfo, + const Ice::Current&) override; + std::shared_ptr registerReplica(std::shared_ptr, + std::shared_ptr, + const Ice::Current&) override; - virtual void registerWithReplica(const InternalRegistryPrx&, const Ice::Current&); + void registerWithReplica(std::shared_ptr, 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 _registry; + const std::shared_ptr _database; + const std::shared_ptr _reaper; + const std::shared_ptr _wellKnownObjects; + const std::shared_ptr _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 4b69434e37e..e4418fb654b 100644 --- a/cpp/src/IceGrid/LocatorI.cpp +++ b/cpp/src/IceGrid/LocatorI.cpp @@ -12,151 +12,23 @@ #include "SynchronizationException.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&)> response, + function exception, + const shared_ptr& locator, const Ice::EncodingVersion& encoding, const LocatorAdapterInfo& adapter) : - _amdCB(amdCB), + _response(std::move(response)), + _exception(std::move(exception)), _locator(locator), _encoding(encoding), _adapter(adapter), @@ -165,20 +37,20 @@ class AdapterRequest : public LocatorI::Request 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& proxy) override { assert(proxy); @@ -187,49 +59,52 @@ class AdapterRequest : public LocatorI::Request // 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&)> _response; + const function _exception; + const shared_ptr _locator; const Ice::EncodingVersion _encoding; const LocatorAdapterInfo _adapter; - const TraceLevelsPtr _traceLevels; + const shared_ptr _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&)> response, + function exception, + const shared_ptr& locator, const string& id, const Ice::EncodingVersion& encoding, const LocatorAdapterInfoSeq& adapters, int count, - Ice::ObjectPrx firstProxy) : - _amdCB(amdCB), + shared_ptr firstProxy) : + _response(std::move(response)), + _exception(std::move(exception)), _locator(locator), _id(id), _encoding(encoding), @@ -256,15 +131,15 @@ class ReplicaGroupRequest : public LocatorI::Request, public IceUtil::Mutex } } - 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(_proxies.size()); i < _count; ++i) { if(_lastAdapter == _adapters.end()) @@ -288,17 +163,17 @@ class ReplicaGroupRequest : public LocatorI::Request, public IceUtil::Mutex } } - 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, @@ -307,7 +182,7 @@ class ReplicaGroupRequest : public LocatorI::Request, public IceUtil::Mutex LocatorAdapterInfo adapter; do { - Lock sync(*this); + lock_guard lock(_mutex); if(_lastAdapter == _adapters.end()) { break; @@ -315,23 +190,23 @@ class ReplicaGroupRequest : public LocatorI::Request, public IceUtil::Mutex 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()) @@ -356,30 +231,31 @@ class ReplicaGroupRequest : public LocatorI::Request, public IceUtil::Mutex 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& 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. { @@ -405,7 +281,7 @@ class ReplicaGroupRequest : public LocatorI::Request, public IceUtil::Mutex { if(_proxies.size() == 1) { - _amdCB->ice_response(_proxies.begin()->second); + _response(_proxies.begin()->second); } else if(_proxies.empty()) { @@ -413,58 +289,63 @@ class ReplicaGroupRequest : public LocatorI::Request, public IceUtil::Mutex // 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::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&)> _response; + const function _exception; + const shared_ptr _locator; const std::string _id; const Ice::EncodingVersion _encoding; LocatorAdapterInfoSeq _adapters; - const TraceLevelsPtr _traceLevels; + const shared_ptr _traceLevels; unsigned int _count; LocatorAdapterInfoSeq::const_iterator _lastAdapter; - std::map _proxies; - IceInternal::UniquePtr _exception; + std::map> _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&)> response, + function exception, + const shared_ptr& locator, + const shared_ptr database, const string& id, const Ice::Current& current, const LocatorAdapterInfoSeq& adapters, int count) : - _amdCB(amdCB), + _response(std::move(response)), + _exception(std::move(exception)), _locator(locator), _database(database), _id(id), @@ -479,8 +360,8 @@ class RoundRobinRequest : public LocatorI::Request, SynchronizationCallback, pub assert(_adapters.empty() || _count > 0); } - virtual void - execute() + void + execute() override { if(_adapters.empty()) { @@ -489,26 +370,26 @@ class RoundRobinRequest : public LocatorI::Request, SynchronizationCallback, pub 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; @@ -516,26 +397,27 @@ class RoundRobinRequest : public LocatorI::Request, SynchronizationCallback, pub _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& 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) { @@ -544,30 +426,30 @@ class RoundRobinRequest : public LocatorI::Request, SynchronizationCallback, pub 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 request = + make_shared(_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 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) @@ -578,34 +460,34 @@ class RoundRobinRequest : public LocatorI::Request, SynchronizationCallback, pub 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()) @@ -620,12 +502,12 @@ class RoundRobinRequest : public LocatorI::Request, SynchronizationCallback, pub 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); } @@ -669,13 +551,15 @@ class RoundRobinRequest : public LocatorI::Request, SynchronizationCallback, pub { assert(_adapters.empty()); bool callback; + auto self = dynamic_pointer_cast(shared_from_this()); + assert(self); if(!_waitForActivation) { - callback = _database->addAdapterSyncCallback(_id, this, _activatingOrFailed); + callback = _database->addAdapterSyncCallback(_id, std::move(self), _activatingOrFailed); } else { - callback = _database->addAdapterSyncCallback(_id, this, _failed); + callback = _database->addAdapterSyncCallback(_id, std::move(self), _failed); } if(callback) { @@ -690,11 +574,11 @@ class RoundRobinRequest : public LocatorI::Request, SynchronizationCallback, pub { 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(); @@ -710,108 +594,117 @@ class RoundRobinRequest : public LocatorI::Request, SynchronizationCallback, pub { 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&)> _response; + const function _exception; + const shared_ptr _locator; + const shared_ptr _database; + const string _id; const Ice::EncodingVersion _encoding; - const Ice::ConnectionPtr _connection; + const shared_ptr _connection; const Ice::Context _context; LocatorAdapterInfoSeq _adapters; - const TraceLevelsPtr _traceLevels; + const shared_ptr _traceLevels; int _count; bool _waitForActivation; set _failed; set _activatingOrFailed; - IceInternal::UniquePtr _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& locator, + function&)> response, + function exception, const string& id, - const Ice::Current& current) : _locator(locator), _cb(cb), _id(id), _current(current) + const Ice::Current& current) : + _locator(locator), + _response(std::move(response)), + _exception(std::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 = _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 _locator; + const function&)> _response; + const function _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& communicator, + const shared_ptr& database, + const shared_ptr& wellKnownObjects, + const shared_ptr& registry, + const shared_ptr& query) : _communicator(communicator), _database(database), _wellKnownObjects(wellKnownObjects), @@ -825,13 +718,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&)> response, + function, + const Ice::Current&) const { try { - cb->ice_response(_database->getObjectProxy(id)); + response(_database->getObjectProxy(id)); } catch(const ObjectNotRegisteredException&) { @@ -844,11 +738,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&)> response, + function exception, + const Ice::Current& current) const { - LocatorIPtr self = const_cast(this); + auto self = const_pointer_cast(shared_from_this()); + bool replicaGroup = false; try { @@ -870,26 +766,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(self, response, exception, id, current))) { return; } } } - RequestPtr request; + shared_ptr request; if(roundRobin) { - request = new RoundRobinRequest(cb, self, _database, id, current, adapters, count); + request = make_shared(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(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(response, exception, self, current.encoding, adapters[0]); } request->execute(); return; @@ -897,95 +795,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 LocatorI::getRegistry(const Ice::Current&) const { return _wellKnownObjects->getLocatorRegistry(); } -RegistryPrx +shared_ptr LocatorI::getLocalRegistry(const Ice::Current&) const { return _localRegistry; } -QueryPrx +shared_ptr LocatorI::getLocalQuery(const Ice::Current&) const { return _localQuery; } -const Ice::CommunicatorPtr& +const shared_ptr& LocatorI::getCommunicator() const { return _communicator; } -const TraceLevelsPtr& +const shared_ptr& LocatorI::getTraceLevels() const { return _database->getTraceLevels(); } bool -LocatorI::getDirectProxy(const LocatorAdapterInfo& adapter, const RequestPtr& request) +LocatorI::getDirectProxy(const LocatorAdapterInfo& adapter, const shared_ptr& 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, std::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& 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); @@ -994,27 +897,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) { @@ -1026,8 +929,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) { @@ -1044,22 +947,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(adapter.proxy->ice_invocationTimeout(timeout))->activateAsync( + [self, adapter] (auto obj) + { + self->getDirectProxyResponse(adapter, std::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 DatabasePtr; - -class WellKnownObjectsManager; -typedef IceUtil::Handle WellKnownObjectsManagerPtr; - class LocatorI; -typedef IceUtil::Handle LocatorIPtr; - class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; +class WellKnownObjectsManager; struct LocatorAdapterInfo; typedef std::vector LocatorAdapterInfoSeq; -class LocatorI : public Locator, public IceUtil::Mutex +class LocatorI : public Locator, public std::enable_shared_from_this { public: - class Request : public virtual IceUtil::Shared + class Request : public std::enable_shared_from_this { 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&) = 0; + virtual void exception(const std::string&, std::exception_ptr) = 0; }; - typedef IceUtil::Handle RequestPtr; - LocatorI(const Ice::CommunicatorPtr&, const DatabasePtr&, const WellKnownObjectsManagerPtr&, const RegistryPrx&, - const QueryPrx&); + LocatorI(const std::shared_ptr&, const std::shared_ptr&, + const std::shared_ptr&, const std::shared_ptr&, + const std::shared_ptr&); - virtual void findObjectById_async(const Ice::AMD_Locator_findObjectByIdPtr&, const Ice::Identity&, - const Ice::Current&) const; + void findObjectByIdAsync(Ice::Identity, + std::function&)>, + std::function, + 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&)>, + std::function, + 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 getRegistry(const Ice::Current&) const override; + std::shared_ptr getLocalRegistry(const Ice::Current&) const override; + std::shared_ptr getLocalQuery(const Ice::Current&) const override; - const Ice::CommunicatorPtr& getCommunicator() const; - const TraceLevelsPtr& getTraceLevels() const; + const std::shared_ptr& getCommunicator() const; + const std::shared_ptr& 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&); + void getDirectProxyResponse(const LocatorAdapterInfo&, const std::shared_ptr&); + 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 _communicator; + const std::shared_ptr _database; + const std::shared_ptr _wellKnownObjects; + const std::shared_ptr _localRegistry; + const std::shared_ptr _localQuery; - typedef std::vector PendingRequests; - typedef std::map PendingRequestsMap; + using PendingRequests = std::vector>; + using PendingRequestsMap = std::map; PendingRequestsMap _pendingRequests; std::set _activating; + + std::mutex _mutex; }; } diff --git a/cpp/src/IceGrid/LocatorRegistryI.cpp b/cpp/src/IceGrid/LocatorRegistryI.cpp index e3c54ae6d19..a55f313238e 100644 --- a/cpp/src/IceGrid/LocatorRegistryI.cpp +++ b/cpp/src/IceGrid/LocatorRegistryI.cpp @@ -16,241 +16,175 @@ using namespace IceGrid; namespace IceGrid { -template -class SetDirectProxyCB : public LocatorRegistryI::AdapterSetDirectProxyCB +tuple, function> +newSetDirectProxyCB(function responseCb, + function exceptionCb, + const shared_ptr& traceLevels, const string& id, + const shared_ptr& 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 = std::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 = std::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 SetDirectProxyCB* -newSetDirectProxyCB(const AmdCB& cb, const TraceLevelsPtr& traceLevels, const string& id, const Ice::ObjectPrx& p) -{ - return new SetDirectProxyCB(cb, traceLevels, id, p); + return { std::move(response), std::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 ServerSetProcessCBPtr; - -class SetAdapterDirectProxyCallback : public SynchronizationCallback -{ -public: - - SetAdapterDirectProxyCallback(const LocatorRegistryIPtr& registry, - const LocatorRegistryI::AdapterSetDirectProxyCBPtr& amiCB, + SetAdapterDirectProxyCallback(const shared_ptr& registry, + function response, + function exception, const string& adapterId, const string& replicaGroupId, - const Ice::ObjectPrx& proxy) : - _registry(registry), _amiCB(amiCB), _adapterId(adapterId), _replicaGroupId(replicaGroupId), _proxy(proxy) + const shared_ptr& proxy) : + _registry(registry), + _response(std::move(response)), + _exception(std::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 _registry; + const function _response; + const function _exception; const string _adapterId; const string _replicaGroupId; - const Ice::ObjectPrx _proxy; + const shared_ptr _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& registry, + const function response, + const function exception, const string& id, - const Ice::ProcessPrx& proxy) : - _registry(registry), _cb(cb), _id(id), _proxy(proxy) + const shared_ptr& proxy) : + _registry(registry), + _response(std::move(response)), + _exception(std::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 _registry; + const function _response; + const function _exception; const string _id; - const Ice::ProcessPrx _proxy; + const shared_ptr _proxy; }; }; -LocatorRegistryI::LocatorRegistryI(const DatabasePtr& database, +LocatorRegistryI::LocatorRegistryI(const shared_ptr& database, bool dynamicRegistration, bool master, ReplicaSessionManager& session) : @@ -262,36 +196,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 proxy, + function response, + function exception, const Ice::Current&) { - setAdapterDirectProxy(newSetDirectProxyCB(cb, _database->getTraceLevels(), adapterId, proxy), - adapterId, + auto [responseCb, exceptionCb] = newSetDirectProxyCB(std::move(response), std::move(exception), _database->getTraceLevels(), + adapterId, proxy); + + setAdapterDirectProxy(adapterId, "", - proxy); + proxy, + std::move(responseCb), + std::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 proxy, + function response, + function exception, + const Ice::Current&) { - setAdapterDirectProxy(newSetDirectProxyCB(cb, _database->getTraceLevels(), adapterId, proxy), - adapterId, + auto [responseCb, exceptionCb] = newSetDirectProxyCB(std::move(response), std::move(exception), _database->getTraceLevels(), + adapterId, proxy); + setAdapterDirectProxy(adapterId, replicaGroupId, - proxy); + proxy, + std::move(responseCb), + std::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 proxy, + function response, + function exception, + const Ice::Current&) { try { @@ -303,7 +243,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 server; while(true) { try @@ -313,46 +253,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(shared_from_this(), response, + exception, id, proxy); + if(_database->getServer(id)->addSyncCallback(std::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 proxy, + function response, + function exception) { // // Ignore request with empty adapter id. // if(adapterId.empty()) { - amiCB->response(); + response(); return; } @@ -364,7 +344,7 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect // // Get the adapter from the registry and set its direct proxy. // - AdapterPrx adapter; + shared_ptr adapter; while(true) { try @@ -378,17 +358,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(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&) @@ -398,13 +380,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(); } @@ -415,7 +397,7 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect try { _database->setAdapterDirectProxy(adapterId, replicaGroupId, proxy); - amiCB->response(); + response(); return; } catch(const AdapterExistsException&) @@ -424,7 +406,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); @@ -435,10 +417,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); @@ -451,7 +433,7 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect try { session->setAdapterDirectProxy(adapterId, replicaGroupId, proxy); - amiCB->response(); + response(); return; } catch(const AdapterExistsException&) @@ -462,13 +444,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(); } @@ -478,7 +461,7 @@ LocatorRegistryI::setAdapterDirectProxy(const LocatorRegistryI::AdapterSetDirect throw Ice::AdapterNotFoundException(); } -const TraceLevelsPtr& +const shared_ptr& 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 #include -#include +#include namespace IceGrid { class Database; -typedef IceUtil::Handle DatabasePtr; - -class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; - class ReplicaSessionManager; +class TraceLevels; -class LocatorRegistryI : public Ice::LocatorRegistry +class LocatorRegistryI final : public Ice::LocatorRegistry, public std::enable_shared_from_this { public: - class AdapterSetDirectProxyCB : public virtual IceUtil::Shared - { - public: - - virtual void response() = 0; - virtual void exception(const ::Ice::Exception&) = 0; - }; - typedef IceUtil::Handle AdapterSetDirectProxyCBPtr; - - LocatorRegistryI(const DatabasePtr&, bool, bool, ReplicaSessionManager&); + LocatorRegistryI(const std::shared_ptr&, 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, + std::function, + std::function, + 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, + std::function, + std::function, + 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, + std::function, + std::function, + 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, + std::function, + std::function); - const TraceLevelsPtr& getTraceLevels() const; + const std::shared_ptr& getTraceLevels() const; private: - const DatabasePtr _database; + const std::shared_ptr _database; const bool _dynamicRegistration; const bool _master; ReplicaSessionManager& _session; }; -typedef IceUtil::Handle LocatorRegistryIPtr; } diff --git a/cpp/src/IceGrid/NodeAdminRouter.cpp b/cpp/src/IceGrid/NodeAdminRouter.cpp index f739f6e06b2..e8c5c92ab2f 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& node) : AdminRouter(node->getTraceLevels()), _node(node) { } void -IceGrid::NodeServerAdminRouter::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, - const std::pair& inParams, - const Current& current) +NodeServerAdminRouter::ice_invokeAsync(pair inParams, + function&)> response, + function 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(_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, std::move(response), std::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&); - virtual void ice_invoke_async(const Ice::AMD_Object_ice_invokePtr&, - const std::pair&, - const Ice::Current&); + void ice_invokeAsync(std::pair, + std::function&)>, + std::function, + const Ice::Current& current) override; private: - NodeIPtr _node; + std::shared_ptr _node; }; } diff --git a/cpp/src/IceGrid/NodeCache.cpp b/cpp/src/IceGrid/NodeCache.cpp index 7aec0f146ac..a8b16941356 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 #include #include #include @@ -16,346 +15,100 @@ using namespace std; using namespace IceGrid; -namespace IceGrid +namespace { -struct ToInternalServerDescriptor +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_", 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()); - - // - // Copy the communicator descriptor properties. - // - if(!communicatorProps.empty()) + if(p->name == name) { - 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)); + value = p->value; + p = properties.erase(p); } - - // - // 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) - { - 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())); - } - 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& communicator, + ReplicaCache& replicaCache, const string& replicaName) : _communicator(communicator), _replicaName(replicaName), _replicaCache(replicaCache) { } -NodeEntryPtr +shared_ptr NodeCache::get(const string& name, bool create) const { - Lock sync(*this); - NodeEntryPtr entry = getImpl(name); + lock_guard lock(_mutex); + + auto entry = getImpl(name); if(!entry && create) { NodeCache& self = const_cast(*this); - entry = new NodeEntry(self, name); + entry = make_shared(self, name); self.addImpl(name, entry); } if(!entry) { throw NodeNotExistException(name); } - return entry; + + // Return a "self removing" shared_ptr to the NodEntry which will remove + // itself from the this cache upon destruction + return entry->selfRemovingPtr(); } NodeEntry::NodeEntry(NodeCache& cache, const std::string& name) : _cache(cache), - _ref(0), _name(name), _registering(false) { } -NodeEntry::~NodeEntry() -{ -} - 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& 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& entry) { - Lock sync(*this); + lock_guard lock(_mutex); _servers.erase(entry->getId()); } void -NodeEntry::setSession(const NodeSessionIPtr& session) +NodeEntry::setSession(const shared_ptr& session) { - Lock sync(*this); + unique_lock lock(_mutex); if(session) { @@ -365,12 +118,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(); @@ -386,7 +139,7 @@ NodeEntry::setSession(const NodeSessionIPtr& session) { } } - sync.acquire(); + lock.lock(); } } @@ -395,7 +148,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 { @@ -406,12 +159,12 @@ NodeEntry::setSession(const NodeSessionIPtr& session) } _session = session; - notifyAll(); + _condVar.notify_all(); if(_registering) { _registering = false; - notifyAll(); + _condVar.notify_all(); } if(session) @@ -432,28 +185,28 @@ NodeEntry::setSession(const NodeSessionIPtr& session) } } -NodePrx +shared_ptr NodeEntry::getProxy() const { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); return _session->getNode(); } -InternalNodeInfoPtr +shared_ptr 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::const_iterator p = _servers.begin(); p != _servers.end(); ++p) + for(map>::const_iterator p = _servers.begin(); p != _servers.end(); ++p) { entries.push_back(p->second); } @@ -463,8 +216,8 @@ NodeEntry::getServers() const LoadInfo NodeEntry::getLoadInfoAndLoadFactor(const string& application, float& loadFactor) const { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); map::const_iterator p = _descriptors.find(application); if(p == _descriptors.end()) @@ -508,46 +261,44 @@ NodeEntry::getLoadInfoAndLoadFactor(const string& application, float& loadFactor return _session->getLoadInfo(); } -NodeSessionIPtr +shared_ptr NodeEntry::getSession() const { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); return _session; } -Ice::ObjectPrx +shared_ptr 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), ptrLock(_selfRemovingMutex); + + return _servers.empty() && !_session && _descriptors.empty() && _selfRemovingPtr.expired(); } void -NodeEntry::loadServer(const ServerEntryPtr& entry, const ServerInfo& server, const SessionIPtr& session, int timeout, - bool noRestart) +NodeEntry::loadServer(const shared_ptr& entry, const ServerInfo& server, + const shared_ptr& session, chrono::seconds timeout, bool noRestart) { try { - NodePrx node; - int sessionTimeout; - InternalServerDescriptorPtr desc; + shared_ptr node; + chrono::seconds sessionTimeout; + shared_ptr 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 @@ -555,9 +306,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(node->ice_invocationTimeout(std::move(timeoutInMilliseconds))); } ServerInfo info = server; @@ -588,38 +340,79 @@ NodeEntry::loadServer(const ServerEntryPtr& entry, const ServerInfo& server, con } } + auto response = [traceLevels = _cache.getTraceLevels(), entry, name = _name, sessionTimeout] + (shared_ptr 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(std::move(serverPrx), std::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(), std::move(response), std::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(), std::move(response), std::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& entry, const ServerInfo& info, chrono::seconds timeout, bool noRestart) { try { - NodePrx node; + shared_ptr node; { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); node = _session->getNode(); // @@ -628,9 +421,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(node->ice_invocationTimeout(std::move(timeoutInMilliseconds))); } } @@ -640,35 +434,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(), std::move(response), std::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(), + std::move(response), std::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& session) { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); ServerInfo info = server; info.descriptor = getServerDescriptor(server, session); @@ -676,11 +502,11 @@ NodeEntry::getServerInfo(const ServerInfo& server, const SessionIPtr& session) return info; } -InternalServerDescriptorPtr -NodeEntry::getInternalServerDescriptor(const ServerInfo& server, const SessionIPtr& session) +shared_ptr +NodeEntry::getInternalServerDescriptor(const ServerInfo& server, const shared_ptr& session) { - Lock sync(*this); - checkSession(); + unique_lock lock(_mutex); + checkSession(lock); ServerInfo info = server; try @@ -700,54 +526,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& lock) const { if(_session) { @@ -781,22 +560,23 @@ NodeEntry::checkSession() const // hang in the while loop. // _registering = true; - NodeEntry* self = const_cast(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. - } + auto self = selfRemovingPtr(); + _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"); @@ -804,9 +584,9 @@ NodeEntry::checkSession() const } void -NodeEntry::setProxy(const NodePrx& node) +NodeEntry::setProxy(const shared_ptr& node) { - Lock sync(*this); + lock_guard lock(_mutex); // // If the node has already established a session with the @@ -823,7 +603,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); @@ -840,29 +620,54 @@ 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) +// Return the weak_ptr's copy or, if nullptr, create a new "self removing" shared_ptr NodeEntry from 'this' +// which removes itself from the NodeCache upon destruction +shared_ptr +NodeEntry::selfRemovingPtr() const +{ + lock_guard lock(_selfRemovingMutex); + + auto entry = _selfRemovingPtr.lock(); + + if (!entry) + { + entry = shared_ptr(const_cast(this), [](NodeEntry* e) { e->_cache.remove(e->_name); }); + _selfRemovingPtr = entry; + } + + return entry; +} + +shared_ptr +NodeEntry::getServerDescriptor(const ServerInfo& server, const shared_ptr& session) { assert(_session); @@ -876,7 +681,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(server.descriptor); if(iceBox) { return IceBoxHelper(iceBox).instantiate(resolve, PropertyDescriptorSeq(), PropertySetDescriptorDict()); @@ -888,7 +693,7 @@ NodeEntry::getServerDescriptor(const ServerInfo& server, const SessionIPtr& sess } } -InternalServerDescriptorPtr +shared_ptr NodeEntry::getInternalServerDescriptor(const ServerInfo& info) const { // @@ -896,7 +701,7 @@ NodeEntry::getInternalServerDescriptor(const ServerInfo& info) const // assert(_session); - InternalServerDescriptorPtr server = new InternalServerDescriptor(); + shared_ptr server = make_shared(); server->id = info.descriptor->id; server->application = info.application; server->uuid = info.uuid; @@ -912,8 +717,9 @@ NodeEntry::getInternalServerDescriptor(const ServerInfo& info) const server->services = Ice::StringSeq(); if(!info.descriptor->distrib.icepatch.empty()) { - server->distrib = new InternalDistributionDescriptor(info.descriptor->distrib.icepatch, - info.descriptor->distrib.directories); + server->distrib = make_shared( + info.descriptor->distrib.icepatch, + info.descriptor->distrib.directories); } server->options = info.descriptor->options; server->envs = info.descriptor->envs; @@ -975,12 +781,12 @@ NodeEntry::getInternalServerDescriptor(const ServerInfo& info) const // Add IceBox properties. // string servicesStr; - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); + auto iceBox = dynamic_pointer_cast(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; // @@ -1034,6 +840,108 @@ NodeEntry::getInternalServerDescriptor(const ServerInfo& info) const // logs, adapters and properties to the internal server // descriptor. // - forEachCommunicator(ToInternalServerDescriptor(server, _session->getInfo(), iceVersion))(info.descriptor); + forEachCommunicator(info.descriptor, + [server, node = _session->getInfo(), iceVersion](const auto& desc) + { + // + // Figure out the configuration file name for the communicator + // (if it's a service, it's "config_", if it's + // the server, it's just "config"). + // + string filename = "config"; + auto svc = dynamic_pointer_cast(desc); + if(svc) + { + 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) + { + if(getPropertyAsInt(server->properties["config"], "Ice.Admin.Enabled") > 0 || + getProperty(server->properties["config"], "Ice.Admin.Endpoints") != "") + { + ignoreServerLifetime = true; + } + } + } + // + // Add the adapters and their configuration. + // + for(const auto& adapter : desc->adapters) + { + server->adapters.push_back(make_shared(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; + } + } + } + + server->logs.insert(server->logs.end(), desc->logs.begin(), desc->logs.end()); + + // + // Copy the communicator descriptor properties. + // + if(!communicatorProps.empty()) + { + 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)); + } + + // + // 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..cca0374f7ec 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 -#include #include #include @@ -14,90 +12,91 @@ namespace IceGrid { class NodeCache; - -class SessionI; -typedef IceUtil::Handle SessionIPtr; - class NodeSessionI; -typedef IceUtil::Handle NodeSessionIPtr; - +class ReplicaCache; class ServerEntry; -typedef IceUtil::Handle ServerEntryPtr; -typedef std::vector ServerEntrySeq; +class SessionI; -class ReplicaCache; +using ServerEntrySeq = std::vector>; -class NodeEntry : private IceUtil::Monitor +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&); + void removeServer(const std::shared_ptr&); + void setSession(const std::shared_ptr&); - NodePrx getProxy() const; - InternalNodeInfoPtr getInfo() const; + std::shared_ptr getProxy() const; + std::shared_ptr getInfo() const; ServerEntrySeq getServers() const; LoadInfo getLoadInfoAndLoadFactor(const std::string&, float&) const; - NodeSessionIPtr getSession() const; + std::shared_ptr getSession() const; - Ice::ObjectPrx getAdminProxy() const; + std::shared_ptr 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&, const ServerInfo&, const std::shared_ptr&, + std::chrono::seconds, bool); + void destroyServer(const std::shared_ptr&, 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&); + std::shared_ptr getInternalServerDescriptor(const ServerInfo&, const std::shared_ptr&); - void __incRef(); - void __decRef(); - - void checkSession() const; - void setProxy(const NodePrx&); + void checkSession(std::unique_lock&) const; + void setProxy(const std::shared_ptr&); 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 selfRemovingPtr() const; + + std::shared_ptr getServerDescriptor(const ServerInfo&, const std::shared_ptr&); + std::shared_ptr getInternalServerDescriptor(const ServerInfo&) const; NodeCache& _cache; - IceUtil::Mutex _refMutex; - int _ref; const std::string _name; - NodeSessionIPtr _session; - std::map _servers; + std::shared_ptr _session; + std::map> _servers; std::map _descriptors; mutable bool _registering; - mutable NodePrx _proxy; + mutable std::shared_ptr _proxy; + + mutable std::mutex _mutex; + mutable std::condition_variable _condVar; + + // "self removing" shared_ptr of 'this' which removes itself from the NodeCache upon destruction + mutable std::weak_ptr _selfRemovingPtr; + mutable std::mutex _selfRemovingMutex; + + friend NodeCache; }; -typedef IceUtil::Handle NodeEntryPtr; class NodeCache : public CacheByString { public: - NodeCache(const Ice::CommunicatorPtr&, ReplicaCache&, const std::string&); + using ValueType = NodeEntry*; + + NodeCache(const std::shared_ptr&, ReplicaCache&, const std::string&); - NodeEntryPtr get(const std::string&, bool = false) const; + std::shared_ptr get(const std::string&, bool = false) const; - const Ice::CommunicatorPtr& getCommunicator() const { return _communicator; } + const std::shared_ptr& 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 _communicator; const std::string _replicaName; ReplicaCache& _replicaCache; }; diff --git a/cpp/src/IceGrid/NodeI.cpp b/cpp/src/IceGrid/NodeI.cpp index d07257220f0..32a244deb6a 100644 --- a/cpp/src/IceGrid/NodeI.cpp +++ b/cpp/src/IceGrid/NodeI.cpp @@ -27,7 +27,7 @@ class LogPatcherFeedback : public IcePatch2::PatcherFeedback { public: - LogPatcherFeedback(const TraceLevelsPtr& traceLevels, const string& dest) : + LogPatcherFeedback(const shared_ptr& traceLevels, const string& dest) : _traceLevels(traceLevels), _startedPatch(false), _lastProgress(0), @@ -177,125 +177,46 @@ class LogPatcherFeedback : public IcePatch2::PatcherFeedback private: - const TraceLevelsPtr _traceLevels; + const shared_ptr _traceLevels; bool _startedPatch; int _lastProgress; string _path; string _dest; }; -class NodeUp : public NodeI::Update -{ -public: - - NodeUp(const NodeIPtr& node, const NodeObserverPrx& observer, NodeDynamicInfo info) : - NodeI::Update(node, observer), _info(info) - { - } - - virtual bool - send() - { - try - { - _observer->begin_nodeUp(_info, newCallback(static_cast(this), &NodeI::Update::completed)); - } - catch(const Ice::LocalException&) - { - return false; - } - return true; - } - -private: - - NodeDynamicInfo _info; -}; +} -class UpdateServer : public NodeI::Update +NodeI::Update::Update(UpdateFunction updateFunction, const shared_ptr& node, + const shared_ptr& observer) : _func(std::move(updateFunction)), + _node(node), _observer(observer) { -public: +} - UpdateServer(const NodeIPtr& node, const NodeObserverPrx& observer, ServerDynamicInfo info) : - NodeI::Update(node, observer), _info(info) +bool +NodeI::Update::send() +{ + 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_updateServer(_node->getName(Ice::emptyCurrent), - _info, - newCallback(static_cast(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) + catch(const std::exception&) { + return false; } - - virtual bool - send() - { - try - { - _observer->begin_updateAdapter(_node->getName(Ice::emptyCurrent), - _info, - newCallback(static_cast(this), &NodeI::Update::completed)); - } - catch(const Ice::LocalException&) - { - return false; - } - return true; - } - -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& adapter, NodeSessionManager& sessions, - const ActivatorPtr& activator, + const shared_ptr& activator, const IceUtil::TimerPtr& timer, - const TraceLevelsPtr& traceLevels, - const NodePrx& proxy, + const shared_ptr& traceLevels, + const shared_ptr& proxy, const string& name, - const UserAccountMapperPrx& mapper, + const shared_ptr& mapper, const string& instanceName) : _communicator(adapter->getCommunicator()), _adapter(adapter), @@ -311,16 +232,16 @@ NodeI::NodeI(const Ice::ObjectAdapterPtr& adapter, _instanceName(instanceName), _userAccountMapper(mapper), _platform("IceGrid.Node", _communicator, _traceLevels), - _fileCache(new FileCache(_communicator)), + _fileCache(make_shared(_communicator)), _serial(1), _consistencyCheckDone(false) { - Ice::PropertiesPtr props = _communicator->getProperties(); + auto props = _communicator->getProperties(); const_cast(_dataDir) = _platform.getDataDir(); const_cast(_serversDir) = _dataDir + "/servers"; const_cast(_tmpDir) = _dataDir + "/tmp"; - const_cast(_waitTime) = props->getPropertyAsIntWithDefault("IceGrid.Node.WaitTime", 60); + const_cast(_waitTime) = props->getPropertyAsIntWithDefault("IceGrid.Node.WaitTime", 60); const_cast(_outputDir) = props->getProperty("IceGrid.Node.Output"); const_cast(_redirectErrToOut) = props->getPropertyAsInt("IceGrid.Node.RedirectErrToOut") > 0; const_cast(_allowEndpointsOverride) = props->getPropertyAsInt("IceGrid.Node.AllowEndpointsOverride") > 0; @@ -339,155 +260,76 @@ 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 descriptor, string replicaName, + function&, const AdapterPrxDict&, int, int)> response, + function exception, const Ice::Current& current) { + loadServer(std::move(descriptor), std::move(replicaName), false, std::move(response), std::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 descriptor, + string replicaName, + function&, + const AdapterPrxDict&, int, int)> response, + function exception, + const Ice::Current& current) { - loadServer(amdCB, descriptor, replicaName, false, current); + loadServer(std::move(descriptor), std::move(replicaName), true, std::move(response), std::move(exception), current); } void -NodeI::loadServerWithoutRestart_async(const AMD_Node_loadServerWithoutRestartPtr& amdCB, - const InternalServerDescriptorPtr& descriptor, - const string& replicaName, - const Ice::Current& current) +NodeI::destroyServerAsync(string serverId, string uuid, int revision, string replicaName, + function response, function exception, + 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); -} - -void -NodeI::destroyServer_async(const AMD_Node_destroyServerPtr& amdCB, - const string& serverId, - const string& uuid, - int revision, - const string& replicaName, - const Ice::Current& current) -{ - destroyServer(amdCB, serverId, uuid, revision, replicaName, false, current); + destroyServer(std::move(serverId), std::move(uuid), std::move(revision), std::move(replicaName), false, + std::move(response), std::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 response, function 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(std::move(serverId), std::move(uuid), std::move(revision), std::move(replicaName), true, + std::move(response), std::move(exception), current); } void -NodeI::patch_async(const AMD_Node_patchPtr& amdCB, - const PatcherFeedbackPrx& feedback, - const string& application, - const string& server, - const InternalDistributionDescriptorPtr& appDistrib, - bool shutdown, - const Ice::Current&) +NodeI::patchAsync( + std::shared_ptr feedback, + std::string application, + std::string server, + std::shared_ptr appDistrib, + bool shutdown, + std::function response, + std::function, + const Ice::Current&) { - amdCB->ice_response(); + response(); { - Lock sync(*this); + unique_lock lock(_serversMutex); while(_patchInProgress.find(application) != _patchInProgress.end()) { - wait(); + _condVar.wait(lock); } _patchInProgress.insert(application); } - set servers; + set> servers; bool patchApplication = !appDistrib->icepatch.empty(); if(server.empty()) { @@ -498,10 +340,10 @@ NodeI::patch_async(const AMD_Node_patchPtr& amdCB, } else { - ServerIPtr svr; + shared_ptr svr; try { - svr = ServerIPtr::dynamicCast(_adapter->find(createServerIdentity(server))); + svr = dynamic_pointer_cast(_adapter->find(createServerIdentity(server))); } catch(const Ice::ObjectAdapterDeactivatedException&) { @@ -530,7 +372,7 @@ NodeI::patch_async(const AMD_Node_patchPtr& amdCB, } } - for(set::iterator s = servers.begin(); s != servers.end();) + for(set>::iterator s = servers.begin(); s != servers.end();) { if(!appDistrib->icepatch.empty() && (*s)->dependsOnApplicationDistrib()) { @@ -556,7 +398,7 @@ NodeI::patch_async(const AMD_Node_patchPtr& amdCB, try { vector running; - for(set::iterator s = servers.begin(); s != servers.end();) + for(set>::iterator s = servers.begin(); s != servers.end();) { try { @@ -588,7 +430,7 @@ NodeI::patch_async(const AMD_Node_patchPtr& amdCB, } } - for(set::iterator s = servers.begin(); s != servers.end(); ++s) + for (set>::iterator s = servers.begin(); s != servers.end(); ++s) { (*s)->waitForPatch(); } @@ -596,11 +438,11 @@ NodeI::patch_async(const AMD_Node_patchPtr& amdCB, // // Patch the application. // - FileServerPrx icepatch; + shared_ptr icepatch; if(patchApplication) { assert(!appDistrib->icepatch.empty()); - icepatch = FileServerPrx::checkedCast(_communicator->stringToProxy(appDistrib->icepatch)); + icepatch = Ice::checkedCast(_communicator->stringToProxy(appDistrib->icepatch)); if(!icepatch) { throw runtime_error("proxy `" + appDistrib->icepatch + "' is not a file server."); @@ -611,12 +453,12 @@ NodeI::patch_async(const AMD_Node_patchPtr& amdCB, // // Patch the server(s). // - for(set::iterator s = servers.begin(); s != servers.end(); ++s) + for(set>::iterator s = servers.begin(); s != servers.end(); ++s) { InternalDistributionDescriptorPtr dist = (*s)->getDistribution(); if(dist && (server.empty() || (*s)->getId() == server)) { - icepatch = FileServerPrx::checkedCast(_communicator->stringToProxy(dist->icepatch)); + icepatch = Ice::checkedCast(_communicator->stringToProxy(dist->icepatch)); if(!icepatch) { throw runtime_error("proxy `" + dist->icepatch + "' is not a file server."); @@ -630,21 +472,21 @@ NodeI::patch_async(const AMD_Node_patchPtr& amdCB, } } } - catch(const exception& ex) + catch(const std::exception& ex) { failure = ex.what(); } - for(set::const_iterator s = servers.begin(); s != servers.end(); ++s) + for(set>::const_iterator s = servers.begin(); s != servers.end(); ++s) { (*s)->finishPatch(); } } { - Lock sync(*this); + unique_lock lock(_mutex); _patchInProgress.erase(application); - notifyAll(); + _condVar.notify_all(); } try @@ -664,27 +506,27 @@ NodeI::patch_async(const AMD_Node_patchPtr& amdCB, } void -NodeI::registerWithReplica(const InternalRegistryPrx& replica, const Ice::Current&) +NodeI::registerWithReplica(shared_ptr replica, const Ice::Current&) { - _sessions.create(replica); + _sessions.create(std::move(replica)); } void -NodeI::replicaInit(const InternalRegistryPrxSeq& replicas, const Ice::Current&) +NodeI::replicaInit(InternalRegistryPrxSeq replicas, const Ice::Current&) { - _sessions.replicaInit(replicas); + _sessions.replicaInit(std::move(replicas)); } void -NodeI::replicaAdded(const InternalRegistryPrx& replica, const Ice::Current&) +NodeI::replicaAdded(shared_ptr replica, const Ice::Current&) { - _sessions.replicaAdded(replica); + _sessions.replicaAdded(std::move(replica)); } void -NodeI::replicaRemoved(const InternalRegistryPrx& replica, const Ice::Current&) +NodeI::replicaRemoved(shared_ptr replica, const Ice::Current&) { - _sessions.replicaRemoved(replica); + _sessions.replicaRemoved(std::move(replica)); } std::string @@ -717,14 +559,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); @@ -733,31 +575,30 @@ NodeI::read(const string& filename, Ice::Long pos, int size, Ice::Long& newPos, void NodeI::shutdown() { - IceUtil::Mutex::Lock sync(_serversLock); - for(map >::const_iterator p = _serversByApplication.begin(); - p != _serversByApplication.end(); ++p) + lock_guard lock(_serversMutex); + for(const auto& servers : _serversByApplication) { - for(set::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 NodeI::getCommunicator() const { return _communicator; } -Ice::ObjectAdapterPtr +shared_ptr NodeI::getAdapter() const { return _adapter; } -ActivatorPtr +shared_ptr NodeI::getActivator() const { return _activator; @@ -769,31 +610,31 @@ NodeI::getTimer() const return _timer; } -TraceLevelsPtr +shared_ptr NodeI::getTraceLevels() const { return _traceLevels; } -UserAccountMapperPrx +shared_ptr NodeI::getUserAccountMapper() const { return _userAccountMapper; } PlatformInfo& -NodeI::getPlatformInfo() const +NodeI::getPlatformInfo() { return _platform; } -FileCachePtr +shared_ptr NodeI::getFileCache() const { return _fileCache; } -NodePrx +shared_ptr NodeI::getProxy() const { return _proxy; @@ -829,14 +670,14 @@ NodeI::allowEndpointsOverride() const return _allowEndpointsOverride; } -NodeSessionPrx -NodeI::registerWithRegistry(const InternalRegistryPrx& registry) +shared_ptr +NodeI::registerWithRegistry(const shared_ptr& registry) { return registry->registerNode(_platform.getInternalNodeInfo(), _proxy, _platform.getLoadInfo()); } void -NodeI::checkConsistency(const NodeSessionPrx& session) +NodeI::checkConsistency(const shared_ptr& session) { // // Only do the consistency check on the startup. This ensures that servers can't @@ -860,11 +701,11 @@ NodeI::checkConsistency(const NodeSessionPrx& session) // unsigned long serial = 0; Ice::StringSeq servers; - vector commands; + vector> commands; while(true) { { - Lock sync(*this); + lock_guard lock(_mutex); if(serial == _serial) { _serial = 1; // We can reset the serial number. @@ -884,58 +725,57 @@ NodeI::checkConsistency(const NodeSessionPrx& session) } sort(servers.begin(), servers.end()); } -#ifdef ICE_CPP11_COMPILER - for_each(commands.begin(), commands.end(), [](const auto& it) { it->execute(); }); -#else - for_each(commands.begin(), commands.end(), IceUtil::voidMemFun(&ServerCommand::execute)); -#endif + + for(const auto& command : commands) + { + command->execute(); + } } void -NodeI::addObserver(const NodeSessionPrx& session, const NodeObserverPrx& observer) +NodeI::addObserver(const shared_ptr& session, const shared_ptr& 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::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::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(), std::move(serverInfos), std::move(adapterInfos) }; + queueUpdate(observer, [observer, info = std::move(info)] (auto&& response, auto&& exception) + { + observer->nodeUpAsync(info, std::move(response), std::move(exception)); + }); } void -NodeI::removeObserver(const NodeSessionPrx& session) +NodeI::removeObserver(const shared_ptr& 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); } @@ -950,13 +790,20 @@ NodeI::observerUpdateServer(const ServerDynamicInfo& info) // registered twice if a replica is removed and added right away // after). // - set sent; - for(map::const_iterator p = _observers.begin(); p != _observers.end(); ++p) + set> 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, std::move(response), std::move(exception)); + }); + + sent.insert(observer.second); } } } @@ -964,7 +811,7 @@ NodeI::observerUpdateServer(const ServerDynamicInfo& info) void NodeI::observerUpdateAdapter(const AdapterDynamicInfo& info) { - IceUtil::Mutex::Lock sync(_observerMutex); + lock_guard observerLock(_observerMutex); if(info.proxy) { @@ -981,22 +828,29 @@ NodeI::observerUpdateAdapter(const AdapterDynamicInfo& info) // registered twice if a replica is removed and added right away // after). // - set sent; - for(map::const_iterator p = _observers.begin(); p != _observers.end(); ++p) + set> 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, std::move(response), std::move(exception)); + }); + sent.insert(observer.second); } } } void -NodeI::queueUpdate(const NodeObserverPrx& proxy, const UpdatePtr& update) +NodeI::queueUpdate(const shared_ptr& proxy, Update::UpdateFunction updateFunction) { - //Lock sync(*this); Called within the synchronization - map >::iterator p = _observerUpdates.find(proxy); + // Must be called with mutex locked + auto update = make_shared(std::move(updateFunction), shared_from_this(), proxy); + auto p = _observerUpdates.find(proxy); if(p == _observerUpdates.end()) { if(update->send()) @@ -1011,10 +865,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& proxy, const shared_ptr& update, bool all) { - IceUtil::Mutex::Lock sync(_observerMutex); - map >::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; @@ -1034,23 +888,22 @@ NodeI::dequeueUpdate(const NodeObserverPrx& proxy, const UpdatePtr& update, bool } void -NodeI::addServer(const ServerIPtr& server, const string& application) +NodeI::addServer(const shared_ptr& server, const string& application) { - IceUtil::Mutex::Lock sync(_serversLock); - map >::iterator p = _serversByApplication.find(application); + lock_guard serversLock(_serversMutex); + auto p = _serversByApplication.find(application); if(p == _serversByApplication.end()) { - map >::value_type v(application, set()); - 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& server, const std::string& application) { - IceUtil::Mutex::Lock sync(_serversLock); - map >::iterator p = _serversByApplication.find(application); + lock_guard serversLock(_serversMutex); + auto p = _serversByApplication.find(application); if(p != _serversByApplication.end()) { p->second.erase(server); @@ -1078,10 +931,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 @@ -1090,10 +940,10 @@ NodeI::getServerAdminCategory() const return _instanceName + "-NodeServerAdminRouter"; } -vector +vector> NodeI::checkConsistencyNoSync(const Ice::StringSeq& servers) { - vector commands; + vector> commands; // // Check if the servers directory doesn't contain more servers @@ -1119,10 +969,10 @@ NodeI::checkConsistencyNoSync(const Ice::StringSeq& servers) // try { - vector::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(_adapter->find(createServerIdentity(*p))); if(server) { // @@ -1130,7 +980,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); @@ -1190,7 +1040,7 @@ NodeI::checkConsistencyNoSync(const Ice::StringSeq& servers) return commands; } -NodeSessionPrx +shared_ptr NodeI::getMasterNodeSession() const { return _sessions.getMasterNodeSession(); @@ -1206,7 +1056,6 @@ NodeI::canRemoveServerDirectory(const string& name) set contents(c.begin(), c.end()); contents.erase("dbs"); contents.erase("config"); - contents.erase("distrib"); contents.erase("revision"); contents.erase("data"); Ice::StringSeq serviceDataDirs; @@ -1280,25 +1129,25 @@ NodeI::canRemoveServerDirectory(const string& name) } void -NodeI::patch(const FileServerPrx& icepatch, const string& dest, const vector& directories) +NodeI::patch(const shared_ptr& icepatch, const string& dest, const vector& directories) { - IcePatch2::PatcherFeedbackPtr feedback = new LogPatcherFeedback(_traceLevels, dest); + IcePatch2::PatcherFeedbackPtr feedback = make_shared(_traceLevels, dest); IcePatch2Internal::createDirectory(_dataDir + "/" + dest); PatcherPtr patcher = PatcherFactory::create(icepatch, feedback, _dataDir + "/" + dest, false, 100, 1); bool aborted = !patcher->prepare(); - if(!aborted) + if (!aborted) { - if(directories.empty()) + if (directories.empty()) { aborted = !patcher->patch(""); dynamic_cast(feedback.get())->finishPatch(); } else { - for(vector::const_iterator p = directories.begin(); p != directories.end(); ++p) + for (vector::const_iterator p = directories.begin(); p != directories.end(); ++p) { dynamic_cast(feedback.get())->setPatchingPath(*p); - if(!patcher->patch(*p)) + if (!patcher->patch(*p)) { aborted = true; break; @@ -1307,7 +1156,7 @@ NodeI::patch(const FileServerPrx& icepatch, const string& dest, const vectorfinish(); } @@ -1317,12 +1166,12 @@ NodeI::patch(const FileServerPrx& icepatch, const string& dest, const vector +set> NodeI::getApplicationServers(const string& application) const { - IceUtil::Mutex::Lock sync(_serversLock); - set servers; - map >::const_iterator p = _serversByApplication.find(application); + lock_guard lock(_serversMutex); + set> servers; + auto p = _serversByApplication.find(application); if(p != _serversByApplication.end()) { servers = p->second; @@ -1358,18 +1207,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 descriptor, string replicaName, bool noRestart, + function &, const AdapterPrxDict &, int, int)>&& response, + function&& exception, const Ice::Current& current) { - ServerCommandPtr command; + shared_ptr 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 @@ -1379,14 +1227,14 @@ NodeI::loadServer(const AMD_Node_loadServerPtr& amdCB, while(true) { bool added = false; - ServerIPtr server; + shared_ptr server; try { - server = ServerIPtr::dynamicCast(_adapter->find(id)); + server = dynamic_pointer_cast(_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(_adapter->createProxy(id)); + server = make_shared(shared_from_this(), proxy, _serversDir, descriptor->id, _waitTime); _adapter->add(server, id); added = true; } @@ -1406,7 +1254,7 @@ NodeI::loadServer(const AMD_Node_loadServerPtr& amdCB, try { - command = server->load(amdCB, descriptor, replicaName, noRestart); + command = server->load(descriptor, replicaName, noRestart, std::move(response), std::move(exception)); } catch(const Ice::ObjectNotExistException&) { @@ -1438,30 +1286,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 response, + function, const Ice::Current& current) { - ServerCommandPtr command; + shared_ptr command; { - Lock sync(*this); + lock_guard lock(_mutex); ++_serial; - ServerIPtr server; + shared_ptr server; try { - server = ServerIPtr::dynamicCast(_adapter->find(createServerIdentity(serverId))); + server = dynamic_pointer_cast(_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. @@ -1471,7 +1316,7 @@ NodeI::destroyServer(const AMD_Node_destroyServerPtr& amdCB, if(!server) { - server = new ServerI(this, 0, _serversDir, serverId, _waitTime); + server = make_shared(shared_from_this(), nullptr, _serversDir, serverId, _waitTime); } // @@ -1479,11 +1324,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 5d3afb7f270..899f5434958 100644 --- a/cpp/src/IceGrid/NodeI.h +++ b/cpp/src/IceGrid/NodeI.h @@ -12,108 +12,98 @@ #include #include #include +#include namespace IceGrid { -class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; - class Activator; -typedef IceUtil::Handle ActivatorPtr; - -class ServerI; -typedef IceUtil::Handle ServerIPtr; - -class ServerCommand; -typedef IceUtil::Handle ServerCommandPtr; - class NodeSessionManager; +class ServerCommand; +class ServerI; +class TraceLevels; -class NodeI; -typedef IceUtil::Handle NodeIPtr; - -class NodeI : public Node, public IceUtil::Monitor +class NodeI : public Node, public std::enable_shared_from_this { public: - class Update : public virtual IceUtil::Shared + class Update final : public std::enable_shared_from_this { public: - Update(const NodeIPtr&, const NodeObserverPrx&); - virtual ~Update(); - - virtual bool send() = 0; + using UpdateFunction = std::function, std::function)>; - void finished(bool); + Update(UpdateFunction, const std::shared_ptr&, const std::shared_ptr&); + bool send(); - void completed(const Ice::AsyncResultPtr&); + private: - protected: - - const NodeIPtr _node; - const NodeObserverPrx _observer; + UpdateFunction _func; + std::shared_ptr _node; + std::shared_ptr _observer; }; - typedef IceUtil::Handle 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 patch_async(const AMD_Node_patchPtr&, const PatcherFeedbackPrx&, const std::string&, - const std::string&, const InternalDistributionDescriptorPtr&, bool, 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; + + NodeI(const std::shared_ptr&, NodeSessionManager&, const std::shared_ptr&, + const IceUtil::TimerPtr&, const std::shared_ptr&, const std::shared_ptr&, + const std::string&, const std::shared_ptr&, const std::string&); + + void loadServerAsync(std::shared_ptr, std::string, + std::function &, const AdapterPrxDict &, int, int)>, + std::function, + const Ice::Current &) override; + + void loadServerWithoutRestartAsync(std::shared_ptr, std::string, + std::function&, + const AdapterPrxDict&, int, int)>, + std::function, + const Ice::Current &) override; + + void destroyServerAsync(std::string, std::string, int, std::string, + std::function, + std::function, + const Ice::Current&) override; + + void destroyServerWithoutRestartAsync(std::string, std::string, int, std::string, + std::function, + std::function, + const ::Ice::Current& current) override; + + void patchAsync( + std::shared_ptr feedback, + std::string application, + std::string server, + std::shared_ptr appDistrib, + bool shutdown, + std::function response, + std::function exception, + const Ice::Current&) override; + + void registerWithReplica(std::shared_ptr, const Ice::Current&) override; + + void replicaInit(InternalRegistryPrxSeq, const Ice::Current&) override; + void replicaAdded(std::shared_ptr, const Ice::Current&) override; + void replicaRemoved(std::shared_ptr, 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 getCommunicator() const; + std::shared_ptr getAdapter() const; + std::shared_ptr getActivator() const; + std::shared_ptr getTraceLevels() const; + std::shared_ptr getUserAccountMapper() const; + PlatformInfo& getPlatformInfo(); + std::shared_ptr getFileCache() const; + std::shared_ptr getProxy() const; const PropertyDescriptorSeq& getPropertiesOverride() const; const std::string& getInstanceName() const; @@ -121,19 +111,20 @@ class NodeI : public Node, public IceUtil::Monitor bool getRedirectErrToOut() const; bool allowEndpointsOverride() const; - NodeSessionPrx registerWithRegistry(const InternalRegistryPrx&); - void checkConsistency(const NodeSessionPrx&); - NodeSessionPrx getMasterNodeSession() const; + std::shared_ptr registerWithRegistry(const std::shared_ptr&); + void checkConsistency(const std::shared_ptr&); + std::shared_ptr getMasterNodeSession() const; - void addObserver(const NodeSessionPrx&, const NodeObserverPrx&); - void removeObserver(const NodeSessionPrx&); + void addObserver(const std::shared_ptr&, const std::shared_ptr&); + void removeObserver(const std::shared_ptr&); 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&, Update::UpdateFunction); + void dequeueUpdate(const std::shared_ptr&, const std::shared_ptr&, bool); + + void addServer(const std::shared_ptr&, const std::string&); + void removeServer(const std::shared_ptr&, const std::string&); Ice::Identity createServerIdentity(const std::string&) const; std::string getServerAdminCategory() const; @@ -142,54 +133,60 @@ class NodeI : public Node, public IceUtil::Monitor private: - std::vector checkConsistencyNoSync(const Ice::StringSeq&); - void patch(const IcePatch2::FileServerPrx&, const std::string&, const std::vector&); + std::vector> checkConsistencyNoSync(const Ice::StringSeq&); + void patch(const std::shared_ptr&, const std::string&, const std::vector&); - std::set getApplicationServers(const std::string&) const; + std::set> 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, std::string, bool, + std::function &, const AdapterPrxDict &, int, int)>&&, + std::function&&, 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, + std::function, + const Ice::Current&); - const Ice::CommunicatorPtr _communicator; - const Ice::ObjectAdapterPtr _adapter; + const std::shared_ptr _communicator; + const std::shared_ptr _adapter; NodeSessionManager& _sessions; - const ActivatorPtr _activator; + const std::shared_ptr _activator; const IceUtil::TimerPtr _timer; - const TraceLevelsPtr _traceLevels; + const std::shared_ptr _traceLevels; const std::string _name; - const NodePrx _proxy; + const std::shared_ptr _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 _userAccountMapper; + PlatformInfo _platform; const std::string _dataDir; const std::string _serversDir; const std::string _tmpDir; - const FileCachePtr _fileCache; + const std::shared_ptr _fileCache; PropertyDescriptorSeq _propertiesOverride; unsigned long _serial; bool _consistencyCheckDone; - IceUtil::Mutex _observerMutex; - std::map _observers; + std::mutex _observerMutex; + std::map, std::shared_ptr> _observers; std::map _serversDynamicInfo; std::map _adaptersDynamicInfo; - std::map > _observerUpdates; + std::map, std::deque>> _observerUpdates; - IceUtil::Mutex _serversLock; - std::map > _serversByApplication; + mutable std::mutex _serversMutex; + std::map> > _serversByApplication; std::set _patchInProgress; + + std::mutex _mutex; + std::condition_variable _condVar; }; -typedef IceUtil::Handle NodeIPtr; } diff --git a/cpp/src/IceGrid/NodeSessionI.cpp b/cpp/src/IceGrid/NodeSessionI.cpp index 2676b07a7fe..db8a93f2708 100644 --- a/cpp/src/IceGrid/NodeSessionI.cpp +++ b/cpp/src/IceGrid/NodeSessionI.cpp @@ -14,14 +14,15 @@ using namespace IceGrid; namespace IceGrid { -class PatcherFeedbackI : public PatcherFeedback +class PatcherFeedbackI : public PatcherFeedback, public std::enable_shared_from_this { public: - PatcherFeedbackI(const string& node, - const NodeSessionIPtr& session, - const Ice::Identity id, - const PatcherFeedbackAggregatorPtr& aggregator) : + PatcherFeedbackI( + const string& node, + const shared_ptr& session, + const Ice::Identity id, + const shared_ptr& aggregator) : _node(node), _session(session), _id(id), @@ -32,30 +33,31 @@ class PatcherFeedbackI : public PatcherFeedback void finished(const Ice::Current&) { _aggregator->finished(_node); - _session->removeFeedback(this, _id); + _session->removeFeedback(shared_from_this(), _id); } - virtual void failed(const string& reason, const Ice::Current& = Ice::Current()) + virtual void failed(string reason, const Ice::Current & = Ice::Current()) { - _aggregator->failed(_node, reason); - _session->removeFeedback(this, _id); + _aggregator->failed(_node, std::move(reason)); + _session->removeFeedback(shared_from_this(), _id); } private: const std::string _node; - const NodeSessionIPtr _session; + const shared_ptr _session; const Ice::Identity _id; - const PatcherFeedbackAggregatorPtr _aggregator; + const shared_ptr _aggregator; }; -}; +} -PatcherFeedbackAggregator::PatcherFeedbackAggregator(Ice::Identity id, - const TraceLevelsPtr& traceLevels, - const string& type, - const string& name, - int nodeCount) : +PatcherFeedbackAggregator::PatcherFeedbackAggregator( + Ice::Identity id, + const shared_ptr& traceLevels, + const string& type, + const string& name, + int nodeCount) : _id(id), _traceLevels(traceLevels), _type(type), @@ -71,13 +73,13 @@ PatcherFeedbackAggregator::~PatcherFeedbackAggregator() void PatcherFeedbackAggregator::finished(const string& node) { - Lock sync(*this); - if(_successes.find(node) != _successes.end() || _failures.find(node) != _failures.end()) + lock_guard lock(_mutex); + if (_successes.find(node) != _successes.end() || _failures.find(node) != _failures.end()) { return; } - if(_traceLevels->patch > 0) + if (_traceLevels->patch > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat); out << "finished patching of " << _type << " `" << _name << "' on node `" << node << "'"; @@ -88,18 +90,18 @@ PatcherFeedbackAggregator::finished(const string& node) } void -PatcherFeedbackAggregator::failed(const string& node, const string& failure) +PatcherFeedbackAggregator::failed(string node, const string& failure) { - Lock sync(*this); - if(_successes.find(node) != _successes.end() || _failures.find(node) != _failures.end()) + lock_guard lock(_mutex); + if (_successes.find(node) != _successes.end() || _failures.find(node) != _failures.end()) { return; } - if(_traceLevels->patch > 0) + if (_traceLevels->patch > 0) { Ice::Trace out(_traceLevels->logger, _traceLevels->patchCat); - out << "patching of " << _type << " `" << _name << "' on node `" << node <<"' failed:\n" << failure; + out << "patching of " << _type << " `" << _name << "' on node `" << node << "' failed:\n" << failure; } _failures.insert(node); @@ -110,14 +112,19 @@ PatcherFeedbackAggregator::failed(const string& node, const string& failure) void PatcherFeedbackAggregator::checkIfDone() { - if(static_cast(_successes.size() + _failures.size()) == _count) + if (static_cast(_successes.size() + _failures.size()) == _count) { - if(!_failures.empty()) + if (!_failures.empty()) { - sort(_reasons.begin(), _reasons.end()); - PatchException ex; - ex.reasons = _reasons; - exception(ex); + try + { + sort(_reasons.begin(), _reasons.end()); + throw PatchException(_reasons); + } + catch (...) + { + exception(current_exception()); + } } else { @@ -126,66 +133,74 @@ PatcherFeedbackAggregator::checkIfDone() } } -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::create(const shared_ptr& database, + const shared_ptr& node, + const shared_ptr& info, + std::chrono::seconds timeout, + const LoadInfo& load) { - __setNoDelete(true); + shared_ptr 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( + 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, + const shared_ptr& node, + const shared_ptr& 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 = std::move(load); if(_traceLevels->node > 2) { @@ -196,9 +211,10 @@ NodeSessionI::keepAlive(const LoadInfo& load, const Ice::Current&) } void -NodeSessionI::setReplicaObserver(const ReplicaObserverPrx& observer, const Ice::Current&) +NodeSessionI::setReplicaObserver(shared_ptr observer, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); + if(_destroy) { return; @@ -216,17 +232,18 @@ NodeSessionI::setReplicaObserver(const ReplicaObserverPrx& observer, const Ice:: int NodeSessionI::getTimeout(const Ice::Current&) const { - return _timeout; + return secondsToInt(_timeout); } -NodeObserverPrx +shared_ptr NodeSessionI::getObserver(const Ice::Current&) const { - return NodeObserverTopicPtr::dynamicCast(_database->getObserverTopic(NodeObserverTopicName))->getPublisher(); + return dynamic_pointer_cast( + _database->getObserverTopic(TopicName::NodeObserver))->getPublisher(); } void -NodeSessionI::loadServers_async(const AMD_NodeSession_loadServersPtr& amdCB, const Ice::Current&) const +NodeSessionI::loadServersAsync(function response, function, const Ice::Current&) const { // // No need to wait for the servers to be loaded. If we were @@ -234,38 +251,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 response, function exception, const Ice::Current&) const { - _database->waitForApplicationUpdate(cb, application, revision); + _database->waitForApplicationUpdate(std::move(application), std::move(revision), std::move(response), std::move(exception)); } void @@ -274,10 +290,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__); @@ -292,30 +308,31 @@ NodeSessionI::shutdown() } void -NodeSessionI::patch(const PatcherFeedbackAggregatorPtr& aggregator, - const string& application, - const string& server, - const InternalDistributionDescriptorPtr& dist, - bool shutdown) +NodeSessionI::patch( + const shared_ptr& aggregator, + const string& application, + const string& server, + const shared_ptr& dist, + bool shutdown) { Ice::Identity id; id.category = _database->getInstanceName(); id.name = Ice::generateUUID(); - PatcherFeedbackPtr obj = new PatcherFeedbackI(_info->name, this, id, aggregator); + auto obj = make_shared(_info->name, shared_from_this(), id, aggregator); try { - PatcherFeedbackPrx feedback = PatcherFeedbackPrx::uncheckedCast(_database->getInternalAdapter()->add(obj, id)); + auto feedback = Ice::uncheckedCast(_database->getInternalAdapter()->add(obj, id)); _node->patch(feedback, application, server, dist, shutdown); - Lock sync(*this); - if(_destroy) + lock_guard lock(_mutex); + if (_destroy) { throw NodeUnreachableException(_info->name, "node is down"); } _feedbacks.insert(obj); } - catch(const Ice::LocalException& ex) + catch (const Ice::LocalException& ex) { ostringstream os; os << "node unreachable:\n" << ex; @@ -323,13 +340,13 @@ NodeSessionI::patch(const PatcherFeedbackAggregatorPtr& aggregator, } } -const NodePrx& +const shared_ptr& NodeSessionI::getNode() const { return _node; } -const InternalNodeInfoPtr& +const shared_ptr& NodeSessionI::getInfo() const { return _info; @@ -338,11 +355,11 @@ NodeSessionI::getInfo() const const LoadInfo& NodeSessionI::getLoadInfo() const { - Lock sync(*this); + lock_guard lock(_mutex); return _load; } -NodeSessionPrx +shared_ptr NodeSessionI::getProxy() const { return _proxy; @@ -351,7 +368,7 @@ NodeSessionI::getProxy() const bool NodeSessionI::isDestroyed() const { - Lock sync(*this); + lock_guard lock(_mutex); return _destroy; } @@ -359,7 +376,7 @@ void NodeSessionI::destroyImpl(bool shutdown) { { - Lock sync(*this); + lock_guard lock(_mutex); if(_destroy) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); @@ -368,11 +385,10 @@ NodeSessionI::destroyImpl(bool shutdown) } ServerEntrySeq servers = _database->getNode(_info->name)->getServers(); -#ifdef ICE_CPP11_COMPILER - for_each(servers.begin(), servers.end(), [](const ServerEntryPtr& it) {it->unsync(); }); -#else - for_each(servers.begin(), servers.end(), IceUtil::voidMemFun(&ServerEntry::unsync)); -#endif + for(const auto& server : servers) + { + server->unsync(); + } // // If the registry isn't being shutdown we remove the node @@ -386,7 +402,8 @@ NodeSessionI::destroyImpl(bool shutdown) // // Next we notify the observer. // - NodeObserverTopicPtr::dynamicCast(_database->getObserverTopic(NodeObserverTopicName))->nodeDown(_info->name); + static_pointer_cast( + _database->getObserverTopic(TopicName::NodeObserver))->nodeDown(_info->name); // // Unsubscribe the node replica observer. @@ -394,7 +411,7 @@ NodeSessionI::destroyImpl(bool shutdown) if(_replicaObserver) { _database->getReplicaCache().unsubscribe(_replicaObserver); - _replicaObserver = 0; + _replicaObserver = nullptr; } // @@ -402,18 +419,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); - - // - // Clean up the patcher feedback servants (this will call back - // removeFeedback so we need to use a temporary set). - // - set feedbacks; - _feedbacks.swap(feedbacks); - for(set::const_iterator p = feedbacks.begin(); p != feedbacks.end(); ++p) - { - (*p)->failed("node is down"); - } + _database->getNode(_info->name)->setSession(nullptr); if(!shutdown) { @@ -427,18 +433,18 @@ NodeSessionI::destroyImpl(bool shutdown) } } -void -NodeSessionI::removeFeedback(const PatcherFeedbackPtr& feedback, const Ice::Identity& id) +void NodeSessionI::removeFeedback( + const shared_ptr& feedback, + const Ice::Identity& id) { try { _database->getInternalAdapter()->remove(id); } - catch(const Ice::LocalException&) - { - } + catch (const Ice::LocalException&) { - Lock sync(*this); - _feedbacks.erase(feedback); } + + lock_guard lock(_mutex); + _feedbacks.erase(feedback); } diff --git a/cpp/src/IceGrid/NodeSessionI.h b/cpp/src/IceGrid/NodeSessionI.h index 637f0ceac2f..b2d3d7b47f4 100644 --- a/cpp/src/IceGrid/NodeSessionI.h +++ b/cpp/src/IceGrid/NodeSessionI.h @@ -12,24 +12,26 @@ namespace IceGrid { class Database; -typedef IceUtil::Handle DatabasePtr; - class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; -class PatcherFeedbackAggregator : public IceUtil::Mutex, public IceUtil::Shared +class PatcherFeedbackAggregator { public: - PatcherFeedbackAggregator(Ice::Identity, const TraceLevelsPtr&, const std::string&, const std::string&, int); + PatcherFeedbackAggregator( + Ice::Identity, + const std::shared_ptr&, + const std::string&, + const std::string&, + int); virtual ~PatcherFeedbackAggregator(); void finished(const std::string&); - void failed(const std::string&, const std::string&); + void failed(std::string, const std::string&); protected: - virtual void exception(const Ice::Exception&) = 0; + virtual void exception(std::exception_ptr) = 0; virtual void response() = 0; private: @@ -37,63 +39,73 @@ class PatcherFeedbackAggregator : public IceUtil::Mutex, public IceUtil::Shared void checkIfDone(); const Ice::Identity _id; - const TraceLevelsPtr _traceLevels; + const std::shared_ptr _traceLevels; const std::string _type; const std::string _name; const int _count; std::set _successes; std::set _failures; Ice::StringSeq _reasons; + std::mutex _mutex; }; -typedef IceUtil::Handle PatcherFeedbackAggregatorPtr; -class NodeSessionI : public NodeSession, public IceUtil::Mutex +class NodeSessionI : public NodeSession, public std::enable_shared_from_this { 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(); - void patch(const PatcherFeedbackAggregatorPtr&, const std::string&, const std::string&, - const InternalDistributionDescriptorPtr&, bool); - - const NodePrx& getNode() const; - const InternalNodeInfoPtr& getInfo() const; + static std::shared_ptr create(const std::shared_ptr&, const std::shared_ptr&, + const std::shared_ptr&, + std::chrono::seconds, const LoadInfo&); + + void keepAlive(LoadInfo, const Ice::Current&) override; + void setReplicaObserver(std::shared_ptr, const Ice::Current&) override; + int getTimeout(const Ice::Current&) const override; + std::shared_ptr getObserver(const Ice::Current&) const override; + void loadServersAsync(std::function, std::function, + const Ice::Current&) const override; + Ice::StringSeq getServers(const Ice::Current&) const override; + void waitForApplicationUpdateAsync(std::string, int, std::function, std::function, + const Ice::Current&) const override; + void destroy(const Ice::Current&) override; + + std::chrono::steady_clock::time_point timestamp() const; + void shutdown(); + void patch( + const std::shared_ptr&, + const std::string&, + const std::string&, + const std::shared_ptr&, bool); + + const std::shared_ptr& getNode() const; + const std::shared_ptr& getInfo() const; const LoadInfo& getLoadInfo() const; - NodeSessionPrx getProxy() const; + std::shared_ptr getProxy() const; bool isDestroyed() const; - void removeFeedback(const PatcherFeedbackPtr&, const Ice::Identity&); + void removeFeedback(const std::shared_ptr&, const Ice::Identity&); private: + NodeSessionI(const std::shared_ptr&, const std::shared_ptr&, + const std::shared_ptr&, std::chrono::seconds, const LoadInfo&); + void destroyImpl(bool); - const DatabasePtr _database; - const TraceLevelsPtr _traceLevels; + const std::shared_ptr _database; + const std::shared_ptr _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 _node; + const std::shared_ptr _info; + const std::chrono::seconds _timeout; + std::shared_ptr _proxy; + std::shared_ptr _replicaObserver; + std::chrono::steady_clock::time_point _timestamp; LoadInfo _load; bool _destroy; - std::set _feedbacks; + std::set> _feedbacks; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle NodeSessionIPtr; }; diff --git a/cpp/src/IceGrid/NodeSessionManager.cpp b/cpp/src/IceGrid/NodeSessionManager.cpp index ab9ef518313..719aff922ba 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& registry, + const shared_ptr& node, NodeSessionManager& manager) : SessionKeepAliveThread(registry, node->getTraceLevels()->logger), _node(node), _manager(manager) { @@ -26,12 +26,12 @@ NodeSessionKeepAliveThread::NodeSessionKeepAliveThread(const InternalRegistryPrx const_cast(_replicaName) = name; } -NodeSessionPrx -NodeSessionKeepAliveThread::createSession(InternalRegistryPrx& registry, IceUtil::Time& timeout) +shared_ptr +NodeSessionKeepAliveThread::createSession(shared_ptr& registry, chrono::seconds& timeout) { - NodeSessionPrx session; - IceInternal::UniquePtr exception; - TraceLevelsPtr traceLevels = _node->getTraceLevels(); + shared_ptr 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 used; + set> 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(registry->ice_endpoints(Ice::EndpointSeq())); } } if(!session) { - vector results; - vector queryObjects = _manager.getQueryObjects(); - for(vector::const_iterator q = queryObjects.begin(); q != queryObjects.end(); ++q) + vector>> 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::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 newRegistry; try { - Ice::ObjectPrx obj = query->end_findObjectById(*p); - newRegistry = InternalRegistryPrx::uncheckedCast(obj); + auto obj = result.get(); + newRegistry = Ice::uncheckedCast(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 +NodeSessionKeepAliveThread::createSessionImpl(const shared_ptr& registry, chrono::seconds& timeout) { - NodeSessionPrx session; + shared_ptr 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& session) { _node->removeObserver(session); @@ -196,7 +197,7 @@ NodeSessionKeepAliveThread::destroySession(const NodeSessionPrx& session) } bool -NodeSessionKeepAliveThread::keepAlive(const NodeSessionPrx& session) +NodeSessionKeepAliveThread::keepAlive(const shared_ptr& 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& 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& node) { { - Lock sync(*this); + lock_guard lock(_mutex); assert(!_node); - const_cast(_node) = node; - _thread = new Thread(*this); - _thread->start(); + const_cast&>(_node) = node; + _thread = make_shared(*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& replica) { assert(_thread); - NodeSessionKeepAliveThreadPtr thread; + shared_ptr 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& 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& 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 +NodeSessionManager::addReplicaSession(const shared_ptr& replica) { assert(!_destroyed); - NodeSessionMap::const_iterator p = _sessions.find(replica->ice_getIdentity()); - NodeSessionKeepAliveThreadPtr thread; + auto p = _sessions.find(replica->ice_getIdentity()); + shared_ptr 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(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 reap; + // NodeSessionKeepAliveThread's destructor will join its thread on destruction + // Keep this vector do the destruction outside the lock + vector> 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::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& 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& session) { bool activated; { - Lock sync(*this); + lock_guard lock(_mutex); activated = _activated; } @@ -534,9 +538,10 @@ NodeSessionManager::createdSession(const NodeSessionPrx& session) } else { - vector results1; - vector results2; - vector queryObjects = findAllQueryObjects(false); + + vector> results1; + vector> 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::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::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 proxies; - for(vector::const_iterator p = results1.begin(); p != results1.end(); ++p) + map> 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::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(prx->ice_identity(id))); + + proxies[id] = std::move(prx); } } catch(const Ice::LocalException&) @@ -614,15 +620,15 @@ NodeSessionManager::createdSession(const NodeSessionPrx& session) } } - for(map::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(prx.second)); } } - vector sessions; + vector> 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::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(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 -#include -#include - #include #include #include @@ -18,40 +14,40 @@ namespace IceGrid { class NodeI; -typedef IceUtil::Handle NodeIPtr; - class NodeSessionManager; class NodeSessionKeepAliveThread : public SessionKeepAliveThread { public: - NodeSessionKeepAliveThread(const InternalRegistryPrx&, const NodeIPtr&, NodeSessionManager&); + NodeSessionKeepAliveThread(const std::shared_ptr&, const std::shared_ptr&, + NodeSessionManager&); - virtual NodeSessionPrx createSession(InternalRegistryPrx&, IceUtil::Time&); - virtual void destroySession(const NodeSessionPrx&); - virtual bool keepAlive(const NodeSessionPrx&); + virtual std::shared_ptr createSession(std::shared_ptr&, + std::chrono::seconds&) override; + virtual void destroySession(const std::shared_ptr&) override; + virtual bool keepAlive(const std::shared_ptr&) 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 createSessionImpl(const std::shared_ptr&, + std::chrono::seconds&); - const NodeIPtr _node; + const std::shared_ptr _node; const std::string _replicaName; NodeSessionManager& _manager; }; -typedef IceUtil::Handle NodeSessionKeepAliveThreadPtr; class NodeSessionManager : public SessionManager { public: - NodeSessionManager(const Ice::CommunicatorPtr&, const std::string&); + NodeSessionManager(const std::shared_ptr&, const std::string&); - void create(const NodeIPtr&); - void create(const InternalRegistryPrx&); + void create(const std::shared_ptr&); + void create(const std::shared_ptr&); void activate(); bool isWaitingForCreate(); bool waitForCreate(); @@ -59,27 +55,27 @@ class NodeSessionManager : public SessionManager void destroy(); void replicaInit(const InternalRegistryPrxSeq&); - void replicaAdded(const InternalRegistryPrx&); - void replicaRemoved(const InternalRegistryPrx&); + void replicaAdded(const std::shared_ptr&); + void replicaRemoved(const std::shared_ptr&); - NodeSessionPrx getMasterNodeSession() const { return _thread->getSession(); } - std::vector getQueryObjects() { return findAllQueryObjects(true); } + std::shared_ptr getMasterNodeSession() const { return _thread->getSession(); } + std::vector> getQueryObjects() { return findAllQueryObjects(true); } private: - NodeSessionKeepAliveThreadPtr addReplicaSession(const InternalRegistryPrx&); + std::shared_ptr addReplicaSession(const std::shared_ptr&); void reapReplicas(); - void syncServers(const NodeSessionPrx&); + void syncServers(const std::shared_ptr&); bool isDestroyed() { - Lock sync(*this); + std::lock_guard lock(_mutex); return _destroyed; } - class Thread : public NodeSessionKeepAliveThread + class Thread final : public NodeSessionKeepAliveThread { public: @@ -87,41 +83,40 @@ class NodeSessionManager : public SessionManager { } - virtual NodeSessionPrx - createSession(InternalRegistryPrx& master, IceUtil::Time& timeout) + std::shared_ptr + createSession(std::shared_ptr& 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& session) override { NodeSessionKeepAliveThread::destroySession(session); _manager.reapReplicas(); } - virtual bool - keepAlive(const NodeSessionPrx& session) + bool + keepAlive(const std::shared_ptr& session) override { bool alive = NodeSessionKeepAliveThread::keepAlive(session); _manager.reapReplicas(); return alive; } }; - typedef IceUtil::Handle ThreadPtr; friend class Thread; - void createdSession(const NodeSessionPrx&); + void createdSession(const std::shared_ptr&); - const NodeIPtr _node; - ThreadPtr _thread; + const std::shared_ptr _node; + std::shared_ptr _thread; bool _destroyed; bool _activated; - typedef std::map NodeSessionMap; + using NodeSessionMap = std::map>; NodeSessionMap _sessions; std::set _replicas; }; diff --git a/cpp/src/IceGrid/ObjectCache.cpp b/cpp/src/IceGrid/ObjectCache.cpp index 9d1e15cab56..3ea4e33495d 100644 --- a/cpp/src/IceGrid/ObjectCache.cpp +++ b/cpp/src/IceGrid/ObjectCache.cpp @@ -17,52 +17,40 @@ using namespace IceGrid; namespace IceGrid { -struct ObjectEntryCI +bool compareObjectEntryCI(const shared_ptr& lhs, const shared_ptr& 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 +bool compareObjectLoadCI(const pair& lhs, const pair& rhs) { - bool operator()(const pair& lhs, const pair& 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& 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& obj) { // // No mutex protection here, this is called with the cache locked. // - vector::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& communicator) : _communicator(communicator) { } @@ -71,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()); @@ -79,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(info, application, server); addImpl(id, entry); map::iterator p = _types.find(entry->getType()); if(p == _types.end()) { - p = _types.insert(p, map::value_type(entry->getType(), TypeEntry())); + p = _types.insert(p, { entry->getType(), TypeEntry() }); } p->second.add(entry); @@ -96,11 +84,11 @@ ObjectCache::add(const ObjectInfo& info, const string& application, const string } } -ObjectEntryPtr +shared_ptr ObjectCache::get(const Ice::Identity& id) const { - Lock sync(*this); - ObjectEntryPtr entry = getImpl(id); + lock_guard lock(_mutex); + shared_ptr entry = getImpl(id); if(!entry) { throw ObjectNotRegisteredException(id); @@ -111,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 entry = getImpl(id); if(!entry) { Ice::Error out(_communicator->getLogger()); @@ -135,14 +123,14 @@ ObjectCache::remove(const Ice::Identity& id) } } -vector +vector> ObjectCache::getObjectsByType(const string& type) { - Lock sync(*this); + lock_guard lock(_mutex); map::const_iterator p = _types.find(type); if(p == _types.end()) { - return vector(); + return vector>(); } return p->second.getObjects(); } @@ -150,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::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)) { @@ -165,7 +153,7 @@ ObjectCache::getAll(const string& expression) ObjectInfoSeq ObjectCache::getAllByType(const string& type) { - Lock sync(*this); + lock_guard lock(_mutex); ObjectInfoSeq infos; map::const_iterator p = _types.find(type); if(p == _types.end()) @@ -173,8 +161,8 @@ ObjectCache::getAllByType(const string& type) return infos; } - const vector& objects = p->second.getObjects(); - for(vector::const_iterator q = objects.begin(); q != objects.end(); ++q) + const vector>& objects = p->second.getObjects(); + for(vector>::const_iterator q = objects.begin(); q != objects.end(); ++q) { infos.push_back((*q)->getObjectInfo()); } @@ -188,7 +176,7 @@ ObjectEntry::ObjectEntry(const ObjectInfo& info, const string& application, cons { } -Ice::ObjectPrx +shared_ptr ObjectEntry::getProxy() const { return _info.proxy; diff --git a/cpp/src/IceGrid/ObjectCache.h b/cpp/src/IceGrid/ObjectCache.h index b279389f19e..2f578b92158 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 #include #include #include @@ -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 getProxy() const; std::string getType() const; std::string getApplication() const; std::string getServer() const; @@ -34,24 +33,23 @@ class ObjectEntry : public IceUtil::Shared const std::string _application; const std::string _server; }; -typedef IceUtil::Handle ObjectEntryPtr; class ObjectCache : public Cache { public: - ObjectCache(const Ice::CommunicatorPtr&); + ObjectCache(const std::shared_ptr&); void add(const ObjectInfo&, const std::string&, const std::string&); - ObjectEntryPtr get(const Ice::Identity&) const; + std::shared_ptr get(const Ice::Identity&) const; void remove(const Ice::Identity&); - std::vector getObjectsByType(const std::string&); + std::vector> 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& getCommunicator() const { return _communicator; } private: @@ -59,19 +57,17 @@ class ObjectCache : public Cache { public: - TypeEntry(); + void add(const std::shared_ptr&); + bool remove(const std::shared_ptr&); - void add(const ObjectEntryPtr&); - bool remove(const ObjectEntryPtr&); - - const std::vector& getObjects() const { return _objects; } + const std::vector>& getObjects() const { return _objects; } private: - std::vector _objects; + std::vector> _objects; }; - const Ice::CommunicatorPtr _communicator; + const std::shared_ptr _communicator; std::map _types; }; diff --git a/cpp/src/IceGrid/Parser.cpp b/cpp/src/IceGrid/Parser.cpp index edcf11e4c69..d5a04e40f60 100644 --- a/cpp/src/IceGrid/Parser.cpp +++ b/cpp/src/IceGrid/Parser.cpp @@ -242,7 +242,7 @@ const char* _commandsHelp[][3] = { int loggerCallbackCount = 0; #ifdef _WIN32 -Ice::StringConverterPtr windowsConsoleConverter = 0; +shared_ptr windowsConsoleConverter = nullptr; #endif void outputNewline() @@ -292,12 +292,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()) @@ -308,12 +308,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; @@ -325,27 +325,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 _monitor; + mutex _mutex; + condition_variable _condVar; bool _initDone; bool _destroyed; string _prefix; }; -typedef IceUtil::Handle RemoteLoggerIPtr; - RemoteLoggerI::RemoteLoggerI() : _initDone(false), _destroyed(false) @@ -353,31 +352,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::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::Lock lock(_monitor); - while(!_initDone && !_destroyed) - { - _monitor.wait(); - } + unique_lock lock(_mutex); + + _condVar.wait(lock, [this] { return _initDone || _destroyed; } ); + if(!_destroyed) { printLogMessage(_prefix, logMessage); @@ -387,9 +385,9 @@ RemoteLoggerI::log(const Ice::LogMessage& logMessage, const Ice::Current&) void RemoteLoggerI::destroy() { - IceUtil::Monitor::Lock lock(_monitor); + lock_guard lock(_mutex); _destroyed = true; - _monitor.notifyAll(); + _condVar.notify_all(); } } @@ -401,11 +399,31 @@ Parser* parser; } -ParserPtr -Parser::createParser(const CommunicatorPtr& communicator, const AdminSessionPrx& session, const AdminPrx& admin, - bool interactive) +Parser::Parser(shared_ptr communicator, + shared_ptr session, + shared_ptr admin, + bool interactive) : + _communicator(std::move(communicator)), + _session(std::move(session)), + _admin(std::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 @@ -468,22 +486,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; } @@ -492,7 +510,7 @@ Parser::checkInterrupted() { if(!_interactive) { - Lock sync(*this); + lock_guard lock(_mutex); if(_interrupted) { throw runtime_error("interrupted with Ctrl-C"); @@ -511,9 +529,9 @@ Parser::addApplication(const list& origArgs) vector args; try { - for(list::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); } @@ -639,9 +657,9 @@ Parser::diffApplication(const list& origArgs) vector args; try { - for(list::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); } @@ -906,8 +924,8 @@ Parser::describeServerTemplate(const list& 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(q->second.descriptor); + auto iceBox = dynamic_pointer_cast(server); if(iceBox) { IceBoxHelper(iceBox).print(_communicator, out); @@ -997,7 +1015,7 @@ Parser::describeServiceTemplate(const list& args) out << nl << "parameters = `" << toString(q->second.parameters) << "'"; out << nl; - ServiceDescriptorPtr desc = ServiceDescriptorPtr::dynamicCast(q->second.descriptor); + auto desc = dynamic_pointer_cast(q->second.descriptor); ServiceHelper(desc).print(_communicator, out); out << eb; out << nl; @@ -1451,8 +1469,8 @@ Parser::writeMessage(const list& args, int fd) list::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(serverAdmin, "Process"); process->writeMessage(*p, fd); } @@ -1484,7 +1502,7 @@ Parser::describeServer(const list& args) ServerInfo info = _admin->getServerInfo(args.front()); ostringstream os; Output out(os); - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); + auto iceBox = dynamic_pointer_cast(info.descriptor); if(iceBox) { IceBoxHelper(iceBox).print(_communicator, out, info); @@ -1517,39 +1535,39 @@ Parser::stateServer(const list& 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; @@ -1607,8 +1625,8 @@ Parser::propertiesServer(const list& 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(serverAdmin, "Properties"); if(single) { @@ -1617,10 +1635,9 @@ Parser::propertiesServer(const list& 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; } } } @@ -1699,8 +1716,8 @@ Parser::startService(const list& 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(admin, "IceBox.ServiceManager"); manager->startService(service); } catch(const IceBox::AlreadyStartedException&) @@ -1738,8 +1755,8 @@ Parser::stopService(const list& 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(admin, "IceBox.ServiceManager"); manager->stopService(service); } catch(const IceBox::AlreadyStoppedException&) @@ -1778,7 +1795,7 @@ Parser::describeService(const list& args) try { ServerInfo info = _admin->getServerInfo(server); - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); + auto iceBox = dynamic_pointer_cast(info.descriptor); if(!iceBox) { error("server `" + server + "' is not an IceBox server"); @@ -1788,11 +1805,11 @@ Parser::describeService(const list& 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; @@ -1837,7 +1854,7 @@ Parser::propertiesService(const list& 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(info.descriptor); if(!iceBox) { error("server `" + server + "' is not an IceBox server"); @@ -1845,9 +1862,10 @@ Parser::propertiesService(const list& 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; @@ -1859,15 +1877,15 @@ Parser::propertiesService(const list& args, bool single) return; } - Ice::ObjectPrx admin = _admin->getServerAdmin(server); - Ice::PropertiesAdminPrx propAdmin; + auto admin = _admin->getServerAdmin(server); + shared_ptr propAdmin; if(getPropertyAsInt(info.descriptor->propertySet.properties, "IceBox.UseSharedCommunicator." + service) > 0) { - propAdmin = Ice::PropertiesAdminPrx::uncheckedCast(admin, "IceBox.SharedCommunicator.Properties"); + propAdmin = Ice::uncheckedCast(admin, "IceBox.SharedCommunicator.Properties"); } else { - propAdmin = Ice::PropertiesAdminPrx::uncheckedCast(admin, "IceBox.Service." + service + ".Properties"); + propAdmin = Ice::uncheckedCast(admin, "IceBox.Service." + service + ".Properties"); } if(single) @@ -1911,17 +1929,17 @@ Parser::listServices(const list& args) try { ServerInfo info = _admin->getServerInfo(server); - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); + auto iceBox = dynamic_pointer_cast(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; } } } @@ -2259,7 +2277,7 @@ Parser::showFile(const string& id, const string& reader, const string& filename, int maxBytes = _communicator->getProperties()->getPropertyAsIntWithDefault("Ice.MessageSizeMax", 1024) * 1024; - FileIteratorPrx it; + shared_ptr it; try { @@ -2322,10 +2340,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(); } } @@ -2336,10 +2354,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(); } } @@ -2365,12 +2383,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); } } } @@ -2404,7 +2422,7 @@ Parser::showLog(const string& id, const string& reader, bool tail, bool follow, { outputNewline(); - Ice::ObjectPrx admin; + shared_ptr admin; if(reader == "server") { @@ -2425,11 +2443,11 @@ Parser::showLog(const string& id, const string& reader, bool tail, bool follow, return; } - Ice::LoggerAdminPrx loggerAdmin; + shared_ptr loggerAdmin; try { - loggerAdmin = Ice::LoggerAdminPrx::checkedCast(admin, "Logger"); + loggerAdmin = Ice::checkedCast(admin, "Logger"); } catch(const Ice::Exception&) { @@ -2443,7 +2461,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) { @@ -2454,44 +2472,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(); + auto prx = Ice::uncheckedCast(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(); @@ -2844,33 +2857,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 1197b4f55a6..e23449b785e 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 #include #include + #include #include @@ -38,19 +38,11 @@ YY_DECL; namespace IceGrid { -class Parser; -typedef ::IceUtil::Handle ParserPtr; - -} - -namespace IceGrid -{ - -class Parser : public ::IceUtil::SimpleShared, IceUtil::Monitor +class Parser { public: - static ParserPtr createParser(const Ice::CommunicatorPtr&, const AdminSessionPrx&, const AdminPrx&, bool); + Parser(std::shared_ptr, std::shared_ptr, std::shared_ptr, bool); void usage(); void usage(const std::string&, const std::string& = std::string()); @@ -148,16 +140,18 @@ class Parser : public ::IceUtil::SimpleShared, IceUtil::Monitor 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 _communicator; + std::shared_ptr _session; + std::shared_ptr _admin; bool _continue; bool _interrupted; int _errors; diff --git a/cpp/src/IceGrid/PlatformInfo.cpp b/cpp/src/IceGrid/PlatformInfo.cpp index e3e8479d8c4..a15e2fd89dc 100644 --- a/cpp/src/IceGrid/PlatformInfo.cpp +++ b/cpp/src/IceGrid/PlatformInfo.cpp @@ -22,13 +22,6 @@ # include # if defined(__APPLE__) || defined(__FreeBSD__) || defined(__FreeBSD_kernel__) # include -# elif defined(__sun) -# include -# elif defined(__hpux) -# include -# elif defined(_AIX) -# include -# include # 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& logger) { vector localized; unsigned long size = 256; @@ -95,7 +88,7 @@ class UpdateUtilizationAverageThread : public IceUtil::Thread typedef BOOL (WINAPI *LPFN_GLPI)(PSYSTEM_LOGICAL_PROCESSOR_INFORMATION, PDWORD); int -getSocketCount(const Ice::LoggerPtr& logger) +getSocketCount(const shared_ptr& 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& replica) { RegistryInfo info; info.name = replica->name; @@ -158,7 +151,7 @@ toRegistryInfo(const InternalReplicaInfoPtr& replica) } NodeInfo -toNodeInfo(const InternalNodeInfoPtr& node) +toNodeInfo(const shared_ptr& 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& communicator, + const shared_ptr& 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("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 // @@ -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::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 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(_name, _os, _hostname, _release, _version, + _machine, _nProcessorThreads, _dataDir); } -InternalReplicaInfoPtr +shared_ptr PlatformInfo::getInternalReplicaInfo() const { - InternalReplicaInfoPtr info = new InternalReplicaInfo(); - info->name = _name; - info->hostname = _hostname; - return info; + return make_shared(_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::Lock sync(_utilizationMonitor); + lock_guard lock(_utilizationMutex); info.avg1 = static_cast(_last1Total) / _usages1.size() / 100.0f; info.avg5 = static_cast(_last5Total) / _usages5.size() / 100.0f; info.avg15 = static_cast(_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(loadAvg[0]); info.avg5 = static_cast(loadAvg[1]); info.avg15 = static_cast(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("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::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 #include #ifdef _WIN32 @@ -17,28 +16,26 @@ namespace IceGrid { class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; -NodeInfo toNodeInfo(const InternalNodeInfoPtr&); -RegistryInfo toRegistryInfo(const InternalReplicaInfoPtr&); +NodeInfo toNodeInfo(const std::shared_ptr&); +RegistryInfo toRegistryInfo(const std::shared_ptr&); -class PlatformInfo +class PlatformInfo final { public: - PlatformInfo(const std::string&, const Ice::CommunicatorPtr&, const TraceLevelsPtr&); - ~PlatformInfo(); + PlatformInfo(const std::string&, const std::shared_ptr&, const std::shared_ptr&); void start(); void stop(); - InternalNodeInfoPtr getInternalNodeInfo() const; - InternalReplicaInfoPtr getInternalReplicaInfo() const; + std::shared_ptr getInternalNodeInfo() const; + std::shared_ptr 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 @@ class PlatformInfo private: - const TraceLevelsPtr _traceLevels; + const std::shared_ptr _traceLevels; std::string _name; std::string _os; std::string _hostname; @@ -64,17 +61,16 @@ class PlatformInfo int _nProcessorSockets; #if defined(_WIN32) - IceUtil::ThreadPtr _updateUtilizationThread; - IceUtil::Monitor _utilizationMonitor; - bool _terminated; std::deque _usages1; std::deque _usages5; std::deque _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..aeb2fb83ed1 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&); } @@ -26,23 +26,23 @@ class Init Init() { - IceGrid::setRegistryPluginFacade(new RegistryPluginFacadeI); + IceGrid::setRegistryPluginFacade(make_shared()); } ~Init() { - IceGrid::setRegistryPluginFacade(0); + IceGrid::setRegistryPluginFacade(nullptr); } }; Init init; bool -hasAdapter(const CommunicatorDescriptorPtr& descriptor, const string& adapterId) +hasAdapter(const shared_ptr& 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(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& filter) ICE_NOEXCEPT { - Lock sync(*this); - map >::iterator p = _replicaGroupFilters.find(id); + lock_guard lock(_mutex); + map> >::iterator p = _replicaGroupFilters.find(id); if(p == _replicaGroupFilters.end()) { - p = _replicaGroupFilters.insert(make_pair(id, vector())).first; + p = _replicaGroupFilters.insert(make_pair(id, vector>())).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& filter) ICE_NOEXCEPT { - Lock sync(*this); + lock_guard lock(_mutex); - map >::iterator p = _replicaGroupFilters.find(id); + map> >::iterator p = _replicaGroupFilters.find(id); if(p == _replicaGroupFilters.end()) { return false; } - vector::iterator q = find(p->second.begin(), p->second.end(), filter); + vector>::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& filter) ICE_NOEXCEPT { - Lock sync(*this); - map >::iterator p = _typeFilters.find(id); + lock_guard lock(_mutex); + map> >::iterator p = _typeFilters.find(id); if(p == _typeFilters.end()) { - p = _typeFilters.insert(make_pair(id, vector())).first; + p = _typeFilters.insert(make_pair(id, vector>())).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& filter) ICE_NOEXCEPT { - Lock sync(*this); + lock_guard lock(_mutex); - map >::iterator p = _typeFilters.find(id); + map> >::iterator p = _typeFilters.find(id); if(p == _typeFilters.end()) { return false; } - vector::iterator q = find(p->second.begin(), p->second.end(), filter); + vector>::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 +vector> RegistryPluginFacadeI::getReplicaGroupFilters(const string& id) const { - Lock sync(*this); - map >::const_iterator p = _replicaGroupFilters.find(id); + lock_guard lock(_mutex); + map> >::const_iterator p = _replicaGroupFilters.find(id); if(p != _replicaGroupFilters.end()) { return p->second; } - return vector(); + return vector>(); } bool @@ -281,16 +277,16 @@ RegistryPluginFacadeI::hasReplicaGroupFilters() const return !_replicaGroupFilters.empty(); } -vector +vector> RegistryPluginFacadeI::getTypeFilters(const string& id) const { - Lock sync(*this); - map >::const_iterator p = _typeFilters.find(id); + lock_guard lock(_mutex); + map> >::const_iterator p = _typeFilters.find(id); if(p != _typeFilters.end()) { return p->second; } - return vector(); + return vector>(); } bool @@ -300,8 +296,8 @@ RegistryPluginFacadeI::hasTypeFilters() const } void -RegistryPluginFacadeI::setDatabase(const DatabasePtr& database) +RegistryPluginFacadeI::setDatabase(const shared_ptr& 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 -#include - #include namespace IceGrid { class Database; -typedef IceUtil::Handle 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&) noexcept override; + bool removeReplicaGroupFilter(const std::string&, const std::shared_ptr&) 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&) noexcept override; + bool removeTypeFilter(const std::string&, const std::shared_ptr&) noexcept override; - std::vector getReplicaGroupFilters(const std::string&) const; + std::vector> getReplicaGroupFilters(const std::string&) const; bool hasReplicaGroupFilters() const; - std::vector getTypeFilters(const std::string&) const; + std::vector> getTypeFilters(const std::string&) const; bool hasTypeFilters() const; - void setDatabase(const DatabasePtr&); + void setDatabase(const std::shared_ptr&); private: - DatabasePtr _database; - std::map > _replicaGroupFilters; - std::map > _typeFilters; + std::shared_ptr _database; + std::map> > _replicaGroupFilters; + std::map> > _typeFilters; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle RegistryPluginFacadeIPtr; } diff --git a/cpp/src/IceGrid/QueryI.cpp b/cpp/src/IceGrid/QueryI.cpp index e6f5b1ee090..8f68cabf57e 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, const shared_ptr& database) : _communicator(communicator), _database(database) { } -QueryI::~QueryI() -{ -} - -Ice::ObjectPrx -QueryI::findObjectById(const Ice::Identity& id, const Ice::Current&) const +shared_ptr +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 +QueryI::findObjectByType(string type, const Ice::Current& current) const { - return _database->getObjectByType(type, current.con, current.ctx); + return _database->getObjectByType(std::move(type), current.con, current.ctx); } -Ice::ObjectPrx -QueryI::findObjectByTypeOnLeastLoadedNode(const string& type, LoadSample sample, const Ice::Current& current) const +shared_ptr +QueryI::findObjectByTypeOnLeastLoadedNode(string type, LoadSample sample, const Ice::Current& current) const { - return _database->getObjectByTypeOnLeastLoadedNode(type, sample, current.con, current.ctx); + return _database->getObjectByTypeOnLeastLoadedNode(std::move(type), std::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(std::move(type), current.con, current.ctx); } Ice::ObjectProxySeq -QueryI::findAllReplicas(const Ice::ObjectPrx& proxy, const Ice::Current& current) const +QueryI::findAllReplicas(shared_ptr 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 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&, const std::shared_ptr&); - virtual Ice::ObjectPrx findObjectById(const ::Ice::Identity&, const ::Ice::Current&) const; + std::shared_ptr findObjectById(Ice::Identity, const Ice::Current&) const override; - virtual Ice::ObjectPrx findObjectByType(const ::std::string&, const ::Ice::Current&) const; + std::shared_ptr findObjectByType(std::string, const Ice::Current&) const override; - virtual Ice::ObjectPrx findObjectByTypeOnLeastLoadedNode(const ::std::string&, LoadSample, - const ::Ice::Current&) const; + std::shared_ptr 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, const Ice::Current&) const override; private: - const Ice::CommunicatorPtr _communicator; - const DatabasePtr _database; + const std::shared_ptr _communicator; + const std::shared_ptr _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::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 >::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::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 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 >::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::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, chrono::seconds timeout, + const shared_ptr& 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 >::iterator p = _connections.find(connection); + auto p = _connections.find(connection); if(p == _connections.end()) { - p = _connections.insert(make_pair(connection, set())).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& con) { - Lock sync(*this); - map >::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::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& con) { - Lock sync(*this); - map >::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::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::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 -#include -#include - #include #include #include @@ -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 ReapablePtr; template class SessionReapable : public Reapable { - typedef IceUtil::Handle TPtr; - public: - SessionReapable(const Ice::LoggerPtr& logger, const TPtr& session) : + SessionReapable(const std::shared_ptr& logger, const std::shared_ptr& 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 @@ class SessionReapable : public Reapable protected: - const Ice::LoggerPtr _logger; - const TPtr _session; + const std::shared_ptr _logger; + const std::shared_ptr _session; }; template -class SessionReapableWithHeartbeat : public SessionReapable +class SessionReapableWithHeartbeat final : public SessionReapable { - typedef IceUtil::Handle TPtr; - public: - SessionReapableWithHeartbeat(const Ice::LoggerPtr& logger, const TPtr& session) : + SessionReapableWithHeartbeat(const std::shared_ptr& logger, const std::shared_ptr& session) : SessionReapable(logger, session) { } - virtual void - heartbeat() const + void + heartbeat() const override { try { @@ -110,39 +97,44 @@ class SessionReapableWithHeartbeat : public SessionReapable } }; -class ReapThread : public IceUtil::Thread, public IceUtil::Monitor +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&, std::chrono::seconds, const std::shared_ptr& = nullptr); - void connectionHeartbeat(const Ice::ConnectionPtr&); - void connectionClosed(const Ice::ConnectionPtr&); + void connectionHeartbeat(const std::shared_ptr&); + void connectionClosed(const std::shared_ptr&); 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 item; + std::shared_ptr connection; + std::chrono::milliseconds timeout; }; std::list _sessions; - std::map > _connections; -}; -typedef IceUtil::Handle ReapThreadPtr; + std::map, std::set> > _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 27de3bea72d..c1a078e5a6d 100644 --- a/cpp/src/IceGrid/RegistryAdminRouter.cpp +++ b/cpp/src/IceGrid/RegistryAdminRouter.cpp @@ -14,15 +14,20 @@ using namespace std; namespace { -class SynchronizationCallbackI : public SynchronizationCallback +class SynchronizationCallbackI final : public SynchronizationCallback { public: - SynchronizationCallbackI(const IceUtil::Handle& adminRouter, - const AMD_Object_ice_invokePtr& cb, + SynchronizationCallbackI(const shared_ptr& adminRouter, const pair& inParams, + function&)> response, + function exception, const Current& current) : - _adminRouter(adminRouter), _callback(cb), _inParams(inParams.first, inParams.second), _current(current) + _adminRouter(adminRouter), + _response(std::move(response)), + _exception(std::move(exception)), + _inParams(inParams.first, inParams.second), + _current(current) { } @@ -31,47 +36,51 @@ class SynchronizationCallbackI : public SynchronizationCallback // // 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() }, + std::move(_response), std::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 _adminRouter; - const AMD_Object_ice_invokePtr _callback; + const shared_ptr _adminRouter; + function&)> _response; + function _exception; const vector _inParams; const Current _current; }; } -IceGrid::RegistryServerAdminRouter::RegistryServerAdminRouter(const DatabasePtr& database) : +RegistryServerAdminRouter::RegistryServerAdminRouter(const shared_ptr& database) : AdminRouter(database->getTraceLevels()), _database(database) { } void -IceGrid::RegistryServerAdminRouter::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, - const std::pair& inParams, - const Current& current) +RegistryServerAdminRouter::ice_invokeAsync(pair inParams, + function&)> response, + function exception, + const Ice::Current& current) { - ObjectPrx target = 0; + shared_ptr 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(shared_from_this(), inParams, + std::move(response), std::move(exception), current)); return; // Wait for the server synchronization to complete and retry. } } @@ -85,17 +94,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, std::move(response), std::move(exception), current); } -IceGrid::RegistryNodeAdminRouter::RegistryNodeAdminRouter(const string& collocNodeName, const DatabasePtr& database) : +RegistryNodeAdminRouter::RegistryNodeAdminRouter(const string& collocNodeName, const shared_ptr& database) : AdminRouter(database->getTraceLevels()), _collocNodeName(collocNodeName), _database(database) @@ -103,11 +112,12 @@ IceGrid::RegistryNodeAdminRouter::RegistryNodeAdminRouter(const string& collocNo } void -IceGrid::RegistryNodeAdminRouter::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, - const std::pair& inParams, - const Current& current) +RegistryNodeAdminRouter::ice_invokeAsync(pair inParams, + function&)> response, + function exception, + const Ice::Current& current) { - ObjectPrx target; + shared_ptr target; if(!_collocNodeName.empty() && current.id.name == _collocNodeName) { @@ -141,11 +151,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, std::move(response), std::move(exception), current); } -IceGrid::RegistryReplicaAdminRouter::RegistryReplicaAdminRouter(const string& name, - const DatabasePtr& database) : +RegistryReplicaAdminRouter::RegistryReplicaAdminRouter(const string& name, + const shared_ptr& database) : AdminRouter(database->getTraceLevels()), _name(name), _database(database) @@ -153,11 +163,12 @@ IceGrid::RegistryReplicaAdminRouter::RegistryReplicaAdminRouter(const string& na } void -IceGrid::RegistryReplicaAdminRouter::ice_invoke_async(const AMD_Object_ice_invokePtr& cb, - const std::pair& inParams, - const Current& current) +RegistryReplicaAdminRouter::ice_invokeAsync(pair inParams, + function&)> response, + function exception, + const Ice::Current& current) { - ObjectPrx target; + shared_ptr target; if(current.id.name == _name) { @@ -176,7 +187,7 @@ IceGrid::RegistryReplicaAdminRouter::ice_invoke_async(const AMD_Object_ice_invok } } - if(target == 0) + if(target == nullptr) { if(_traceLevels->admin > 0) { @@ -189,5 +200,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, std::move(response), std::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 { public: - RegistryServerAdminRouter(const DatabasePtr&); + RegistryServerAdminRouter(const std::shared_ptr&); - virtual void ice_invoke_async(const Ice::AMD_Object_ice_invokePtr&, - const std::pair&, - const Ice::Current&); + void ice_invokeAsync(std::pair, + std::function&)>, + std::function, + const Ice::Current& current) override; private: - const DatabasePtr _database; + const std::shared_ptr _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&); - virtual void ice_invoke_async(const Ice::AMD_Object_ice_invokePtr&, - const std::pair&, - const Ice::Current&); + void ice_invokeAsync(std::pair, + std::function&)>, + std::function, + const Ice::Current& current) override; private: const std::string _collocNodeName; - const DatabasePtr _database; + const std::shared_ptr _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&); - virtual void ice_invoke_async(const Ice::AMD_Object_ice_invokePtr&, - const std::pair&, - const Ice::Current&); + void ice_invokeAsync(std::pair, + std::function&)>, + std::function, + const Ice::Current& current) override; private: const std::string _name; - const DatabasePtr _database; + const std::shared_ptr _database; }; } diff --git a/cpp/src/IceGrid/RegistryI.cpp b/cpp/src/IceGrid/RegistryI.cpp index 092ac2bf322..845e5363166 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& wellKnownObjects, + const shared_ptr& 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 reply, + const Ice::Current&) override { if(!instanceName.empty() && instanceName != _instanceName) { @@ -75,11 +76,11 @@ class LookupI : public IceLocatorDiscovery::Lookup 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 getLocator(const Ice::Current&) { return _wellKnownObjects->getLocator(); @@ -88,59 +89,59 @@ class LookupI : public IceLocatorDiscovery::Lookup private: const string _instanceName; - const WellKnownObjectsManagerPtr _wellKnownObjects; - const TraceLevelsPtr _traceLevels; + const shared_ptr _wellKnownObjects; + const shared_ptr _traceLevels; }; -class FinderI : public Ice::LocatorFinder +class FinderI final : public Ice::LocatorFinder { public: - FinderI(const WellKnownObjectsManagerPtr& wellKnownObjects) : _wellKnownObjects(wellKnownObjects) + FinderI(const shared_ptr& wellKnownObjects) : _wellKnownObjects(wellKnownObjects) { } - virtual Ice::LocatorPrx - getLocator(const Ice::Current&) + shared_ptr + getLocator(const Ice::Current&) override { return _wellKnownObjects->getLocator(); } private: - const WellKnownObjectsManagerPtr _wellKnownObjects; + const shared_ptr _wellKnownObjects; }; -class ProcessI : public Process +class ProcessI final : public Process { public: - ProcessI(const RegistryIPtr&, const ProcessPtr&); + ProcessI(const shared_ptr&, const shared_ptr&); - 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 _registry; + shared_ptr _origProcess; }; -Ice::IPConnectionInfoPtr -getIPConnectionInfo(const Ice::ConnectionInfoPtr& info) +shared_ptr +getIPConnectionInfo(const shared_ptr& 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(p); if(ipInfo) { return ipInfo; } } - return ICE_NULLPTR; + return nullptr; } -ProcessI::ProcessI(const RegistryIPtr& registry, const ProcessPtr& origProcess) : +ProcessI::ProcessI(const shared_ptr& registry, const shared_ptr& 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(std::move(message), std::move(fd), current); } } -RegistryI::RegistryI(const CommunicatorPtr& communicator, - const TraceLevelsPtr& traceLevels, +RegistryI::RegistryI(const shared_ptr& communicator, + const shared_ptr& 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(_communicator, _instanceName); // // Create the registry database. @@ -384,8 +377,7 @@ RegistryI::startImpl() // // Create the reaper thread. // - _reaper = new ReapThread(); - _reaper->start(); + _reaper = make_shared(); // // 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(_database); if(!_initFromReplica.empty()) { - Ice::Identity id; + Identity id; id.category = _instanceName; id.name = (_initFromReplica == "Master") ? "Registry" : "Registry-" + _initFromReplica; - Ice::ObjectPrx proxy; + + shared_ptr proxy; try { proxy = _database->getObjectProxy(id); id.name = "Query"; - IceGrid::QueryPrx query = IceGrid::QueryPrx::uncheckedCast(proxy->ice_identity(id)); + auto query = uncheckedCast(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(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(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(_database); + auto nodeAdminRouter = make_shared(_collocatedNodeName, _database); + auto replicaAdminRouter = make_shared(_replicaName, _database); + auto adminCallbackRouter = make_shared(); - _servantManager = new SessionServantManager(_clientAdapter, _instanceName, true, - getServerAdminCategory(), serverAdminRouter, - getNodeAdminCategory(), nodeAdminRouter, - getReplicaAdminCategory(), replicaAdminRouter, - adminCallbackRouter); + _servantManager = make_shared(_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(_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 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(_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(_database, dynReg, _master, *_session), locatorRegId); } -IceGrid::LocatorPrx -RegistryI::setupLocator(const RegistryPrx& registry, const QueryPrx& query) +shared_ptr +RegistryI::setupLocator(const shared_ptr& registry, const shared_ptr& query) { - LocatorPtr locator = new LocatorI(_communicator, _database, _wellKnownObjects, registry, query); + auto locator = make_shared(_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(_registryAdapter->addWithUUID(locator)); } -QueryPrx +shared_ptr 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(_clientAdapter->add(make_shared(_communicator, _database), std::move(queryId))); } -RegistryPrx +shared_ptr 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(_clientAdapter->add(shared_from_this(), std::move(registryId))); _wellKnownObjects->add(proxy, Registry::ice_staticId()); return proxy; } -InternalRegistryPrx +shared_ptr 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(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(_communicator->removeAdminFacet("Process")); + _communicator->addAdminFacet(make_shared(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, std::move(adminId)); } - InternalRegistryPrx registry = InternalRegistryPrx::uncheckedCast(proxy); + auto registry = uncheckedCast(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(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 +RegistryI::setupClientSessionFactory(const shared_ptr& locator) { - Ice::PropertiesPtr properties = _communicator->getProperties(); + auto properties = _communicator->getProperties(); - Ice::ObjectAdapterPtr adapter; - SessionServantManagerPtr servantManager; + shared_ptr adapter; + shared_ptr 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(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(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(_clientSessionFactory), sessionMgrId); + adapter->add(make_shared(_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(std::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 +RegistryI::setupAdminSessionFactory(const shared_ptr& serverAdminRouter, + const shared_ptr& nodeAdminRouter, + const shared_ptr& replicaAdminRouter, + const shared_ptr& locator) { - Ice::PropertiesPtr properties = _communicator->getProperties(); + auto properties = _communicator->getProperties(); - Ice::ObjectAdapterPtr adapter; - SessionServantManagerPtr servantManager; + shared_ptr adapter; + shared_ptr servantManager; if(!properties->getProperty("IceGrid.Registry.AdminSessionManager.Endpoints").empty()) { adapter = _communicator->createObjectAdapter("IceGrid.Registry.AdminSessionManager"); - servantManager = new SessionServantManager(adapter, _instanceName, false, + servantManager = make_shared(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(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(_adminSessionFactory), sessionMgrId); + adapter->add(make_shared(_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(std::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 +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(_traceLevels->logger, session), _sessionTimeout, + auto session = _clientSessionFactory->createSessionServant(user, nullptr); + auto proxy = session->_register(_servantManager, current.con); + _reaper->add(make_shared>(_traceLevels->logger, session), _sessionTimeout, current.con); - return SessionPrx::uncheckedCast(proxy); + return uncheckedCast(proxy); } -AdminSessionPrx -RegistryI::createAdminSession(const string& user, const string& password, const Current& current) +shared_ptr +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(_traceLevels->logger, session), _sessionTimeout, + auto session = _adminSessionFactory->createSessionServant(user); + auto proxy = session->_register(_servantManager, current.con); + _reaper->add(make_shared>(_traceLevels->logger, session), _sessionTimeout, current.con); - return AdminSessionPrx::uncheckedCast(proxy); + return uncheckedCast(proxy); } -SessionPrx +shared_ptr 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(_traceLevels->logger, session), _sessionTimeout, + auto session = _clientSessionFactory->createSessionServant(userDN, 0); + auto proxy = session->_register(_servantManager, current.con); + _reaper->add(make_shared>(_traceLevels->logger, session), _sessionTimeout, current.con); - return SessionPrx::uncheckedCast(proxy); + return uncheckedCast(proxy); } -AdminSessionPrx +shared_ptr 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(_traceLevels->logger, session), _sessionTimeout, + auto session = _adminSessionFactory->createSessionServant(userDN); + auto proxy = session->_register(_servantManager, current.con); + _reaper->add(make_shared>(_traceLevels->logger, session), _sessionTimeout, current.con); - return AdminSessionPrx::uncheckedCast(proxy); + return uncheckedCast(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 RegistryI::createAdminCallbackProxy(const Identity& id) const { return _serverAdapter->createProxy(id); } -Ice::LocatorPrx +shared_ptr RegistryI::getLocator() { return _wellKnownObjects->getLocator(); } -Glacier2::PermissionsVerifierPrx -RegistryI::getPermissionsVerifier(const IceGrid::LocatorPrx& locator, +shared_ptr +RegistryI::getPermissionsVerifier(const shared_ptr& locator, const string& verifierProperty) { // // Get the permissions verifier // - ObjectPrx verifier; + shared_ptr 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 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(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(verifier->ice_locator(locator)); } return verifierPrx; } -Glacier2::SSLPermissionsVerifierPrx -RegistryI::getSSLPermissionsVerifier(const IceGrid::LocatorPrx& locator, const string& verifierProperty) +shared_ptr +RegistryI::getSSLPermissionsVerifier(const shared_ptr& locator, const string& verifierProperty) { // // Get the permissions verifier, or create a default one if no // verifier is specified. // - ObjectPrx verifier; + shared_ptr 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 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(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(verifier->ice_locator(locator)); } return verifierPrx; } Glacier2::SSLInfo -RegistryI::getSSLInfo(const ConnectionPtr& connection, string& userDN) +RegistryI::getSSLInfo(const shared_ptr& connection, string& userDN) { Glacier2::SSLInfo sslinfo; try { - IceSSL::ConnectionInfoPtr info = IceSSL::ConnectionInfoPtr::dynamicCast(connection->getInfo()); + auto info = dynamic_pointer_cast(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::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& 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 replicas; - Ice::ObjectProxySeq proxies = _database->getObjectsByType(InternalRegistry::ice_staticId()); - for(ObjectProxySeq::const_iterator p = proxies.begin(); p != proxies.end(); ++p) + map, shared_ptr> replicas; + + for(const auto& p : _database->getObjectsByType(InternalRegistry::ice_staticId())) { - replicas.insert(pair(InternalRegistryPrx::uncheckedCast(*p), RegistryPrx())); + replicas.insert({ uncheckedCast(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(p->ice_identity(id))); - for(map::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::uncheckedCast(prx), - RegistryPrx::uncheckedCast(*p))); + replicas.insert({uncheckedCast(prx), uncheckedCast(p)}); } - set nodes; + set> nodes; nodes.insert(dbNodes.begin(), dbNodes.end()); - vector results; - for(map::const_iterator r = replicas.begin(); r != replicas.end(); ++r) + map, future> 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, std::move(fut)}); } } - for(vector::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::const_iterator q = replicas.begin(); q != replicas.end(); ++q) + shared_ptr 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::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&, 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..9154045d288 100644 --- a/cpp/src/IceGrid/RegistryI.h +++ b/cpp/src/IceGrid/RegistryI.h @@ -6,7 +6,6 @@ #define ICE_GRID_REGISTRYI_H #include -#include #include #include #include @@ -18,48 +17,36 @@ namespace IceGrid { +class AdminSessionFactory; +class ClientSessionFactory; class Database; -typedef IceUtil::Handle DatabasePtr; - -class WellKnownObjectsManager; -typedef IceUtil::Handle WellKnownObjectsManagerPtr; - -class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; - class ReapThread; -typedef IceUtil::Handle ReapThreadPtr; - class SessionServantManager; -typedef IceUtil::Handle SessionServantManagerPtr; - -class ClientSessionFactory; -typedef IceUtil::Handle ClientSessionFactoryPtr; - -class AdminSessionFactory; -typedef IceUtil::Handle AdminSessionFactoryPtr; +class TraceLevels; +class WellKnownObjectsManager; -std::string getInstanceName(const Ice::CommunicatorPtr&); +std::string getInstanceName(const std::shared_ptr&); -class RegistryI : public Registry +class RegistryI : public Registry, public std::enable_shared_from_this { public: - RegistryI(const Ice::CommunicatorPtr&, const TraceLevelsPtr&, bool, bool, const std::string&, const std::string&); - ~RegistryI(); + RegistryI(const std::shared_ptr&, const std::shared_ptr&, 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 createSession(std::string, std::string, const Ice::Current&) override; + std::shared_ptr createAdminSession(std::string, std::string, const Ice::Current&) override; - virtual SessionPrx createSessionFromSecureConnection(const Ice::Current&); - virtual AdminSessionPrx createAdminSessionFromSecureConnection(const Ice::Current&); + std::shared_ptr createSessionFromSecureConnection(const Ice::Current&) override; + std::shared_ptr 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 @@ class RegistryI : public Registry std::string getNodeAdminCategory() const { return _instanceName + "-RegistryNodeAdminRouter"; } std::string getReplicaAdminCategory() const { return _instanceName + "-RegistryReplicaAdminRouter"; } - Ice::ObjectPrx createAdminCallbackProxy(const Ice::Identity&) const; + std::shared_ptr createAdminCallbackProxy(const Ice::Identity&) const; - const Ice::ObjectAdapterPtr& getRegistryAdapter() { return _registryAdapter; } + const std::shared_ptr& getRegistryAdapter() { return _registryAdapter; } - Ice::LocatorPrx getLocator(); + std::shared_ptr getLocator(); private: void setupLocatorRegistry(); - LocatorPrx setupLocator(const RegistryPrx&, const QueryPrx&); - QueryPrx setupQuery(); - RegistryPrx setupRegistry(); - InternalRegistryPrx setupInternalRegistry(); + std::shared_ptr setupLocator(const std::shared_ptr&, const std::shared_ptr&); + std::shared_ptr setupQuery(); + std::shared_ptr setupRegistry(); + std::shared_ptr 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 setupClientSessionFactory(const std::shared_ptr&); + std::shared_ptr setupAdminSessionFactory(const std::shared_ptr&, + const std::shared_ptr&, + const std::shared_ptr&, + const std::shared_ptr&); + + std::shared_ptr getPermissionsVerifier(const std::shared_ptr&, + const std::string&); + std::shared_ptr getSSLPermissionsVerifier(const std::shared_ptr&, + const std::string&); + Glacier2::SSLInfo getSSLInfo(const std::shared_ptr&, std::string&); + + NodePrxSeq registerReplicas(const std::shared_ptr&, const NodePrxSeq&); + void registerNodes(const std::shared_ptr&, const NodePrxSeq&); + + const std::shared_ptr _communicator; + const std::shared_ptr _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; + std::shared_ptr _clientAdapter; + std::shared_ptr _serverAdapter; + std::shared_ptr _registryAdapter; + std::shared_ptr _wellKnownObjects; std::string _instanceName; bool _master; std::string _replicaName; - ReapThreadPtr _reaper; + std::shared_ptr _reaper; IceUtil::TimerPtr _timer; - SessionServantManagerPtr _servantManager; - int _sessionTimeout; - IceInternal::UniquePtr _session; + std::shared_ptr _servantManager; + std::chrono::seconds _sessionTimeout; + std::unique_ptr _session; mutable PlatformInfo _platform; - ClientSessionFactoryPtr _clientSessionFactory; - Glacier2::PermissionsVerifierPrx _clientVerifier; - Glacier2::SSLPermissionsVerifierPrx _sslClientVerifier; + std::shared_ptr _clientSessionFactory; + std::shared_ptr _clientVerifier; + std::shared_ptr _sslClientVerifier; - AdminSessionFactoryPtr _adminSessionFactory; - Glacier2::PermissionsVerifierPrx _adminVerifier; - Glacier2::SSLPermissionsVerifierPrx _sslAdminVerifier; + std::shared_ptr _adminSessionFactory; + std::shared_ptr _adminVerifier; + std::shared_ptr _sslAdminVerifier; - IceStormInternal::ServicePtr _iceStorm; + std::shared_ptr _iceStorm; }; -typedef IceUtil::Handle RegistryIPtr; } diff --git a/cpp/src/IceGrid/ReplicaCache.cpp b/cpp/src/IceGrid/ReplicaCache.cpp index 56cfac1d3e7..8733e82378b 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& communicator, + const shared_ptr& topicManager) : _communicator(communicator) { - IceStorm::TopicPrx t; + shared_ptr t; try { t = topicManager->create("ReplicaObserverTopic"); @@ -25,22 +26,25 @@ ReplicaCache::ReplicaCache(const Ice::CommunicatorPtr& communicator, const IceSt t = topicManager->retrieve("ReplicaObserverTopic"); } - const_cast(_topic) = IceStorm::TopicPrx::uncheckedCast(t->ice_endpoints(Ice::EndpointSeq())); - const_cast(_observers) = ReplicaObserverPrx::uncheckedCast(_topic->getPublisher()->ice_endpoints(Ice::EndpointSeq())); + const_cast&>(_topic) = + Ice::uncheckedCast(t->ice_endpoints(Ice::EndpointSeq())); + const_cast&>(_observers) = + Ice::uncheckedCast(_topic->getPublisher()->ice_endpoints(Ice::EndpointSeq())); } -ReplicaEntryPtr -ReplicaCache::add(const string& name, const ReplicaSessionIPtr& session) +shared_ptr +ReplicaCache::add(const string& name, const shared_ptr& session) { - Lock sync(*this); + unique_lock lock(_mutex); - ReplicaEntryPtr entry; + shared_ptr 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(name, session)); } -ReplicaEntryPtr +shared_ptr 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 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& observer) { try { - Lock sync(*this); + lock_guard lock(_mutex); InternalRegistryPrxSeq replicas; - for(map::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(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& 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 +ReplicaCache::getEndpoints(const string& name, const shared_ptr& 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::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& proxy) { // // Setup this replica internal registry proxy. @@ -251,7 +255,7 @@ ReplicaCache::setInternalRegistry(const InternalRegistryPrx& proxy) _self = proxy; } -InternalRegistryPrx +shared_ptr 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& session) : _name(name), _session(session) { } -ReplicaEntry::~ReplicaEntry() -{ -} - -const ReplicaSessionIPtr& +const shared_ptr& ReplicaEntry::getSession() const { return _session; } -InternalReplicaInfoPtr +shared_ptr ReplicaEntry::getInfo() const { return _session->getInfo(); } -InternalRegistryPrx +shared_ptr ReplicaEntry::getProxy() const { return _session->getInternalRegistry(); } -Ice::ObjectPrx +shared_ptr 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(std::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 -#include #include #include #include @@ -15,59 +13,51 @@ namespace IceGrid { class ReplicaCache; - class ReplicaSessionI; -typedef IceUtil::Handle 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&); bool canRemove() const { return true; } - const ReplicaSessionIPtr& getSession() const; - InternalReplicaInfoPtr getInfo() const; - InternalRegistryPrx getProxy() const; + const std::shared_ptr& getSession() const; + std::shared_ptr getInfo() const; + std::shared_ptr getProxy() const; - Ice::ObjectPrx getAdminProxy() const; + std::shared_ptr getAdminProxy() const; private: const std::string _name; - const ReplicaSessionIPtr _session; + const std::shared_ptr _session; }; -typedef IceUtil::Handle ReplicaEntryPtr; -class ReplicaCache : public CacheByString +class ReplicaCache final : public CacheByString { public: -#ifdef __SUNPRO_CC - using CacheByString::remove; -#endif - - ReplicaCache(const Ice::CommunicatorPtr&, const IceStorm::TopicManagerPrx&); + ReplicaCache(const std::shared_ptr&, const std::shared_ptr&); - ReplicaEntryPtr add(const std::string&, const ReplicaSessionIPtr&); - ReplicaEntryPtr remove(const std::string&, bool); - ReplicaEntryPtr get(const std::string&) const; + std::shared_ptr add(const std::string&, const std::shared_ptr&); + std::shared_ptr remove(const std::string&, bool); + std::shared_ptr get(const std::string&) const; - void subscribe(const ReplicaObserverPrx&); - void unsubscribe(const ReplicaObserverPrx&); + void subscribe(const std::shared_ptr&); + void unsubscribe(const std::shared_ptr&); - Ice::ObjectPrx getEndpoints(const std::string&, const Ice::ObjectPrx&) const; + std::shared_ptr getEndpoints(const std::string&, const std::shared_ptr&) const; - void setInternalRegistry(const InternalRegistryPrx&); - InternalRegistryPrx getInternalRegistry() const; + void setInternalRegistry(const std::shared_ptr&); + std::shared_ptr 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 _communicator; + const std::shared_ptr _topic; + const std::shared_ptr _observers; + std::shared_ptr _self; // This replica internal registry proxy. }; }; diff --git a/cpp/src/IceGrid/ReplicaSessionI.cpp b/cpp/src/IceGrid/ReplicaSessionI.cpp index 6d9030fb886..3333a600543 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::create(const shared_ptr& database, + const shared_ptr& wellKnownObjects, + const shared_ptr& info, + const shared_ptr& proxy, + chrono::seconds timeout) { - __setNoDelete(true); + + shared_ptr 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(obsv)->registryUp(toRegistryInfo(info)); - _proxy = ReplicaSessionPrx::uncheckedCast(_database->getInternalAdapter()->addWithUUID(this)); + replicaSession->_proxy = + Ice::uncheckedCast(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(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, + const shared_ptr& wellKnownObjects, + const shared_ptr& info, + const shared_ptr& 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& slaveSerials, +ReplicaSessionI::setDatabaseObserver(shared_ptr observer, + IceUtil::Optional 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 = std::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 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& ReplicaSessionI::getInternalRegistry() const { return _internalRegistry; } -const InternalReplicaInfoPtr& +const shared_ptr& ReplicaSessionI::getInfo() const { return _info; } -ReplicaSessionPrx +shared_ptr ReplicaSessionI::getProxy() const { return _proxy; } -Ice::ObjectPrx +shared_ptr 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(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 DatabasePtr; - -class WellKnownObjectsManager; -typedef IceUtil::Handle WellKnownObjectsManagerPtr; - class TraceLevels; -typedef IceUtil::Handle 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&, - 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 create(const std::shared_ptr&, + const std::shared_ptr&, + const std::shared_ptr&, + const std::shared_ptr&, + std::chrono::seconds); + + void keepAlive(const Ice::Current&) override; + int getTimeout(const Ice::Current&) const override; + void setDatabaseObserver(std::shared_ptr, IceUtil::Optional, + 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, 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& getInternalRegistry() const; + const std::shared_ptr& getInfo() const; + std::shared_ptr getProxy() const; + + std::shared_ptr getEndpoint(const std::string&); bool isDestroyed() const; private: + ReplicaSessionI(const std::shared_ptr&, const std::shared_ptr&, + const std::shared_ptr&, const std::shared_ptr&, + 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; + const std::shared_ptr _wellKnownObjects; + const std::shared_ptr _traceLevels; + const std::shared_ptr _internalRegistry; + const std::shared_ptr _info; + const std::chrono::seconds _timeout; + std::shared_ptr _proxy; + std::shared_ptr _observer; ObjectInfoSeq _replicaWellKnownObjects; StringObjectProxyDict _replicaEndpoints; - IceUtil::Time _timestamp; + std::chrono::steady_clock::time_point _timestamp; bool _destroy; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle ReplicaSessionIPtr; }; diff --git a/cpp/src/IceGrid/ReplicaSessionManager.cpp b/cpp/src/IceGrid/ReplicaSessionManager.cpp index da6f5cb4983..094c7f112ff 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& thread, + const shared_ptr& database, + const shared_ptr& 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(std::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(std::move(application), nullptr, getSerials(current.ctx, serial)); } catch(const DeploymentException& ex) { @@ -50,17 +50,17 @@ class MasterDatabaseObserverI : public DatabaseObserver, public IceUtil::Mutex 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 @@ class MasterDatabaseObserverI : public DatabaseObserver, public IceUtil::Mutex 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(std::move(update), false, nullptr, getSerials(current.ctx, serial)); } catch(const DeploymentException& ex) { @@ -92,19 +92,19 @@ class MasterDatabaseObserverI : public DatabaseObserver, public IceUtil::Mutex 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 @@ class MasterDatabaseObserverI : public DatabaseObserver, public IceUtil::Mutex { 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 @@ class MasterDatabaseObserverI : public DatabaseObserver, public IceUtil::Mutex { 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(std::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 @@ class MasterDatabaseObserverI : public DatabaseObserver, public IceUtil::Mutex 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 @@ class MasterDatabaseObserverI : public DatabaseObserver, public IceUtil::Mutex 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 @@ class MasterDatabaseObserverI : public DatabaseObserver, public IceUtil::Mutex 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 @@ class MasterDatabaseObserverI : public DatabaseObserver, public IceUtil::Mutex 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 @@ class MasterDatabaseObserverI : public DatabaseObserver, public IceUtil::Mutex } } - const ReplicaSessionManager::ThreadPtr _thread; - const DatabasePtr _database; - const ReplicaSessionPrx _session; + const shared_ptr _thread; + const shared_ptr _database; + const shared_ptr _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& info, + const shared_ptr& database, + const shared_ptr& wellKnownObjects, + const shared_ptr& 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(*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& 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; { - 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 ReplicaSessionManager::findInternalRegistryForReplica(const Ice::Identity& id) { - vector results; - vector queryObjects = findAllQueryObjects(true); - for(vector::const_iterator q = queryObjects.begin(); q != queryObjects.end(); ++q) + vector>> results; + for(const auto& obj : findAllQueryObjects(true)) { - results.push_back((*q)->begin_findObjectById(id)); + results.push_back(obj->findObjectByIdAsync(id)); } - for(vector::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(result.get()); } catch(const Ice::Exception&) { } } - return 0; + return nullptr; } bool -ReplicaSessionManager::keepAlive(const ReplicaSessionPrx& session) +ReplicaSessionManager::keepAlive(const shared_ptr& session) { try { @@ -456,11 +447,11 @@ ReplicaSessionManager::keepAlive(const ReplicaSessionPrx& session) } } -ReplicaSessionPrx -ReplicaSessionManager::createSession(InternalRegistryPrx& registry, IceUtil::Time& timeout) +shared_ptr +ReplicaSessionManager::createSession(shared_ptr& registry, chrono::seconds& timeout) { - ReplicaSessionPrx session; - IceInternal::UniquePtr exception; + shared_ptr 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 used; + set> 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(registry->ice_endpoints({})); } } if(!session) { - vector results; - vector queryObjects = findAllQueryObjects(false); - for(vector::const_iterator q = queryObjects.begin(); q != queryObjects.end(); ++q) + vector>> 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::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 newRegistry; try { - Ice::ObjectPrx obj = query->end_findObjectById(*p); - newRegistry = InternalRegistryPrx::uncheckedCast(obj); + auto obj = result.get(); + newRegistry = Ice::uncheckedCast(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 +ReplicaSessionManager::createSessionImpl(const shared_ptr& registry, chrono::seconds& timeout) { - ReplicaSessionPrx session; + shared_ptr 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(_thread, _database, session); + _observer = Ice::uncheckedCast(_database->getInternalAdapter()->addWithUUID(servant)); StringLongDict serials = _database->getSerials(); IceUtil::Optional 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& 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 DatabasePtr; - -class WellKnownObjectsManager; -typedef IceUtil::Handle WellKnownObjectsManagerPtr; - class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; +class WellKnownObjectsManager; class ReplicaSessionManager : public SessionManager { @@ -32,26 +27,27 @@ class ReplicaSessionManager : public SessionManager { public: - Thread(ReplicaSessionManager& manager, const InternalRegistryPrx& master, const Ice::LoggerPtr& logger) : + Thread(ReplicaSessionManager& manager, const std::shared_ptr& master, + const std::shared_ptr& logger) : SessionKeepAliveThread(master, logger), _manager(manager) { } - virtual ReplicaSessionPrx - createSession(InternalRegistryPrx& master, IceUtil::Time& timeout) + std::shared_ptr + createSession(std::shared_ptr& master, std::chrono::seconds& timeout) override { return _manager.createSession(master, timeout); } - virtual void - destroySession(const ReplicaSessionPrx& session) + void + destroySession(const std::shared_ptr& session) override { _manager.destroySession(session); } - virtual bool - keepAlive(const ReplicaSessionPrx& session) + bool + keepAlive(const std::shared_ptr& session) override { return _manager.keepAlive(session); } @@ -62,19 +58,20 @@ class ReplicaSessionManager : public SessionManager ReplicaSessionManager& _manager; }; - typedef IceUtil::Handle 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&, const std::shared_ptr&, + const std::shared_ptr&, const std::shared_ptr&); + void create(const std::shared_ptr&); + NodePrxSeq getNodes(const NodePrxSeq&) const; void destroy(); void registerAllWellKnownObjects(); - ReplicaSessionPrx getSession() const { return _thread ? _thread->getSession() : ReplicaSessionPrx(); } + std::shared_ptr getSession() const { return _thread ? _thread->getSession() : nullptr; } - IceGrid::InternalRegistryPrx findInternalRegistryForReplica(const Ice::Identity&); + std::shared_ptr findInternalRegistryForReplica(const Ice::Identity&); private: @@ -82,24 +79,24 @@ class ReplicaSessionManager : public SessionManager bool isDestroyed() { - Lock sync(*this); + std::lock_guard 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 createSession(std::shared_ptr&, std::chrono::seconds&); + std::shared_ptr createSessionImpl(const std::shared_ptr&, std::chrono::seconds&); + void destroySession(const std::shared_ptr&); + bool keepAlive(const std::shared_ptr&); - ThreadPtr _thread; + std::shared_ptr _thread; std::string _name; - InternalReplicaInfoPtr _info; - RegistryPrx _registry; - InternalRegistryPrx _internalRegistry; - DatabaseObserverPrx _observer; - DatabasePtr _database; - WellKnownObjectsManagerPtr _wellKnownObjects; - TraceLevelsPtr _traceLevels; + std::shared_ptr _info; + std::shared_ptr _registry; + std::shared_ptr _internalRegistry; + std::shared_ptr _observer; + std::shared_ptr _database; + std::shared_ptr _wellKnownObjects; + std::shared_ptr _traceLevels; }; } diff --git a/cpp/src/IceGrid/Scanner.cpp b/cpp/src/IceGrid/Scanner.cpp index f805c70b18a..b8bf0597b2e 100644 --- a/cpp/src/IceGrid/Scanner.cpp +++ b/cpp/src/IceGrid/Scanner.cpp @@ -492,16 +492,6 @@ using namespace IceGrid; # 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) namespace IceGrid @@ -517,8 +507,8 @@ std::string parseSingleQuotedString(); } #define YY_USER_INIT initScanner(); -#line 519 "src/IceGrid/Scanner.cpp" -#line 520 "src/IceGrid/Scanner.cpp" +#line 509 "src/IceGrid/Scanner.cpp" +#line 510 "src/IceGrid/Scanner.cpp" #define INITIAL 0 @@ -735,10 +725,10 @@ YY_DECL } { -#line 76 "src/IceGrid/Scanner.l" +#line 66 "src/IceGrid/Scanner.l" -#line 740 "src/IceGrid/Scanner.cpp" +#line 730 "src/IceGrid/Scanner.cpp" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { @@ -797,7 +787,7 @@ YY_DECL case 1: YY_RULE_SETUP -#line 78 "src/IceGrid/Scanner.l" +#line 68 "src/IceGrid/Scanner.l" { // C++-style comment int c; @@ -810,7 +800,7 @@ YY_RULE_SETUP YY_BREAK case 2: YY_RULE_SETUP -#line 88 "src/IceGrid/Scanner.l" +#line 78 "src/IceGrid/Scanner.l" { // C-style comment while(true) @@ -839,7 +829,7 @@ YY_RULE_SETUP case 3: /* rule 3 can match eol */ YY_RULE_SETUP -#line 113 "src/IceGrid/Scanner.l" +#line 103 "src/IceGrid/Scanner.l" { size_t len = strlen(yytext); for(size_t i = 0; i < len; ++i) @@ -854,14 +844,14 @@ YY_RULE_SETUP case 4: /* rule 4 can match eol */ YY_RULE_SETUP -#line 124 "src/IceGrid/Scanner.l" +#line 114 "src/IceGrid/Scanner.l" { return ';'; } YY_BREAK case 5: YY_RULE_SETUP -#line 128 "src/IceGrid/Scanner.l" +#line 118 "src/IceGrid/Scanner.l" { // "..."-type strings string s = parseDoubleQuotedString(); @@ -872,7 +862,7 @@ YY_RULE_SETUP YY_BREAK case 6: YY_RULE_SETUP -#line 136 "src/IceGrid/Scanner.l" +#line 126 "src/IceGrid/Scanner.l" { // '...'-type strings string s; @@ -900,7 +890,7 @@ YY_RULE_SETUP YY_BREAK case 7: YY_RULE_SETUP -#line 161 "src/IceGrid/Scanner.l" +#line 151 "src/IceGrid/Scanner.l" { // Simple strings string s; @@ -939,10 +929,10 @@ YY_RULE_SETUP YY_BREAK case 8: YY_RULE_SETUP -#line 197 "src/IceGrid/Scanner.l" +#line 187 "src/IceGrid/Scanner.l" ECHO; YY_BREAK -#line 944 "src/IceGrid/Scanner.cpp" +#line 934 "src/IceGrid/Scanner.cpp" case YY_STATE_EOF(INITIAL): yyterminate(); @@ -1947,8 +1937,7 @@ void yyfree (void * ptr ) #define YYTABLES_NAME "yytables" -#line 197 "src/IceGrid/Scanner.l" - +#line 187 "src/IceGrid/Scanner.l" namespace IceGrid { diff --git a/cpp/src/IceGrid/Scanner.l b/cpp/src/IceGrid/Scanner.l index 1de7e5def65..53e6ca282d4 100644 --- a/cpp/src/IceGrid/Scanner.l +++ b/cpp/src/IceGrid/Scanner.l @@ -39,16 +39,6 @@ using namespace IceGrid; # 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) namespace IceGrid diff --git a/cpp/src/IceGrid/ServerAdapterI.cpp b/cpp/src/IceGrid/ServerAdapterI.cpp index ef2e664cfbb..7041901f553 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& node, ServerI* server, const string& serverName, - const AdapterPrx& proxy, + const shared_ptr& 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&)> response, + function, + 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 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 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 = std::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::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::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::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 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 #include namespace IceGrid { class NodeI; -typedef IceUtil::Handle 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&, ServerI*, const std::string&, + const std::shared_ptr&, const std::string&, bool); + ~ServerAdapterI() override; + + void activateAsync(std::function&)>, + std::function, + const Ice::Current&) override; + std::shared_ptr getDirectProxy(const Ice::Current&) const override; + void setDirectProxy(std::shared_ptr, 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 getProxy() const; private: - const NodeIPtr _node; - const AdapterPrx _this; + const std::shared_ptr _node; + const std::shared_ptr _this; const std::string _serverId; const std::string _id; const std::string _replicaId; ServerI* _server; - Ice::ObjectPrx _proxy; + std::shared_ptr _proxy; bool _enabled; - std::vector _activateCB; + std::vector&)>> _activateCB; bool _activateAfterDeactivating; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle ServerAdapterIPtr; } diff --git a/cpp/src/IceGrid/ServerCache.cpp b/cpp/src/IceGrid/ServerCache.cpp index eb636c97b94..5928530a972 100644 --- a/cpp/src/IceGrid/ServerCache.cpp +++ b/cpp/src/IceGrid/ServerCache.cpp @@ -20,64 +20,12 @@ using namespace std; using namespace IceGrid; -namespace IceGrid -{ - - struct AddCommunicator - { - 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 - { - 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&& result) : + _server(server), _node(node), _remove(remove), _noRestart(noRestart), _result(std::move(result)) { } @@ -86,7 +34,7 @@ CheckUpdateResult::getResult() { try { - return ServerPrx::uncheckedCast(_result->getProxy())->end_checkUpdate(_result); + return _result.get(); } catch(const DeploymentException& ex) { @@ -117,7 +65,7 @@ CheckUpdateResult::getResult() } } -ServerCache::ServerCache(const Ice::CommunicatorPtr& communicator, +ServerCache::ServerCache(const shared_ptr& communicator, const string& instanceName, NodeCache& nodeCache, AdapterCache& adapterCache, @@ -132,22 +80,25 @@ ServerCache::ServerCache(const Ice::CommunicatorPtr& communicator, { } -ServerEntryPtr +shared_ptr 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(*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) { @@ -158,11 +109,11 @@ ServerCache::add(const ServerInfo& info) return entry; } -ServerEntryPtr +shared_ptr 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); @@ -173,22 +124,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 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 @@ -206,16 +159,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); } @@ -230,12 +186,12 @@ ServerCache::preUpdate(const ServerInfo& newInfo, bool noRestart) } } -ServerEntryPtr +shared_ptr 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(); @@ -244,7 +200,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) @@ -259,20 +220,20 @@ ServerCache::postUpdate(const ServerInfo& info, bool noRestart) void ServerCache::clear(const string& id) { - Lock sync(*this); + lock_guard lock(_mutex); CacheByString::removeImpl(id); } void -ServerCache::setNodeObserverTopic(const NodeObserverTopicPtr& nodeObserverTopic) +ServerCache::setNodeObserverTopic(const shared_ptr& nodeObserverTopic) { _nodeObserverTopic = nodeObserverTopic; } void -ServerCache::addCommunicator(const CommunicatorDescriptorPtr& oldDesc, - const CommunicatorDescriptorPtr& newDesc, - const ServerEntryPtr& server, +ServerCache::addCommunicator(const shared_ptr& oldDesc, + const shared_ptr& newDesc, + const shared_ptr& server, const string& application) { if(!newDesc) @@ -313,9 +274,9 @@ ServerCache::addCommunicator(const CommunicatorDescriptorPtr& oldDesc, } void -ServerCache::removeCommunicator(const CommunicatorDescriptorPtr& oldDesc, - const CommunicatorDescriptorPtr& newDesc, - const ServerEntryPtr& /*entry*/) +ServerCache::removeCommunicator(const shared_ptr& oldDesc, + const shared_ptr& newDesc, + const shared_ptr&) { if(!oldDesc) { @@ -355,7 +316,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), @@ -373,13 +334,13 @@ ServerEntry::sync() } void -ServerEntry::waitForSync(int timeout) +ServerEntry::waitForSync(chrono::seconds timeout) { - waitImpl(timeout); + waitImpl(std::move(timeout)); } void -ServerEntry::waitForSyncNoThrow(int timeout) +ServerEntry::waitForSyncNoThrow(chrono::seconds timeout) { try { @@ -387,7 +348,7 @@ ServerEntry::waitForSyncNoThrow(int timeout) } catch(const SynchronizationException&) { - assert(timeout >= 0); + assert(timeout >= 0s); } catch(const Ice::Exception&) { @@ -397,21 +358,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& callback) { - Lock sync(*this); + lock_guard lock(_mutex); if(!_loaded.get() && !_load.get()) { throw ServerNotExistException(); @@ -426,10 +387,9 @@ ServerEntry::addSyncCallback(const SynchronizationCallbackPtr& callback) void ServerEntry::update(const ServerInfo& info, bool noRestart) { - Lock sync(*this); + lock_guard lock(_mutex); - IceInternal::UniquePtr descriptor(new ServerInfo()); - *descriptor = info; + auto descriptor = make_unique(info); _updated = true; @@ -459,7 +419,7 @@ ServerEntry::update(const ServerInfo& info, bool noRestart) void ServerEntry::destroy(bool noRestart) { - Lock sync(*this); + lock_guard lock(_mutex); _updated = true; @@ -488,9 +448,9 @@ ServerInfo ServerEntry::getInfo(bool resolve) const { ServerInfo info; - SessionIPtr session; + shared_ptr session; { - Lock sync(*this); + lock_guard lock(_mutex); if(!_loaded.get() && !_load.get()) { throw ServerNotExistException(); @@ -524,21 +484,22 @@ ServerEntry::getId() const return _id; } -ServerPrx -ServerEntry::getProxy(bool upToDate, int timeout) +shared_ptr +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 +ServerEntry::getProxy(chrono::seconds& activationTimeout, chrono::seconds& deactivationTimeout, string& node, + bool upToDate, chrono::seconds timeout) { // // NOTE: this might throw ServerNotExistException, NodeUnreachableException @@ -547,7 +508,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()); @@ -567,19 +528,16 @@ ServerEntry::getProxy(int& activationTimeout, int& deactivationTimeout, string& } } -Ice::ObjectPrx +shared_ptr 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 ServerEntry::getAdapter(const string& id, bool upToDate) { // @@ -587,12 +545,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 +ServerEntry::getAdapter(chrono::seconds& activationTimeout, chrono::seconds& deactivationTimeout, const string& id, + bool upToDate) { // // NOTE: this might throw AdapterNotExistException, NodeUnreachableException @@ -601,8 +560,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()) @@ -617,14 +576,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 } } @@ -634,7 +593,7 @@ ServerEntry::getLoad(LoadSample sample) const string application; string node; { - Lock sync(*this); + lock_guard lock(_mutex); if(_loaded.get()) { application = _loaded->application; @@ -655,11 +614,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); @@ -671,13 +630,13 @@ void ServerEntry::syncImpl() { ServerInfo load; - SessionIPtr session; + shared_ptr session; ServerInfo destroy; - int timeout = -1; + auto timeout = -1s; bool noRestart = false; { - Lock sync(*this); + lock_guard lock(_mutex); if(_synchronizing) { return; @@ -689,7 +648,7 @@ ServerEntry::syncImpl() } _updated = false; - _exception.reset(0); + _exception = nullptr; if(_destroy.get()) { @@ -715,44 +674,44 @@ ServerEntry::syncImpl() { try { - _cache.getNodeCache().get(destroy.node)->destroyServer(this, destroy, timeout, noRestart); + _cache.getNodeCache().get(destroy.node)->destroyServer(static_pointer_cast(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(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); } } } @@ -761,11 +720,11 @@ ServerEntry::waitImpl(int timeout) throw SynchronizationException(__FILE__, __LINE__); } - if(_exception.get()) + if(_exception) { try { - _exception->ice_throw(); + rethrow_exception(_exception); } catch(const DeploymentException&) { @@ -775,11 +734,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); @@ -793,18 +752,18 @@ ServerEntry::waitImpl(int timeout) void ServerEntry::synchronized() { - vector callbacks; + vector> callbacks; { - Lock sync(*this); + lock_guard lock(_mutex); _callbacks.swap(callbacks); } - for(vector::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); } @@ -812,20 +771,20 @@ ServerEntry::synchronized() } void -ServerEntry::synchronized(const Ice::Exception& ex) +ServerEntry::synchronized(exception_ptr ex) { - vector callbacks; + vector> callbacks; { - Lock sync(*this); + lock_guard lock(_mutex); _callbacks.swap(callbacks); } - for(vector::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); } @@ -833,17 +792,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& proxy, const AdapterPrxDict& adpts, + chrono::seconds activationTimeout, chrono::seconds deactivationTimeout) { ServerInfo load; - SessionIPtr session; + shared_ptr 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) { // @@ -857,13 +817,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 { @@ -894,22 +854,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(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(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"))); } } } @@ -919,21 +879,21 @@ ServerEntry::destroyCallback() { ServerInfo load; bool noRestart = false; - SessionIPtr session; + shared_ptr 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 { @@ -948,11 +908,12 @@ ServerEntry::destroyCallback() { try { - _cache.getNodeCache().get(load.node)->loadServer(this, load, session, -1, noRestart); + _cache.getNodeCache().get(load.node)->loadServer(static_pointer_cast(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 @@ -963,31 +924,31 @@ ServerEntry::destroyCallback() } void -ServerEntry::exception(const Ice::Exception& ex) +ServerEntry::exception(exception_ptr ex) { ServerInfo load; - SessionIPtr session; + shared_ptr 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; @@ -1000,11 +961,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(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 @@ -1020,24 +982,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 ServerEntry::checkUpdate(const ServerInfo& info, bool noRestart) { - SessionIPtr session; + shared_ptr session; ServerInfo oldInfo; { - Lock sync(*this); + lock_guard lock(_mutex); if(!_loaded.get() && !_load.get()) { throw ServerNotExistException(); @@ -1047,7 +1009,7 @@ ServerEntry::checkUpdate(const ServerInfo& info, bool noRestart) session = _allocationSession; } - NodeEntryPtr node; + shared_ptr node; try { node = _cache.getNodeCache().get(oldInfo.node); @@ -1057,10 +1019,10 @@ ServerEntry::checkUpdate(const ServerInfo& info, bool noRestart) throw NodeUnreachableException(info.node, "node is not active"); } - ServerPrx server; + shared_ptr server; try { - server = getProxy(true, 5); + server = getProxy(true, 5s); } catch(const SynchronizationException&) { @@ -1080,7 +1042,7 @@ ServerEntry::checkUpdate(const ServerInfo& info, bool noRestart) else { // Otherwise, we do as if the update is valid. - return 0; + return nullptr; } } @@ -1089,13 +1051,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 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(_id, oldInfo.node, noRestart, desc != nullptr, + server->checkUpdateAsync(desc, noRestart)); } bool @@ -1105,21 +1068,21 @@ ServerEntry::isEnabled() const } void -ServerEntry::allocated(const SessionIPtr& session) +ServerEntry::allocated(const shared_ptr& 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 @@ -1138,34 +1101,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 adapterIds; multiset 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::iterator p = adapterIds.begin(); p != adapterIds.end(); ++p) - { - adapterIdSeq.push_back(*p); - } - Ice::IdentitySeq identitySeq; - for(multiset::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) { @@ -1180,10 +1127,10 @@ ServerEntry::allocated(const SessionIPtr& session) } void -ServerEntry::allocatedNoSync(const SessionIPtr& /*session*/) +ServerEntry::allocatedNoSync(const shared_ptr&) { { - Lock sync(*this); + lock_guard lock(_mutex); if(!_updated || (_loaded.get() && _loaded->descriptor->activation != "session") || (_load.get() && _load->descriptor->activation != "session")) @@ -1197,14 +1144,14 @@ ServerEntry::allocatedNoSync(const SessionIPtr& /*session*/) } void -ServerEntry::released(const SessionIPtr& session) +ServerEntry::released(const shared_ptr& 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 @@ -1221,39 +1168,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 adapterIds; multiset 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::iterator p = adapterIds.begin(); p != adapterIds.end(); ++p) - { - adapterIdSeq.push_back(*p); - } - Ice::IdentitySeq identitySeq; - for(multiset::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) { @@ -1274,10 +1205,10 @@ ServerEntry::released(const SessionIPtr& session) } void -ServerEntry::releasedNoSync(const SessionIPtr& /*session*/) +ServerEntry::releasedNoSync(const shared_ptr& /*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 -#include -#include #include #include #include @@ -17,26 +14,20 @@ namespace IceGrid { -class ServerCache; -class ObjectCache; class AdapterCache; class AllocatableObjectCache; +class CheckServerResult; class NodeCache; - class NodeEntry; -typedef IceUtil::Handle NodeEntryPtr; - -class CheckServerResult; -typedef IceUtil::Handle CheckServerResultPtr; - class NodeObserverTopic; -typedef IceUtil::Handle 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 getResult(); @@ -48,30 +39,29 @@ class CheckUpdateResult : public IceUtil::Shared const std::string _node; const bool _remove; const bool _noRestart; - const Ice::AsyncResultPtr _result; + std::future _result; }; -typedef IceUtil::Handle 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&); void update(const ServerInfo&, bool); @@ -80,101 +70,104 @@ class ServerEntry : public Allocatable 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 getProxy(std::chrono::seconds&, std::chrono::seconds&, std::string&, bool = true, + std::chrono::seconds = std::chrono::seconds(0)); + std::shared_ptr getProxy(bool = true, std::chrono::seconds = std::chrono::seconds(0)); + std::shared_ptr getAdminProxy(); - AdapterPrx getAdapter(const std::string&, bool); - AdapterPrx getAdapter(int&, int&, const std::string&, bool); + std::shared_ptr getAdapter(const std::string&, bool); + std::shared_ptr 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 checkUpdate(const ServerInfo&, bool); bool isDestroyed(); - void loadCallback(const ServerPrx&, const AdapterPrxDict&, int, int); + void loadCallback(const std::shared_ptr&, 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&) override; + void allocatedNoSync(const std::shared_ptr&) override; + void released(const std::shared_ptr&) override; + void releasedNoSync(const std::shared_ptr&) 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 _loaded; - IceInternal::UniquePtr _load; - IceInternal::UniquePtr _destroy; + std::unique_ptr _loaded; + std::unique_ptr _load; + std::unique_ptr _destroy; - ServerPrx _proxy; + std::shared_ptr _proxy; AdapterPrxDict _adapters; - int _activationTimeout; - int _deactivationTimeout; + std::chrono::seconds _activationTimeout; + std::chrono::seconds _deactivationTimeout; bool _synchronizing; bool _updated; - IceInternal::UniquePtr _exception; + std::exception_ptr _exception; bool _noRestart; - std::vector _callbacks; + std::vector> _callbacks; + + std::shared_ptr _allocationSession; - SessionIPtr _allocationSession; + mutable std::mutex _mutex; + std::condition_variable _condVar; }; -typedef IceUtil::Handle ServerEntryPtr; -typedef std::vector ServerEntrySeq; +using ServerEntrySeq = std::vector>; class ServerCache : public CacheByString { public: -#ifdef __SUNPRO_CC - using CacheByString::remove; -#endif - - ServerCache(const Ice::CommunicatorPtr&, const std::string&, NodeCache&, AdapterCache&, ObjectCache&, + ServerCache(const std::shared_ptr&, const std::string&, NodeCache&, AdapterCache&, ObjectCache&, AllocatableObjectCache&); - ServerEntryPtr add(const ServerInfo&); - ServerEntryPtr get(const std::string&) const; + std::shared_ptr add(const ServerInfo&); + std::shared_ptr get(const std::string&) const; bool has(const std::string&) const; - ServerEntryPtr remove(const std::string&, bool); + std::shared_ptr remove(const std::string&, bool); void preUpdate(const ServerInfo&, bool); - ServerEntryPtr postUpdate(const ServerInfo&, bool); + std::shared_ptr postUpdate(const ServerInfo&, bool); void clear(const std::string&); NodeCache& getNodeCache() const { return _nodeCache; } - Ice::CommunicatorPtr getCommunicator() const { return _communicator; } + std::shared_ptr 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& getNodeObserverTopic() const { return _nodeObserverTopic; } + void setNodeObserverTopic(const std::shared_ptr&); 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&, const std::shared_ptr&, + const std::shared_ptr&, const std::string&); + void removeCommunicator(const std::shared_ptr&, + const std::shared_ptr&, const std::shared_ptr&); friend struct AddCommunicator; friend struct RemoveCommunicator; - const Ice::CommunicatorPtr _communicator; + const std::shared_ptr _communicator; const std::string _instanceName; NodeCache& _nodeCache; AdapterCache& _adapterCache; ObjectCache& _objectCache; AllocatableObjectCache& _allocatableObjectCache; - NodeObserverTopicPtr _nodeObserverTopic; + std::shared_ptr _nodeObserverTopic; + + mutable std::mutex _mutex; }; }; diff --git a/cpp/src/IceGrid/ServerI.cpp b/cpp/src/IceGrid/ServerI.cpp index 3294d6ae178..9d402157f2d 100644 --- a/cpp/src/IceGrid/ServerI.cpp +++ b/cpp/src/IceGrid/ServerI.cpp @@ -103,7 +103,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& lhs, const shared_ptr& rhs, bool noProps = false) { if(lhs->uuid == rhs->uuid && lhs->revision == rhs->revision) { @@ -189,39 +189,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& command) : _command(command) { } - virtual void runTimerTask() + void runTimerTask() override { _command->timeout(); } private: - const TimedServerCommandPtr _command; + const shared_ptr _command; }; class DelayedStart : public IceUtil::TimerTask { public: - DelayedStart(const ServerIPtr& server, const TraceLevelsPtr& traceLevels) : + DelayedStart(const shared_ptr& server, const shared_ptr& 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 +237,19 @@ class DelayedStart : public IceUtil::TimerTask private: - const ServerIPtr _server; - const TraceLevelsPtr _traceLevels; + const shared_ptr _server; + const shared_ptr _traceLevels; }; -class ResetPropertiesCB : public IceUtil::Shared +class ResetPropertiesCB : public enable_shared_from_this { public: - ResetPropertiesCB(const ServerIPtr& server, - const Ice::ObjectPrx admin, - const InternalServerDescriptorPtr& desc, - const InternalServerDescriptorPtr& old, - const TraceLevelsPtr& traceLevels) : + ResetPropertiesCB(const shared_ptr& server, + const shared_ptr admin, + const shared_ptr& desc, + const shared_ptr& old, + const shared_ptr& traceLevels) : _server(server), _admin(admin), _desc(desc), @@ -282,13 +282,13 @@ class ResetPropertiesCB : public IceUtil::Shared 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 +329,97 @@ class ResetPropertiesCB : public IceUtil::Shared // ++_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(_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 _server; + const shared_ptr _admin; + const shared_ptr _desc; + const shared_ptr _traceLevels; PropertyDescriptorSeqDict _properties; PropertyDescriptorSeqDict _oldProperties; PropertyDescriptorSeqDict::const_iterator _p; }; -typedef IceUtil::Handle ResetPropertiesCBPtr; -struct EnvironmentEval +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 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 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(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(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 = v.find("}"); - if(end == string::npos) - { - break; - } - variable = v.substr(beg + 2, end - beg - 2); - } - else + end = beg + 1; + while((isalnum(static_cast(v[end])) || v[end] == '_') && end < v.size()) { - end = beg + 1; - while((isalnum(static_cast(v[end])) || v[end] == '_') && end < v.size()) - { - ++end; - } - variable = v.substr(beg + 1, end - beg - 1); - --end; + ++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& server) : _server(server) { } -TimedServerCommand::TimedServerCommand(const ServerIPtr& server, const IceUtil::TimerPtr& timer, int timeout) : +TimedServerCommand::TimedServerCommand(const shared_ptr& server, const IceUtil::TimerPtr& timer, + chrono::seconds timeout) : ServerCommand(server), _timer(timer), _timeout(timeout) { } @@ -437,12 +427,12 @@ TimedServerCommand::TimedServerCommand(const ServerIPtr& server, const IceUtil:: void TimedServerCommand::startTimer() { - _timerTask = new CommandTimeoutTimerTask(this); + _timerTask = make_shared(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 +444,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& server, + const shared_ptr& runtime, + const shared_ptr& traceLevels) : ServerCommand(server), _runtime(runtime), _updating(false), _traceLevels(traceLevels) { } @@ -474,7 +464,7 @@ LoadCommand::canExecute(ServerI::InternalServerState state) ServerI::InternalServerState LoadCommand::nextState() { - return ServerI::Loading; + return ServerI::InternalServerState::Loading; } void @@ -484,13 +474,13 @@ LoadCommand::execute() } void -LoadCommand::setUpdate(const InternalServerDescriptorPtr& descriptor, bool clearDir) +LoadCommand::setUpdate(const shared_ptr& descriptor, bool clearDir) { _clearDir = clearDir; _desc = descriptor; } -InternalServerDescriptorPtr +shared_ptr LoadCommand::getInternalServerDescriptor() const { return _desc; @@ -503,13 +493,14 @@ LoadCommand::clearDir() const } void -LoadCommand::addCallback(const AMD_Node_loadServerPtr& amdCB) +LoadCommand::addCallback(function&, const AdapterPrxDict &, int, int)> response, + function exception) { - _loadCB.push_back(amdCB); + _loadCB.push_back({std::move(response), std::move(exception)}); } void -LoadCommand::startRuntimePropertiesUpdate(const Ice::ObjectPrx& process) +LoadCommand::startRuntimePropertiesUpdate(const shared_ptr& process) { if(_updating) { @@ -518,12 +509,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(_server, process, _desc, _runtime, _traceLevels); cb->execute(); } bool -LoadCommand::finishRuntimePropertiesUpdate(const InternalServerDescriptorPtr& runtime, const Ice::ObjectPrx& process) +LoadCommand::finishRuntimePropertiesUpdate(const shared_ptr& runtime, + const shared_ptr& process) { _updating = false; _runtime = runtime; // The new runtime server descriptor. @@ -546,26 +538,27 @@ LoadCommand::finishRuntimePropertiesUpdate(const InternalServerDescriptorPtr& ru } void -LoadCommand::failed(const Ice::Exception& ex) +LoadCommand::failed(exception_ptr ex) { - for(vector::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& proxy, const AdapterPrxDict& adapters, + chrono::seconds at, chrono::seconds dt) { - for(vector::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& server, bool loadFailure, bool clearDir) : ServerCommand(server), _loadFailure(loadFailure), _clearDir(clearDir) @@ -591,17 +584,17 @@ DestroyCommand::execute() } void -DestroyCommand::addCallback(const AMD_Node_destroyServerPtr& amdCB) +DestroyCommand::addCallback(function response) { - _destroyCB.push_back(amdCB); + _destroyCB.push_back(std::move(response)); } void DestroyCommand::finished() { - for(vector::const_iterator p = _destroyCB.begin(); p != _destroyCB.end(); ++p) + for(const auto& cb : _destroyCB) { - (*p)->ice_response(); + cb(); } } @@ -617,7 +610,7 @@ DestroyCommand::clearDir() const return _clearDir; } -PatchCommand::PatchCommand(const ServerIPtr& server) : +PatchCommand::PatchCommand(const std::shared_ptr& server) : ServerCommand(server), _notified(false), _destroyed(false) @@ -639,18 +632,18 @@ PatchCommand::nextState() void PatchCommand::execute() { - Lock sync(*this); + unique_lock lock(_mutex); _notified = true; - notifyAll(); + _condVar.notify_all(); } bool PatchCommand::waitForPatch() { - Lock sync(*this); - while(!_notified && !_destroyed) + unique_lock lock(_mutex); + while (!_notified && !_destroyed) { - wait(); + _condVar.wait(lock); } return _destroyed; } @@ -658,9 +651,9 @@ PatchCommand::waitForPatch() void PatchCommand::destroyed() { - Lock sync(*this); + unique_lock lock(_mutex); _destroyed = true; - notifyAll(); + _condVar.notify_all(); } void @@ -668,11 +661,6 @@ PatchCommand::finished() { } -StartCommand::StartCommand(const ServerIPtr& server, const IceUtil::TimerPtr& timer, int timeout) : - TimedServerCommand(server, timer, timeout) -{ -} - bool StartCommand::canExecute(ServerI::InternalServerState state) { @@ -699,19 +687,19 @@ StartCommand::timeout() } void -StartCommand::addCallback(const AMD_Server_startPtr& amdCB) +StartCommand::addCallback(function response, function exception) { - _startCB.push_back(amdCB); + _startCB.push_back({std::move(response), std::move(exception)}); } void StartCommand::failed(const string& reason) { stopTimer(); - ServerStartException ex(_server->getId(), reason); - for(vector::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(); } @@ -720,14 +708,15 @@ void StartCommand::finished() { stopTimer(); - for(vector::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& server, const IceUtil::TimerPtr& timer, + chrono::seconds timeout, bool deactivate) : TimedServerCommand(server, timer, timeout), _deactivate(deactivate) { } @@ -768,19 +757,19 @@ StopCommand::timeout() } void -StopCommand::addCallback(const AMD_Server_stopPtr& amdCB) +StopCommand::addCallback(function response, function exception) { - _stopCB.push_back(amdCB); + _stopCB.push_back({std::move(response), std::move(exception)}); } void StopCommand::failed(const string& reason) { stopTimer(); - ServerStopException ex(_server->getId(), reason); - for(vector::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(); } @@ -789,52 +778,46 @@ void StopCommand::finished() { stopTimer(); - for(vector::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& node, const shared_ptr& 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(_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 response, function exception, const Ice::Current&) { - start(Manual, amdCB); + start(Manual, std::move(response), std::move(exception)); } void -ServerI::stop_async(const AMD_Server_stopPtr& amdCB, const Ice::Current&) +ServerI::stopAsync(function response, function exception, const Ice::Current&) { - ServerCommandPtr command; + shared_ptr command; { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); if(StopCommand::isStopped(_state)) @@ -848,11 +831,12 @@ ServerI::stop_async(const AMD_Server_stopPtr& amdCB, const Ice::Current&) if(!_stop) { - _stop = new StopCommand(this, _node->getTimer(), _deactivationTimeout); + _stop = make_shared(shared_from_this(), _node->getTimer(), _deactivationTimeout); } - if(amdCB) + if(response) { - _stop->addCallback(amdCB); + assert(exception); + _stop->addCallback(std::move(response), std::move(exception)); } command = nextCommand(); } @@ -863,23 +847,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, std::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(std::move(message), fd); } - catch(const Ice::LocalException&) + catch(const std::exception&) { } } @@ -888,7 +872,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); } @@ -899,14 +883,14 @@ ServerI::getPid(const Ice::Current&) const return _node->getActivator()->getServerPid(_id); } -Ice::ObjectPrx +shared_ptr 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 { @@ -920,24 +904,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 @@ -949,9 +933,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) @@ -975,21 +959,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 process, function response, + function, const Ice::Current&) { bool deact = false; ServerAdapterDict adpts; - ServerCommandPtr command; + shared_ptr command; { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); - _process = process; + _process = std::move(process); if(_state == DeactivatingWaitForProcess) { deact = true; @@ -1003,13 +988,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&) { @@ -1027,23 +1013,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(std::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(std::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; @@ -1087,36 +1073,35 @@ ServerI::getId() const InternalDistributionDescriptorPtr ServerI::getDistribution() const { - Lock sync(*this); + lock_guard lock(_mutex); return _desc ? _desc->distrib : InternalDistributionDescriptorPtr(); } bool ServerI::dependsOnApplicationDistrib() const { - Lock sync(*this); + lock_guard lock(_mutex); return _desc ? _desc->applicationDistrib : false; } void -ServerI::start(ServerActivation activation, const AMD_Server_startPtr& amdCB) +ServerI::start(ServerActivation activation, function response , function exception) { - ServerCommandPtr command; + shared_ptr 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; } } @@ -1129,7 +1114,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) @@ -1166,16 +1151,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(shared_from_this(), _node->getTimer(), _activationTimeout); } - if(amdCB) + if(response) { - _start->addCallback(amdCB); + assert(response && exception); + _start->addCallback(std::move(response), std::move(exception)); } command = nextCommand(); } @@ -1185,11 +1171,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 +ServerI::load(const shared_ptr& desc, const string& replicaName, bool noRestart, + function &, const AdapterPrxDict &, int, int)> response, + function exception) { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); checkRevision(replicaName, desc->uuid, desc->revision); @@ -1203,7 +1190,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) @@ -1217,19 +1204,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 @@ -1246,28 +1233,28 @@ ServerI::load(const AMD_Node_loadServerPtr& amdCB, const InternalServerDescripto } else { - _stop = new StopCommand(this, _node->getTimer(), _deactivationTimeout); + _stop = make_shared(shared_from_this(), _node->getTimer(), _deactivationTimeout); } } if(!_load) { - _load = new LoadCommand(this, _desc, _node->getTraceLevels()); + _load = make_shared(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 @@ -1277,30 +1264,29 @@ 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); - } - else if(_state == ServerI::Active) + response(_this, adapters, secondsToInt(_activationTimeout), secondsToInt(_deactivationTimeout)); } + 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 desc, bool noRestart, const Ice::Current&) { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); if(!_desc) @@ -1317,7 +1303,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); @@ -1343,7 +1329,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) @@ -1352,18 +1338,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 +ServerI::destroy(const string& uuid, int revision, const string& replicaName, bool noRestart, function 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) @@ -1372,7 +1357,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(shared_from_this(), _node->getTimer(), _deactivationTimeout); } if(!_destroy) @@ -1381,11 +1366,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(shared_from_this(), false, !uuid.empty()); } - if(amdCB) + if(response) { - _destroy->addCallback(amdCB); + _destroy->addCallback(std::move(response)); } return nextCommand(); } @@ -1393,9 +1378,9 @@ ServerI::destroy(const AMD_Node_destroyServerPtr& amdCB, const string& uuid, int bool ServerI::startPatch(bool shutdown) { - ServerCommandPtr command; + shared_ptr command; { - Lock sync(*this); + lock_guard lock(_mutex); checkDestroyed(); if(!StopCommand::isStopped(_state)) { @@ -1405,12 +1390,12 @@ ServerI::startPatch(bool shutdown) } else if(!_stop) { - _stop = new StopCommand(this, _node->getTimer(), _deactivationTimeout); + _stop = make_shared(shared_from_this(), _node->getTimer(), _deactivationTimeout); } } if(!_patch) { - _patch = new PatchCommand(this); + _patch = make_shared(shared_from_this()); } command = nextCommand(); } @@ -1424,9 +1409,9 @@ ServerI::startPatch(bool shutdown) bool ServerI::waitForPatch() { - PatchCommandPtr patch; + shared_ptr patch; { - Lock sync(*this); + lock_guard lock(_mutex); if(!_patch) { return true; @@ -1441,7 +1426,7 @@ ServerI::finishPatch() { #ifndef _WIN32 { - Lock sync(*this); + lock_guard lock(_mutex); try { chownRecursive(_serverDir + "/distrib", _uid, _gid); @@ -1459,13 +1444,13 @@ ServerI::finishPatch() void ServerI::adapterActivated(const string& id) { - ServerCommandPtr command; + shared_ptr 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; } @@ -1476,13 +1461,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&) { @@ -1498,18 +1483,16 @@ ServerI::adapterActivated(const string& id) void ServerI::adapterDeactivated(const string& id) { - ServerCommandPtr command; + shared_ptr 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(shared_from_this(), _node->getTimer(), _deactivationTimeout, false); } command = nextCommand(); } @@ -1544,27 +1527,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 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) { @@ -1575,11 +1558,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&) { @@ -1595,7 +1578,7 @@ ServerI::activationTimedOut() void ServerI::activate() { - InternalServerDescriptorPtr desc; + shared_ptr desc; ServerAdapterDict adpts; bool waitForReplication; @@ -1607,7 +1590,7 @@ ServerI::activate() try { { - Lock sync(*this); + lock_guard lock(_mutex); assert(_state == Activating && _desc); desc = _desc; adpts = _adapters; @@ -1641,11 +1624,14 @@ 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(); + }); return; } } @@ -1654,27 +1640,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&) { @@ -1682,28 +1668,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 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&) { @@ -1730,16 +1716,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&) { @@ -1753,7 +1739,7 @@ void ServerI::kill() { { - Lock sync(*this); + lock_guard lock(_mutex); if(_state != Destroying && _state != Deactivating && _state != DeactivatingWaitForProcess) { return; @@ -1776,9 +1762,9 @@ ServerI::kill() void ServerI::deactivate() { - Ice::ProcessPrx process; + shared_ptr process; { - Lock sync(*this); + lock_guard lock(_mutex); if(_state != Deactivating && _state != DeactivatingWaitForProcess) { return; @@ -1793,7 +1779,7 @@ ServerI::deactivate() // if(_desc->processRegistered && !_process) { - setStateNoSync(ServerI::DeactivatingWaitForProcess); + setStateNoSync(InternalServerState::DeactivatingWaitForProcess); return; } process = _process; @@ -1804,7 +1790,7 @@ ServerI::deactivate() // // Deactivate the server and for the termination of the server. // - _node->getActivator()->deactivate(_id, process); + _node->getActivator()->deactivate(_id, std::move(process)); return; } catch(const Ice::Exception& ex) @@ -1836,13 +1822,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 @@ -1868,11 +1854,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&) { @@ -1887,11 +1873,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(); @@ -1913,9 +1898,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"; @@ -1932,7 +1917,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()); } } @@ -1941,11 +1926,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&) { @@ -1953,16 +1938,16 @@ ServerI::terminated(const string& msg, int status) } bool doDestroy = false; - ServerCommandPtr command; + shared_ptr 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(); } } @@ -1979,28 +1964,28 @@ 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(!_patch); assert(!_start); - _timerTask = 0; + _timerTask = nullptr; } void ServerI::update() { - ServerCommandPtr command; + shared_ptr 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 { @@ -2033,8 +2018,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) @@ -2045,13 +2030,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); } @@ -2069,7 +2054,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) { @@ -2079,10 +2064,10 @@ ServerI::update() } else if(!_destroy) { - _destroy = new DestroyCommand(this, true, true); + _destroy = make_shared(shared_from_this(), true, true); } - _load->failed(ex); + _load->failed(current_exception()); } if(oldDescriptor && disabled != (_activation == Disabled)) @@ -2099,7 +2084,7 @@ ServerI::update() } void -ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) +ServerI::updateImpl(const shared_ptr& descriptor) { assert(_load && descriptor); @@ -2125,27 +2110,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(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(adapter->createProxy(id)); + servant = make_shared(_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&) @@ -2155,19 +2139,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&) { @@ -2176,7 +2160,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; } } } @@ -2188,27 +2172,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; } @@ -2217,9 +2218,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 = IcePatch2Internal::simplify(*p); + string path = IcePatch2Internal::simplify(log); if(IceUtilInternal::isAbsolutePath(path)) { _logs.push_back(path); @@ -2269,26 +2270,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(); @@ -2300,19 +2301,19 @@ ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) // Ice::StringSeq files = IcePatch2Internal::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 { - IcePatch2Internal::remove(_serverDir + "/config/" + *q); + IcePatch2Internal::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(); } } } @@ -2336,25 +2337,25 @@ ServerI::updateImpl(const InternalServerDescriptorPtr& descriptor) // Ice::StringSeq dirs = IcePatch2Internal::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) + std::set_difference(svcDirs.begin(), svcDirs.end(), knownDirs.begin(), knownDirs.end(), back_inserter(toDel)); + for(const auto& str : toDel) { try { - IcePatch2Internal::removeRecursive(_serverDir + "/" + *p); + IcePatch2Internal::removeRecursive(_serverDir + "/" + str); } catch(const exception& ex) { Ice::Warning out(_node->getTraceLevels()->logger); - out << "couldn't remove directory `" << _serverDir << "/" << *p << "':\n" << ex.what(); + out << "couldn't remove directory `" << _serverDir << "/" << str << "':\n" << ex.what(); } } } @@ -2417,7 +2418,7 @@ ServerI::checkRevision(const string& replicaName, const string& uuid, int revisi } void -ServerI::checkNoRestart(const InternalServerDescriptorPtr& desc) +ServerI::checkNoRestart(const shared_ptr& desc) { assert(_desc); @@ -2434,10 +2435,10 @@ ServerI::checkNoRestart(const InternalServerDescriptorPtr& desc) #ifndef _WIN32 void -ServerI::checkAndUpdateUser(const InternalServerDescriptorPtr& desc, bool update) +ServerI::checkAndUpdateUser(const shared_ptr& desc, bool update) #else void -ServerI::checkAndUpdateUser(const InternalServerDescriptorPtr& desc, bool /*update*/) +ServerI::checkAndUpdateUser(const shared_ptr& desc, bool /*update*/) #endif { #ifndef _WIN32 @@ -2472,7 +2473,7 @@ ServerI::checkAndUpdateUser(const InternalServerDescriptorPtr& desc, bool /*upda if(!user.empty()) { - UserAccountMapperPrx mapper = _node->getUserAccountMapper(); + auto mapper = _node->getUserAccountMapper(); if(mapper) { try @@ -2601,9 +2602,9 @@ ServerI::updateRevision(const string& uuid, int revision) } void -ServerI::updateRuntimePropertiesCallback(const InternalServerDescriptorPtr& desc) +ServerI::updateRuntimePropertiesCallback(const shared_ptr& desc) { - Lock sync(*this); + lock_guard lock(_mutex); if(_state != Active || !_load) { return; @@ -2612,18 +2613,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& desc) { - Lock sync(*this); + lock_guard lock(_mutex); if(_state != Active || !_load) { return; @@ -2639,7 +2640,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 @@ -2649,7 +2650,7 @@ ServerI::checkActivation() includes(_activatedAdapters.begin(), _activatedAdapters.end(), _serverLifetimeAdapters.begin(), _serverLifetimeAdapters.end())) { - setStateNoSync(ServerI::Active); + setStateNoSync(InternalServerState::Active); return true; } } @@ -2659,9 +2660,9 @@ ServerI::checkActivation() void ServerI::setState(InternalServerState st, const std::string& reason) { - ServerCommandPtr command; + shared_ptr command; { - Lock sync(*this); + lock_guard lock(_mutex); setStateNoSync(st, reason); command = nextCommand(); } @@ -2671,10 +2672,10 @@ ServerI::setState(InternalServerState st, const std::string& reason) } } -ServerCommandPtr +shared_ptr ServerI::nextCommand() { - ServerCommandPtr command; + shared_ptr command; if(_stop && _stop->canExecute(_state)) { command = _stop; @@ -2703,7 +2704,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. @@ -2759,7 +2760,7 @@ ServerI::setStateNoSync(InternalServerState st, const std::string& reason) case Inactive: if(previous == Loading) { - _load = 0; + _load = nullptr; } if(previous == Patching) { @@ -2768,28 +2769,28 @@ ServerI::setStateNoSync(InternalServerState st, const std::string& reason) 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: @@ -2801,18 +2802,18 @@ ServerI::setStateNoSync(InternalServerState st, const std::string& reason) } 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: @@ -2820,9 +2821,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; @@ -2831,7 +2832,7 @@ ServerI::setStateNoSync(InternalServerState st, const std::string& reason) if(_timerTask) { _node->getTimer()->cancel(_timerTask); - _timerTask = 0; + _timerTask = nullptr; } if(_state == Destroyed && !_load) @@ -2848,14 +2849,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(shared_from_this(), _node->getTraceLevels()); try { _node->getTimer()->schedule(_timerTask, IceUtil::Time::milliSeconds(500)); @@ -2865,7 +2866,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 @@ -2875,15 +2878,15 @@ ServerI::setStateNoSync(InternalServerState st, const std::string& reason) // callback is executed. // assert(!_timerTask); - _timerTask = new DelayedStart(this, _node->getTraceLevels()); + _timerTask = make_shared(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(_disableOnFailure - (now - *_failureTime)); + _node->getTimer()->schedule(_timerTask, IceUtil::Time::milliSeconds((delay + 500ms).count())); } else { @@ -2984,27 +2987,27 @@ ServerI::toServerState(InternalServerState st) const { switch(st) { - case ServerI::Inactive: - case ServerI::Activating: - case ServerI::Patching: - 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::Patching: + 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; } } @@ -3091,7 +3094,7 @@ ServerI::getFilePath(const string& filename) const } PropertyDescriptorSeqDict -ServerI::getProperties(const InternalServerDescriptorPtr& desc) +ServerI::getProperties(const shared_ptr& desc) { // // Copy the descriptor properties. @@ -3131,7 +3134,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 80c9fe9271a..9c47520d440 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 #include #include #include + +#include #include #ifndef _WIN32 @@ -19,23 +20,15 @@ namespace IceGrid { class NodeI; -typedef IceUtil::Handle NodeIPtr; class ServerAdapterI; -typedef IceUtil::Handle ServerAdapterIPtr; class ServerCommand; -typedef IceUtil::Handle ServerCommandPtr; class DestroyCommand; -typedef IceUtil::Handle DestroyCommandPtr; class StopCommand; -typedef IceUtil::Handle StopCommandPtr; class StartCommand; -typedef IceUtil::Handle StartCommandPtr; class PatchCommand; -typedef IceUtil::Handle PatchCommandPtr; class LoadCommand; -typedef IceUtil::Handle LoadCommandPtr; -class ServerI : public Server, public IceUtil::Monitor +class ServerI final : public Server, public std::enable_shared_from_this { public: @@ -70,36 +63,40 @@ class ServerI : public Server, public IceUtil::Monitor # pragma clang diagnostic pop #endif - ServerI(const NodeIPtr&, const ServerPrx&, const std::string&, const std::string&, int); - virtual ~ServerI(); + ServerI(const std::shared_ptr&, const std::shared_ptr&, + 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, std::function, const Ice::Current&) override; + void stopAsync(std::function, std::function, 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, std::function, + std::function, 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; InternalDistributionDescriptorPtr getDistribution() const; bool dependsOnApplicationDistrib() 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 = nullptr, std::function = nullptr); + std::shared_ptr load(const std::shared_ptr&, const std::string&, bool, + std::function &, const AdapterPrxDict &, int, int)>, + std::function); + bool checkUpdate(std::shared_ptr, 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 destroy(const std::string&, int, const std::string &, bool, std::function); + bool startPatch(bool); bool waitForPatch(); void finishPatch(); @@ -119,26 +116,26 @@ class ServerI : public Server, public IceUtil::Monitor // // A proxy to the Process facet of the real Admin object; called by the AdminFacade servant implementation // - Ice::ObjectPrx getProcess() const; + std::shared_ptr getProcess() const; - PropertyDescriptorSeqDict getProperties(const InternalServerDescriptorPtr&); + PropertyDescriptorSeqDict getProperties(const std::shared_ptr&); - void updateRuntimePropertiesCallback(const InternalServerDescriptorPtr&); - void updateRuntimePropertiesCallback(const Ice::Exception&, const InternalServerDescriptorPtr&); + void updateRuntimePropertiesCallback(const std::shared_ptr&); + void updateRuntimePropertiesCallback(std::exception_ptr, const std::shared_ptr&); private: - void updateImpl(const InternalServerDescriptorPtr&); + void updateImpl(const std::shared_ptr&); 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&); + void checkAndUpdateUser(const std::shared_ptr&, 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 nextCommand(); void setStateNoSync(InternalServerState, const std::string& = std::string()); ServerState toServerState(InternalServerState) const; @@ -146,67 +143,69 @@ class ServerI : public Server, public IceUtil::Monitor ServerDynamicInfo getDynamicInfo() const; std::string getFilePath(const std::string&) const; - const NodeIPtr _node; - const ServerPrx _this; + const std::shared_ptr _node; + const std::shared_ptr _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 _desc; #ifndef _WIN32 uid_t _uid; gid_t _gid; #endif InternalServerState _state; ServerActivation _activation; - int _activationTimeout; - int _deactivationTimeout; - typedef std::map ServerAdapterDict; + std::chrono::seconds _activationTimeout; + std::chrono::seconds _deactivationTimeout; + using ServerAdapterDict = std::map> ; ServerAdapterDict _adapters; std::set _serverLifetimeAdapters; - Ice::ProcessPrx _process; + std::shared_ptr _process; std::set _activatedAdapters; - IceUtil::Time _failureTime; + std::optional _failureTime; ServerActivation _previousActivation; - IceUtil::TimerTaskPtr _timerTask; + std::shared_ptr_timerTask; bool _waitForReplication; std::string _stdErrFile; std::string _stdOutFile; Ice::StringSeq _logs; PropertyDescriptorSeq _properties; - DestroyCommandPtr _destroy; - StopCommandPtr _stop; - LoadCommandPtr _load; - PatchCommandPtr _patch; - StartCommandPtr _start; + std::shared_ptr _destroy; + std::shared_ptr _stop; + std::shared_ptr _load; + std::shared_ptr _patch; + std::shared_ptr _start; int _pid; + + mutable std::mutex _mutex; + std::condition_variable _condVar; }; -typedef IceUtil::Handle ServerIPtr; -class ServerCommand : public IceUtil::SimpleShared +class ServerCommand { public: - ServerCommand(const ServerIPtr&); - virtual ~ServerCommand(); + ServerCommand(const std::shared_ptr&); + 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 _server; }; -typedef IceUtil::Handle ServerCommandPtr; -class TimedServerCommand : public ServerCommand +class TimedServerCommand : public ServerCommand, public std::enable_shared_from_this { public: - TimedServerCommand(const ServerIPtr&, const IceUtil::TimerPtr&, int); + TimedServerCommand(const std::shared_ptr&, const IceUtil::TimerPtr&, std::chrono::seconds); virtual void timeout() = 0; void startTimer(); @@ -215,22 +214,21 @@ class TimedServerCommand : public ServerCommand private: IceUtil::TimerPtr _timer; - IceUtil::TimerTaskPtr _timerTask; - int _timeout; + std::shared_ptr _timerTask; + std::chrono::seconds _timeout; }; -typedef IceUtil::Handle TimedServerCommandPtr; class DestroyCommand : public ServerCommand { public: - DestroyCommand(const ServerIPtr&, bool, bool); + DestroyCommand(const std::shared_ptr&, 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 finished(); bool loadFailure() const; bool clearDir() const; @@ -239,29 +237,33 @@ class DestroyCommand : public ServerCommand const bool _loadFailure; const bool _clearDir; - std::vector _destroyCB; + std::vector> _destroyCB; }; class StopCommand : public TimedServerCommand { public: - StopCommand(const ServerIPtr&, const IceUtil::TimerPtr&, int, bool = true); + StopCommand( + const std::shared_ptr&, + 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, std::function); void failed(const std::string& reason); void finished(); private: - std::vector _stopCB; + std::vector, std::function>> _stopCB; bool _deactivate; }; @@ -269,27 +271,27 @@ 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, std::function); + void failed(const std::string&); void finished(); private: - std::vector _startCB; + std::vector, std::function>> _startCB; }; -class PatchCommand : public ServerCommand, public IceUtil::Monitor +class PatchCommand : public ServerCommand { public: - PatchCommand(const ServerIPtr&); + PatchCommand(const std::shared_ptr&); bool canExecute(ServerI::InternalServerState); ServerI::InternalServerState nextState(); @@ -303,36 +305,41 @@ class PatchCommand : public ServerCommand, public IceUtil::Monitor&, const std::shared_ptr&, + const std::shared_ptr&); - 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&, 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 getInternalServerDescriptor() const; + void addCallback(std::function&, const AdapterPrxDict &, int, int)>, + std::function); + void startRuntimePropertiesUpdate(const std::shared_ptr&); + bool finishRuntimePropertiesUpdate(const std::shared_ptr&, + const std::shared_ptr&); + void failed(std::exception_ptr); + void finished(const std::shared_ptr&, const AdapterPrxDict&, std::chrono::seconds, std::chrono::seconds); private: - std::vector _loadCB; + std::vector &, const AdapterPrxDict &, int, int)>, + std::function>> _loadCB; bool _clearDir; - InternalServerDescriptorPtr _desc; - IceInternal::UniquePtr _exception; - InternalServerDescriptorPtr _runtime; + std::shared_ptr _desc; + std::shared_ptr _runtime; bool _updating; - TraceLevelsPtr _traceLevels; + std::shared_ptr _traceLevels; }; } diff --git a/cpp/src/IceGrid/SessionI.cpp b/cpp/src/IceGrid/SessionI.cpp index 16b27d53d11..228ae3c6068 100644 --- a/cpp/src/IceGrid/SessionI.cpp +++ b/cpp/src/IceGrid/SessionI.cpp @@ -18,54 +18,50 @@ using namespace IceGrid; namespace IceGrid { -template -class AllocateObject : public ObjectAllocationRequest +class AllocateObject final : public ObjectAllocationRequest { - typedef IceUtil::Handle TPtr; public: - AllocateObject(const SessionIPtr& session, const TPtr& cb) : - ObjectAllocationRequest(session), _cb(cb) + AllocateObject(const shared_ptr& session, + function& returnValue)>&& response, + function&& exception) : + ObjectAllocationRequest(session), _response(std::move(response)), _exception(std::move(exception)) { } - virtual void - response(const Ice::ObjectPrx& proxy) + void + response(const shared_ptr& 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& returnValue)> _response; + function _exception; }; -template AllocateObject* -newAllocateObject(const SessionIPtr& session, const IceUtil::Handle& cb) -{ - return new AllocateObject(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) : _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 BaseSessionI::getGlacier2IdentitySet() { assert(_servantManager); - return _servantManager->getGlacier2IdentitySet(this); + return _servantManager->getGlacier2IdentitySet(shared_from_this()); } -Glacier2::StringSetPrx +shared_ptr 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, + 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 +SessionI::_register(const shared_ptr& servantManager, const shared_ptr& 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& returnValue)> response, + function exception, + const Ice::Current&) { - _database->getAllocatableObject(id)->allocate(newAllocateObject(this, cb)); + auto allocatedObject = make_shared(static_pointer_cast(shared_from_this()), + std::move(response), std::move(exception)); + _database->getAllocatableObject(id)->allocate(std::move(allocatedObject)); } void -SessionI::allocateObjectByType_async(const AMD_Session_allocateObjectByTypePtr& cb, - const string& type, - const Ice::Current&) +SessionI::allocateObjectByTypeAsync(string type, + function& returnValue)> response, + function exception, + const Ice::Current&) { - _database->getAllocatableObjectCache().allocateByType(type, newAllocateObject(this, cb)); + auto allocatedObject = make_shared(static_pointer_cast(shared_from_this()), + std::move(response), std::move(exception)); + _database->getAllocatableObjectCache().allocateByType(type, std::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(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& 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& 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) { - 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) { - 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::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::const_iterator q = _allocations.begin(); q != _allocations.end(); ++q) + for(const auto& allocation : _allocations) { try { - (*q)->release(this); + allocation->release(dynamic_pointer_cast(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& servantManager, + const shared_ptr& database, const IceUtil::TimerPtr& timer, - const ReapThreadPtr& reaper) : + const shared_ptr& 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(_filters) = properties->getPropertyAsIntWithDefault("IceGrid.Registry.SessionFilters", 0) > 0; } } -Glacier2::SessionPrx -ClientSessionFactory::createGlacier2Session(const string& sessionId, const Glacier2::SessionControlPrx& ctl) +shared_ptr +ClientSessionFactory::createGlacier2Session(const string& sessionId, + const shared_ptr& 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, { std::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(_database->getTraceLevels()->logger, session), timeout); - return Glacier2::SessionPrx::uncheckedCast(proxy); + _reaper->add(make_shared>(_database->getTraceLevels()->logger, session), timeout); + return Ice::uncheckedCast(proxy); } -SessionIPtr -ClientSessionFactory::createSessionServant(const string& userId, const Glacier2::SessionControlPrx&) +shared_ptr +ClientSessionFactory::createSessionServant(const string& userId, const shared_ptr&) { - return new SessionI(userId, _database, _timer); + return make_shared(userId, _database, _timer); } -const TraceLevelsPtr& +const shared_ptr& ClientSessionFactory::getTraceLevels() const { return _database->getTraceLevels(); } -ClientSessionManagerI::ClientSessionManagerI(const ClientSessionFactoryPtr& factory) : _factory(factory) +ClientSessionManagerI::ClientSessionManagerI(const shared_ptr& factory) : _factory(factory) { } -Glacier2::SessionPrx -ClientSessionManagerI::create(const string& user, const Glacier2::SessionControlPrx& ctl, const Ice::Current&) +shared_ptr +ClientSessionManagerI::create(string user, shared_ptr ctl, const Ice::Current&) { - return _factory->createGlacier2Session(user, ctl); + return _factory->createGlacier2Session(std::move(user), std::move(ctl)); } -ClientSSLSessionManagerI::ClientSSLSessionManagerI(const ClientSessionFactoryPtr& factory) : _factory(factory) +ClientSSLSessionManagerI::ClientSSLSessionManagerI(const shared_ptr& factory) : _factory(factory) { } -Glacier2::SessionPrx -ClientSSLSessionManagerI::create(const Glacier2::SSLInfo& info, - const Glacier2::SessionControlPrx& ctl, +shared_ptr +ClientSSLSessionManagerI::create(Glacier2::SSLInfo info, + shared_ptr 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 761fb6fde98..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 #include #include #include @@ -15,139 +14,137 @@ namespace IceGrid { -class Database; -typedef IceUtil::Handle DatabasePtr; - -class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; - -class AllocationRequest; -typedef IceUtil::Handle AllocationRequestPtr; - class Allocatable; -typedef IceUtil::Handle AllocatablePtr; - +class AllocationRequest; +class Database; class SessionI; -typedef IceUtil::Handle SessionIPtr; +class TraceLevels; -class BaseSessionI : public virtual Ice::Object, public IceUtil::Mutex +class BaseSessionI : public virtual Ice::Object, public std::enable_shared_from_this { 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 getGlacier2IdentitySet(); + std::shared_ptr 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&); const std::string _id; const std::string _prefix; - const TraceLevelsPtr _traceLevels; - const DatabasePtr _database; - SessionServantManagerPtr _servantManager; + const std::shared_ptr _traceLevels; + const std::shared_ptr _database; + std::shared_ptr _servantManager; bool _destroyed; - IceUtil::Time _timestamp; + std::chrono::steady_clock::time_point _timestamp; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle 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&, const IceUtil::TimerPtr&); - virtual void keepAlive(const Ice::Current& current) { BaseSessionI::keepAlive(current); } + std::shared_ptr _register(const std::shared_ptr&, + const std::shared_ptr&); - 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& returnValue)> response, + std::function exception, const Ice::Current& current) + override; + void allocateObjectByTypeAsync(std::string, + std::function& returnValue)> response, + std::function 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&); + void removeAllocationRequest(const std::shared_ptr&); + void addAllocation(const std::shared_ptr&); + void removeAllocation(const std::shared_ptr&); protected: - virtual void destroyImpl(bool); + void destroyImpl(bool) override; const IceUtil::TimerPtr _timer; int _allocationTimeout; - std::set _requests; - std::set _allocations; + std::set> _requests; + std::set> _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&, const std::shared_ptr&, + const IceUtil::TimerPtr&, + const std::shared_ptr&); - Glacier2::SessionPrx createGlacier2Session(const std::string&, const Glacier2::SessionControlPrx&); - SessionIPtr createSessionServant(const std::string&, const Glacier2::SessionControlPrx&); + std::shared_ptr createGlacier2Session(const std::string&, + const std::shared_ptr&); + std::shared_ptr createSessionServant(const std::string&, + const std::shared_ptr&); - const TraceLevelsPtr& getTraceLevels() const; + const std::shared_ptr& getTraceLevels() const; private: - const SessionServantManagerPtr _servantManager; - const DatabasePtr _database; + const std::shared_ptr _servantManager; + const std::shared_ptr _database; const IceUtil::TimerPtr _timer; - const ReapThreadPtr _reaper; + const std::shared_ptr _reaper; const bool _filters; }; -typedef IceUtil::Handle ClientSessionFactoryPtr; -class ClientSessionManagerI : public virtual Glacier2::SessionManager +class ClientSessionManagerI final : public Glacier2::SessionManager { public: - ClientSessionManagerI(const ClientSessionFactoryPtr&); + ClientSessionManagerI(const std::shared_ptr&); - virtual Glacier2::SessionPrx create(const std::string&, const Glacier2::SessionControlPrx&, const Ice::Current&); + std::shared_ptr create(std::string, std::shared_ptr, + const Ice::Current&) override; private: - const ClientSessionFactoryPtr _factory; + const std::shared_ptr _factory; }; -class ClientSSLSessionManagerI : public virtual Glacier2::SSLSessionManager +class ClientSSLSessionManagerI final : public Glacier2::SSLSessionManager { public: - ClientSSLSessionManagerI(const ClientSessionFactoryPtr&); + ClientSSLSessionManagerI(const std::shared_ptr&); - virtual Glacier2::SessionPrx create(const Glacier2::SSLInfo&, const Glacier2::SessionControlPrx&, - const Ice::Current&); + std::shared_ptr create(Glacier2::SSLInfo, std::shared_ptr, + const Ice::Current&) override; private: - const ClientSessionFactoryPtr _factory; + const std::shared_ptr _factory; }; }; diff --git a/cpp/src/IceGrid/SessionManager.cpp b/cpp/src/IceGrid/SessionManager.cpp index 646db8244a4..eb3a6b8200a 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& 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(prx->ice_identity(std::move(id))->ice_endpoints({})); } } -SessionManager::~SessionManager() -{ -} - -vector +vector> SessionManager::findAllQueryObjects(bool cached) { - vector queryObjects; - Ice::LocatorPrx locator; + vector> queryObjects; + shared_ptr locator; { - Lock sync(*this); + lock_guard lock(_mutex); if(!_communicator) { return queryObjects; @@ -48,14 +43,14 @@ SessionManager::findAllQueryObjects(bool cached) if(!cached) { - for(vector::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(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(query->ice_endpoints({endpoint}))); } } // // Find all known query objects by querying all the registries we can find. // - map proxies; - set requested; + map> proxies; + set> requested; while(true) { - vector results; - for(vector::const_iterator q = queryObjects.begin(); q != queryObjects.end(); ++q) + vector> 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::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(prx->ice_identity(std::move(id))); } } } @@ -146,20 +135,20 @@ SessionManager::findAllQueryObjects(bool cached) } queryObjects.clear(); - for(map::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::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 -#include -#include -#include - #include #include #include #include +#include namespace IceGrid { template -class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor +class SessionKeepAliveThread { #if defined(__clang__) # pragma clang diagnostic push @@ -47,21 +43,28 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor& registry, + const std::shared_ptr& 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 session; + std::shared_ptr registry; + std::chrono::seconds timeout = 10s; Action action = Connect; try @@ -69,7 +72,7 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor lock(_mutex); if(_state == Destroyed) { break; @@ -98,7 +101,7 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor 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 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitorice_timeout(static_cast(timeout.toMilliSeconds()))); + assert(timeout != 0s); + using namespace std::chrono; + + registry = Ice::uncheckedCast(_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 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor lock(_mutex); return _state != Destroyed && _state != Connected; } virtual bool waitForCreate() { - Lock sync(*this); - while(_state != Destroyed && _state != Connected) - { - wait(); - } + std::unique_lock lock(_mutex); + _condVar.wait(lock, [this] { return _state == Destroyed || _state == Connected; }); return _state != Destroyed; } void tryCreateSession() { + std::lock_guard 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 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 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor lock(_mutex); if(_state == Destroyed || _state == Disconnected) { return; } _nextAction = Disconnect; - notifyAll(); + _condVar.notify_all(); } bool terminateIfDisconnected() { - Lock sync(*this); + std::lock_guard lock(_mutex); if(_state != Disconnected) { return false; // Nothing we can do for now. @@ -267,14 +270,14 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor lock(_mutex); if(_state == Destroyed) { return; @@ -282,67 +285,80 @@ class SessionKeepAliveThread : public IceUtil::Thread, public IceUtil::Monitor lock(_mutex); return _state == Destroyed; } - TPrx + std::shared_ptr getSession() { - Lock sync(*this); + std::lock_guard lock(_mutex); return _session; } void - setRegistry(const InternalRegistryPrx& registry) + setRegistry(const std::shared_ptr& registry) { - Lock sync(*this); + std::lock_guard lock(_mutex); _registry = registry; } - InternalRegistryPrx + std::shared_ptr getRegistry() const { - Lock sync(*this); + std::lock_guard 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 createSession(std::shared_ptr&, std::chrono::seconds&) = 0; + virtual void destroySession(const std::shared_ptr&) = 0; + virtual bool keepAlive(const std::shared_ptr&) = 0; protected: - InternalRegistryPrx _registry; - Ice::LoggerPtr _logger; - TPrx _session; + std::shared_ptr _registry; + std::shared_ptr _logger; + std::shared_ptr _session; State _state; Action _nextAction; + + mutable std::mutex _mutex; + std::condition_variable _condVar; + std::thread _thread; }; -class SessionManager : public IceUtil::Monitor +class SessionManager { public: - SessionManager(const Ice::CommunicatorPtr&, const std::string&); - virtual ~SessionManager(); + SessionManager(const std::shared_ptr&, const std::string&); + virtual ~SessionManager() = default; virtual bool isDestroyed() = 0; protected: - std::vector findAllQueryObjects(bool); + std::vector> findAllQueryObjects(bool); - Ice::CommunicatorPtr _communicator; + std::shared_ptr _communicator; std::string _instanceName; - InternalRegistryPrx _master; - std::vector _queryObjects; + std::shared_ptr _master; + std::vector> _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& adapter, const string& instanceName, bool checkConnection, const string& serverAdminCategory, - const Ice::ObjectPtr& serverAdminRouter, + const shared_ptr& serverAdminRouter, const string& nodeAdminCategory, - const Ice::ObjectPtr& nodeAdminRouter, + const shared_ptr& nodeAdminRouter, const string& replicaAdminCategory, - const Ice::ObjectPtr& replicaAdminRouter, - const AdminCallbackRouterPtr& adminCallbackRouter) : + const shared_ptr& replicaAdminRouter, + const shared_ptr& 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 +SessionServantManager::locate(const Ice::Current& current, shared_ptr&) { - Lock sync(*this); - Ice::ObjectPtr servant; + lock_guard lock(_mutex); + + shared_ptr 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::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&, const shared_ptr&) { } 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 +SessionServantManager::addSession(const shared_ptr& session, + const shared_ptr& 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& session, + const shared_ptr& ctl, const Ice::IdentitySeq& ids) { - Lock sync(*this); + lock_guard lock(_mutex); - map::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 +SessionServantManager::getGlacier2IdentitySet(const shared_ptr& session) { - Lock sync(*this); - map::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 +SessionServantManager::getGlacier2AdapterIdSet(const shared_ptr& session) { - Lock sync(*this); - map::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& session) { - Lock sync(*this); + lock_guard lock(_mutex); - map::iterator p = _sessions.find(session); + auto p = _sessions.find(session); assert(p != _sessions.end()); // // Remove all the servants associated with the session. // - for(set::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 +SessionServantManager::add(const shared_ptr& servant, const shared_ptr& 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::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::iterator q = _sessions.find(p->second.session); + map, 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 +SessionServantManager::addImpl(const shared_ptr& servant, const shared_ptr& session) { - map::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 -#include #include #include @@ -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&, const std::string&, bool, + const std::string&, const std::shared_ptr&, + const std::string&, const std::shared_ptr&, + const std::string&, const std::shared_ptr&, + const std::shared_ptr&); - Ice::ObjectPtr locate(const Ice::Current&, Ice::LocalObjectPtr&); - void finished(const Ice::Current&, const Ice::ObjectPtr&, const Ice::LocalObjectPtr&); + std::shared_ptr locate(const Ice::Current&, std::shared_ptr&); + void finished(const Ice::Current&, const std::shared_ptr&, const std::shared_ptr&); 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 addSession(const std::shared_ptr&, + const std::shared_ptr&, + const std::string&); + void setSessionControl(const std::shared_ptr&, + const std::shared_ptr&, const Ice::IdentitySeq&); + std::shared_ptr getGlacier2IdentitySet(const std::shared_ptr&); + std::shared_ptr getGlacier2AdapterIdSet(const std::shared_ptr&); + void removeSession(const std::shared_ptr&); - Ice::ObjectPrx add(const Ice::ObjectPtr&, const Ice::ObjectPtr&); + std::shared_ptr add(const std::shared_ptr&, const std::shared_ptr&); void remove(const Ice::Identity&); - void connectionHeartbeat(const Ice::ConnectionPtr&); - void connectionClosed(const Ice::ConnectionPtr&); + void connectionHeartbeat(const std::shared_ptr&); + void connectionClosed(const std::shared_ptr&); private: - Ice::ObjectPrx addImpl(const Ice::ObjectPtr&, const Ice::ObjectPtr&); + std::shared_ptr addImpl(const std::shared_ptr&, const std::shared_ptr&); struct ServantInfo { - ServantInfo(const Ice::ObjectPtr& s, const Ice::ConnectionPtr& con, const Ice::ObjectPtr& ss) : + ServantInfo(const std::shared_ptr& s, + const std::shared_ptr& con, + const std::shared_ptr& ss) : servant(s), connection(con), session(ss) { } - const Ice::ObjectPtr servant; - const Ice::ConnectionPtr connection; - const Ice::ObjectPtr session; + const std::shared_ptr servant; + const std::shared_ptr connection; + const std::shared_ptr session; }; struct SessionInfo { - SessionInfo(const Ice::ConnectionPtr& c, const std::string& cat) : connection(c), category(cat) { } + SessionInfo(const std::shared_ptr& c, const std::string& cat) : connection(c), category(cat) + { + } - const Ice::ConnectionPtr connection; + const std::shared_ptr connection; const std::string category; - Glacier2::SessionControlPrx sessionControl; - Glacier2::IdentitySetPrx identitySet; - Glacier2::StringSetPrx adapterIdSet; + std::shared_ptr sessionControl; + std::shared_ptr identitySet; + std::shared_ptr adapterIdSet; std::set identities; }; - const Ice::ObjectAdapterPtr _adapter; + const std::shared_ptr _adapter; const std::string _instanceName; const bool _checkConnection; const std::string _serverAdminCategory; - const Ice::ObjectPtr _serverAdminRouter; + const std::shared_ptr _serverAdminRouter; const std::string _nodeAdminCategory; - const Ice::ObjectPtr _nodeAdminRouter; + const std::shared_ptr _nodeAdminRouter; const std::string _replicaAdminCategory; - const Ice::ObjectPtr _replicaAdminRouter; - const AdminCallbackRouterPtr _adminCallbackRouter; + const std::shared_ptr _replicaAdminRouter; + const std::shared_ptr _adminCallbackRouter; std::map _servants; - std::map _sessions; - std::multiset _adminConnections; + std::map, SessionInfo> _sessions; + std::multiset> _adminConnections; + + std::mutex _mutex; }; -typedef IceUtil::Handle 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& topicManager, const string& name, + long long dbSerial) : _logger(topicManager->ice_getCommunicator()->getLogger()), _serial(0), _dbSerial(dbSerial) { for(int i = 0; i < static_cast(sizeof(encodings) / sizeof(Ice::EncodingVersion)); ++i) { ostringstream os; os << name << "-" << Ice::encodingVersionToString(encodings[i]); - IceStorm::TopicPrx t; + shared_ptr 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& 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::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& observer, const string& name) { - Lock sync(*this); + lock_guard lock(_mutex); Ice::EncodingVersion v = IceInternal::getCompatibleEncoding(observer->ice_getEncodingVersion()); - map::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 >::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 >::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 >::const_iterator p = _waitForUpdates.find(serial); + auto p = _waitForUpdates.find(serial); if(p == _waitForUpdates.end()) { - map >::iterator q = _updateFailures.find(serial); + auto q = _updateFailures.find(serial); if(q != _updateFailures.end()) { map 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& topicManager) : ObserverTopic(topicManager, "RegistryObserver") { _publishers = getPublishers(); @@ -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::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::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& obsv) { - RegistryObserverPrx observer = RegistryObserverPrx::uncheckedCast(obsv); + auto observer = Ice::uncheckedCast(obsv); RegistryInfoSeq registries; registries.reserve(_registries.size()); - for(map::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::create(const shared_ptr& topicManager, + const shared_ptr& adapter) { - _publishers = getPublishers(); + shared_ptr topic(new NodeObserverTopic(topicManager)); + try { - const_cast(_externalPublisher) = NodeObserverPrx::uncheckedCast(adapter->addWithUUID(this)); + const_cast&>(topic->_externalPublisher) = + Ice::uncheckedCast(adapter->addWithUUID(topic)); } catch(const Ice::LocalException&) { } + + return topic; +} + +NodeObserverTopic::NodeObserverTopic(const shared_ptr& topicManager) : + ObserverTopic(topicManager, "NodeObserver") +{ + _publishers = getPublishers(); } 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::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::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::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::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& obsv) { - NodeObserverPrx observer = NodeObserverPrx::uncheckedCast(obsv); + auto observer = Ice::uncheckedCast(obsv); NodeDynamicInfoSeq nodes; nodes.reserve(_nodes.size()); - for(map::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& applications, Ice::Long serial) : +ApplicationObserverTopic::ApplicationObserverTopic(const shared_ptr& topicManager, + const map& 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::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::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::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::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& obsv) { - ApplicationObserverPrx observer = ApplicationObserverPrx::uncheckedCast(obsv); + auto observer = Ice::uncheckedCast(obsv); ApplicationInfoSeq applications; - for(map::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& adapters, Ice::Long serial) : +AdapterObserverTopic::AdapterObserverTopic(const shared_ptr& topicManager, + const map& 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::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::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::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::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& obsv) { - AdapterObserverPrx observer = AdapterObserverPrx::uncheckedCast(obsv); + auto observer = Ice::uncheckedCast(obsv); AdapterInfoSeq adapters; - for(map::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& objects, Ice::Long serial) : +ObjectObserverTopic::ObjectObserverTopic(const shared_ptr& topicManager, + const map& 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::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::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::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::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::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::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::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::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& obsv) { - ObjectObserverPrx observer = ObjectObserverPrx::uncheckedCast(obsv); + auto observer = Ice::uncheckedCast(obsv); ObjectInfoSeq objects; - for(map::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 #include #include #include @@ -14,20 +13,20 @@ namespace IceGrid { -class ObserverTopic : public IceUtil::Monitor, public virtual Ice::Object +class ObserverTopic { public: - ObserverTopic(const IceStorm::TopicManagerPrx&, const std::string&, Ice::Long = 0); - virtual ~ObserverTopic(); + ObserverTopic(const std::shared_ptr&, 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&, const std::string& = std::string()); + void unsubscribe(const std::shared_ptr&, 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&) = 0; void waitForSyncedSubscribers(int, const std::string& = std::string()); @@ -36,140 +35,139 @@ class ObserverTopic : public IceUtil::Monitor, public virtual Ic 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 std::vector getPublishers() const + template std::vector> getPublishers() const { - std::vector publishers; - for(std::vector::const_iterator p = _basePublishers.begin(); p != _basePublishers.end(); ++p) + std::vector> publishers; + for(const auto& publisher :_basePublishers) { - publishers.push_back(T::uncheckedCast(*p)); + publishers.push_back(Ice::uncheckedCast(publisher)); } return publishers; } - Ice::LoggerPtr _logger; - std::map _topics; - std::vector _basePublishers; + std::shared_ptr _logger; + std::map> _topics; + std::vector> _basePublishers; int _serial; - Ice::Long _dbSerial; + long long _dbSerial; std::set _syncSubscribers; std::map > _waitForUpdates; std::map > _updateFailures; + + mutable std::mutex _mutex; + std::condition_variable _condVar; }; -typedef IceUtil::Handle ObserverTopicPtr; class RegistryObserverTopic : public ObserverTopic { public: - RegistryObserverTopic(const IceStorm::TopicManagerPrx&); + RegistryObserverTopic(const std::shared_ptr&); void registryUp(const RegistryInfo&); void registryDown(const std::string&); - virtual void initObserver(const Ice::ObjectPrx&); + virtual void initObserver(const std::shared_ptr&); private: - std::vector _publishers; + std::vector> _publishers; std::map _registries; }; -typedef IceUtil::Handle 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 + create(const std::shared_ptr&, const std::shared_ptr&); - 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& getPublisher() { return _externalPublisher; } void nodeDown(const std::string&); - virtual void initObserver(const Ice::ObjectPrx&); + void initObserver(const std::shared_ptr&) override; bool isServerEnabled(const std::string&) const; private: - const NodeObserverPrx _externalPublisher; - std::vector _publishers; + NodeObserverTopic(const std::shared_ptr&); + + const std::shared_ptr _externalPublisher; + std::vector> _publishers; std::map _nodes; std::map _serverStatus; }; -typedef IceUtil::Handle NodeObserverTopicPtr; class ApplicationObserverTopic : public ObserverTopic { public: - ApplicationObserverTopic(const IceStorm::TopicManagerPrx&, const std::map&, Ice::Long); + ApplicationObserverTopic(const std::shared_ptr&, const std::map&, 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&); private: - std::vector _publishers; + std::vector> _publishers; std::map _applications; }; -typedef IceUtil::Handle ApplicationObserverTopicPtr; class AdapterObserverTopic : public ObserverTopic { public: - AdapterObserverTopic(const IceStorm::TopicManagerPrx&, const std::map&, Ice::Long); + AdapterObserverTopic(const std::shared_ptr&, const std::map&, 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&); private: - std::vector _publishers; + std::vector> _publishers; std::map _adapters; }; -typedef IceUtil::Handle AdapterObserverTopicPtr; class ObjectObserverTopic : public ObserverTopic { public: - ObjectObserverTopic(const IceStorm::TopicManagerPrx&, const std::map&, Ice::Long); + ObjectObserverTopic(const std::shared_ptr&, const std::map&, 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&); private: - std::vector _publishers; + std::vector> _publishers; std::map _objects; }; -typedef IceUtil::Handle ObjectObserverTopicPtr; }; diff --git a/cpp/src/IceGrid/TraceLevels.cpp b/cpp/src/IceGrid/TraceLevels.cpp index 4d776d822f1..baa4b58cc9f 100644 --- a/cpp/src/IceGrid/TraceLevels.cpp +++ b/cpp/src/IceGrid/TraceLevels.cpp @@ -9,34 +9,34 @@ using namespace std; using namespace IceGrid; -TraceLevels::TraceLevels(const Ice::CommunicatorPtr& communicator, const string& prefix) : - admin(0), +TraceLevels::TraceLevels(const shared_ptr& 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"), - patch(0), + patch(), patchCat("Patch"), - 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(admin) = properties->getPropertyAsInt(keyBase + adminCat); @@ -52,7 +52,3 @@ TraceLevels::TraceLevels(const Ice::CommunicatorPtr& communicator, const string& const_cast(session) = properties->getPropertyAsInt(keyBase + sessionCat); const_cast(discovery) = properties->getPropertyAsInt(keyBase + discoveryCat); } - -TraceLevels::~TraceLevels() -{ -} diff --git a/cpp/src/IceGrid/TraceLevels.h b/cpp/src/IceGrid/TraceLevels.h index 43a2bbf66c5..262f293277e 100644 --- a/cpp/src/IceGrid/TraceLevels.h +++ b/cpp/src/IceGrid/TraceLevels.h @@ -5,61 +5,57 @@ #ifndef ICE_GRID_TRACE_LEVELS_H #define ICE_GRID_TRACE_LEVELS_H -#include #include #include namespace IceGrid { -class TraceLevels : public ::IceUtil::Shared +class TraceLevels { public: - TraceLevels(const Ice::CommunicatorPtr&, const std::string&); - virtual ~TraceLevels(); + TraceLevels(const std::shared_ptr&, 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 patch; - const char* patchCat; + const std::string patchCat; 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 logger; }; -typedef IceUtil::Handle TraceLevelsPtr; - } // End namespace IceGrid #endif diff --git a/cpp/src/IceGrid/Util.cpp b/cpp/src/IceGrid/Util.cpp index b77215d8de9..6630ba42e3f 100644 --- a/cpp/src/IceGrid/Util.cpp +++ b/cpp/src/IceGrid/Util.cpp @@ -29,12 +29,12 @@ IceGrid::toString(const vector& 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) { @@ -197,7 +197,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& communicator, const ObjectDescriptor& obj, + const string& adapterId) { ObjectInfo info; info.type = obj.type; @@ -222,7 +223,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, const string& name, int size, int sizeMax, bool serialize) { if(properties->getPropertyAsIntWithDefault(name + ".Size", 0) < size) { @@ -324,3 +325,10 @@ IceGrid::getMMVersion(const string& o) return ver; } + +int +IceGrid::secondsToInt(const std::chrono::seconds& sec) +{ + return chrono::duration_cast>(sec).count(); +} + diff --git a/cpp/src/IceGrid/Util.h b/cpp/src/IceGrid/Util.h index d3d0ba30a5b..14b48bbc3db 100644 --- a/cpp/src/IceGrid/Util.h +++ b/cpp/src/IceGrid/Util.h @@ -23,7 +23,7 @@ inline set_inserter(T& container) } std::string toString(const std::vector&, 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,124 +32,88 @@ 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&, const ObjectDescriptor&, const std::string&); -void setupThreadPool(const Ice::PropertiesPtr&, const std::string&, int, int = 0, bool = false); +void setupThreadPool(const std::shared_ptr&, const std::string&, int, int = 0, bool = false); int getMMVersion(const std::string&); -template -struct ForEachCommunicator +int secondsToInt(const std::chrono::seconds&); + +inline void +forEachCommunicator(const std::shared_ptr& descriptor, + std::function&)> callback) { - ForEachCommunicator(Function f) : _function(f) + callback(descriptor); + auto iceBox = std::dynamic_pointer_cast(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& oldDescriptor, + const std::shared_ptr& newDescriptor, + std::function&, + const std::shared_ptr&)> callback) +{ + callback(oldDescriptor, newDescriptor); + + auto oldIceBox = std::dynamic_pointer_cast(oldDescriptor); + auto newIceBox = std::dynamic_pointer_cast(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 ForEachCommunicator -inline forEachCommunicator(Function function) -{ - return ForEachCommunicator(function); -} - -template -struct ObjFunc -{ - 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 ObjFunc -inline objFunc(T& obj, void (T::*p)(A)) -{ - return ObjFunc(obj, p); } template std::vector 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 -#include - -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 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::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::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::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::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 -#include - -#include - -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 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 _waitQueue; - bool _destroyed; -}; - -typedef IceUtil::Handle WaitQueuePtr; - -} - -#endif diff --git a/cpp/src/IceGrid/WellKnownObjectsManager.cpp b/cpp/src/IceGrid/WellKnownObjectsManager.cpp index f4f7227bcd1..db2e28c26f3 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), _initialized(false) { } void -WellKnownObjectsManager::add(const Ice::ObjectPrx& proxy, const string& type) +WellKnownObjectsManager::add(const std::shared_ptr& 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(std::move(info)); } void -WellKnownObjectsManager::addEndpoint(const string& name, const Ice::ObjectPrx& proxy) +WellKnownObjectsManager::addEndpoint(const string& name, const std::shared_ptr& 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& 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 WellKnownObjectsManager::getEndpoints(const string& name) { - Lock sync(*this); + lock_guard lock(_mutex); return _endpoints[name]; } -LocatorPrx +shared_ptr 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(getWellKnownObjectReplicatedProxy(std::move(id), "Client")); } -Ice::LocatorRegistryPrx +shared_ptr 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(getWellKnownObjectReplicatedProxy(std::move(id), "Server")); } -Ice::ObjectPrx +std::shared_ptr 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 DatabasePtr; -class WellKnownObjectsManager : public IceUtil::Mutex, public IceUtil::Shared +class WellKnownObjectsManager { public: - WellKnownObjectsManager(const DatabasePtr&); + WellKnownObjectsManager(const std::shared_ptr&); - void add(const Ice::ObjectPrx&, const std::string&); - void addEndpoint(const std::string&, const Ice::ObjectPrx&); + void add(const std::shared_ptr&, const std::string&); + void addEndpoint(const std::string&, const std::shared_ptr&); void finish(); void registerAll(); - void registerAll(const ReplicaSessionPrx&); + void registerAll(const std::shared_ptr&); void updateReplicatedWellKnownObjects(); - Ice::ObjectPrx getEndpoints(const std::string&); + std::shared_ptr getEndpoints(const std::string&); - LocatorPrx getLocator(); - Ice::LocatorRegistryPrx getLocatorRegistry(); + std::shared_ptr getLocator(); + std::shared_ptr getLocatorRegistry(); private: bool initialized() const; - Ice::ObjectPrx getWellKnownObjectReplicatedProxy(const Ice::Identity&, const std::string&); + std::shared_ptr getWellKnownObjectReplicatedProxy(const Ice::Identity&, const std::string&); - const DatabasePtr _database; + const std::shared_ptr _database; bool _initialized; StringObjectProxyDict _endpoints; ObjectInfoSeq _wellKnownObjects; + + mutable std::mutex _mutex; }; -typedef IceUtil::Handle WellKnownObjectsManagerPtr; }; diff --git a/cpp/src/IceGrid/msbuild/icegridadmin/icegridadmin.vcxproj b/cpp/src/IceGrid/msbuild/icegridadmin/icegridadmin.vcxproj index 1afe0507f03..66b56aa16e1 100644 --- a/cpp/src/IceGrid/msbuild/icegridadmin/icegridadmin.vcxproj +++ b/cpp/src/IceGrid/msbuild/icegridadmin/icegridadmin.vcxproj @@ -21,6 +21,7 @@ {1F4CA1BE-B405-400F-912E-F0CC7E369D59} + icegridadmin++11 @@ -44,7 +45,7 @@ $(DefaultPlatformToolset) - + diff --git a/cpp/src/IceGrid/msbuild/icegridnode/icegridnode.vcxproj b/cpp/src/IceGrid/msbuild/icegridnode/icegridnode.vcxproj index 65dc60de0a1..fd92cc87f37 100644 --- a/cpp/src/IceGrid/msbuild/icegridnode/icegridnode.vcxproj +++ b/cpp/src/IceGrid/msbuild/icegridnode/icegridnode.vcxproj @@ -21,6 +21,7 @@ {48EF9416-336F-4FA5-A376-FDFB7726ADBA} + icegridnode++11 @@ -44,7 +45,7 @@ $(DefaultPlatformToolset) - + diff --git a/cpp/src/IceGrid/msbuild/icegridregistry/icegridregistry.vcxproj b/cpp/src/IceGrid/msbuild/icegridregistry/icegridregistry.vcxproj index a783b56b165..b4a8a7404d5 100644 --- a/cpp/src/IceGrid/msbuild/icegridregistry/icegridregistry.vcxproj +++ b/cpp/src/IceGrid/msbuild/icegridregistry/icegridregistry.vcxproj @@ -21,6 +21,7 @@ {64490115-464B-4DC3-B7C6-D0AF1B68B6F9} + icegridregistry++11 @@ -44,7 +45,7 @@ $(DefaultPlatformToolset) - + diff --git a/cpp/src/IcePatch2Lib/ClientUtil.cpp b/cpp/src/IcePatch2Lib/ClientUtil.cpp index 134fd1c2888..f4594698a8f 100644 --- a/cpp/src/IcePatch2Lib/ClientUtil.cpp +++ b/cpp/src/IcePatch2Lib/ClientUtil.cpp @@ -4,10 +4,12 @@ #include #include +#include #include #include #include #include +#include using namespace std; using namespace Ice; @@ -57,7 +59,7 @@ class PatcherI : public Patcher public: PatcherI(const Ice::CommunicatorPtr&, const PatcherFeedbackPtr&); - PatcherI(const FileServerPrx&, const PatcherFeedbackPtr&, const std::string&, bool, Ice::Int, Ice::Int); + PatcherI(const FileServerPrxPtr&, const PatcherFeedbackPtr&, const std::string&, bool, Ice::Int, Ice::Int); virtual ~PatcherI(); virtual bool prepare(); @@ -66,7 +68,7 @@ class PatcherI : public Patcher private: - void init(const FileServerPrx&); + void init(const FileServerPrxPtr&); bool removeFiles(const LargeFileInfoSeq&); bool updateFiles(const LargeFileInfoSeq&); bool updateFilesInternal(const LargeFileInfoSeq&, const DecompressorPtr&); @@ -77,8 +79,8 @@ class PatcherI : public Patcher const bool _thorough; const Ice::Int _chunkSize; const Ice::Int _remove; - const FileServerPrx _serverCompress; - const FileServerPrx _serverNoCompress; + const FileServerPrxPtr _serverCompress; + const FileServerPrxPtr _serverNoCompress; LargeFileInfoSeq _localFiles; LargeFileInfoSeq _updateFiles; @@ -209,7 +211,7 @@ PatcherI::PatcherI(const CommunicatorPtr& communicator, const PatcherFeedbackPtr throw runtime_error("property `IcePatch2Client.Proxy' is not set"); } - FileServerPrx server = FileServerPrx::checkedCast(communicator->stringToProxy(clientProxy)); + FileServerPrxPtr server = ICE_CHECKED_CAST(FileServerPrx, communicator->stringToProxy(clientProxy)); if(!server) { throw runtime_error("proxy `" + clientProxy + "' is not a file server."); @@ -218,7 +220,7 @@ PatcherI::PatcherI(const CommunicatorPtr& communicator, const PatcherFeedbackPtr init(server); } -PatcherI::PatcherI(const FileServerPrx& server, +PatcherI::PatcherI(const FileServerPrxPtr& server, const PatcherFeedbackPtr& feedback, const string& dataDir, bool thorough, @@ -243,6 +245,66 @@ PatcherI::~PatcherI() } } +#ifdef ICE_CPP11_MAPPING +class GetFileInfoSeqAsyncCB +{ +public: + + GetFileInfoSeqAsyncCB(bool useSmallFileAPI) : + _useSmallFileAPI(useSmallFileAPI) + + { + _largeFileInfoSeqFuture = _largeFileInfoSeqPromise.get_future(); + _fileInfoSeqFuture = _fileInfoSeqPromise.get_future(); + } + + void complete(FileInfoSeq fileInfoSeq) + { + assert(_useSmallFileAPI); + _fileInfoSeqPromise.set_value(fileInfoSeq); + } + + void complete(LargeFileInfoSeq largeFileInfoSeq) + { + assert(!_useSmallFileAPI); + _largeFileInfoSeqPromise.set_value(largeFileInfoSeq); + } + + void exception(std::exception_ptr exception) + { + if (_useSmallFileAPI) + { + _fileInfoSeqPromise.set_exception(exception); + } + else + { + _largeFileInfoSeqPromise.set_exception(exception); + } + } + + FileInfoSeq getFileInfoSeq() + { + assert(_useSmallFileAPI); + return _fileInfoSeqFuture.get(); + } + + LargeFileInfoSeq getLargeFileInfoSeq() + { + assert(!_useSmallFileAPI); + return _largeFileInfoSeqFuture.get(); + } + +private: + + std::promise _largeFileInfoSeqPromise; + std::promise _fileInfoSeqPromise; + + std::future _largeFileInfoSeqFuture; + std::future _fileInfoSeqFuture; + bool _useSmallFileAPI; +}; +#endif + class PatcherGetFileInfoSeqCB : public GetFileInfoSeqCB { public: @@ -252,14 +314,12 @@ class PatcherGetFileInfoSeqCB : public GetFileInfoSeqCB { } - virtual bool - remove(const string&) + virtual bool remove(const string&) { return true; } - virtual bool - checksum(const string& path) + virtual bool checksum(const string& path) { return _feedback->checksumProgress(path); } @@ -337,19 +397,43 @@ PatcherI::prepare() while(true) { +#ifdef ICE_CPP11_MAPPING + std::shared_ptr curCB; + std::shared_ptr nxtCB; +#else AsyncResultPtr curCB; AsyncResultPtr nxtCB; +#endif try { for(size_t node0 = 0; node0 < 256; ++node0) { if(tree0.nodes[node0].checksum != checksumSeq[node0]) { - if(!curCB) + if (!curCB) { +#ifdef ICE_CPP11_MAPPING + curCB = std::make_shared(_useSmallFileAPI); + if (_useSmallFileAPI) + { + _serverCompress->getFileInfoSeqAsync( + static_cast(node0), + [curCB](FileInfoSeq fileInfoSeq) { curCB->complete(fileInfoSeq); }, + [curCB](exception_ptr exception) { curCB->exception(exception); }); + } + else + { + _serverCompress->getLargeFileInfoSeqAsync( + static_cast(node0), + [curCB](LargeFileInfoSeq fileInfoSeq) { curCB->complete(fileInfoSeq); }, + [curCB](exception_ptr exception) { curCB->exception(exception); }); + } +#else assert(!nxtCB); - curCB = _useSmallFileAPI ? _serverCompress->begin_getFileInfoSeq(static_cast(node0)) : + curCB = _useSmallFileAPI ? + _serverCompress->begin_getFileInfoSeq(static_cast(node0)) : _serverCompress->begin_getLargeFileInfoSeq(static_cast(node0)); +#endif // ICE_CPP11_MAPPING } else { @@ -358,7 +442,6 @@ PatcherI::prepare() } size_t node0Nxt = node0; - do { ++node0Nxt; @@ -367,12 +450,42 @@ PatcherI::prepare() if(node0Nxt < 256) { +#ifdef ICE_CPP11_MAPPING + nxtCB = std::make_shared(_useSmallFileAPI); + if (_useSmallFileAPI) + { + _serverCompress->getFileInfoSeqAsync( + static_cast(node0Nxt), + [nxtCB](FileInfoSeq fileInfoSeq) { nxtCB->complete(fileInfoSeq); }, + [nxtCB](exception_ptr exception) { nxtCB->exception(exception); }); + } + else + { + _serverCompress->getLargeFileInfoSeqAsync( + static_cast(node0Nxt), + [nxtCB](LargeFileInfoSeq fileInfoSeq) { nxtCB->complete(fileInfoSeq); }, + [nxtCB](exception_ptr exception) { nxtCB->exception(exception); }); + } +#else nxtCB = _useSmallFileAPI ? _serverCompress->begin_getFileInfoSeq(static_cast(node0Nxt)) : _serverCompress->begin_getLargeFileInfoSeq(static_cast(node0Nxt)); +#endif } LargeFileInfoSeq files; +#ifdef ICE_CPP11_MAPPING + if (_useSmallFileAPI) + { + FileInfoSeq smallFiles = curCB->getFileInfoSeq(); + files.resize(smallFiles.size()); + transform(smallFiles.begin(), smallFiles.end(), files.begin(), toLargeFileInfo); + } + else + { + files = curCB->getLargeFileInfoSeq(); + } +#else if(_useSmallFileAPI) { FileInfoSeq smallFiles = _serverCompress->end_getFileInfoSeq(curCB); @@ -383,7 +496,7 @@ PatcherI::prepare() { files = _serverCompress->end_getLargeFileInfoSeq(curCB); } - +#endif sort(files.begin(), files.end(), FileInfoLess()); files.erase(unique(files.begin(), files.end(), FileInfoEqual()), files.end()); @@ -590,7 +703,7 @@ PatcherI::finish() } void -PatcherI::init(const FileServerPrx& server) +PatcherI::init(const FileServerPrxPtr& server) { if(_dataDir.empty()) { @@ -633,8 +746,10 @@ PatcherI::init(const FileServerPrx& server) const_cast(_dataDir) = simplify(cwd + '/' + _dataDir); } - const_cast(_serverCompress) = FileServerPrx::uncheckedCast(server->ice_compress(true)); - const_cast(_serverNoCompress) = FileServerPrx::uncheckedCast(server->ice_compress(false)); + const_cast(_serverCompress) = + ICE_UNCHECKED_CAST(FileServerPrx, server->ice_compress(true)); + const_cast(_serverNoCompress) = + ICE_UNCHECKED_CAST(FileServerPrx, server->ice_compress(false)); } bool @@ -725,6 +840,66 @@ PatcherI::updateFiles(const LargeFileInfoSeq& files) return result; } +#ifdef ICE_CPP11_MAPPING +class GetFileCompressedCB +{ +public: + + GetFileCompressedCB() + { + _bytesFuture = _bytesPromise.get_future(); + } + + void complete(ByteSeq bytes) + { + _bytesPromise.set_value(bytes); + } + + void exception(std::exception_ptr exception) + { + _bytesPromise.set_exception(exception); + } + + ByteSeq getFileCompressed() + { + return _bytesFuture.get(); + } + +private: + + std::promise _bytesPromise; + std::future _bytesFuture; +}; + +void getFileCompressed( + FileServerPrxPtr serverNoCompress, + std::string path, + Ice::Long pos, + int chunkSize, + std::shared_ptr cb, + bool useSmallFileAPI) +{ + if (useSmallFileAPI) + { + serverNoCompress->getFileCompressedAsync( + path, + static_cast(pos), + chunkSize, + [cb](std::pair result) { cb->complete(ByteSeq(result.first, result.second)); }, + [cb](exception_ptr exception) { cb->exception(exception); }); + } + else + { + serverNoCompress->getLargeFileCompressedAsync( + path, + pos, + chunkSize, + [cb](std::pair result) { cb->complete(ByteSeq(result.first, result.second)); }, + [cb](exception_ptr exception) { cb->exception(exception); }); + } +} +#endif + bool PatcherI::updateFilesInternal(const LargeFileInfoSeq& files, const DecompressorPtr& decompressor) { @@ -739,8 +914,13 @@ PatcherI::updateFilesInternal(const LargeFileInfoSeq& files, const DecompressorP } } +#ifdef ICE_CPP11_MAPPING + shared_ptr curCB; + shared_ptr nxtCB; +#else AsyncResultPtr curCB; AsyncResultPtr nxtCB; +#endif // ICE_CPP11_MAPPING for(LargeFileInfoSeq::const_iterator p = files.begin(); p != files.end(); ++p) { @@ -802,9 +982,21 @@ PatcherI::updateFilesInternal(const LargeFileInfoSeq& files, const DecompressorP if(!curCB) { assert(!nxtCB); +#ifdef ICE_CPP11_MAPPING + curCB = std::make_shared(); + getFileCompressed( + _serverNoCompress, + p->path, + pos, + _chunkSize, + curCB, + _useSmallFileAPI); +#else + curCB = _useSmallFileAPI ? _serverNoCompress->begin_getFileCompressed(p->path, static_cast(pos), _chunkSize) : _serverNoCompress->begin_getLargeFileCompressed(p->path, pos, _chunkSize); +#endif // ICE_CPP11_MAPPING } else { @@ -814,9 +1006,20 @@ PatcherI::updateFilesInternal(const LargeFileInfoSeq& files, const DecompressorP if(pos + _chunkSize < p->size) { +#ifdef ICE_CPP11_MAPPING + nxtCB = std::make_shared(); + getFileCompressed( + _serverNoCompress, + p->path, + pos + _chunkSize, + _chunkSize, + nxtCB, + _useSmallFileAPI); +#else nxtCB = _useSmallFileAPI ? _serverNoCompress->begin_getFileCompressed(p->path, static_cast(pos + _chunkSize), _chunkSize) : _serverNoCompress->begin_getLargeFileCompressed(p->path, pos + _chunkSize, _chunkSize); +#endif } else { @@ -829,18 +1032,32 @@ PatcherI::updateFilesInternal(const LargeFileInfoSeq& files, const DecompressorP if(q != files.end()) { +#ifdef ICE_CPP11_MAPPING + nxtCB = std::make_shared(); + getFileCompressed( + _serverNoCompress, + q->path, + 0, + _chunkSize, + nxtCB, + _useSmallFileAPI); +#else nxtCB = _useSmallFileAPI ? _serverNoCompress->begin_getFileCompressed(q->path, 0, _chunkSize) : _serverNoCompress->begin_getLargeFileCompressed(q->path, 0, _chunkSize); +#endif } } ByteSeq bytes; - try { +#ifdef ICE_CPP11_MAPPING + bytes = curCB->getFileCompressed(); +#else bytes = _useSmallFileAPI ? _serverNoCompress->end_getFileCompressed(curCB) : - _serverNoCompress->end_getLargeFileCompressed(curCB); + _serverNoCompress->end_getLargeFileCompressed(curCB); +#endif // ICE_CPP11_MAPPING } catch(const FileAccessException& ex) { @@ -972,7 +1189,7 @@ PatcherI::updateFlags(const LargeFileInfoSeq& files) PatcherPtr PatcherFactory::create(const Ice::CommunicatorPtr& communicator, const PatcherFeedbackPtr& feedback) { - return new PatcherI(communicator, feedback); + return ICE_MAKE_SHARED(PatcherI, communicator, feedback); } // @@ -980,12 +1197,12 @@ PatcherFactory::create(const Ice::CommunicatorPtr& communicator, const PatcherFe // are equivalent to the configuration properties described above. // PatcherPtr -PatcherFactory::create(const FileServerPrx& server, +PatcherFactory::create(const FileServerPrxPtr& server, const PatcherFeedbackPtr& feedback, const string& dataDir, bool thorough, Ice::Int chunkSize, Ice::Int remove) { - return new PatcherI(server, feedback, dataDir, thorough, chunkSize, remove); + return ICE_MAKE_SHARED(PatcherI, server, feedback, dataDir, thorough, chunkSize, remove); } diff --git a/cpp/src/IcePatch2Lib/Util.cpp b/cpp/src/IcePatch2Lib/Util.cpp index 6080dd44558..e387f9072d9 100644 --- a/cpp/src/IcePatch2Lib/Util.cpp +++ b/cpp/src/IcePatch2Lib/Util.cpp @@ -75,11 +75,23 @@ IcePatch2Internal::toLargeFileInfo(const FileInfo& info) bool IcePatch2Internal::writeFileInfo(FILE* fp, const LargeFileInfo& info) { - int rc = fprintf(fp, "%s\t%s\t" ICE_INT64_FORMAT "\t%d\n", - escapeString(info.path, "", IceUtilInternal::Compat).c_str(), - bytesToString(info.checksum).c_str(), - info.size, - static_cast(info.executable)); + int rc = fprintf(fp, +#ifdef ICE_CPP11_MAPPING + "%s\t%s\t%lld\t%d\n", +#else + "%s\t%s\t" ICE_INT64_FORMAT "\t%d\n", +#endif + IceUtilInternal::escapeString( + info.path, "", +#ifdef ICE_CPP11_MAPPING + IceUtilInternal::ToStringMode::Compat +#else + IceUtilInternal::Compat +#endif // ICE_CPP11_MAPPING + ).c_str(), + bytesToString(info.checksum).c_str(), + info.size, + static_cast(info.executable)); return rc > 0; } diff --git a/cpp/src/IcePatch2Lib/msbuild/icepatch2++11/icepatch2++11.vcxproj b/cpp/src/IcePatch2Lib/msbuild/icepatch2++11/icepatch2++11.vcxproj new file mode 100644 index 00000000000..df6d8bb7453 --- /dev/null +++ b/cpp/src/IcePatch2Lib/msbuild/icepatch2++11/icepatch2++11.vcxproj @@ -0,0 +1,226 @@ + + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + {18F381D8-BA61-4E6A-B877-9F6BC28C07E5} + IcePatch2 + 10.0 + + + + DynamicLibrary + true + $(DefaultPlatformToolset) + + + DynamicLibrary + false + $(DefaultPlatformToolset) + + + DynamicLibrary + true + $(DefaultPlatformToolset) + + + DynamicLibrary + false + $(DefaultPlatformToolset) + + + + + + + + + + + + + + + + + + + + + + ICEPATCH2_API_EXPORTS;%(PreprocessorDefinitions) + 4996;%(DisableSpecificWarnings) + + + + + ICEPATCH2_API_EXPORTS;%(PreprocessorDefinitions) + 4996;%(DisableSpecificWarnings) + + + + + ICEPATCH2_API_EXPORTS;%(PreprocessorDefinitions) + 4996;%(DisableSpecificWarnings) + + + + + ICEPATCH2_API_EXPORTS;%(PreprocessorDefinitions) + 4996;%(DisableSpecificWarnings) + + + + + $(IceSrcRootDir)\include\generated\cpp11\$(Platform)\$(Configuration)\IcePatch2\ + IcePatch2 + + + + + + + + + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileServer.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileServer.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileServer.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileServer.ice + + + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileServer.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileServer.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileServer.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice + + + true + true + true + ..\..\..\..\..\slice\IcePatch2\FileServer.ice + + + + + + + + + + + + + + + + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + + \ No newline at end of file diff --git a/cpp/src/IcePatch2Lib/msbuild/icepatch2++11/icepatch2++11.vcxproj.filters b/cpp/src/IcePatch2Lib/msbuild/icepatch2++11/icepatch2++11.vcxproj.filters new file mode 100644 index 00000000000..f0f9eb6ecfd --- /dev/null +++ b/cpp/src/IcePatch2Lib/msbuild/icepatch2++11/icepatch2++11.vcxproj.filters @@ -0,0 +1,143 @@ + + + + + {d2712066-1923-447a-ad64-c80f747fb1ea} + h;hh;hpp;hxx;hm;inl;inc;xsd + + + {af5258c0-2b8d-40ab-be90-0b7b080169c2} + rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms + + + {f59eb29a-8e4d-4f96-956f-912bb71723f5} + ice + + + {efca70d0-5c94-455a-b115-a1627cd37f1f} + cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx + + + {b2de4f44-f7bf-4d2b-8b1f-7a7eb14023b8} + + + {53019a64-4101-485f-9cbc-06003a1dbf05} + + + {9e5ee2e4-9fa9-4c5c-a39f-e25b5abadf9b} + + + {c6d023b5-a4f9-4400-acf3-492ab13e1559} + + + {c290a809-84db-4a63-b1ab-d797afc58dbe} + + + {28be0f87-bd50-4e44-b1ba-0e1ae0fca153} + + + {69f748d0-0821-4b05-8824-22b83945880a} + + + {859e3a89-2f71-4335-806c-3c306d75b0c8} + + + {46937cff-2db3-4117-8063-dbe9fd345624} + + + {d98eb1b4-139b-4c19-b728-3eb412a4b718} + + + {f630f65f-1553-46f9-b40b-c7a0731de52a} + + + {6a79f0b3-e47f-4f69-9431-d0d1fe23696e} + + + + + Source Files + + + Source Files + + + Source Files\Win32\Debug + + + Source Files\x64\Debug + + + Source Files\Win32\Release + + + Source Files\x64\Release + + + Source Files\Win32\Debug + + + Source Files\x64\Debug + + + Source Files\Win32\Release + + + Source Files\x64\Release + + + + + Header Files + + + Header Files + + + Header Files + + + Header Files + + + Header Files\Win32\Debug + + + Header Files\x64\Debug + + + Header Files\Win32\Release + + + Header Files\x64\Release + + + Header Files\Win32\Debug + + + Header Files\x64\Debug + + + Header Files\Win32\Release + + + Header Files\x64\Release + + + + + Resource Files + + + + + + + + Slice Files + + + Slice Files + + + \ No newline at end of file diff --git a/cpp/src/IcePatch2Lib/msbuild/packages.config b/cpp/src/IcePatch2Lib/msbuild/icepatch2++11/packages.config similarity index 100% rename from cpp/src/IcePatch2Lib/msbuild/packages.config rename to cpp/src/IcePatch2Lib/msbuild/icepatch2++11/packages.config diff --git a/cpp/src/IcePatch2Lib/msbuild/icepatch2.vcxproj b/cpp/src/IcePatch2Lib/msbuild/icepatch2/icepatch2.vcxproj similarity index 72% rename from cpp/src/IcePatch2Lib/msbuild/icepatch2.vcxproj rename to cpp/src/IcePatch2Lib/msbuild/icepatch2/icepatch2.vcxproj index b9202465258..c3dcc9837bf 100644 --- a/cpp/src/IcePatch2Lib/msbuild/icepatch2.vcxproj +++ b/cpp/src/IcePatch2Lib/msbuild/icepatch2/icepatch2.vcxproj @@ -1,6 +1,6 @@  - + Debug @@ -45,7 +45,7 @@ $(DefaultPlatformToolset) - + @@ -93,133 +93,133 @@ - - + + - - + + true true true - ..\..\..\..\slice\IcePatch2\FileInfo.ice + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice true true true - ..\..\..\..\slice\IcePatch2\FileServer.ice + ..\..\..\..\..\slice\IcePatch2\FileServer.ice true true true - ..\..\..\..\slice\IcePatch2\FileInfo.ice + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice true true true - ..\..\..\..\slice\IcePatch2\FileServer.ice + ..\..\..\..\..\slice\IcePatch2\FileServer.ice true true true - ..\..\..\..\slice\IcePatch2\FileInfo.ice + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice true true true - ..\..\..\..\slice\IcePatch2\FileServer.ice + ..\..\..\..\..\slice\IcePatch2\FileServer.ice true true true - ..\..\..\..\slice\IcePatch2\FileInfo.ice + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice true true true - ..\..\..\..\slice\IcePatch2\FileServer.ice + ..\..\..\..\..\slice\IcePatch2\FileServer.ice - + true true true - ..\..\..\..\slice\IcePatch2\FileInfo.ice + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice - + true true true - ..\..\..\..\slice\IcePatch2\FileServer.ice + ..\..\..\..\..\slice\IcePatch2\FileServer.ice - + true true true - ..\..\..\..\slice\IcePatch2\FileInfo.ice + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice - + true true true - ..\..\..\..\slice\IcePatch2\FileServer.ice + ..\..\..\..\..\slice\IcePatch2\FileServer.ice - + true true true - ..\..\..\..\slice\IcePatch2\FileInfo.ice + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice - + true true true - ..\..\..\..\slice\IcePatch2\FileServer.ice + ..\..\..\..\..\slice\IcePatch2\FileServer.ice - + true true true - ..\..\..\..\slice\IcePatch2\FileInfo.ice + ..\..\..\..\..\slice\IcePatch2\FileInfo.ice - + true true true - ..\..\..\..\slice\IcePatch2\FileServer.ice + ..\..\..\..\..\slice\IcePatch2\FileServer.ice - - - - + + + + - + - - + + - + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. - - - + + + \ No newline at end of file diff --git a/cpp/src/IcePatch2Lib/msbuild/icepatch2.vcxproj.filters b/cpp/src/IcePatch2Lib/msbuild/icepatch2/icepatch2.vcxproj.filters similarity index 78% rename from cpp/src/IcePatch2Lib/msbuild/icepatch2.vcxproj.filters rename to cpp/src/IcePatch2Lib/msbuild/icepatch2/icepatch2.vcxproj.filters index 64702f77cf6..cf8b0fcdf5b 100644 --- a/cpp/src/IcePatch2Lib/msbuild/icepatch2.vcxproj.filters +++ b/cpp/src/IcePatch2Lib/msbuild/icepatch2/icepatch2.vcxproj.filters @@ -55,77 +55,77 @@ - + Source Files - + Source Files Source Files\Win32\Debug - - Source Files\Win32\Debug - Source Files\x64\Debug - - Source Files\x64\Debug - Source Files\Win32\Release - - Source Files\Win32\Release - Source Files\x64\Release + + Source Files\Win32\Debug + + + Source Files\x64\Debug + + + Source Files\Win32\Release + Source Files\x64\Release - + Header Files - - Header Files\Win32\Debug + + Header Files - - Header Files\Win32\Debug + + Header Files - - Header Files\x64\Debug + + Header Files - - Header Files\x64\Debug + + Header Files\Win32\Debug - - Header Files\Win32\Release + + Header Files\x64\Debug - + Header Files\Win32\Release - + Header Files\x64\Release - - Header Files\x64\Release + + Header Files\Win32\Debug - - Header Files + + Header Files\x64\Debug - - Header Files + + Header Files\Win32\Release - - Header Files + + Header Files\x64\Release - + Resource Files @@ -133,10 +133,10 @@ - + Slice Files - + Slice Files diff --git a/cpp/src/IcePatch2Lib/msbuild/icepatch2/packages.config b/cpp/src/IcePatch2Lib/msbuild/icepatch2/packages.config new file mode 100644 index 00000000000..7c322b5c366 --- /dev/null +++ b/cpp/src/IcePatch2Lib/msbuild/icepatch2/packages.config @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/cpp/src/IceStorm/Admin.cpp b/cpp/src/IceStorm/Admin.cpp index a59a5a0c82b..8714cc0644b 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&, const Ice::StringSeq&); int #ifdef _WIN32 @@ -47,12 +39,13 @@ main(int argc, char* argv[]) 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& 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 managers; - Ice::PropertiesPtr properties = communicator->getProperties(); - IceStorm::TopicManagerPrx defaultManager; + map> managers; + auto properties = communicator->getProperties(); + shared_ptr 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::value_type( - manager->ice_getIdentity(), manager)); + auto manager = Ice::uncheckedCast( + 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(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(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/IceStormDB.cpp b/cpp/src/IceStorm/IceStormDB.cpp index ccd7d0e3d7f..f82475dc5a1 100644 --- a/cpp/src/IceStorm/IceStormDB.cpp +++ b/cpp/src/IceStorm/IceStormDB.cpp @@ -9,20 +9,14 @@ #include #include #include + #include +#include using namespace std; using namespace IceInternal; -int run(const Ice::StringSeq&); - -Ice::CommunicatorPtr communicator; - -void -destroyCommunicator(int) -{ - communicator->destroy(); -} +int run(const shared_ptr&, const Ice::StringSeq&); int #ifdef _WIN32 @@ -37,11 +31,7 @@ main(int argc, char* argv[]) { 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 +60,7 @@ usage(const string& name) } int -run(const Ice::StringSeq& args) +run(const shared_ptr& communicator, const Ice::StringSeq& args) { IceUtilInternal::Options opts; opts.addOpt("h", "help"); @@ -144,10 +134,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 +221,14 @@ run(const Ice::StringSeq& args) IceDB::Dbi 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 838c31d2c9e..87edeee5a15 100644 --- a/cpp/src/IceStorm/IceStormInternal.ice +++ b/cpp/src/IceStorm/IceStormInternal.ice @@ -19,7 +19,7 @@ module IceStorm { /// The event data. -["cpp:class"] struct EventData +struct EventData { /// The operation name. string op; @@ -32,7 +32,7 @@ module IceStorm } /// A sequence of EventData. -["cpp:type:std::deque< ::IceStorm::EventDataPtr>"] sequence EventDataSeq; +["cpp:type:std::deque"] sequence EventDataSeq; /// The TopicLink interface. This is used to forward events between federated Topic instances. /// @see TopicInternal diff --git a/cpp/src/IceStorm/Instance.cpp b/cpp/src/IceStorm/Instance.cpp index ad22c9151ad..56db7a8d95e 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 lg(_mutex); _topics.push_back(name); } vector TopicReaper::consumeReapedTopics() { - Lock sync(*this); + lock_guard lg(_mutex); vector 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 communicator, + shared_ptr publishAdapter, + shared_ptr topicAdapter, + shared_ptr nodeAdapter, + shared_ptr 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(std::move(communicator)), + _publishAdapter(std::move(publishAdapter)), + _topicAdapter(std::move(topicAdapter)), + _nodeAdapter(std::move(nodeAdapter)), + _nodeProxy(std::move(nodeProxy)), + _traceLevels(make_shared(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()), + _observers(make_shared(_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(_topicReplicaProxy) = communicator->stringToProxy("dummy:" + p); + const_cast&>(_topicReplicaProxy) = + _communicator->stringToProxy("dummy:" + p); } p = properties->getProperty(name + ".ReplicatedPublishEndpoints"); if(!p.empty()) { - const_cast(_publisherReplicaProxy) = communicator->stringToProxy("dummy:" + p); + const_cast&>(_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(_communicator->getObserver()); if(o) { - _observer = new TopicManagerObserverI(o->getFacet()); + _observer = make_shared(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 node) { - _node = node; + _node = std::move(node); } string @@ -187,109 +142,103 @@ Instance::serviceName() const return _serviceName; } -Ice::CommunicatorPtr +shared_ptr Instance::communicator() const { return _communicator; } -Ice::PropertiesPtr +shared_ptr Instance::properties() const { return _communicator->getProperties(); } -Ice::ObjectAdapterPtr +shared_ptr Instance::publishAdapter() const { return _publishAdapter; } -Ice::ObjectAdapterPtr +shared_ptr Instance::topicAdapter() const { return _topicAdapter; } -Ice::ObjectAdapterPtr +shared_ptr Instance::nodeAdapter() const { return _nodeAdapter; } -ObserversPtr +shared_ptr Instance::observers() const { return _observers; } -NodeIPtr +shared_ptr Instance::node() const { return _node; } -NodePrx +shared_ptr Instance::nodeProxy() const { return _nodeProxy; } -TraceLevelsPtr +shared_ptr Instance::traceLevels() const { return _traceLevels; } -IceUtil::TimerPtr -Instance::batchFlusher() const -{ - return _batchFlusher; -} - IceUtil::TimerPtr Instance::timer() const { return _timer; } -Ice::ObjectPrx +shared_ptr Instance::topicReplicaProxy() const { return _topicReplicaProxy; } -Ice::ObjectPrx +shared_ptr Instance::publisherReplicaProxy() const { return _publisherReplicaProxy; } -IceStorm::Instrumentation::TopicManagerObserverPtr +shared_ptr Instance::observer() const { return _observer; } -IceStorm::TopicReaperPtr +shared_ptr 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,64 @@ 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 communicator, + shared_ptr publishAdapter, + shared_ptr topicAdapter, + shared_ptr nodeAdapter, + shared_ptr nodeProxy) : + Instance( + instanceName, + name, + communicator, + std::move(publishAdapter), + std::move(topicAdapter), + std::move(nodeAdapter), + std::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 = std::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 #include #include -#include #include #include #include -namespace IceUtil -{ - -class Timer; -typedef IceUtil::Handle TimerPtr; - -} - namespace IceStormElection { class Observers; -typedef IceUtil::Handle ObserversPtr; - class NodeI; -typedef IceUtil::Handle NodeIPtr; } @@ -36,9 +24,8 @@ namespace IceStorm { class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; -class TopicReaper : public IceUtil::Shared, private IceUtil::Mutex +class TopicReaper { public: @@ -48,10 +35,11 @@ class TopicReaper : public IceUtil::Shared, private IceUtil::Mutex private: std::vector _topics; + + std::mutex _mutex; }; -typedef IceUtil::Handle TopicReaperPtr; -class Instance : public IceUtil::Shared +class Instance { public: @@ -61,32 +49,35 @@ class Instance : public IceUtil::Shared 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, + std::shared_ptr, std::shared_ptr, + std::shared_ptr = nullptr, + std::shared_ptr = nullptr); + + virtual ~Instance(); - void setNode(const IceStormElection::NodeIPtr&); + void setNode(std::shared_ptr); 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 communicator() const; + std::shared_ptr properties() const; + std::shared_ptr publishAdapter() const; + std::shared_ptr topicAdapter() const; + std::shared_ptr nodeAdapter() const; + std::shared_ptr observers() const; + std::shared_ptr node() const; + std::shared_ptr nodeProxy() const; + std::shared_ptr 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 topicReplicaProxy() const; + std::shared_ptr publisherReplicaProxy() const; + std::shared_ptr observer() const; + std::shared_ptr 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 @@ class Instance : public IceUtil::Shared 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 _communicator; + const std::shared_ptr _publishAdapter; + const std::shared_ptr _topicAdapter; + const std::shared_ptr _nodeAdapter; + const std::shared_ptr _nodeProxy; + const std::shared_ptr _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 _topicReplicaProxy; + const std::shared_ptr _publisherReplicaProxy; + const std::shared_ptr _topicReaper; + std::shared_ptr _node; + std::shared_ptr _observers; IceUtil::TimerPtr _timer; - IceStorm::Instrumentation::TopicManagerObserverPtr _observer; - + std::shared_ptr _observer; }; -typedef IceUtil::Handle InstancePtr; -typedef IceDB::ReadWriteCursor - SubscriberMapRWCursor; +using SubscriberMapRWCursor = IceDB::ReadWriteCursor; -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, + std::shared_ptr, std::shared_ptr, + std::shared_ptr = nullptr, + std::shared_ptr = 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 @@ class PersistentInstance : public Instance LLUMap _lluMap; SubscriberMap _subscriberMap; }; -typedef IceUtil::Handle PersistentInstancePtr; } // End namespace IceStorm diff --git a/cpp/src/IceStorm/InstrumentationI.cpp b/cpp/src/IceStorm/InstrumentationI.cpp index 5675c261122..4c94d8b67f6 100644 --- a/cpp/src/IceStorm/InstrumentationI.cpp +++ b/cpp/src/IceStorm/InstrumentationI.cpp @@ -77,8 +77,8 @@ class SubscriberHelper : public MetricsHelperT 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 @@ class SubscriberHelper : public MetricsHelperT }; 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& proxy, + const IceStorm::QoS& qos, shared_ptr link, SubscriberState state) : + _service(svc), _topic(topic), _proxy(proxy), _qos(qos), _link(std::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 @@ class SubscriberHelper : public MetricsHelperT return _id; } - const ::Ice::ObjectPrx& + const shared_ptr& getProxy() const { return _proxy; @@ -186,11 +186,11 @@ class SubscriberHelper : public MetricsHelperT { 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 @@ class SubscriberHelper : public MetricsHelperT const string& _service; const string& _topic; - const ::Ice::ObjectPrx& _proxy; + const shared_ptr& _proxy; const IceStorm::QoS& _qos; - const IceStorm::TopicPrx _link; + const shared_ptr _link; const SubscriberState _state; mutable string _id; }; @@ -240,7 +240,7 @@ struct QueuedUpdate { } - void operator()(const SubscriberMetricsPtr& v) + void operator()(const shared_ptr& v) { v->queued += count; } @@ -264,7 +264,7 @@ struct OutstandingUpdate { } - void operator()(const SubscriberMetricsPtr& v) + void operator()(const shared_ptr& v) { if(v->queued > 0) { @@ -293,7 +293,7 @@ struct DeliveredUpdate { } - void operator()(const SubscriberMetricsPtr& v) + void operator()(const shared_ptr& 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& 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& 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 +TopicManagerObserverI::getTopicObserver(const string& service, const string& topic, const shared_ptr& 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 TopicManagerObserverI::getSubscriberObserver(const string& svc, const string& topic, - const ::Ice::ObjectPrx& proxy, + const shared_ptr& proxy, const IceStorm::QoS& qos, - const IceStorm::TopicPrx& link, + const shared_ptr& link, SubscriberState state, - const SubscriberObserverPtr& old) + const shared_ptr& 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 +class TopicObserverI final : public IceStorm::Instrumentation::TopicObserver, + public IceMX::ObserverT { public: - virtual void published(); - virtual void forwarded(); + void published() override; + void forwarded() override; }; -class SubscriberObserverI : public IceStorm::Instrumentation::SubscriberObserver, - public IceMX::ObserverT +class SubscriberObserverI final : public IceStorm::Instrumentation::SubscriberObserver, + public IceMX::ObserverT { 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&); - virtual void setObserverUpdater(const IceStorm::Instrumentation::ObserverUpdaterPtr&); + void setObserverUpdater(const std::shared_ptr&) override; - virtual IceStorm::Instrumentation::TopicObserverPtr getTopicObserver( - const std::string&, const std::string&, const IceStorm::Instrumentation::TopicObserverPtr&); + std::shared_ptr + getTopicObserver(const std::string&, const std::string&, + const std::shared_ptr&) 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 + getSubscriberObserver(const std::string &, + const std::string &, + const std::shared_ptr &, + const IceStorm::QoS &, + const std::shared_ptr &, + IceStorm::Instrumentation::SubscriberState, + const std::shared_ptr&) override; private: - const IceInternal::MetricsAdminIPtr _metrics; + const std::shared_ptr _metrics; IceMX::ObserverFactoryT _topics; IceMX::ObserverFactoryT _subscribers; }; -typedef IceUtil::Handle TopicManagerObserverIPtr; -}; +} #endif diff --git a/cpp/src/IceStorm/Makefile.mk b/cpp/src/IceStorm/Makefile.mk index 1ced398b9e9..74527bcbf21 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 \ @@ -46,6 +46,6 @@ icestormadmin_sources := $(addprefix $(currentdir)/,Admin.cpp \ icestormdb_targetdir := $(bindir) icestormdb_dependencies := IcePatch2 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..f1ac96610cd 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 _node; public: - CheckTask(const NodeIPtr& node) : _node(node) { } + CheckTask(shared_ptr node) : _node(std::move(node)) { } virtual void runTimerTask() { _node->check(); @@ -29,12 +29,12 @@ class CheckTask : public IceUtil::TimerTask class MergeTask : public IceUtil::TimerTask { - const NodeIPtr _node; + const shared_ptr _node; const set _s; public: - MergeTask(const NodeIPtr& node, const set& s) : _node(node), _s(s) { } + MergeTask(shared_ptr node, const set& s) : _node(std::move(node)), _s(s) { } virtual void runTimerTask() { _node->merge(_s); @@ -43,11 +43,11 @@ class MergeTask : public IceUtil::TimerTask class MergeContinueTask : public IceUtil::TimerTask { - const NodeIPtr _node; + const shared_ptr _node; public: - MergeContinueTask(const NodeIPtr& node) : _node(node) { } + MergeContinueTask(shared_ptr node) : _node(std::move(node)) { } virtual void runTimerTask() { _node->mergeContinue(); @@ -56,11 +56,11 @@ class MergeContinueTask : public IceUtil::TimerTask class TimeoutTask: public IceUtil::TimerTask { - const NodeIPtr _node; + const shared_ptr _node; public: - TimeoutTask(const NodeIPtr& node) : _node(node) { } + TimeoutTask(shared_ptr node) : _node(std::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 o) : + id(i), llu(l), observer(std::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(this->id) = other.id; - const_cast(this->llu) = other.llu; - const_cast(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, 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& s) } -NodeI::NodeI(const InstancePtr& instance, - const ReplicaPtr& replica, - const Ice::ObjectPrx& replicaProxy, - int id, const map& nodes) : +NodeI::NodeI(const shared_ptr& instance, + shared_ptr replica, + shared_ptr replicaProxy, + int id, const map>& nodes) : _timer(instance->timer()), _traceLevels(instance->traceLevels()), _observers(instance->observers()), - _replica(replica), - _replicaProxy(replicaProxy), + _replica(std::move(replica)), + _replicaProxy(std::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 oneway; - for(map::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(node.second->ice_oneway()); + const_cast>& >(_nodesOneway)[node.first] = std::move(prx); } - const_cast& >(_nodesOneway) = oneway; - - Ice::PropertiesPtr properties = instance->communicator()->getProperties(); - const_cast(_masterTimeout) = getTimeout( - instance->serviceName() + ".Election.MasterTimeout", 10, properties, _traceLevels); - const_cast(_electionTimeout) = getTimeout( - instance->serviceName() + ".Election.ElectionTimeout", 10, properties, _traceLevels); - const_cast(_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 lg(_mutex); - _checkTask = new CheckTask(this); + _checkTask = make_shared(shared_from_this()); _timer->schedule(_checkTask, IceUtil::Time::seconds(static_cast(_nodes.size() - static_cast(_id)) * 2)); recovery(); @@ -216,17 +198,17 @@ void NodeI::check() { { - Lock sync(*this); + lock_guard 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::const_iterator p = dead.begin(); p != dead.end(); ++p) + for(const auto& node : dead) { - set::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 tmpset; int max = -1; - for(map::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 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(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 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::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& coordinatorSet) set invited; string gp; { - Lock sync(*this); + unique_lock 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& 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::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& coordinatorSet) Ice::Trace out(_traceLevels->logger, _traceLevels->electionCat); out << "node " << _id << ": inviting node " << *p << " to group " << gp; } - map::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& coordinatorSet) // Now we wait for responses to our invitation. { - Lock sync(*this); + lock_guard lg(_mutex); if(_destroy) { return; @@ -492,17 +475,17 @@ NodeI::merge(const set& coordinatorSet) // Schedule the mergeContinueTask. assert(_mergeContinueTask == 0); - _mergeContinueTask = new MergeContinueTask(this); + _mergeContinueTask = make_shared(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 tmpSet; { - Lock sync(*this); + lock_guard lg(_mutex); if(_destroy) { return; @@ -520,14 +503,14 @@ NodeI::mergeContinue() // Copy variables for thread safety. gp = _group; - tmpSet = _up; + tmpSet = set(_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::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::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(tmpSet.size()) + 1; { - Lock sync(*this); + lock_guard lg(_mutex); if(max > _max) { _max = max; @@ -655,11 +638,11 @@ NodeI::mergeContinue() } // Tell each node to go. - for(set::const_iterator p = tmpSet.begin(); p != tmpSet.end(); ++p) + for(const auto& n : tmpSet) { try { - map::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(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 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(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 tmpSet; { - Lock sync(*this); + unique_lock 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(_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::const_iterator p = tmpSet.begin(); p != tmpSet.end(); ++p) + for(const auto& n : tmpSet) { try { - map::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 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(shared_from_this()); + _timer->scheduleRepeated(_timeoutTask, IceUtil::Time::seconds(_masterTimeout.count())); } } try { - map::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 coordinator, int max, Ice::Long generation, const Ice::Current&) { - Lock sync(*this); - if(!_destroy && _state == NodeStateReorganization && _group == gn) + lock_guard 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(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 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 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 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 lg(_mutex); return _group == gn && _coord == _id && _up.find(GroupNodeInfo(j)) != _up.end(); } -Ice::ObjectPrx +shared_ptr NodeI::sync(const Ice::Current&) const { return _replica->getSync(); @@ -959,12 +943,9 @@ NodeInfoSeq NodeI::nodes(const Ice::Current&) const { NodeInfoSeq seq; - for(map::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 lg(_mutex); QueryInfo info; info.id = _id; info.coord = _coord; info.group = _group; info.replica = _replicaProxy; info.state = _state; - info.max = static_cast(_max); + info.max = static_cast(_max); - for(set::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 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(shared_from_this()); + _timer->schedule(_checkTask, IceUtil::Time::seconds(_electionTimeout.count())); } } void NodeI::destroy() { - Lock sync(*this); + unique_lock 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 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 NodeI::startUpdate(Ice::Long& generation, const char* file, int line) { bool majority = _observers->check(); - Lock sync(*this); + unique_lock 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 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 NodeI::startCachedRead(Ice::Long& generation, const char* file, int line) { - Lock sync(*this); - while(!_destroy && _state != NodeStateNormal) - { - wait(); - } + unique_lock 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 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 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 = std::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 #include @@ -11,20 +11,21 @@ #include #include #include + #include +#include namespace IceStormElection { class Observers; -typedef IceUtil::Handle ObserversPtr; -class NodeI : public Node, public IceUtil::Monitor +class NodeI final : public Node, public std::enable_shared_from_this { public: - NodeI(const IceStorm::InstancePtr&, const ReplicaPtr&, const Ice::ObjectPrx&, - int, const std::map&); + NodeI(const std::shared_ptr&, std::shared_ptr, std::shared_ptr, + int, const std::map>&); void start(); @@ -32,23 +33,23 @@ class NodeI : public Node, public IceUtil::Monitor void timeout(); void merge(const std::set&); 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, int, Ice::Long, const Ice::Current&) override; + void accept(int, std::string, Ice::IntSeq, std::shared_ptr, 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 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 startUpdate(Ice::Long&, const char*, int); + std::shared_ptr startCachedRead(Ice::Long&, const char*, int); void startObserverUpdate(Ice::Long, const char*, int); bool updateMaster(const char*, int); @@ -60,18 +61,18 @@ class NodeI : public Node, public IceUtil::Monitor 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 _traceLevels; + const std::shared_ptr _observers; + const std::shared_ptr _replica; // The replica. + const std::shared_ptr _replicaProxy; // A proxy to the individual replica. const int _id; // My node id. - const std::map _nodes; // The nodes indexed by their id. - const std::map _nodesOneway; // The nodes indexed by their id (as oneway proxies). + const std::map> _nodes; // The nodes indexed by their id. + const std::map> _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 @@ class NodeI : public Node, public IceUtil::Monitor 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 _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 NodeIPtr; class FinishUpdateHelper { public: - FinishUpdateHelper(const NodeIPtr& node) : - _node(node) + FinishUpdateHelper(std::shared_ptr node) : + _node(std::move(node)) { } @@ -116,15 +118,15 @@ class FinishUpdateHelper private: - const NodeIPtr _node; + const std::shared_ptr _node; }; class CachedReadHelper { public: - CachedReadHelper(const NodeIPtr& node, const char* file, int line) : - _node(node) + CachedReadHelper(std::shared_ptr node, const char* file, int line) : + _node(std::move(node)) { if(_node) { @@ -140,7 +142,7 @@ class CachedReadHelper } } - Ice::ObjectPrx + std::shared_ptr getMaster() const { return _master; @@ -160,8 +162,8 @@ class CachedReadHelper private: - const NodeIPtr _node; - Ice::ObjectPrx _master; + const std::shared_ptr _node; + std::shared_ptr _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 node, Ice::Long generation, const char* file, int line) : + _node(std::move(node)) { if(_node) { @@ -188,9 +190,9 @@ class ObserverUpdateHelper private: - const NodeIPtr _node; + const std::shared_ptr _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..dac1503c6df 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(std::move(traceLevels)), _majority(0) { } @@ -25,10 +25,11 @@ Observers::setMajority(unsigned int majority) bool Observers::check() { - Lock sync(*this); + lock_guard lg(_mutex); + if(_observers.size() >= _majority) { - vector::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 reapedLock(_reapedMutex); _reaped.push_back(id); - _reapedMutex.unlock(); continue; } ++p; @@ -61,14 +59,14 @@ Observers::check() void Observers::clear() { - Lock sync(*this); + lock_guard lg(_mutex); _observers.clear(); } void Observers::getReapedSlaves(std::vector& d) { - IceUtil::Mutex::Lock sync(_reapedMutex); + lock_guard reapedLock(_reapedMutex); d.swap(_reaped); } @@ -76,65 +74,64 @@ void Observers::init(const set& slaves, const LogUpdate& llu, const TopicContentSeq& content) { { - IceUtil::Mutex::Lock sync(_reapedMutex); + lock_guard reapedLock(_reapedMutex); _reaped.clear(); } - Lock sync(*this); + lock_guard lg(_mutex); _observers.clear(); vector observers; - for(set::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(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, std::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::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 = std::move(observers); } void Observers::createTopic(const LogUpdate& llu, const string& name) { - Lock sync(*this); - for(vector::iterator p = _observers.begin(); p != _observers.end(); ++p) + lock_guard 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::iterator p = _observers.begin(); p != _observers.end(); ++p) + lock_guard 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::iterator p = _observers.begin(); p != _observers.end(); ++p) + lock_guard 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::iterator p = _observers.begin(); p != _observers.end(); ++p) + lock_guard 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 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 #include -#ifdef __SUNPRO_CC -# pragma error_messages(off,hidef) -#endif - namespace IceStorm { -class Instance; -typedef IceUtil::Handle InstancePtr; class TraceLevels; -typedef IceUtil::Handle TraceLevelsPtr; } namespace IceStormElection { -class Observers : public IceUtil::Shared, public IceUtil::Mutex +class Observers { public: - Observers(const IceStorm::InstancePtr&); + Observers(std::shared_ptr); void setMajority(unsigned int); @@ -47,26 +40,22 @@ class Observers : public IceUtil::Shared, public IceUtil::Mutex void wait(const std::string&); - const IceStorm::TraceLevelsPtr _traceLevels; + const std::shared_ptr _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 observer; + std::future future; }; std::vector _observers; - IceUtil::Mutex _reapedMutex; + + std::mutex _reapedMutex; std::vector _reaped; + + std::mutex _mutex; }; -typedef IceUtil::Handle 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..c6ba6534dd9 100644 --- a/cpp/src/IceStorm/Parser.cpp +++ b/cpp/src/IceStorm/Parser.cpp @@ -29,7 +29,7 @@ namespace IceStorm Parser* parser; #ifdef _WIN32 -Ice::StringConverterPtr windowsConsoleConverter = 0; +shared_ptr windowsConsoleConverter = nullptr; #endif } @@ -37,51 +37,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); + return _name.c_str(); } - virtual void - ice_throw() const - { - throw *this; - } - - const string name; +private: + const string _name; }; } -ParserPtr -Parser::createParser(const CommunicatorPtr& communicator, const TopicManagerPrx& admin, - const map& managers) +Parser::Parser(shared_ptr communicator, shared_ptr admin, + map> managers) : + _communicator(std::move(communicator)), + _defaultManager(std::move(admin)), + _managers(std::move(managers)) { - return new Parser(communicator, admin, managers); +#ifdef _WIN32 + if(!windowsConsoleConverter) + { + windowsConsoleConverter = Ice::createWindowsStringConverter(GetConsoleOutputCP()); + } +#endif } void @@ -114,17 +100,17 @@ Parser::create(const list& args) return; } - for(list::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 +124,15 @@ Parser::destroy(const list& args) return; } - for(list::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 +150,15 @@ Parser::link(const list& args) { list::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 +175,14 @@ Parser::unlink(const list& args) { list::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 +197,7 @@ Parser::links(const list& args) try { - TopicManagerPrx manager; + shared_ptr manager; if(args.size() == 0) { manager = _defaultManager; @@ -221,19 +207,17 @@ Parser::links(const list& 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 +232,7 @@ Parser::topics(const list& args) try { - TopicManagerPrx manager; + shared_ptr manager; if(args.size() == 0) { manager = _defaultManager; @@ -258,15 +242,14 @@ Parser::topics(const list& 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 +264,7 @@ Parser::replica(const list& args) try { - TopicManagerPrx m; + shared_ptr m; if(args.size() == 0) { m = _defaultManager; @@ -290,63 +273,63 @@ Parser::replica(const list& args) { m = findManagerByCategory(args.front()); } - TopicManagerInternalPrx manager = TopicManagerInternalPrx::uncheckedCast(m); - IceStormElection::NodePrx node = manager->getReplicaNode(); + auto manager = Ice::uncheckedCast(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 +343,19 @@ Parser::subscribers(const list& args) } try { - for(list::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 +375,13 @@ Parser::current(const list& 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()); } } @@ -625,67 +607,51 @@ Parser::parse(const std::string& commands, bool debug) return status; } -TopicManagerPrx +shared_ptr 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::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 Parser::findManagerByCategory(const string& full) const { - Ice::Identity id; - id.category = full; - id.name = "TopicManager"; - map::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 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& 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 +671,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 +685,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 #include #include #include @@ -37,18 +36,12 @@ YY_DECL; namespace IceStorm { -// -// Forward declaration. -// -class Parser; -typedef ::IceUtil::Handle ParserPtr; - -class Parser : public ::IceUtil::SimpleShared +class Parser { public: - static ParserPtr createParser(const Ice::CommunicatorPtr&, const TopicManagerPrx&, - const std::map&); + Parser(std::shared_ptr, std::shared_ptr, + std::map>); void usage(); @@ -88,17 +81,15 @@ class Parser : public ::IceUtil::SimpleShared 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&); + std::shared_ptr findManagerById(const std::string&, std::string&) const; + std::shared_ptr findManagerByCategory(const std::string&) const; + std::shared_ptr 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 _managers; + const std::shared_ptr _communicator; + std::shared_ptr _defaultManager; + const std::map> _managers; std::string _commands; bool _continue; int _errors; diff --git a/cpp/src/IceStorm/Replica.h b/cpp/src/IceStorm/Replica.h index 41e354d7cb1..5f3d7422315 100644 --- a/cpp/src/IceStorm/Replica.h +++ b/cpp/src/IceStorm/Replica.h @@ -14,35 +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 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) -# ifdef ICE_CPP11_COMPILER - GroupNodeInfo(const GroupNodeInfo&) = default; -# endif - GroupNodeInfo& operator=(const GroupNodeInfo&); -#endif + const int id; const LogUpdate llu; - const Ice::ObjectPrx observer; + const std::shared_ptr 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&) = 0; virtual void initMaster(const std::set&, const LogUpdate&) = 0; - virtual Ice::ObjectPrx getObserver() const = 0; - virtual Ice::ObjectPrx getSync() const = 0; + virtual std::shared_ptr getObserver() const = 0; + virtual std::shared_ptr getSync() const = 0; }; -typedef IceUtil::Handle ReplicaPtr; } diff --git a/cpp/src/IceStorm/Scanner.cpp b/cpp/src/IceStorm/Scanner.cpp index 01d120edcdb..5181ebf5933 100644 --- a/cpp/src/IceStorm/Scanner.cpp +++ b/cpp/src/IceStorm/Scanner.cpp @@ -578,7 +578,6 @@ extern int yywrap ( void ); #ifndef YY_NO_UNPUT static void yyunput ( int c, char *buf_ptr ); - #endif #ifndef yytext_ptr @@ -1110,7 +1109,7 @@ case YY_STATE_EOF(INITIAL): */ static int yy_get_next_buffer (void) { - char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; + char *dest = YY_CURRENT_BUFFER_LVALUE->yy_ch_buf; char *source = (yytext_ptr); int number_to_move, i; int ret_val; @@ -1281,7 +1280,7 @@ static int yy_get_next_buffer (void) static yy_state_type yy_try_NUL_trans (yy_state_type yy_current_state ) { int yy_is_jam; - char *yy_cp = (yy_c_buf_p); + char *yy_cp = (yy_c_buf_p); YY_CHAR yy_c = 1; if ( yy_accept[yy_current_state] ) @@ -1799,7 +1798,6 @@ static void yynoreturn yy_fatal_error (const char* msg ) */ int yyget_lineno (void) { - return yylineno; } @@ -1929,7 +1927,6 @@ int yylex_destroy (void) #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, const char * s2, int n ) { - int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; @@ -1954,7 +1951,6 @@ void *yyalloc (yy_size_t 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 diff --git a/cpp/src/IceStorm/Service.cpp b/cpp/src/IceStorm/Service.cpp index 453d20a4c00..3a06090f4c5 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&, + const std::shared_ptr&, + const std::shared_ptr&, + const std::string&, + const Ice::Identity&, + const std::string&); - virtual void start(const string&, - const CommunicatorPtr&, - const StringSeq&); + std::shared_ptr 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&, 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&); + void validateProperties(const std::string&, + const std::shared_ptr&, + const std::shared_ptr&); - TopicManagerImplPtr _manager; - TransientTopicManagerImplPtr _transientManager; - TopicManagerPrx _managerProxy; - InstancePtr _instance; + std::shared_ptr _manager; + std::shared_ptr _transientManager; + std::shared_ptr _managerProxy; + std::shared_ptr _instance; }; -class FinderI : public IceStorm::Finder +class FinderI final : public IceStorm::Finder { public: - FinderI(const TopicManagerPrx& topicManager) : _topicManager(topicManager) + FinderI(shared_ptr topicManager) : _topicManager(std::move(topicManager)) { } - virtual TopicManagerPrx - getTopicManager(const Ice::Current&) + shared_ptr + getTopicManager(const Ice::Current&) override { return _topicManager; } private: - const TopicManagerPrx _topicManager; + const shared_ptr _topicManager; }; } @@ -90,42 +86,30 @@ extern "C" { ICESTORM_SERVICE_API ::IceBox::Service* -createIceStorm(CommunicatorPtr) +createIceStorm(const shared_ptr&) { 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::create(const shared_ptr& communicator, + const shared_ptr& topicAdapter, + const shared_ptr& publishAdapter, + const string& name, + const Ice::Identity& id, + const string& dbEnv) { - ServiceI* service = new ServiceI; - ServicePtr svc = service; + shared_ptr 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, 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(instanceName, name, communicator, publishAdapter, topicAdapter, nullptr); try { - TransientTopicManagerImplPtr manager = new TransientTopicManagerImpl(_instance); - _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->add(manager, topicManagerId)); + auto manager = make_shared(_instance); + _managerProxy = Ice::uncheckedCast(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(instanceName, name, communicator, publishAdapter, topicAdapter); + _manager = TopicManagerImpl::create(instance); + _instance = std::move(instance); + _managerProxy = uncheckedCast(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 nodes; + // Here we want to create a map of id -> election node proxies. + map> 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(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(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((*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(instanceName, name, communicator, publishAdapter, + topicAdapter, nodeAdapter, nodes[id]); _instance = instance; _instance->observers()->setMajority(static_cast(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::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(topicAdapter->createProxy(topicManagerId)); } else { // If we're using IceGrid deployment we need to create // indirect proxies. - _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->createIndirectProxy(topicManagerId)); + _managerProxy = uncheckedCast(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(_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(uncheckedCast(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, + const shared_ptr& topicAdapter, + const shared_ptr& 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(instanceName, name, communicator, publishAdapter, topicAdapter, nullptr); try { - TransientTopicManagerImplPtr manager = new TransientTopicManagerImpl(_instance); - _managerProxy = TopicManagerPrx::uncheckedCast(topicAdapter->add(manager, id)); + auto manager = make_shared(_instance); + _managerProxy = uncheckedCast(topicAdapter->add(manager, id)); } catch(const Ice::Exception& ex) { @@ -432,7 +417,7 @@ ServiceI::start(const CommunicatorPtr& communicator, } } -TopicManagerPrx +shared_ptr 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, const shared_ptr& logger) { static const string suffixes[] = { diff --git a/cpp/src/IceStorm/Service.h b/cpp/src/IceStorm/Service.h index 11c7a80a2ad..4bbc0fd9246 100644 --- a/cpp/src/IceStorm/Service.h +++ b/cpp/src/IceStorm/Service.h @@ -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 create(const std::shared_ptr&, + const std::shared_ptr&, + const std::shared_ptr&, + const std::string&, + const Ice::Identity&, + const std::string&); - virtual void stop() = 0; + ICESTORM_SERVICE_API virtual std::shared_ptr getTopicManager() const = 0; }; }; diff --git a/cpp/src/IceStorm/Subscriber.cpp b/cpp/src/IceStorm/Subscriber.cpp index c85baa345a2..00797353a0c 100644 --- a/cpp/src/IceStorm/Subscriber.cpp +++ b/cpp/src/IceStorm/Subscriber.cpp @@ -23,54 +23,53 @@ using namespace IceStormElection; namespace { -class PerSubscriberPublisherI : public Ice::BlobjectArray +struct SendQueueSizeMaxReached : std::exception +{ + const char* what() const noexcept override + { + return "maximum size of send queue reached"; + } +}; + +class PerSubscriberPublisherI final : public Ice::BlobjectArray { public: - PerSubscriberPublisherI(const InstancePtr& instance) : - _instance(instance) + PerSubscriberPublisherI(shared_ptr instance) : + _instance(std::move(instance)) { } void - setSubscriber(const SubscriberPtr& subscriber) + setSubscriber(shared_ptr subscriber) { - _subscriber = subscriber; + _subscriber = std::move(subscriber); } - virtual bool - ice_invoke(const pair& inParams, + bool + ice_invoke(pair inParams, vector&, - 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(std::move(event)); + _subscriber->queue(false, std::move(e)); return true; } private: - const InstancePtr _instance; - /*const*/ SubscriberPtr _subscriber; + const shared_ptr _instance; + shared_ptr _subscriber; }; -typedef IceUtil::Handle PerSubscriberPublisherIPtr; IceStorm::Instrumentation::SubscriberState toSubscriberState(Subscriber::SubscriberState s) @@ -78,15 +77,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; } } @@ -96,231 +95,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 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 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&, const SubscriberRecord&, + const shared_ptr&, int, shared_ptr); - virtual void flush(); + void flush() override; + void sentAsynchronously(); private: - const Ice::ObjectPrx _obj; + const shared_ptr _obj; }; -class SubscriberLink : public Subscriber +class SubscriberTwoway final : public Subscriber { public: - SubscriberLink(const InstancePtr&, const SubscriberRecord&); + SubscriberTwoway(const shared_ptr&, const SubscriberRecord&, const shared_ptr&, int, int, + shared_ptr); - virtual void flush(); + void flush() override; private: - const TopicLinkPrx _obj; + const shared_ptr _obj; }; -class FlushTimerTask : public IceUtil::TimerTask +class SubscriberLink final : public Subscriber { public: - FlushTimerTask(const SubscriberBatchPtr& subscriber) : - _subscriber(subscriber) - { - } + SubscriberLink(const shared_ptr&, const SubscriberRecord&); - virtual void - runTimerTask() - { - _subscriber->doFlush(); - } + void flush() override; private: - const SubscriberBatchPtr _subscriber; + const shared_ptr _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::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(v.size()); - _observer->outstanding(_outstandingCount); - } - - try - { - vector 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::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, + const SubscriberRecord& rec, + const shared_ptr& proxy, + int retryCount, + shared_ptr obj) : Subscriber(instance, rec, proxy, retryCount, 5), - _obj(obj) + _obj(std::move(obj)) { } void SubscriberOneway::flush() { - IceUtil::Monitor::Lock sync(_lock); + lock_guard lg(_mutex); // // If the subscriber isn't online we're done. @@ -337,8 +169,8 @@ SubscriberOneway::flush() // Dequeue the head event, count one more outstanding AMI // request. // - EventDataPtr e = _events.front(); - _events.erase(_events.begin()); + EventData e = std::move(_events.front()); + _events.pop_front(); if(_observer) { _observer->outstanding(1); @@ -346,11 +178,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(shared_from_this()); + auto isSent = make_shared>(); + 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; } @@ -359,28 +215,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::Lock sync(_lock); + lock_guard lg(_mutex); // Decrement the _outstanding count. --_outstanding; @@ -392,7 +243,7 @@ SubscriberOneway::sent(bool sentSynchronously) if(_events.empty() && _outstanding == 0 && _shutdown) { - _lock.notify(); + _condVar.notify_one(); } else if(_outstanding <= 0 && !_events.empty()) { @@ -400,22 +251,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, + const SubscriberRecord& rec, + const shared_ptr& proxy, + int retryCount, + int maxOutstanding, + shared_ptr obj) : Subscriber(instance, rec, proxy, retryCount, maxOutstanding), - _obj(obj) + _obj(std::move(obj)) { } void SubscriberTwoway::flush() { - IceUtil::Monitor::Lock sync(_lock); + lock_guard lg(_mutex); // // If the subscriber isn't online we're done. @@ -432,9 +282,11 @@ SubscriberTwoway::flush() // Dequeue the head event, count one more outstanding AMI // request. // - EventDataPtr e = _events.front(); - _events.erase(_events.begin()); + EventData e = std::move(_events.front()); + _events.pop_front(); + ++_outstanding; + if(_observer) { _observer->outstanding(1); @@ -442,12 +294,21 @@ SubscriberTwoway::flush() try { - _obj->begin_ice_invoke(e->op, e->mode, e->data, e->context, - Ice::newCallback(static_cast(this), &Subscriber::completed)); + auto self = static_pointer_cast(shared_from_this()); + _obj->ice_invokeAsync(e.op, e.mode, e.data, + [self](bool, vector) + { + 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; } } @@ -456,18 +317,18 @@ SubscriberTwoway::flush() namespace { -SubscriberLink::SubscriberLink( - const InstancePtr& instance, - const SubscriberRecord& rec) : +SubscriberLink::SubscriberLink(const shared_ptr& 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( + rec.obj->ice_collocationOptimized(false)->ice_timeout(static_cast(instance->sendTimeout().count())))) { } void SubscriberLink::flush() { - IceUtil::Monitor::Lock sync(_lock); + lock_guard lg(_mutex); if(_state != SubscriberStateOnline || _outstanding > 0) { @@ -477,16 +338,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) { @@ -504,39 +372,48 @@ SubscriberLink::flush() ++_outstanding; if(_observer) { - _outstandingCount = static_cast(v.size()); + _outstandingCount = static_cast(v.size()); _observer->outstanding(_outstandingCount); } - _obj->begin_forward(v, Ice::newCallback(static_cast(this), &Subscriber::completed)); + + auto self = static_pointer_cast(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::create(const shared_ptr& instance, + const SubscriberRecord& rec) { if(rec.link) { - return new SubscriberLink(instance, rec); + return make_shared(instance, rec); } else { - PerSubscriberPublisherIPtr per = new PerSubscriberPublisherI(instance); + auto per = make_shared(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; try { @@ -561,10 +438,10 @@ Subscriber::create( // // Override the timeout. // - Ice::ObjectPrx newObj; + shared_ptr newObj; try { - newObj = rec.obj->ice_timeout(instance->sendTimeout()); + newObj = rec.obj->ice_timeout(static_cast(instance->sendTimeout().count())); } catch(const Ice::FixedProxyException&) { @@ -600,26 +477,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(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(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(instance, rec, proxy, retryCount, 5, newObj); } per->setSubscriber(subscriber); } @@ -633,7 +517,7 @@ Subscriber::create( } } -Ice::ObjectPrx +shared_ptr Subscriber::proxy() const { return _proxyReplica; @@ -654,7 +538,7 @@ Subscriber::record() const bool Subscriber::queue(bool forwarded, const EventDataSeq& events) { - IceUtil::Monitor::Lock sync(_lock); + lock_guard lg(_mutex); // If this is a link subscriber if the set of events were // forwarded from another IceStorm instance then do not queue the @@ -668,7 +552,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; } @@ -688,7 +572,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 @@ -719,7 +603,7 @@ Subscriber::queue(bool forwarded, const EventDataSeq& events) bool Subscriber::reap() { - IceUtil::Monitor::Lock sync(_lock); + lock_guard lg(_mutex); assert(_state >= SubscriberStateError); if(_state == SubscriberStateError) { @@ -732,7 +616,8 @@ Subscriber::reap() void Subscriber::resetIfReaped() { - IceUtil::Monitor::Lock sync(_lock); + lock_guard lg(_mutex); + if(_state == SubscriberStateReaped) { setState(SubscriberStateError); @@ -742,7 +627,8 @@ Subscriber::resetIfReaped() bool Subscriber::errored() const { - IceUtil::Monitor::Lock sync(_lock); + lock_guard lg(_mutex); + return _state >= SubscriberStateError; } @@ -768,14 +654,43 @@ Subscriber::destroy() } } - IceUtil::Monitor::Lock sync(_lock); + lock_guard lg(_mutex); _observer.detach(); } void -Subscriber::error(bool dec, const Ice::Exception& e) +Subscriber::completed() { - IceUtil::Monitor::Lock sync(_lock); + lock_guard 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) +{ + lock_guard lg(_mutex); if(dec) { @@ -792,16 +707,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(&e) || - dynamic_cast(&e) || - dynamic_cast(&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 @@ -809,7 +746,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; @@ -824,7 +761,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); @@ -833,8 +770,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 { @@ -846,8 +783,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; } } @@ -865,7 +802,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); @@ -874,64 +811,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::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::Lock sync(_lock); + lock_guard lg(_mutex); _shutdown = true; while(_outstanding > 0 && !_events.empty()) { - _lock.wait(); + _condVar.notify_one(); } _observer.detach(); @@ -940,7 +839,8 @@ Subscriber::shutdown() void Subscriber::updateObserver() { - IceUtil::Monitor::Lock sync(_lock); + lock_guard lg(_mutex); + if(_instance->observer()) { _observer.attach(_instance->observer()->getSubscriberObserver(_instance->serviceName(), @@ -953,18 +853,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, + SubscriberRecord rec, + shared_ptr proxy, + int retryCount, + int maxOutstanding) : + _instance(std::move(instance)), + _rec(std::move(rec)), _retryCount(retryCount), _maxOutstanding(maxOutstanding), - _proxy(proxy), - _proxyReplica(proxy), + _proxy(std::move(proxy)), + _proxyReplica(_proxy), _shutdown(false), _state(SubscriberStateOnline), _outstanding(0), @@ -973,7 +872,7 @@ Subscriber::Subscriber( { if(_proxy && _instance->publisherReplicaProxy()) { - const_cast(_proxyReplica) = + const_cast&>(_proxyReplica) = _instance->publisherReplicaProxy()->ice_identity(_proxy->ice_getIdentity()); } @@ -1017,7 +916,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); @@ -1040,7 +939,7 @@ Subscriber::setState(Subscriber::SubscriberState state) } bool -IceStorm::operator==(const SubscriberPtr& subscriber, const Ice::Identity& id) +IceStorm::operator==(const shared_ptr& 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 #include #include -#include + +#include namespace IceStorm { class Instance; -typedef IceUtil::Handle InstancePtr; - -class Subscriber; -typedef IceUtil::Handle SubscriberPtr; -class Subscriber : public IceUtil::Shared +class Subscriber : public std::enable_shared_from_this { public: - static SubscriberPtr create(const InstancePtr&, const IceStorm::SubscriberRecord&); + static std::shared_ptr create(const std::shared_ptr&, const IceStorm::SubscriberRecord&); - Ice::ObjectPrx proxy() const; // Get the per subscriber object. + std::shared_ptr 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 @@ class Subscriber : public IceUtil::Shared 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 @@ class Subscriber : public IceUtil::Shared void setState(SubscriberState); - Subscriber(const InstancePtr&, const IceStorm::SubscriberRecord&, const Ice::ObjectPrx&, int, int); + Subscriber(std::shared_ptr, IceStorm::SubscriberRecord, std::shared_ptr, int, int); // Immutable - const InstancePtr _instance; + const std::shared_ptr _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 _proxy; // The per subscriber object proxy, if any. + const std::shared_ptr _proxyReplica; // The replicated per subscriber object proxy, if any. - IceUtil::Monitor _lock; + mutable std::recursive_mutex _mutex; + std::condition_variable_any _condVar; bool _shutdown; @@ -81,13 +79,13 @@ class Subscriber : public IceUtil::Shared 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 _observer; }; -bool operator==(const IceStorm::SubscriberPtr&, const Ice::Identity&); +bool operator==(const std::shared_ptr&, 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 122fa29b919..70f4c7b0b78 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& 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 topic, shared_ptr instance) : + _topic(std::move(topic)), _instance(std::move(instance)) { } - virtual bool - ice_invoke(const pair& inParams, + bool + ice_invoke(pair 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 = std::move(data); EventDataSeq v; - v.push_back(event); + v.push_back(std::move(event)); _topic->publish(false, v); return true; @@ -64,8 +60,8 @@ class PublisherI : public Ice::BlobjectArray private: - const TopicImplPtr _topic; - const PersistentInstancePtr _instance; + const shared_ptr _topic; + const shared_ptr _instance; }; // @@ -76,66 +72,66 @@ class TopicLinkI : public TopicLink { public: - TopicLinkI(const TopicImplPtr& impl, const PersistentInstancePtr& instance) : - _impl(impl), _instance(instance) + TopicLinkI(shared_ptr impl, shared_ptr instance) : + _impl(std::move(impl)), _instance(std::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, std::move(v)); } private: - const TopicImplPtr _impl; - const PersistentInstancePtr _instance; + const shared_ptr _impl; + const shared_ptr _instance; }; class TopicI : public TopicInternal { public: - TopicI(const TopicImplPtr& impl, const PersistentInstancePtr& instance) : - _impl(impl), _instance(instance) + TopicI(shared_ptr impl, shared_ptr instance) : + _impl(std::move(impl)), _instance(std::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 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 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 subscribeAndGetPublisher(QoS qos, shared_ptr 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(std::move(qos), std::move(obj)); } catch(const Ice::ConnectFailedException&) { @@ -151,22 +147,22 @@ class TopicI : public TopicInternal else { FinishUpdateHelper unlock(_instance->node()); - return _impl->subscribeAndGetPublisher(qos, obj); + return _impl->subscribeAndGetPublisher(std::move(qos), std::move(obj)); } } } - virtual void unsubscribe(const Ice::ObjectPrx& subscriber, const Ice::Current& current) + void unsubscribe(shared_ptr 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(std::move(subscriber)); } catch(const Ice::ConnectFailedException&) { @@ -182,22 +178,22 @@ class TopicI : public TopicInternal else { FinishUpdateHelper unlock(_instance->node()); - _impl->unsubscribe(subscriber); + _impl->unsubscribe(std::move(subscriber)); } break; } } - virtual TopicLinkPrx getLinkProxy(const Ice::Current&) + shared_ptr 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 @@ class TopicI : public TopicInternal _impl->reap(ids); } - virtual void link(const TopicPrx& topic, Ice::Int cost, const Ice::Current& current) + void link(shared_ptr 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(std::move(topic), cost); } catch(const Ice::ConnectFailedException&) { @@ -232,23 +228,23 @@ class TopicI : public TopicInternal else { FinishUpdateHelper unlock(_instance->node()); - _impl->link(topic, cost); + _impl->link(std::move(topic), cost); } break; } } - virtual void unlink(const TopicPrx& topic, const Ice::Current& current) + void unlink(shared_ptr 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(std::move(topic)); } catch(const Ice::ConnectFailedException&) { @@ -264,30 +260,30 @@ class TopicI : public TopicInternal else { FinishUpdateHelper unlock(_instance->node()); - _impl->unlink(topic); + _impl->unlink(std::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 @@ class TopicI : public TopicInternal private: - TopicPrx getMasterFor(const Ice::Current& cur, Ice::Long& generation, const char* file, int line) const + shared_ptr 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 master; if(node) { master = _instance->node()->startUpdate(generation, file, line); } - return (master) ? TopicPrx::uncheckedCast(master->ice_identity(cur.id)) : TopicPrx(); + return master ? Ice::uncheckedCast(master->ice_identity(cur.id)) : nullptr; } - const TopicImplPtr _impl; - const PersistentInstancePtr _instance; + const shared_ptr _impl; + const shared_ptr _instance; }; } -TopicImpl::TopicImpl( - const PersistentInstancePtr& instance, - const string& name, - const Ice::Identity& id, - const SubscriberRecordSeq& subscribers) : - _instance(instance), +shared_ptr +TopicImpl::create(shared_ptr instance, + const string& name, + const Ice::Identity& id, + const SubscriberRecordSeq& subscribers) +{ + shared_ptr topicImpl(new TopicImpl(instance, name, id, subscribers)); + + topicImpl->_servant = make_shared(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=, name=publish, otherwise the name is + // /.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(topicImpl, instance); + topicImpl->_publisherPrx = instance->publishAdapter()->add(publisher, pubid); + auto topicLink = make_shared(topicImpl, instance); + topicImpl->_linkPrx = Ice::uncheckedCast(instance->publishAdapter()->add(topicLink, linkid)); + + return topicImpl; +} + +TopicImpl::TopicImpl(shared_ptr instance, + const string& name, + const Ice::Identity& id, + const SubscriberRecordSeq& subscribers) : + _instance(std::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=, name=publish, otherwise the name is - // /.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 TopicImpl::getPublisher() const { // Immutable @@ -454,7 +453,7 @@ TopicImpl::getPublisher() const return _publisherPrx; } -Ice::ObjectPrx +shared_ptr 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& s) +trace(Ice::Trace& out, const shared_ptr& instance, const vector>& s) { out << '['; - for(vector::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 +TopicImpl::subscribeAndGetPublisher(QoS qos, shared_ptr obj) { if(!obj) { - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -500,11 +499,10 @@ 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(); - - IceUtil::Mutex::Lock sync(_subscribersMutex); + auto traceLevels = _instance->traceLevels(); + lock_guard lg(_subscribersMutex); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -535,15 +533,14 @@ TopicImpl::subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPrx& obj) record.link = false; record.cost = 0; - vector::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 +569,9 @@ TopicImpl::subscribeAndGetPublisher(const QoS& qos, const Ice::ObjectPrx& obj) } void -TopicImpl::unsubscribe(const Ice::ObjectPrx& subscriber) +TopicImpl::unsubscribe(const shared_ptr& subscriber) { - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(!subscriber) { if(traceLevels->topic > 0) @@ -587,7 +584,7 @@ TopicImpl::unsubscribe(const Ice::ObjectPrx& subscriber) Ice::Identity id = subscriber->ice_getIdentity(); - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lg(_subscribersMutex); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -599,30 +596,31 @@ TopicImpl::unsubscribe(const Ice::ObjectPrx& subscriber) trace(out, _instance, _subscribers); } } + Ice::IdentitySeq ids; ids.push_back(id); removeSubscribers(ids); } -TopicLinkPrx +shared_ptr TopicImpl::getLinkProxy() { // immutable if(_instance->publisherReplicaProxy()) { - return TopicLinkPrx::uncheckedCast(_instance->publisherReplicaProxy()->ice_identity( + return Ice::uncheckedCast(_instance->publisherReplicaProxy()->ice_identity( _linkPrx->ice_getIdentity())); } return _linkPrx; } void -TopicImpl::link(const TopicPrx& topic, Ice::Int cost) +TopicImpl::link(const shared_ptr& topic, int cost) { - TopicInternalPrx internal = TopicInternalPrx::uncheckedCast(topic); - TopicLinkPrx link = internal->getLinkProxy(); + auto internal = Ice::uncheckedCast(topic); + auto link = internal->getLinkProxy(); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -630,7 +628,7 @@ TopicImpl::link(const TopicPrx& topic, Ice::Int cost) << " cost " << cost; } - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lg(_subscribersMutex); Ice::Identity id = topic->ice_getIdentity(); @@ -642,8 +640,7 @@ TopicImpl::link(const TopicPrx& topic, Ice::Int cost) record.link = true; record.cost = cost; - vector::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); @@ -651,7 +648,7 @@ TopicImpl::link(const TopicPrx& topic, Ice::Int cost) LogUpdate llu; - SubscriberPtr subscriber = Subscriber::create(_instance, record); + auto subscriber = Subscriber::create(_instance, record); try { @@ -679,9 +676,10 @@ TopicImpl::link(const TopicPrx& topic, Ice::Int cost) } void -TopicImpl::unlink(const TopicPrx& topic) +TopicImpl::unlink(const shared_ptr& topic) { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lg(_subscribersMutex); + if(_destroyed) { throw Ice::ObjectNotExistException(__FILE__, __LINE__); @@ -689,11 +687,12 @@ TopicImpl::unlink(const TopicPrx& topic) Ice::Identity id = topic->ice_getIdentity(); - vector::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); @@ -703,7 +702,6 @@ TopicImpl::unlink(const TopicPrx& topic) throw NoSuchLink(name); } - TraceLevelsPtr traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -718,9 +716,9 @@ TopicImpl::unlink(const TopicPrx& topic) void TopicImpl::reap(const Ice::IdentitySeq& ids) { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lg(_subscribersMutex); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -741,13 +739,14 @@ TopicImpl::reap(const Ice::IdentitySeq& ids) void TopicImpl::shutdown() { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lg(_subscribersMutex); + _servant = 0; // Shutdown each subscriber. This waits for the event queues to drain. - for(vector::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + for(const auto& subscriber : _subscribers) { - (*p)->shutdown(); + subscriber->shutdown(); } _observer.detach(); @@ -756,13 +755,13 @@ TopicImpl::shutdown() LinkInfoSeq TopicImpl::getLinkInfoSeq() const { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lg(_subscribersMutex); LinkInfoSeq seq; - for(vector::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()); @@ -777,12 +776,12 @@ TopicImpl::getLinkInfoSeq() const Ice::IdentitySeq TopicImpl::getSubscribers() const { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lg(_subscribersMutex); Ice::IdentitySeq subscribers; - for(vector::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; } @@ -790,7 +789,7 @@ TopicImpl::getSubscribers() const void TopicImpl::destroy() { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lg(_subscribersMutex); if(_destroyed) { @@ -798,7 +797,7 @@ TopicImpl::destroy() } _destroyed = true; - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -806,7 +805,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(); @@ -815,18 +814,18 @@ TopicImpl::destroy() TopicContent TopicImpl::getContent() const { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lg(_subscribersMutex); TopicContent content; content.id = _id; - for(vector::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; @@ -835,7 +834,7 @@ TopicImpl::getContent() const void TopicImpl::update(const SubscriberRecordSeq& records) { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard 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 @@ -843,7 +842,7 @@ TopicImpl::update(const SubscriberRecordSeq& records) // exist. { - vector::iterator p = _subscribers.begin(); + auto p = _subscribers.begin(); while(p != _subscribers.end()) { SubscriberRecordSeq::const_iterator q; @@ -870,19 +869,19 @@ TopicImpl::update(const SubscriberRecordSeq& records) } } - for(SubscriberRecordSeq::const_iterator p = records.begin(); p != records.end(); ++p) + for(const auto& record : records) { - vector::iterator q; + vector>::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); } } @@ -891,7 +890,8 @@ TopicImpl::update(const SubscriberRecordSeq& records) bool TopicImpl::destroyed() const { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lg(_subscribersMutex); + return _destroyed; } @@ -902,11 +902,11 @@ TopicImpl::id() const return _id; } -TopicPrx +shared_ptr TopicImpl::proxy() const { // immutable - Ice::ObjectPrx prx; + shared_ptr prx; if(_instance->topicReplicaProxy()) { prx = _instance->topicReplicaProxy()->ice_identity(_id); @@ -915,44 +915,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(prx); } void TopicImpl::publish(bool forwarded, const EventDataSeq& events) { - TopicInternalPrx masterInternal; + shared_ptr masterInternal; Ice::Long generation = -1; Ice::IdentitySeq reap; { @@ -963,9 +932,10 @@ TopicImpl::publish(bool forwarded, const EventDataSeq& events) // Copy of the subscriber list so that event publishing can occur // in parallel. // - vector copy; + vector> copy; { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lock(_subscribersMutex); + if(_observer) { if(forwarded) @@ -984,11 +954,11 @@ TopicImpl::publish(bool forwarded, const EventDataSeq& events) // Queue each event, gathering a list of those subscribers that // must be reaped. // - for(vector::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()); } } @@ -999,11 +969,11 @@ TopicImpl::publish(bool forwarded, const EventDataSeq& events) } if(!unlock.getMaster()) { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lock(_subscribersMutex); removeSubscribers(reap); return; } - masterInternal = TopicInternalPrx::uncheckedCast(unlock.getMaster()->ice_identity(_id)); + masterInternal = Ice::uncheckedCast(unlock.getMaster()->ice_identity(_id)); generation = unlock.generation(); } @@ -1016,16 +986,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 lock(_subscribersMutex); - TraceLevelsPtr traceLevels = _instance->traceLevels(); + auto traceLevels = _instance->traceLevels(); if(traceLevels->topic > 0) { Ice::Trace out(traceLevels->logger, traceLevels->topicCat); @@ -1047,8 +1033,7 @@ TopicImpl::observerAddSubscriber(const LogUpdate& llu, const SubscriberRecord& r out << " llu: " << llu.generation << "/" << llu.iteration; } - vector::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. @@ -1060,7 +1045,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()); @@ -1088,7 +1073,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); @@ -1104,19 +1089,16 @@ TopicImpl::observerRemoveSubscriber(const LogUpdate& llu, const Ice::IdentitySeq out << " llu: " << llu.generation << "/" << llu.iteration; } - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard 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); } @@ -1133,9 +1115,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::iterator p = find(_subscribers.begin(), _subscribers.end(), *id); + auto p = find(_subscribers.begin(), _subscribers.end(), id); if(p != _subscribers.end()) { (*p)->destroy(); @@ -1147,7 +1129,7 @@ TopicImpl::observerRemoveSubscriber(const LogUpdate& llu, const Ice::IdentitySeq void TopicImpl::observerDestroyTopic(const LogUpdate& llu) { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lock(_subscribersMutex); if(_destroyed) { @@ -1155,7 +1137,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); @@ -1165,7 +1147,7 @@ TopicImpl::observerDestroyTopic(const LogUpdate& llu) destroyInternal(llu, false); } -Ice::ObjectPtr +shared_ptr TopicImpl::getServant() const { return _servant; @@ -1174,7 +1156,8 @@ TopicImpl::getServant() const void TopicImpl::updateObserver() { - IceUtil::Mutex::Lock sync(_subscribersMutex); + lock_guard lock(_subscribersMutex); + if(_instance->observer()) { _observer.attach(_instance->observer()->getTopicObserver(_instance->serviceName(), _name, _observer.get())); @@ -1184,10 +1167,11 @@ TopicImpl::updateObserver() void TopicImpl::updateSubscriberObservers() { - IceUtil::Mutex::Lock sync(_subscribersMutex); - for(vector::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + lock_guard lock(_subscribersMutex); + + for(const auto& subscriber : _subscribers) { - (*p)->updateObserver(); + subscriber->updateObserver(); } } @@ -1242,9 +1226,9 @@ TopicImpl::destroyInternal(const LogUpdate& origLLU, bool master) _instance->topicReaper()->add(_name); // Destroy each of the subscribers. - for(vector::const_iterator p = _subscribers.begin(); p != _subscribers.end(); ++p) + for(const auto& subscriber : _subscribers) { - (*p)->destroy(); + subscriber->destroy(); } _subscribers.clear(); @@ -1266,11 +1250,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)) { @@ -1304,7 +1286,7 @@ TopicImpl::removeSubscribers(const Ice::IdentitySeq& ids) // removed. for(Ice::IdentitySeq::const_iterator id = ids.begin(); id != ids.end(); ++id) { - vector::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 PersistentInstancePtr; - class Subscriber; -typedef IceUtil::Handle SubscriberPtr; -class TopicImpl : public IceUtil::Shared +class TopicImpl { public: - TopicImpl(const PersistentInstancePtr&, const std::string&, const Ice::Identity&, const SubscriberRecordSeq&); + static std::shared_ptr create(std::shared_ptr, + 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 getPublisher() const; + std::shared_ptr getNonReplicatedPublisher() const; + std::shared_ptr subscribeAndGetPublisher(QoS, std::shared_ptr); + void unsubscribe(const std::shared_ptr&); + std::shared_ptr getLinkProxy(); + void link(const std::shared_ptr&, int); + void unlink(const std::shared_ptr&); LinkInfoSeq getLinkInfoSeq() const; Ice::IdentitySeq getSubscribers() const; void reap(const Ice::IdentitySeq&); @@ -48,7 +48,7 @@ class TopicImpl : public IceUtil::Shared // Internal methods bool destroyed() const; Ice::Identity id() const; - TopicPrx proxy() const; + std::shared_ptr proxy() const; void shutdown(); void publish(bool, const EventDataSeq&); @@ -57,33 +57,35 @@ class TopicImpl : public IceUtil::Shared void observerRemoveSubscriber(const IceStormElection::LogUpdate&, const Ice::IdentitySeq&); void observerDestroyTopic(const IceStormElection::LogUpdate&); - Ice::ObjectPtr getServant() const; + std::shared_ptr getServant() const; void updateObserver(); void updateSubscriberObservers(); private: + TopicImpl(std::shared_ptr, 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 _publisherReplicaProxy; + const std::shared_ptr _instance; const std::string _name; // The topic name const Ice::Identity _id; // The topic identity IceInternal::ObserverHelperT _observer; - /*const*/ Ice::ObjectPrx _publisherPrx; // The actual publisher proxy. - /*const*/ TopicLinkPrx _linkPrx; // The link proxy. + std::shared_ptr _publisherPrx; // The actual publisher proxy. + std::shared_ptr _linkPrx; // The link proxy. - Ice::ObjectPtr _servant; // The topic implementation servant. + std::shared_ptr _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 @@ class TopicImpl : public IceUtil::Shared // vector/list/map and although there was little difference vector // was the fastest of the three. // - std::vector _subscribers; + std::vector> _subscribers; bool _destroyed; // Has this Topic been destroyed? @@ -100,8 +102,6 @@ class TopicImpl : public IceUtil::Shared SubscriberMap _subscriberMap; }; -typedef IceUtil::Handle TopicImplPtr; - } // End namespace IceStorm #endif diff --git a/cpp/src/IceStorm/TopicManagerI.cpp b/cpp/src/IceStorm/TopicManagerI.cpp index 194a896a934..d643b67bc3f 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& 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 instance, shared_ptr impl) : + _instance(std::move(instance)), _impl(std::move(impl)) { } - virtual TopicPrx create(const string& id, const Ice::Current&) + shared_ptr 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(std::move(id)); } catch(const Ice::ConnectFailedException&) { @@ -63,26 +63,26 @@ class TopicManagerI : public TopicManagerInternal else { FinishUpdateHelper unlock(_instance->node()); - return _impl->create(id); + return _impl->create(std::move(id)); } } } - virtual TopicPrx retrieve(const string& id, const Ice::Current&) const + shared_ptr retrieve(string id, const Ice::Current&) override { // Use cached reads. CachedReadHelper unlock(_instance->node(), __FILE__, __LINE__); - return _impl->retrieve(id); + return _impl->retrieve(std::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 getReplicaNode(const Ice::Current&) const override { // This doesn't require the replication to be running. return _instance->nodeProxy(); @@ -90,49 +90,49 @@ class TopicManagerI : public TopicManagerInternal private: - TopicManagerPrx getMaster(Ice::Long& generation, const char* file, int line) const + shared_ptr 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(node->startUpdate(generation, file, line)); } else { - return TopicManagerPrx(); + return nullptr; } } - const PersistentInstancePtr _instance; - const TopicManagerImplPtr _impl; + const shared_ptr _instance; + const shared_ptr _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 instance, shared_ptr impl) : + _instance(std::move(instance)), + _impl(std::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(std::move(llu), std::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, std::move(name)); } catch(const ObserverInconsistencyException& e) { @@ -143,12 +143,12 @@ class ReplicaObserverI : public ReplicaObserver } } - 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, std::move(name)); } catch(const ObserverInconsistencyException& e) { @@ -159,13 +159,12 @@ class ReplicaObserverI : public ReplicaObserver } } - 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, std::move(name), std::move(rec)); } catch(const ObserverInconsistencyException& e) { @@ -176,13 +175,12 @@ class ReplicaObserverI : public ReplicaObserver } } - 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, std::move(name), std::move(id)); } catch(const ObserverInconsistencyException& e) { @@ -195,110 +193,109 @@ class ReplicaObserverI : public ReplicaObserver private: - const PersistentInstancePtr _instance; - const TopicManagerImplPtr _impl; + const shared_ptr _instance; + const shared_ptr _impl; }; -class TopicManagerSyncI : public TopicManagerSync +class TopicManagerSyncI final : public TopicManagerSync { public: - TopicManagerSyncI(const TopicManagerImplPtr& impl) : - _impl(impl) + TopicManagerSyncI(shared_ptr impl) : + _impl(std::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 _impl; }; } -TopicManagerImpl::TopicManagerImpl(const PersistentInstancePtr& instance) : - _instance(instance), - _lluMap(instance->lluMap()), - _subscriberMap(instance->subscriberMap()) +shared_ptr +TopicManagerImpl::create(const std::shared_ptr& instance) { - try + shared_ptr manager(new TopicManagerImpl(instance)); + + if(instance->observer()) { - __setNoDelete(true); + instance->observer()->setObserverUpdater(manager); + } - if(_instance->observer()) - { - _instance->observer()->setObserverUpdater(this); - } + manager->_managerImpl = make_shared(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(instance, manager); + manager->_observer = instance->nodeAdapter()->addWithUUID(observerImpl); + auto syncImpl = make_shared(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 instance) : + _instance(std::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 TopicManagerImpl::create(const string& name) { - Lock sync(*this); + lock_guard 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 +TopicManagerImpl::retrieve(const string& name) { - Lock sync(*this); + lock_guard lg(_mutex); - TopicManagerImpl* This = const_cast(this); - This->reap(); + reap(); - map::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 lg(_mutex); - TopicManagerImpl* This = const_cast(this); - This->reap(); + reap(); TopicDict all; - for(map::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 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::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::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 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 lg(_mutex); - map::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 topic; { - Lock sync(*this); + lock_guard lg(_mutex); - map::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 topic; { - Lock sync(*this); + lock_guard lg(_mutex); - map::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 lg(_mutex); reap(); } try { content.clear(); - for(map::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& master) { - TopicManagerSyncPrx sync = TopicManagerSyncPrx::uncheckedCast(master); + auto sync = Ice::uncheckedCast(master); LogUpdate llu; TopicContentSeq content; @@ -634,7 +630,7 @@ TopicManagerImpl::sync(const Ice::ObjectPrx& master) void TopicManagerImpl::initMaster(const set& slaves, const LogUpdate& llu) { - Lock sync(*this); + lock_guard lg(_mutex); reap(); @@ -657,9 +653,9 @@ TopicManagerImpl::initMaster(const set& slaves, const LogUpdate& IceDB::ReadWriteTxn txn(_instance->dbEnv()); - for(map::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& slaves, const LogUpdate& _instance->observers()->init(slaves, llu, content); } -Ice::ObjectPrx +shared_ptr TopicManagerImpl::getObserver() const { return _observer; } -Ice::ObjectPrx +shared_ptr TopicManagerImpl::getSync() const { return _sync; @@ -695,12 +691,10 @@ TopicManagerImpl::reap() // // Always called with mutex locked. // - // Lock sync(*this); - // vector reaped = _instance->topicReaper()->consumeReapedTopics(); - for(vector::const_iterator p = reaped.begin(); p != reaped.end(); ++p) + for(const auto& topic : reaped) { - map::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 lg(_mutex); - for(map::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 TopicManagerImpl::getServant() const { return _managerImpl; @@ -733,31 +725,33 @@ TopicManagerImpl::getServant() const void TopicManagerImpl::updateTopicObservers() { - Lock sync(*this); - for(map::const_iterator p = _topics.begin(); p != _topics.end(); ++p) + lock_guard lg(_mutex); + + for(const auto& topic : _topics) { - p->second->updateObserver(); + topic.second->updateObserver(); } } void TopicManagerImpl::updateSubscriberObservers() { - Lock sync(*this); - for(map::const_iterator p = _topics.begin(); p != _topics.end(); ++p) + lock_guard lg(_mutex); + + for(const auto& topic : _topics) { - p->second->updateSubscriberObservers(); + topic.second->updateSubscriberObservers(); } } -TopicPrx +shared_ptr 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::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 #include -#include - namespace IceStorm { -// -// Forward declarations. -// class PersistentInstance; -typedef IceUtil::Handle PersistentInstancePtr; - class TopicImpl; -typedef IceUtil::Handle 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 { public: - TopicManagerImpl(const PersistentInstancePtr&); + static std::shared_ptr create(const std::shared_ptr&); // TopicManager methods. - TopicPrx create(const std::string&); - TopicPrx retrieve(const std::string&) const; - TopicDict retrieveAll() const; + std::shared_ptr create(const std::string&); + std::shared_ptr retrieve(const std::string&); + TopicDict retrieveAll(); // Observer methods. void observerInit(const IceStormElection::LogUpdate&, const IceStormElection::TopicContentSeq&); @@ -54,40 +46,41 @@ class TopicManagerImpl : public IceStormElection::Replica, 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&, const IceStormElection::LogUpdate&); - virtual Ice::ObjectPrx getObserver() const; - virtual Ice::ObjectPrx getSync() const; + IceStormElection::LogUpdate getLastLogUpdate() const override; + void sync(const std::shared_ptr&) override; + void initMaster(const std::set&, const IceStormElection::LogUpdate&) override; + std::shared_ptr getObserver() const override; + std::shared_ptr getSync() const override; void reap(); void shutdown(); - Ice::ObjectPtr getServant() const; + std::shared_ptr getServant() const; private: - void updateTopicObservers(); - void updateSubscriberObservers(); + TopicManagerImpl(std::shared_ptr); + + void updateTopicObservers() override; + void updateSubscriberObservers() override; - TopicPrx installTopic(const std::string&, const Ice::Identity&, bool, - const IceStorm::SubscriberRecordSeq& = IceStorm::SubscriberRecordSeq()); + std::shared_ptr installTopic(const std::string&, const Ice::Identity&, bool, + const IceStorm::SubscriberRecordSeq& = IceStorm::SubscriberRecordSeq()); - const PersistentInstancePtr _instance; + const std::shared_ptr _instance; - std::map _topics; + std::map> _topics; - Ice::ObjectPtr _managerImpl; - Ice::ObjectPtr _observerImpl; - Ice::ObjectPrx _observer; - Ice::ObjectPtr _syncImpl; - Ice::ObjectPrx _sync; + std::shared_ptr _managerImpl; + std::shared_ptr _observer; + std::shared_ptr _sync; LLUMap _lluMap; SubscriberMap _subscriberMap; + + std::recursive_mutex _mutex; }; -typedef IceUtil::Handle TopicManagerImplPtr; } // End namespace IceStorm diff --git a/cpp/src/IceStorm/TraceLevels.cpp b/cpp/src/IceStorm/TraceLevels.cpp index afa45876c72..60acd875dbb 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& properties, + shared_ptr 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(std::move(theLogger)) { const string keyBase = name + ".Trace."; const_cast(topicMgr) = properties->getPropertyAsInt(keyBase + topicMgrCat); @@ -28,7 +30,3 @@ TraceLevels::TraceLevels(const string name, const Ice::PropertiesPtr& properties const_cast(subscriber) = properties->getPropertyAsInt(keyBase + subscriberCat); const_cast(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 -#include -#include #include +#include 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&, std::shared_ptr); const int topicMgr; const char* topicMgrCat; @@ -35,11 +32,9 @@ class TraceLevels : public IceUtil::Shared const int replication; const char* replicationCat; - const Ice::LoggerPtr logger; + const std::shared_ptr logger; }; -typedef IceUtil::Handle TraceLevelsPtr; - } // End namespace IceStorm #endif diff --git a/cpp/src/IceStorm/TransientTopicI.cpp b/cpp/src/IceStorm/TransientTopicI.cpp index 055d32caf60..65436155043 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 impl) : + _impl(std::move(impl)) { } - virtual bool - ice_invoke(const pair& inParams, - Ice::ByteSeq&, - const Ice::Current& current) + bool + ice_invoke(pair 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(std::move(event)); _impl->publish(false, v); return true; @@ -60,7 +50,7 @@ class TransientPublisherI : public Ice::BlobjectArray private: - const TransientTopicImplPtr _impl; + const shared_ptr _impl; }; // @@ -71,33 +61,29 @@ class TransientTopicLinkI : public TopicLink { public: - TransientTopicLinkI(const TransientTopicImplPtr& impl) : - _impl(impl) + TransientTopicLinkI(shared_ptr impl) : + _impl(std::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, std::move(v)); } private: - const TransientTopicImplPtr _impl; + const shared_ptr _impl; }; } -TransientTopicImpl::TransientTopicImpl( - const InstancePtr& instance, - const string& name, - const Ice::Identity& id) : - _instance(instance), - _name(name), - _id(id), - _destroyed(false) +shared_ptr +TransientTopicImpl::create(const shared_ptr& instance, const std::string& name, const Ice::Identity& id) { + shared_ptr 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(topicImpl); + topicImpl->_publisherPrx = instance->publishAdapter()->add(publisher, pubid); + auto topicLink = make_shared(topicImpl); + topicImpl->_linkPrx = Ice::uncheckedCast(instance->publishAdapter()->add(topicLink, linkid)); + + return topicImpl; } -TransientTopicImpl::~TransientTopicImpl() +TransientTopicImpl::TransientTopicImpl(shared_ptr instance, + const std::string& name, + const Ice::Identity& id) : + _instance(std::move(instance)), + _name(name), + _id(id), + _destroyed(false) { } @@ -140,128 +136,26 @@ TransientTopicImpl::getName(const Ice::Current&) const return _name; } -Ice::ObjectPrx +shared_ptr TransientTopicImpl::getPublisher(const Ice::Current&) const { // Immutable return _publisherPrx; } -Ice::ObjectPrx +shared_ptr 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::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 +TransientTopicImpl::subscribeAndGetPublisher(QoS qos, shared_ptr 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 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::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 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 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::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 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 topic, int cost, const Ice::Current&) { - TopicInternalPrx internal = TopicInternalPrx::uncheckedCast(topic); - TopicLinkPrx link = internal->getLinkProxy(); + auto internal = Ice::uncheckedCast(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 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::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 topic, const Ice::Current&) { - Lock sync(*this); + lock_guard 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::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 lg(_mutex); + LinkInfoSeq seq; - for(vector::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 lg(_mutex); Ice::IdentitySeq subscribers; - for(vector::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 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::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 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 copy; + vector> copy; { - Lock sync(*this); + lock_guard 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 e; - for(vector::const_iterator p = copy.begin(); p != copy.end(); ++p) + vector 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::const_iterator ep = e.begin(); ep != e.end(); ++ep) + lock_guard 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::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 lg(_mutex); // Shutdown each subscriber. This waits for the event queues to drain. - for(vector::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 InstancePtr; - class Subscriber; -typedef IceUtil::Handle 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 create(const std::shared_ptr&, const std::string&, + const Ice::Identity&); + + std::string getName(const Ice::Current&) const override; + std::shared_ptr getNonReplicatedPublisher(const Ice::Current&) const override; + std::shared_ptr getPublisher(const Ice::Current&) const override; + std::shared_ptr subscribeAndGetPublisher(QoS, std::shared_ptr, const Ice::Current&) override; + void unsubscribe(std::shared_ptr, const Ice::Current&) override; + std::shared_ptr getLinkProxy(const Ice::Current&) override; + void link(std::shared_ptr, int, const Ice::Current&) override; + void unlink(std::shared_ptr, 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 @@ class TransientTopicImpl : public TopicInternal, public IceUtil::Mutex private: + TransientTopicImpl(std::shared_ptr, const std::string&, const Ice::Identity&); + // // Immutable members. // - const InstancePtr _instance; + const std::shared_ptr _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 _publisherPrx; + std::shared_ptr _linkPrx; // // We keep a vector of subscribers since the optimized behaviour @@ -64,12 +62,12 @@ class TransientTopicImpl : public TopicInternal, public IceUtil::Mutex // vector/list/map and although there was little difference vector // was the fastest of the three. // - std::vector _subscribers; + std::vector> _subscribers; bool _destroyed; // Has this Topic been destroyed? -}; -typedef IceUtil::Handle TransientTopicImplPtr; + mutable std::mutex _mutex; +}; } // End namespace IceStorm diff --git a/cpp/src/IceStorm/TransientTopicManagerI.cpp b/cpp/src/IceStorm/TransientTopicManagerI.cpp index 016808d9335..18ade8b9c12 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(std::move(instance)) { } -TransientTopicManagerImpl::~TransientTopicManagerImpl() +shared_ptr +TransientTopicManagerImpl::create(string name, const Ice::Current&) { -} - -TopicPrx -TransientTopicManagerImpl::create(const string& name, const Ice::Current&) -{ - Lock sync(*this); + lock_guard 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::value_type(name, topicImpl)); + auto prx = Ice::uncheckedCast(_instance->topicAdapter()->add(topicImpl, id)); + _topics.insert({ name, topicImpl }); return prx; } -TopicPrx -TransientTopicManagerImpl::retrieve(const string& name, const Ice::Current&) const +shared_ptr +TransientTopicManagerImpl::retrieve(string name, const Ice::Current&) { - Lock sync(*this); + lock_guard lg(_mutex); - TransientTopicManagerImpl* This = const_cast(this); - This->reap(); + reap(); - map::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(_instance->topicAdapter()->createProxy(p->second->id())); } TopicDict -TransientTopicManagerImpl::retrieveAll(const Ice::Current&) const +TransientTopicManagerImpl::retrieveAll(const Ice::Current&) { - Lock sync(*this); + lock_guard lg(_mutex); - TransientTopicManagerImpl* This = const_cast(this); - This->reap(); + reap(); TopicDict all; - for(map::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 "/topic." // name, or if created with pre-3.2 IceStorm "/". // - all.insert(TopicDict::value_type( - p->first, TopicPrx::uncheckedCast(_instance->topicAdapter()->createProxy(p->second->id())))); + all.insert({ topic.first, + Ice::uncheckedCast(_instance->topicAdapter()->createProxy(topic.second->id())) }); } return all; } -IceStormElection::NodePrx +shared_ptr 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 reaped = _instance->topicReaper()->consumeReapedTopics(); for(vector::const_iterator p = reaped.begin(); p != reaped.end(); ++p) { - map::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 lg(_mutex); - for(map::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 InstancePtr; - class TransientTopicImpl; -typedef IceUtil::Handle TransientTopicImplPtr; -// -// TopicManager implementation. -// -class TransientTopicManagerImpl : public TopicManagerInternal, public IceUtil::Mutex +class TransientTopicManagerImpl final : public TopicManagerInternal { public: - TransientTopicManagerImpl(const InstancePtr&); - ~TransientTopicManagerImpl(); + TransientTopicManagerImpl(std::shared_ptr); // 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 create(std::string, const Ice::Current&) override; + std::shared_ptr retrieve(std::string, const Ice::Current&) override; + TopicDict retrieveAll(const Ice::Current&) override; + std::shared_ptr getReplicaNode(const Ice::Current&) const override; void reap(); - void shutdown(); - Ice::ObjectPtr getServant() const; - private: - const InstancePtr _instance; - std::map _topics; + const std::shared_ptr _instance; + std::map> _topics; + + std::mutex _mutex; }; -typedef IceUtil::Handle 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, const string& name) { - // Identity is instanceName>/topic. - Ice::Identity id; - id.category = instance->instanceName(); - id.name = "topic." + name; - - return id; + // Identity is /topic. + return { "topic." + name, instance->instanceName() }; } string -IceStormInternal::describeEndpoints(const Ice::ObjectPrx& proxy) +IceStormInternal::describeEndpoints(const shared_ptr& 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 InstancePtr; -typedef IceDB::Dbi - SubscriberMap; -typedef IceDB::Dbi LLUMap; +using SubscriberMap = IceDB::Dbi; +using LLUMap = IceDB::Dbi; 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&, const std::string&); std::string -describeEndpoints(const Ice::ObjectPrx&); +describeEndpoints(const std::shared_ptr&); int compareSubscriberRecordKey(const MDB_val* v1, const MDB_val* v2); diff --git a/cpp/src/IceStorm/msbuild/icestormadmin/icestormadmin.vcxproj b/cpp/src/IceStorm/msbuild/icestormadmin/icestormadmin.vcxproj index fc591babce9..c7f56156733 100644 --- a/cpp/src/IceStorm/msbuild/icestormadmin/icestormadmin.vcxproj +++ b/cpp/src/IceStorm/msbuild/icestormadmin/icestormadmin.vcxproj @@ -21,6 +21,7 @@ {8F1A1F99-DBE0-408D-99F7-D59142BD008C} + icestormadmin++11 @@ -44,7 +45,7 @@ $(DefaultPlatformToolset) - + diff --git a/cpp/src/IceStorm/msbuild/icestormdb/icestormdb.vcxproj b/cpp/src/IceStorm/msbuild/icestormdb/icestormdb.vcxproj index 15e4245bf24..da01758edbb 100644 --- a/cpp/src/IceStorm/msbuild/icestormdb/icestormdb.vcxproj +++ b/cpp/src/IceStorm/msbuild/icestormdb/icestormdb.vcxproj @@ -21,6 +21,7 @@ {F0B74B00-F252-4D38-A352-ED379CB196E9} + icestormdb++11 @@ -44,7 +45,7 @@ $(DefaultPlatformToolset) - + diff --git a/cpp/src/IceStorm/msbuild/icestormservice/icestormservice.vcxproj b/cpp/src/IceStorm/msbuild/icestormservice/icestormservice.vcxproj index 3f1a4e90a28..bfdd4a83452 100644 --- a/cpp/src/IceStorm/msbuild/icestormservice/icestormservice.vcxproj +++ b/cpp/src/IceStorm/msbuild/icestormservice/icestormservice.vcxproj @@ -22,6 +22,7 @@ {9E13C4B5-5DA9-43C1-9304-AEAC035E854D} IceStorm + icestormservice++11 @@ -45,7 +46,7 @@ $(DefaultPlatformToolset) - + diff --git a/cpp/src/IceXML/Parser.cpp b/cpp/src/IceXML/Parser.cpp index 21f2c737acc..5c29ed371b5 100644 --- a/cpp/src/IceXML/Parser.cpp +++ b/cpp/src/IceXML/Parser.cpp @@ -4,7 +4,9 @@ #include #include + #include + #include #include @@ -24,12 +26,6 @@ IceXML::ParserException::ParserException(const char* file, int line, const strin { } -#ifndef ICE_CPP11_COMPILER -IceXML::ParserException::~ParserException() throw() -{ -} -#endif - string IceXML::ParserException::ice_id() const { @@ -50,14 +46,6 @@ IceXML::ParserException::ice_print(std::ostream& out) const } } -#ifndef ICE_CPP11_MAPPING -IceXML::ParserException* -IceXML::ParserException::ice_clone() const -{ - return new ParserException(*this); -} -#endif - string IceXML::ParserException::reason() const { @@ -67,16 +55,12 @@ IceXML::ParserException::reason() const // // Node // -IceXML::Node::Node(const NodePtr& parent, const string& name, const string& value, int line, int column) : +IceXML::Node::Node(const shared_ptr& parent, const string& name, const string& value, int line, int column) : _parent(parent), _name(name), _value(value), _line(line), _column(column) { } -IceXML::Node::~Node() -{ -} - -IceXML::NodePtr +shared_ptr IceXML::Node::getParent() const { return _parent; @@ -113,7 +97,7 @@ IceXML::Node::getAttribute(const string&) const } bool -IceXML::Node::addChild(const NodePtr&) +IceXML::Node::addChild(const shared_ptr&) { return false; } @@ -139,16 +123,12 @@ IceXML::Node::getColumn() const // // Element // -IceXML::Element::Element(const NodePtr& parent, const string& name, const Attributes& attributes, int line, +IceXML::Element::Element(const shared_ptr& parent, const string& name, const Attributes& attributes, int line, int column) : Node(parent, name, "", line, column), _attributes(attributes) { } -IceXML::Element::~Element() -{ -} - IceXML::NodeList IceXML::Element::getChildren() const { @@ -173,7 +153,7 @@ IceXML::Element::getAttribute(const string& name) const } bool -IceXML::Element::addChild(const NodePtr& child) +IceXML::Element::addChild(const shared_ptr& child) { _children.push_back(child); return true; @@ -192,15 +172,11 @@ IceXML::Element::destroy() // // Text // -IceXML::Text::Text(const NodePtr& parent, const string& value, int line, int column) : +IceXML::Text::Text(const shared_ptr& parent, const string& value, int line, int column) : Node(parent, "", value, line, column) { } -IceXML::Text::~Text() -{ -} - // // Document // @@ -209,10 +185,6 @@ IceXML::Document::Document() : { } -IceXML::Document::~Document() -{ -} - IceXML::NodeList IceXML::Document::getChildren() const { @@ -220,7 +192,7 @@ IceXML::Document::getChildren() const } bool -IceXML::Document::addChild(const NodePtr& child) +IceXML::Document::addChild(const shared_ptr& child) { _children.push_back(child); return true; @@ -267,28 +239,28 @@ class DocumentBuilder : public Handler virtual void endElement(const string&, int, int); virtual void characters(const string&, int, int); - DocumentPtr getDocument() const; + shared_ptr getDocument() const; private: - list _nodeStack; - DocumentPtr _document; + list> _nodeStack; + shared_ptr _document; }; } IceXML::DocumentBuilder::DocumentBuilder() { - _document = new Document; + _document = make_shared(); _nodeStack.push_front(_document); } void IceXML::DocumentBuilder::startElement(const string& name, const Attributes& attributes, int line, int column) { - NodePtr parent = _nodeStack.front(); + auto parent = _nodeStack.front(); + auto element = make_shared(parent, name, attributes, line, column); - Element* element = new Element(parent, name, attributes, line, column); #ifdef NDEBUG parent->addChild(element); #else @@ -308,12 +280,12 @@ IceXML::DocumentBuilder::endElement(const string&, int, int) void IceXML::DocumentBuilder::characters(const string& data, int line, int column) { - NodePtr parent = _nodeStack.front(); - TextPtr text = new Text(parent, data, line, column); + auto parent = _nodeStack.front(); + auto text = make_shared(parent, data, line, column); parent->addChild(text); } -DocumentPtr +shared_ptr IceXML::DocumentBuilder::getDocument() const { return _document; @@ -372,7 +344,7 @@ characterDataHandler(void* data, const XML_Char* s, int len) // // Parser // -IceXML::DocumentPtr +shared_ptr IceXML::Parser::parse(const string& file) { DocumentBuilder builder; @@ -380,7 +352,7 @@ IceXML::Parser::parse(const string& file) return builder.getDocument(); } -IceXML::DocumentPtr +shared_ptr IceXML::Parser::parse(istream& in) { DocumentBuilder builder; diff --git a/cpp/src/IceXML/Parser.h b/cpp/src/IceXML/Parser.h index 71101b7a55a..ddade14a93a 100644 --- a/cpp/src/IceXML/Parser.h +++ b/cpp/src/IceXML/Parser.h @@ -5,8 +5,6 @@ #ifndef ICE_XML_PARSER_H #define ICE_XML_PARSER_H -#include -#include #include #include @@ -37,21 +35,15 @@ namespace IceXML { -class ICE_XML_API ParserException : public IceUtil::ExceptionHelper +class ICE_XML_API ParserException final : public IceUtil::ExceptionHelper { public: ParserException(const std::string&); ParserException(const char*, int, const std::string&); -#ifndef ICE_CPP11_COMPILER - virtual ~ParserException() throw(); -#endif - virtual std::string ice_id() const; - virtual void ice_print(std::ostream&) const; -#ifndef ICE_CPP11_MAPPING - virtual ParserException* ice_clone() const; -#endif + std::string ice_id() const override; + void ice_print(std::ostream&) const override; std::string reason() const; @@ -61,36 +53,28 @@ class ICE_XML_API ParserException : public IceUtil::ExceptionHelper NodePtr; - -typedef std::vector NodeList; - +class Document; class Element; -typedef IceUtil::Handle< Element > ElementPtr; - +class Node; class Text; -typedef IceUtil::Handle< Text > TextPtr; -class Document; -typedef IceUtil::Handle< Document > DocumentPtr; - -typedef std::map Attributes; +using NodeList = std::vector>; +using Attributes = std::map; -class ICE_XML_API Node : public IceUtil::Shared +class ICE_XML_API Node { public: - virtual ~Node(); + virtual ~Node() = default; - virtual NodePtr getParent() const; + virtual std::shared_ptr getParent() const; virtual std::string getName() const; virtual std::string getValue() const; virtual NodeList getChildren() const; virtual Attributes getAttributes() const; virtual std::string getAttribute(const std::string&) const; - virtual bool addChild(const NodePtr&); + virtual bool addChild(const std::shared_ptr&); virtual void destroy(); @@ -99,29 +83,28 @@ class ICE_XML_API Node : public IceUtil::Shared protected: - Node(const NodePtr&, const std::string&, const std::string&, int, int); + Node(const std::shared_ptr&, const std::string&, const std::string&, int, int); - NodePtr _parent; + std::shared_ptr _parent; std::string _name; std::string _value; int _line; int _column; }; -class ICE_XML_API Element : public Node +class ICE_XML_API Element final : public Node { public: - Element(const NodePtr&, const std::string&, const Attributes&, int, int); - virtual ~Element(); + Element(const std::shared_ptr&, const std::string&, const Attributes&, int, int); - virtual NodeList getChildren() const; - virtual Attributes getAttributes() const; - virtual std::string getAttribute(const std::string&) const; + NodeList getChildren() const override; + Attributes getAttributes() const override; + std::string getAttribute(const std::string&) const override; - virtual bool addChild(const NodePtr&); + bool addChild(const std::shared_ptr&) override; - virtual void destroy(); + void destroy() override; private: @@ -129,12 +112,11 @@ class ICE_XML_API Element : public Node Attributes _attributes; }; -class ICE_XML_API Text : public Node +class ICE_XML_API Text final : public Node { public: - Text(const NodePtr&, const std::string&, int, int); - virtual ~Text(); + Text(const std::shared_ptr&, const std::string&, int, int); }; class ICE_XML_API Document : public Node @@ -142,13 +124,12 @@ class ICE_XML_API Document : public Node public: Document(); - virtual ~Document(); - virtual NodeList getChildren() const; + NodeList getChildren() const override; - virtual bool addChild(const NodePtr&); + bool addChild(const std::shared_ptr&) override; - virtual void destroy(); + void destroy() override; private: @@ -171,8 +152,8 @@ class ICE_XML_API Parser { public: - static DocumentPtr parse(const std::string&); // The given filename must be UTF-8 encoded - static DocumentPtr parse(std::istream&); + static std::shared_ptr parse(const std::string&); // The given filename must be UTF-8 encoded + static std::shared_ptr parse(std::istream&); static void parse(const std::string&, Handler&); static void parse(std::istream&, Handler&); diff --git a/cpp/src/IceXML/msbuild/icexml.vcxproj b/cpp/src/IceXML/msbuild/icexml.vcxproj index 37a316f004f..0342322e2db 100644 --- a/cpp/src/IceXML/msbuild/icexml.vcxproj +++ b/cpp/src/IceXML/msbuild/icexml.vcxproj @@ -21,6 +21,7 @@ {90EC26E8-AFFA-4E44-B068-AB5849A96FDD} IceXML + icexml++11 @@ -44,7 +45,7 @@ $(DefaultPlatformToolset) - + diff --git a/cpp/src/icegriddb/IceGridDB.cpp b/cpp/src/icegriddb/IceGridDB.cpp index f403d3e94bf..39d83f42a8b 100644 --- a/cpp/src/icegriddb/IceGridDB.cpp +++ b/cpp/src/icegriddb/IceGridDB.cpp @@ -12,6 +12,7 @@ #include #include +#include #include using namespace std; @@ -64,33 +65,6 @@ class IceBoxDescriptorI : public IceGrid::IceBoxDescriptor string _serverVersion; }; -class ValueFactoryI : public Ice::ValueFactory -{ -public: - - ValueFactoryI(const string& serverVersion) : - _serverVersion(serverVersion) - { - } - - virtual Ice::ObjectPtr create(const string& type) - { - if(type == "::IceGrid::ServerDescriptor") - { - return new ServerDescriptorI(_serverVersion); - } - else if(type == "::IceGrid::IceBoxDescriptor") - { - return new IceBoxDescriptorI(_serverVersion); - } - return 0; - } - -private: - - string _serverVersion; -}; - } // @@ -120,7 +94,7 @@ struct StreamReader int run(const Ice::StringSeq&); -Ice::CommunicatorPtr communicator; +shared_ptr communicator; void destroyCommunicator(int) @@ -301,9 +275,15 @@ run(const Ice::StringSeq& args) if(!serverVersion.empty()) { - Ice::ValueFactoryPtr factory = new ValueFactoryI(serverVersion); - communicator->getValueFactoryManager()->add(factory, "::IceGrid::ServerDescriptor"); - communicator->getValueFactoryManager()->add(factory, "::IceGrid::IceBoxDescriptor"); + communicator->getValueFactoryManager()->add([serverVersion](const string&) + { + return make_shared(serverVersion); + }, IceGrid::ServerDescriptor::ice_staticId()); + + communicator->getValueFactoryManager()->add([serverVersion](const string&) + { + return make_shared(serverVersion); + }, IceGrid::IceBoxDescriptor::ice_staticId()); } Ice::InputStream stream(communicator, dbContext.encoding, buf); diff --git a/cpp/src/icegriddb/msbuild/icegriddb.vcxproj b/cpp/src/icegriddb/msbuild/icegriddb.vcxproj index f540de5f030..e88502855f8 100644 --- a/cpp/src/icegriddb/msbuild/icegriddb.vcxproj +++ b/cpp/src/icegriddb/msbuild/icegriddb.vcxproj @@ -21,6 +21,7 @@ {369524F4-D374-44F4-BCFD-408934595701} + icegriddb++11 @@ -44,7 +45,7 @@ $(DefaultPlatformToolset) - + diff --git a/cpp/test/Glacier2/attack/BackendI.h b/cpp/test/Glacier2/attack/BackendI.h index a22383abb94..9ac0cb658db 100644 --- a/cpp/test/Glacier2/attack/BackendI.h +++ b/cpp/test/Glacier2/attack/BackendI.h @@ -7,11 +7,11 @@ #include -class BackendI : public Test::Backend +class BackendI final : public Test::Backend { public: - virtual void shutdown(const Ice::Current&); + void shutdown(const Ice::Current&) override; }; #endif diff --git a/cpp/test/Glacier2/attack/Client.cpp b/cpp/test/Glacier2/attack/Client.cpp index f0fe833161e..8efc85925a5 100644 --- a/cpp/test/Glacier2/attack/Client.cpp +++ b/cpp/test/Glacier2/attack/Client.cpp @@ -2,28 +2,28 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include #include #include #include #include #include +#include using namespace std; using namespace Ice; using namespace Test; -class AttackClient : public Test::TestHelper +class AttackClient final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void AttackClient::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); // // We want to check whether the client retries for evicted // proxies, even with regular retries disabled. @@ -32,22 +32,22 @@ AttackClient::run(int argc, char** argv) Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); cout << "getting router... " << flush; - ObjectPrx routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50)); - Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(routerBase); + auto routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50)); + auto router = checkedCast(routerBase); test(router); communicator->setDefaultRouter(router); cout << "ok" << endl; cout << "creating session... " << flush; - Glacier2::SessionPrx session = router->createSession("userid", "abc123"); + auto session = router->createSession("userid", "abc123"); cout << "ok" << endl; cout << "making thousands of invocations on proxies... " << flush; - ObjectPrx backendBase = communicator->stringToProxy("dummy:" + getTestEndpoint()); - BackendPrx backend = BackendPrx::uncheckedCast(backendBase); + auto backendBase = communicator->stringToProxy("dummy:" + getTestEndpoint()); + auto backend = checkedCast(backendBase); backend->ice_ping(); - set backends; + set, TargetCompare, std::less>> backends; string msg; for(int i = 1; i <= 10000; ++i) @@ -66,22 +66,23 @@ AttackClient::run(int argc, char** argv) Identity ident; string::iterator p; + random_device rd; - ident.name.resize(1); // 1 + IceUtilInternal::random() % 2); + ident.name.resize(1); for(p = ident.name.begin(); p != ident.name.end(); ++p) { - *p = static_cast('A' + IceUtilInternal::random() % 26); + *p = static_cast('A' + rd() % 26); } - ident.category.resize(IceUtilInternal::random() % 2); + ident.category.resize(rd() % 2); for(p = ident.category.begin(); p != ident.category.end(); ++p) { - *p = static_cast('a' + IceUtilInternal::random() % 26); + *p = static_cast('a' + rd() % 26); } - BackendPrx newBackend = BackendPrx::uncheckedCast(backendBase->ice_identity(ident)); + auto newBackend = uncheckedCast(backendBase->ice_identity(ident)); - set::const_iterator q = backends.find(newBackend); + auto q = backends.find(newBackend); if(q == backends.end()) { @@ -101,8 +102,8 @@ AttackClient::run(int argc, char** argv) cout << "testing server and router shutdown... " << flush; backend->shutdown(); communicator->setDefaultRouter(0); - ObjectPrx adminBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51)); - Ice::ProcessPrx process = Ice::ProcessPrx::checkedCast(adminBase); + auto adminBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51)); + auto process = checkedCast(adminBase); test(process); process->shutdown(); try diff --git a/cpp/test/Glacier2/attack/Server.cpp b/cpp/test/Glacier2/attack/Server.cpp index 7fa07896709..c70ed62ef4c 100644 --- a/cpp/test/Glacier2/attack/Server.cpp +++ b/cpp/test/Glacier2/attack/Server.cpp @@ -10,38 +10,11 @@ using namespace std; using namespace Ice; using namespace Test; -class ServantLocatorI : public virtual ServantLocator +class BackendServer final : public Test::TestHelper { public: - ServantLocatorI() : - _backend(new BackendI) - { - } - - virtual ObjectPtr locate(const Current&, LocalObjectPtr&) - { - return _backend; - } - - virtual void finished(const Current&, const ObjectPtr&, const LocalObjectPtr&) - { - } - - virtual void deactivate(const string&) - { - } - -private: - - BackendPtr _backend; -}; - -class BackendServer : public Test::TestHelper -{ -public: - - void run(int, char**); + void run(int, char**) override; }; void @@ -49,8 +22,8 @@ BackendServer::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); communicator->getProperties()->setProperty("BackendAdapter.Endpoints", getTestEndpoint()); - ObjectAdapterPtr adapter = communicator->createObjectAdapter("BackendAdapter"); - adapter->addServantLocator(new ServantLocatorI, ""); + auto adapter = communicator->createObjectAdapter("BackendAdapter"); + adapter->addDefaultServant(make_shared(), ""); adapter->activate(); communicator->waitForShutdown(); } diff --git a/cpp/test/Glacier2/dynamicFiltering/BackendI.h b/cpp/test/Glacier2/dynamicFiltering/BackendI.h index bf17a14fa6a..7dbcadd2930 100644 --- a/cpp/test/Glacier2/dynamicFiltering/BackendI.h +++ b/cpp/test/Glacier2/dynamicFiltering/BackendI.h @@ -7,11 +7,11 @@ #include -class BackendI : public Test::Backend +class BackendI final : public Test::Backend { public: - virtual void check(const Ice::Current&); - virtual void shutdown(const Ice::Current&); + void check(const Ice::Current&) override; + void shutdown(const Ice::Current&) override; }; #endif diff --git a/cpp/test/Glacier2/dynamicFiltering/Client.cpp b/cpp/test/Glacier2/dynamicFiltering/Client.cpp index 87acfd20165..0a236c00196 100644 --- a/cpp/test/Glacier2/dynamicFiltering/Client.cpp +++ b/cpp/test/Glacier2/dynamicFiltering/Client.cpp @@ -11,17 +11,17 @@ using namespace std; using namespace Ice; using namespace Test; -class SessionControlClient : public Test::TestHelper +class SessionControlClient final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void SessionControlClient::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); // // We want to check whether the client retries for evicted // proxies, even with regular retries disabled. @@ -38,8 +38,8 @@ SessionControlClient::run(int argc, char** argv) cout << "accessing test controller... " << flush; Ice::InitializationData initData; initData.properties = communicator->getProperties(); - Ice::CommunicatorPtr controlComm = Ice::initialize(argc, argv, initData); - TestControllerPrx controller = TestControllerPrx::checkedCast( + auto controlComm = Ice::initialize(argc, argv, initData); + auto controller = checkedCast( controlComm->stringToProxy("testController:" + getTestEndpoint(2, "tcp"))); test(controller); TestToken currentState; @@ -47,28 +47,28 @@ SessionControlClient::run(int argc, char** argv) currentState.expectedResult = false; currentState.config = 0; currentState.caseIndex = 0; - currentState.code = Initial; + currentState.code = StateCode::Initial; controller->step(0, currentState, newState); currentState = newState; cout << "ok" << endl; cout << "getting router... " << flush; - ObjectPrx routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50)); - Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(routerBase); + auto routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50)); + auto router = checkedCast(routerBase); test(router); communicator->setDefaultRouter(router); cout << "ok" << endl; - Glacier2::SessionPrx sessionBase = router->createSession("userid", "abc123"); - Test::TestSessionPrx currentSession = Test::TestSessionPrx::checkedCast(sessionBase); + auto sessionBase = router->createSession("userid", "abc123"); + auto currentSession = checkedCast(sessionBase); bool printOk = false; - while(currentState.code == Running) + while(currentState.code == StateCode::Running) { controller->step(currentSession, currentState, newState); currentState = newState; - if(currentState.code != Running) + if(currentState.code != StateCode::Running) { cout << "ok" << endl; break; @@ -92,7 +92,7 @@ SessionControlClient::run(int argc, char** argv) if(currentState.expectedResult) { - BackendPrx prx = BackendPrx::uncheckedCast(communicator->stringToProxy(currentState.testReference)); + auto prx = uncheckedCast(communicator->stringToProxy(currentState.testReference)); try { prx->check(); @@ -105,7 +105,7 @@ SessionControlClient::run(int argc, char** argv) } else { - BackendPrx prx = BackendPrx::uncheckedCast(communicator->stringToProxy(currentState.testReference)); + auto prx = uncheckedCast(communicator->stringToProxy(currentState.testReference)); try { prx->check(); @@ -134,7 +134,7 @@ SessionControlClient::run(int argc, char** argv) // // Shut down the test server. // - currentSession = Test::TestSessionPrx::uncheckedCast(router->createSession("userid", "abc123")); + currentSession = uncheckedCast(router->createSession("userid", "abc123")); currentSession->shutdown(); } catch(const Glacier2::CannotCreateSessionException& ex) @@ -147,8 +147,8 @@ SessionControlClient::run(int argc, char** argv) // Shut down the router. // communicator->setDefaultRouter(0); - ObjectPrx processBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51)); - Ice::ProcessPrx process = Ice::ProcessPrx::checkedCast(processBase); + auto processBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51)); + auto process = checkedCast(processBase); test(process); process->shutdown(); try diff --git a/cpp/test/Glacier2/dynamicFiltering/Server.cpp b/cpp/test/Glacier2/dynamicFiltering/Server.cpp index 02781f7e8b9..e19f3ad6b73 100644 --- a/cpp/test/Glacier2/dynamicFiltering/Server.cpp +++ b/cpp/test/Glacier2/dynamicFiltering/Server.cpp @@ -19,99 +19,78 @@ using namespace Test; // simplicity, we essentially 'alias' all possible requests to a single // object adapter and a single servant. // -class ServerLocatorRegistry : public virtual LocatorRegistry +class ServerLocatorRegistry final : public LocatorRegistry { public: - virtual void - setAdapterDirectProxy_async(const AMD_LocatorRegistry_setAdapterDirectProxyPtr& cb, const string&, - const ObjectPrx&, const Current&) + void + setAdapterDirectProxyAsync(string, shared_ptr, function response, + function, const Current&) override { - cb->ice_response(); + response(); } - virtual void - setReplicatedAdapterDirectProxy_async(const AMD_LocatorRegistry_setReplicatedAdapterDirectProxyPtr& cb, - const string&, const string&, const ObjectPrx&, const Current&) + void + setReplicatedAdapterDirectProxyAsync(string, string, shared_ptr, + function response, function, + const Current&) override { - cb->ice_response(); + response(); } - virtual void - setServerProcessProxy_async(const AMD_LocatorRegistry_setServerProcessProxyPtr& cb, - const string&, const ProcessPrx&, const Current&) + void + setServerProcessProxyAsync(string, shared_ptr, + function response, function, + const Current&) override { - cb->ice_response(); + response(); } }; -class ServerLocatorI : public virtual Locator +class ServerLocatorI final : public Locator { public: - ServerLocatorI(BackendPtr backend, ObjectAdapterPtr adapter) : - _backend(backend), - _adapter(adapter) + ServerLocatorI(shared_ptr backend, shared_ptr adapter) : + _backend(std::move(backend)), + _adapter(std::move(adapter)) { - _registryPrx = LocatorRegistryPrx::uncheckedCast(adapter->add(new ServerLocatorRegistry, - Ice::stringToIdentity("registry"))); + _registryPrx = uncheckedCast(_adapter->add(make_shared(), + Ice::stringToIdentity("registry"))); } - virtual void - findObjectById_async(const AMD_Locator_findObjectByIdPtr& cb, const Identity& id, const Current&) const + void + findObjectByIdAsync(Identity id, + function&)> response, function, + const Current&) const override { - cb->ice_response(_adapter->createProxy(id)); + response(_adapter->createProxy(id)); } - virtual void - findAdapterById_async(const AMD_Locator_findAdapterByIdPtr& cb, const string&, const Current&) const + void + findAdapterByIdAsync(string, + function&)> response, function, + const Current&) const override { - cb->ice_response(_adapter->createDirectProxy(stringToIdentity("dummy"))); + response(_adapter->createDirectProxy(stringToIdentity("dummy"))); } - virtual LocatorRegistryPrx - getRegistry(const Current&) const + shared_ptr + getRegistry(const Current&) const override { return _registryPrx; } private: - BackendPtr _backend; - ObjectAdapterPtr _adapter; - LocatorRegistryPrx _registryPrx; + shared_ptr _backend; + shared_ptr _adapter; + shared_ptr _registryPrx; }; -class ServantLocatorI : public virtual ServantLocator +class SessionControlServer final : public Test::TestHelper { public: - ServantLocatorI(const BackendPtr& backend) : - _backend(backend) - { - } - - virtual ObjectPtr locate(const Current&, LocalObjectPtr&) - { - return _backend; - } - - virtual void finished(const Current&, const ObjectPtr&, const LocalObjectPtr&) - { - } - - virtual void deactivate(const string&) - { - } - -private: - - BackendPtr _backend; -}; - -class SessionControlServer : public Test::TestHelper -{ -public: - - void run(int, char**); + void run(int, char**) override; }; void @@ -130,23 +109,23 @@ SessionControlServer::run(int argc, char** argv) // expects to use a proxy for the correct type of object. // communicator->getProperties()->setProperty("TestControllerAdapter.Endpoints", getTestEndpoint(2, "tcp")); - ObjectAdapterPtr controllerAdapter = communicator->createObjectAdapter("TestControllerAdapter"); - TestControllerIPtr controller = new TestControllerI(getTestEndpoint(1)); + auto controllerAdapter = communicator->createObjectAdapter("TestControllerAdapter"); + auto controller = make_shared(getTestEndpoint(1)); controllerAdapter->add(controller, Ice::stringToIdentity("testController")); controllerAdapter->activate(); communicator->getProperties()->setProperty("SessionControlAdapter.Endpoints", getTestEndpoint()); - ObjectAdapterPtr adapter = communicator->createObjectAdapter("SessionControlAdapter"); - adapter->add(new SessionManagerI(controller), Ice::stringToIdentity("SessionManager")); + auto adapter = communicator->createObjectAdapter("SessionControlAdapter"); + adapter->add(make_shared(controller), Ice::stringToIdentity("SessionManager")); adapter->activate(); - BackendPtr backend = new BackendI; + auto backend = make_shared(); communicator->getProperties()->setProperty("BackendAdapter.Endpoints", getTestEndpoint(1)); - ObjectAdapterPtr backendAdapter = communicator->createObjectAdapter("BackendAdapter"); - backendAdapter->addServantLocator(new ServantLocatorI(backend), ""); + auto backendAdapter = communicator->createObjectAdapter("BackendAdapter"); + backendAdapter->addDefaultServant(backend, ""); backendAdapter->activate(); - Ice::LocatorPtr locator = new ServerLocatorI(backend, backendAdapter); + auto locator = make_shared(backend, backendAdapter); backendAdapter->add(locator, Ice::stringToIdentity("locator")); communicator->waitForShutdown(); diff --git a/cpp/test/Glacier2/dynamicFiltering/SessionI.cpp b/cpp/test/Glacier2/dynamicFiltering/SessionI.cpp index af7f4f04428..b3b33fcae74 100644 --- a/cpp/test/Glacier2/dynamicFiltering/SessionI.cpp +++ b/cpp/test/Glacier2/dynamicFiltering/SessionI.cpp @@ -8,31 +8,26 @@ using namespace std; using namespace Test; -SessionManagerI::SessionManagerI(const TestControllerIPtr& controller): +SessionManagerI::SessionManagerI(const shared_ptr& controller): _controller(controller) { } -Glacier2::SessionPrx -SessionManagerI::create(const string&, const Glacier2::SessionControlPrx& sessionControl, const Ice::Current& current) +shared_ptr +SessionManagerI::create(string, shared_ptr sessionControl, const Ice::Current& current) { - Glacier2::SessionPrx newSession = Glacier2::SessionPrx::uncheckedCast( - current.adapter->addWithUUID(new SessionI(sessionControl, _controller))); - _controller->addSession(SessionTuple(newSession, sessionControl)); + auto newSession = Ice::uncheckedCast( + current.adapter->addWithUUID(make_shared(sessionControl, _controller))); + _controller->addSession(SessionTuple(newSession, std::move(sessionControl))); return newSession; } -SessionI::SessionI(const Glacier2::SessionControlPrx& sessionControl, const TestControllerIPtr& controller) : - _sessionControl(sessionControl), - _controller(controller) -{ - assert(sessionControl); -} - -void -SessionI::destroySession(const Ice::Current&) +SessionI::SessionI(shared_ptr sessionControl, + shared_ptr controller) : + _sessionControl(std::move(sessionControl)), + _controller(std::move(controller)) { - _sessionControl->destroy(); + assert(_sessionControl); } void diff --git a/cpp/test/Glacier2/dynamicFiltering/SessionI.h b/cpp/test/Glacier2/dynamicFiltering/SessionI.h index 0e5ba644553..d204e0a4f45 100644 --- a/cpp/test/Glacier2/dynamicFiltering/SessionI.h +++ b/cpp/test/Glacier2/dynamicFiltering/SessionI.h @@ -17,31 +17,30 @@ // reason why not as long as there isn't a deadlock situation. // -class SessionManagerI : public Glacier2::SessionManager +class SessionManagerI final : public Glacier2::SessionManager { public: - SessionManagerI(const TestControllerIPtr&); + SessionManagerI(const std::shared_ptr&); - virtual Glacier2::SessionPrx create(const std::string&, const Glacier2::SessionControlPrx&, const Ice::Current&); + std::shared_ptr + create(std::string, std::shared_ptr, const Ice::Current&) override; private: - TestControllerIPtr _controller; + std::shared_ptr _controller; }; -class SessionI : public Test::TestSession +class SessionI final : public Test::TestSession { public: - SessionI(const Glacier2::SessionControlPrx&, const TestControllerIPtr&); - virtual void destroySession(const Ice::Current&); - virtual void shutdown(const Ice::Current&); - - virtual void destroy(const Ice::Current&); + SessionI(std::shared_ptr, std::shared_ptr); + void shutdown(const Ice::Current&) override; + void destroy(const Ice::Current&) override; private: - Glacier2::SessionControlPrx _sessionControl; - TestControllerIPtr _controller; + std::shared_ptr _sessionControl; + std::shared_ptr _controller; }; #endif diff --git a/cpp/test/Glacier2/dynamicFiltering/TestControllerI.cpp b/cpp/test/Glacier2/dynamicFiltering/TestControllerI.cpp index 35f1876fd1a..d220a961f92 100644 --- a/cpp/test/Glacier2/dynamicFiltering/TestControllerI.cpp +++ b/cpp/test/Glacier2/dynamicFiltering/TestControllerI.cpp @@ -52,36 +52,32 @@ TestControllerI::TestControllerI(const string& endpoint) }; void -TestControllerI::step(const Glacier2::SessionPrx& currentSession, const TestToken& currentState, TestToken& newState, +TestControllerI::step(shared_ptr currentSession, TestToken currentState, TestToken& newState, const Ice::Current&) { switch(currentState.code) { - case Test::Finished: + case Test::StateCode::Finished: { assert(false); break; } - case Test::Running: + case Test::StateCode::Running: { TestConfiguration& config = _configurations[static_cast(currentState.config)]; assert(!config.description.empty()); - bool found = false; SessionTuple session; + lock_guard lock(_mutex); + for(const auto& p : _sessions) { - IceUtil::Mutex::Lock sync(_mutex); - for(vector::const_iterator i = _sessions.begin(); i != _sessions.end() && !found; ++i) + if(targetEqualTo(p.session, currentSession)) { - if(i->session == currentSession) - { - session = *i; - found = true; - } + session = p; + break; } } - assert(found); // // New sessions force configuration step. @@ -103,7 +99,7 @@ TestControllerI::step(const Glacier2::SessionPrx& currentSession, const TestToke ++newState.config; if(!(newState.config < (long)_configurations.size())) { - newState.code = Test::Finished; + newState.code = Test::StateCode::Finished; newState.expectedResult = false; newState.description = "No more tests"; newState.testReference = ""; @@ -126,13 +122,13 @@ TestControllerI::step(const Glacier2::SessionPrx& currentSession, const TestToke if(reconfigure) { - Glacier2::StringSetPrx categories = session.sessionControl->categories(); + auto categories = session.sessionControl->categories(); categories->add(config.categoryFiltersAccept); - Glacier2::StringSetPrx adapterIds = session.sessionControl->adapterIds(); + auto adapterIds = session.sessionControl->adapterIds(); adapterIds->add(config.adapterIdFiltersAccept); - Glacier2::IdentitySetPrx ids = session.sessionControl->identities(); + auto ids = session.sessionControl->identities(); ids->add(config.objectIdFiltersAccept); session.configured = true; } @@ -141,7 +137,7 @@ TestControllerI::step(const Glacier2::SessionPrx& currentSession, const TestToke default: { - newState.code = Running; + newState.code = Test::StateCode::Running; newState.config = 0; newState.caseIndex = 0; newState.testReference = ""; @@ -159,19 +155,19 @@ TestControllerI::shutdown(const Ice::Current& current) } void -TestControllerI::addSession(const SessionTuple& s) +TestControllerI::addSession(SessionTuple&& s) { - IceUtil::Mutex::Lock sync(_mutex); - _sessions.push_back(s); + lock_guard lock(_mutex); + _sessions.emplace_back(std::move(s)); } void -TestControllerI::notifyDestroy(const Glacier2::SessionControlPrx& control) +TestControllerI::notifyDestroy(const shared_ptr& control) { - IceUtil::Mutex::Lock sync(_mutex); - for (vector::iterator i = _sessions.begin(); i != _sessions.end(); ++i) + lock_guard lock(_mutex); + for(auto i = _sessions.begin(); i != _sessions.end(); ++i) { - if(i->sessionControl == control) + if(targetEqualTo(i->sessionControl, control)) { _sessions.erase(i); break; diff --git a/cpp/test/Glacier2/dynamicFiltering/TestControllerI.h b/cpp/test/Glacier2/dynamicFiltering/TestControllerI.h index 689680b1bbb..91e7b8f3cdf 100644 --- a/cpp/test/Glacier2/dynamicFiltering/TestControllerI.h +++ b/cpp/test/Glacier2/dynamicFiltering/TestControllerI.h @@ -5,8 +5,6 @@ #ifndef TEST_CONTROLLER_H #define TEST_CONTROLLER_H -#include -#include #include #include #include @@ -14,37 +12,21 @@ struct SessionTuple { - Glacier2::SessionPrx session; - Glacier2::SessionControlPrx sessionControl; - bool configured; - - SessionTuple() {} - SessionTuple(Glacier2::SessionPrx s, Glacier2::SessionControlPrx control): - session(s), - sessionControl(control), + std::shared_ptr session; + std::shared_ptr sessionControl; + bool configured = false; + + SessionTuple() = default; + SessionTuple(std::shared_ptr s, std::shared_ptr control): + session(std::move(s)), + sessionControl(std::move(control)), configured(false) - {} - - SessionTuple(const SessionTuple& st): - session(st.session), - sessionControl(st.sessionControl), - configured(st.configured) { } - SessionTuple& - operator=(const SessionTuple& rhs) - { - if(this == &rhs) - { - return *this; - } - - session = rhs.session; - sessionControl = rhs.sessionControl; - configured = rhs.configured; - return *this; - } + SessionTuple(const SessionTuple&) = delete; + SessionTuple& operator=(const SessionTuple&) = default; + SessionTuple(SessionTuple&&) = default; }; /* @@ -73,33 +55,29 @@ struct TestConfiguration // configuration of the test's session and provides the client with test // cases and expected outcomes. // -class TestControllerI : public Test::TestController +class TestControllerI final : public Test::TestController { public: TestControllerI(const std::string&); - // - // Slice to C++ mapping. - // - void step(const Glacier2::SessionPrx& currentSession, const Test::TestToken& currentState, - Test::TestToken& newState, const Ice::Current&); - void shutdown(const Ice::Current&); + void step(std::shared_ptr currentSession, Test::TestToken currentState, + Test::TestToken& newState, const Ice::Current&) override; + + void shutdown(const Ice::Current&) override; // // Internal methods. // - void addSession(const SessionTuple&); + void addSession(SessionTuple&&); - void notifyDestroy(const Glacier2::SessionControlPrx&); + void notifyDestroy(const std::shared_ptr&); private: - IceUtil::Mutex _mutex; + std::mutex _mutex; std::vector _sessions; std::vector _configurations; }; -typedef IceUtil::Handle TestControllerIPtr; - #endif diff --git a/cpp/test/Glacier2/override/CallbackI.cpp b/cpp/test/Glacier2/override/CallbackI.cpp index 53968ee4bea..daafed5e7ef 100644 --- a/cpp/test/Glacier2/override/CallbackI.cpp +++ b/cpp/test/Glacier2/override/CallbackI.cpp @@ -10,103 +10,41 @@ using namespace std; using namespace Ice; using namespace Test; -class Cookie : public Ice::LocalObject -{ -}; -typedef IceUtil::Handle CookiePtr; - -template -class CookieT : public Cookie -{ -public: - - CookieT(const T& v) : cb(v) - { - } - - T cb; -}; - -template CookiePtr newCookie(const T& cb) -{ - return new CookieT(cb); -} - -template const T& getCookie(const CookiePtr& cookie) -{ - return dynamic_cast* >(cookie.get())->cb; -} - -class AsyncCB : public IceUtil::Shared -{ -public: - - void - responseCallback(const CookiePtr& cookie) - { - getCookie(cookie)->ice_response(); - } - - void - exceptionCallback(const Ice::Exception& ex, const CookiePtr& cookie) - { - getCookie(cookie)->ice_exception(ex); - } - - void - responseCallbackWithPayload(const CookiePtr& cookie) - { - getCookie(cookie)->ice_response(); - } - - void - exceptionCallbackWithPayload(const Ice::Exception& ex, const CookiePtr& cookie) - { - getCookie(cookie)->ice_exception(ex); - } -}; -typedef IceUtil::Handle AsyncCBPtr; - -CallbackReceiverI::CallbackReceiverI() : - _holding(false), - _lastToken(-1), - _callback(0), - _callbackWithPayload(0) -{ -} - void CallbackReceiverI::callback(int token, const Current&) { - Lock sync(*this); - checkForHold(); - - if(token != _lastToken) { - _callback = 0; - _lastToken = token; + unique_lock lock(_mutex); + checkForHold(lock); + if(token != _lastToken) + { + _callback = 0; + _lastToken = token; + } + ++_callback; } - ++_callback; - notifyAll(); + _condVar.notify_all(); } void -CallbackReceiverI::callbackWithPayload(const Ice::ByteSeq&, const Current&) +CallbackReceiverI::callbackWithPayload(Ice::ByteSeq, const Current&) { - Lock sync(*this); - checkForHold(); - ++_callbackWithPayload; - notifyAll(); + { + unique_lock lock(_mutex); + checkForHold(lock); + ++_callbackWithPayload; + } + _condVar.notify_all(); } int CallbackReceiverI::callbackOK(int count, int token) { - Lock sync(*this); + unique_lock lock(_mutex); while(_lastToken != token || _callback < count) { - wait(); + _condVar.wait(lock); } _callback -= count; @@ -116,11 +54,11 @@ CallbackReceiverI::callbackOK(int count, int token) int CallbackReceiverI::callbackWithPayloadOK(int count) { - Lock sync(*this); + unique_lock lock(_mutex); while(_callbackWithPayload < count) { - wait(); + _condVar.wait(lock); } _callbackWithPayload -= count; @@ -130,37 +68,36 @@ CallbackReceiverI::callbackWithPayloadOK(int count) void CallbackReceiverI::hold() { - Lock sync(*this); + lock_guard lg(_mutex); _holding = true; } void CallbackReceiverI::activate() { - Lock sync(*this); - _holding = false; - notifyAll(); + { + lock_guard lg(_mutex); + _holding = false; + } + _condVar.notify_all(); } void -CallbackReceiverI::checkForHold() +CallbackReceiverI::checkForHold(unique_lock& lock) { while(_holding) { - wait(); + _condVar.wait(lock); } } -CallbackI::CallbackI() -{ -} - void -CallbackI::initiateCallback_async(const AMD_Callback_initiateCallbackPtr& cb, - const CallbackReceiverPrx& proxy, int token, const Current& current) +CallbackI::initiateCallbackAsync(shared_ptr proxy, int token, + function response, function error, + const Current& current) { - Ice::Context::const_iterator p = current.ctx.find("serverOvrd"); - Ice::Context ctx = current.ctx; + auto p = current.ctx.find("serverOvrd"); + auto ctx = current.ctx; if(p != current.ctx.end()) { ctx["_ovrd"] = p->second; @@ -168,25 +105,22 @@ CallbackI::initiateCallback_async(const AMD_Callback_initiateCallbackPtr& cb, if(proxy->ice_isTwoway()) { - AsyncCBPtr acb = new AsyncCB(); - proxy->begin_callback(token, ctx, - newCallback_CallbackReceiver_callback(acb, &AsyncCB::responseCallback, &AsyncCB::exceptionCallback), - newCookie(cb)); + proxy->callbackAsync(token, std::move(response), std::move(error), nullptr, ctx); } else { proxy->callback(token, ctx); - cb->ice_response(); + response(); } } void -CallbackI::initiateCallbackWithPayload_async(const AMD_Callback_initiateCallbackWithPayloadPtr& cb, - const CallbackReceiverPrx& proxy, - const Current& current) +CallbackI::initiateCallbackWithPayloadAsync(shared_ptr proxy, + function response, function error, + const Current& current) { - Ice::Context::const_iterator p = current.ctx.find("serverOvrd"); - Ice::Context ctx = current.ctx; + auto p = current.ctx.find("serverOvrd"); + auto ctx = current.ctx; if(p != current.ctx.end()) { ctx["_ovrd"] = p->second; @@ -195,18 +129,12 @@ CallbackI::initiateCallbackWithPayload_async(const AMD_Callback_initiateCallback Ice::ByteSeq seq(1000 * 1024, 0); if(proxy->ice_isTwoway()) { - AsyncCBPtr acb = new AsyncCB(); - proxy->begin_callbackWithPayload(seq, ctx, - newCallback_CallbackReceiver_callbackWithPayload( - acb, - &AsyncCB::responseCallbackWithPayload, - &AsyncCB::exceptionCallbackWithPayload), - newCookie(cb)); + proxy->callbackWithPayloadAsync(seq, std::move(response), std::move(error), nullptr, ctx); } else { proxy->callbackWithPayload(seq, ctx); - cb->ice_response(); + response(); } } diff --git a/cpp/test/Glacier2/override/CallbackI.h b/cpp/test/Glacier2/override/CallbackI.h index 2dbfac8750b..2b2fe7bc7c4 100644 --- a/cpp/test/Glacier2/override/CallbackI.h +++ b/cpp/test/Glacier2/override/CallbackI.h @@ -5,19 +5,15 @@ #ifndef CALLBACK_I_H #define CALLBACK_I_H -#include -#include #include #include -class CallbackReceiverI : public ::Test::CallbackReceiver, public IceUtil::Monitor +class CallbackReceiverI final : public Test::CallbackReceiver { public: - CallbackReceiverI(); - - virtual void callback(int token, const Ice::Current&); - virtual void callbackWithPayload(const Ice::ByteSeq&, const ::Ice::Current&); + void callback(int token, const Ice::Current&) override; + void callbackWithPayload(Ice::ByteSeq, const ::Ice::Current&) override; int callbackOK(int, int); int callbackWithPayloadOK(int); @@ -27,28 +23,29 @@ class CallbackReceiverI : public ::Test::CallbackReceiver, public IceUtil::Monit private: - void checkForHold(); + void checkForHold(std::unique_lock&); + + bool _holding = false; - bool _holding; + int _lastToken = -1; + int _callback = 0; + int _callbackWithPayload = 0; - int _lastToken; - int _callback; - int _callbackWithPayload; + std::mutex _mutex; + std::condition_variable _condVar; }; -typedef IceUtil::Handle CallbackReceiverIPtr; -class CallbackI : public ::Test::Callback +class CallbackI final : public Test::Callback { public: - CallbackI(); - - virtual void initiateCallback_async(const ::Test::AMD_Callback_initiateCallbackPtr&, - const ::Test::CallbackReceiverPrx&, int, const Ice::Current&); - virtual void initiateCallbackWithPayload_async(const ::Test::AMD_Callback_initiateCallbackWithPayloadPtr&, - const ::Test::CallbackReceiverPrx&, - const ::Ice::Current&); - virtual void shutdown(const Ice::Current&); + void initiateCallbackAsync(std::shared_ptr, int, + std::function, std::function, + const Ice::Current&) override; + void initiateCallbackWithPayloadAsync(std::shared_ptr, + std::function, std::function, + const ::Ice::Current&) override; + void shutdown(const Ice::Current&) override; }; #endif diff --git a/cpp/test/Glacier2/override/Client.cpp b/cpp/test/Glacier2/override/Client.cpp index 1b8d5833b36..ff472f864e8 100644 --- a/cpp/test/Glacier2/override/Client.cpp +++ b/cpp/test/Glacier2/override/Client.cpp @@ -2,58 +2,60 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include #include #include #include #include +#include +#include using namespace std; +using namespace std::chrono_literals; + using namespace Ice; using namespace Test; -class CallbackClient : public Test::TestHelper +class CallbackClient final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void CallbackClient::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); properties->setProperty("Ice.Warn.Connections", "0"); properties->setProperty("Ice.ThreadPool.Client.Serialize", "1"); Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); - ObjectPrx routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50)); - Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(routerBase); + auto routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50)); + auto router = checkedCast(routerBase); communicator->setDefaultRouter(router); - ObjectPrx base = communicator->stringToProxy("c/callback:" + getTestEndpoint()); - Glacier2::SessionPrx session = router->createSession("userid", "abc123"); + auto base = communicator->stringToProxy("c/callback:" + getTestEndpoint()); + auto session = router->createSession("userid", "abc123"); base->ice_ping(); - CallbackPrx twoway = CallbackPrx::checkedCast(base); - CallbackPrx oneway = twoway->ice_oneway(); - CallbackPrx batchOneway = twoway->ice_batchOneway(); + auto twoway = checkedCast(base); + auto oneway = twoway->ice_oneway(); + auto batchOneway = twoway->ice_batchOneway(); communicator->getProperties()->setProperty("Ice.PrintAdapterReady", "0"); - ObjectAdapterPtr adapter = communicator->createObjectAdapterWithRouter("CallbackReceiverAdapter", router); + auto adapter = communicator->createObjectAdapterWithRouter("CallbackReceiverAdapter", router); adapter->activate(); string category = router->getCategoryForClient(); - CallbackReceiverI* callbackReceiverImpl = new CallbackReceiverI; - ObjectPtr callbackReceiver = callbackReceiverImpl; + auto callbackReceiver = make_shared(); Identity callbackReceiverIdent; callbackReceiverIdent.name = "callbackReceiver"; callbackReceiverIdent.category = category; - CallbackReceiverPrx twowayR = - CallbackReceiverPrx::uncheckedCast(adapter->add(callbackReceiver, callbackReceiverIdent)); - CallbackReceiverPrx onewayR = twowayR->ice_oneway(); + auto twowayR = + uncheckedCast(adapter->add(callbackReceiver, callbackReceiverIdent)); + auto onewayR = twowayR->ice_oneway(); { cout << "testing client request override... " << flush; @@ -62,7 +64,7 @@ CallbackClient::run(int argc, char** argv) { oneway->initiateCallback(twowayR, 0); oneway->initiateCallback(twowayR, 0); - callbackReceiverImpl->callbackOK(2, 0); + callbackReceiver->callbackOK(2, 0); } } @@ -74,8 +76,8 @@ CallbackClient::run(int argc, char** argv) oneway->initiateCallback(twowayR, i, ctx); oneway->initiateCallback(twowayR, i, ctx); oneway->initiateCallback(twowayR, i, ctx); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100)); - test(callbackReceiverImpl->callbackOK(1, i) < 3); + this_thread::sleep_for(100ms); + test(callbackReceiver->callbackOK(1, i) < 3); } } cout << "ok" << endl; @@ -90,17 +92,17 @@ CallbackClient::run(int argc, char** argv) oneway->initiateCallback(onewayR, i, ctx); oneway->initiateCallback(onewayR, i, ctx); oneway->initiateCallback(onewayR, i, ctx); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100)); - test(callbackReceiverImpl->callbackOK(1, i) < 3); + this_thread::sleep_for(100ms); + test(callbackReceiver->callbackOK(1, i) < 3); } oneway->initiateCallback(twowayR, 0); - test(callbackReceiverImpl->callbackOK(1, 0) == 0); + test(callbackReceiver->callbackOK(1, 0) == 0); int count = 0; int nRetry = 0; do { - callbackReceiverImpl->hold(); + callbackReceiver->hold(); oneway->initiateCallbackWithPayload(onewayR, ctx); oneway->initiateCallbackWithPayload(onewayR, ctx); oneway->initiateCallbackWithPayload(onewayR, ctx); @@ -112,18 +114,18 @@ CallbackClient::run(int argc, char** argv) oneway->initiateCallbackWithPayload(onewayR, ctx); oneway->initiateCallbackWithPayload(onewayR, ctx); oneway->initiateCallback(twowayR, 0); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200 + nRetry * 200)); - callbackReceiverImpl->activate(); - test(callbackReceiverImpl->callbackOK(1, 0) == 0); - count = callbackReceiverImpl->callbackWithPayloadOK(0); - callbackReceiverImpl->callbackWithPayloadOK(count); + this_thread::sleep_for(chrono::milliseconds(200 + nRetry * 200)); + callbackReceiver->activate(); + test(callbackReceiver->callbackOK(1, 0) == 0); + count = callbackReceiver->callbackWithPayloadOK(0); + callbackReceiver->callbackWithPayloadOK(count); } while(count == 10 && nRetry++ < 10); test(count < 10); oneway->initiateCallbackWithPayload(twowayR); oneway->initiateCallbackWithPayload(twowayR); - callbackReceiverImpl->hold(); + callbackReceiver->hold(); oneway->initiateCallbackWithPayload(twowayR); oneway->initiateCallback(onewayR, 0, ctx); oneway->initiateCallback(onewayR, 0, ctx); @@ -131,11 +133,11 @@ CallbackClient::run(int argc, char** argv) oneway->initiateCallback(onewayR, 0, ctx); oneway->initiateCallback(onewayR, 0, ctx); oneway->initiateCallbackWithPayload(twowayR); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(1000)); - callbackReceiverImpl->activate(); - test(callbackReceiverImpl->callbackWithPayloadOK(4) == 0); + this_thread::sleep_for(1000ms); + callbackReceiver->activate(); + test(callbackReceiver->callbackWithPayloadOK(4) == 0); - int remainingCallbacks = callbackReceiverImpl->callbackOK(1, 0); + int remainingCallbacks = callbackReceiver->callbackOK(1, 0); // // Occasionally, Glacier2 flushes in the middle of our 5 // callbacks, so we get more than 1 callback @@ -147,13 +149,13 @@ CallbackClient::run(int argc, char** argv) test(remainingCallbacks <= 4); if(remainingCallbacks > 0) { - test(callbackReceiverImpl->callbackOK(remainingCallbacks, 0) == 0); + test(callbackReceiver->callbackOK(remainingCallbacks, 0) == 0); } ctx["_fwd"] = "O"; oneway->initiateCallbackWithPayload(twowayR); - callbackReceiverImpl->hold(); + callbackReceiver->hold(); oneway->initiateCallbackWithPayload(twowayR); oneway->initiateCallback(onewayR, 0, ctx); oneway->initiateCallback(onewayR, 0, ctx); @@ -161,16 +163,16 @@ CallbackClient::run(int argc, char** argv) oneway->initiateCallback(onewayR, 0, ctx); oneway->initiateCallback(onewayR, 0, ctx); oneway->initiateCallbackWithPayload(twowayR); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); - callbackReceiverImpl->activate(); - test(callbackReceiverImpl->callbackWithPayloadOK(3) == 0); - remainingCallbacks = callbackReceiverImpl->callbackOK(1, 0); + this_thread::sleep_for(200ms); + callbackReceiver->activate(); + test(callbackReceiver->callbackWithPayloadOK(3) == 0); + remainingCallbacks = callbackReceiver->callbackOK(1, 0); // Unlikely but sometime we get more than just one callback if the flush // occurs in the middle of our 5 callbacks. test(remainingCallbacks <= 3); if(remainingCallbacks > 0) { - test(callbackReceiverImpl->callbackOK(remainingCallbacks, 0) == 0); + test(callbackReceiver->callbackOK(remainingCallbacks, 0) == 0); } cout << "ok" << endl; @@ -190,8 +192,8 @@ CallbackClient::run(int argc, char** argv) } communicator->setDefaultRouter(0); - ObjectPrx processBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51)); - Ice::ProcessPrx process = Ice::ProcessPrx::checkedCast(processBase); + auto processBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51)); + auto process = checkedCast(processBase); process->shutdown(); try { diff --git a/cpp/test/Glacier2/override/Server.cpp b/cpp/test/Glacier2/override/Server.cpp index 61df40c3658..85c4ba60c82 100644 --- a/cpp/test/Glacier2/override/Server.cpp +++ b/cpp/test/Glacier2/override/Server.cpp @@ -10,25 +10,25 @@ using namespace std; using namespace Ice; using namespace Test; -class CallbackServer : public Test::TestHelper +class CallbackServer final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void CallbackServer::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); properties->setProperty("Ice.Warn.Connections", "0"); properties->setProperty("Ice.Warn.Dispatch", "0"); properties->setProperty("Ice.ThreadPool.Server.Serialize", "1"); Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); communicator->getProperties()->setProperty("CallbackAdapter.Endpoints", getTestEndpoint()); - ObjectAdapterPtr adapter = communicator->createObjectAdapter("CallbackAdapter"); - adapter->add(new CallbackI(), Ice::stringToIdentity("c/callback")); + auto adapter = communicator->createObjectAdapter("CallbackAdapter"); + adapter->add(make_shared(), Ice::stringToIdentity("c/callback")); adapter->activate(); communicator->waitForShutdown(); } diff --git a/cpp/test/Glacier2/router/CallbackI.cpp b/cpp/test/Glacier2/router/CallbackI.cpp index 920a611c266..df3a1f6fa5d 100644 --- a/cpp/test/Glacier2/router/CallbackI.cpp +++ b/cpp/test/Glacier2/router/CallbackI.cpp @@ -7,116 +7,19 @@ #include using namespace std; +using namespace std::chrono_literals; + using namespace Ice; using namespace Test; -class Cookie : public Ice::LocalObject -{ -}; -typedef IceUtil::Handle CookiePtr; - -template -class CookieT : public Cookie -{ -public: - - CookieT(const T& v) : cb(v) - { - } - - T cb; -}; - -template CookiePtr newCookie(const T& cb) -{ - return new CookieT(cb); -} - -template const T& getCookie(const CookiePtr& cookie) -{ - return dynamic_cast* >(cookie.get())->cb; -} - -class AsyncCB : public IceUtil::Shared -{ -public: - - void - responseCallback(const CookiePtr& cookie) - { - getCookie(cookie)->ice_response(); - } - - void - exceptionCallback(const Ice::Exception& ex, const CookiePtr& cookie) - { - getCookie(cookie)->ice_exception(ex); - } - - void - responseCallbackEx(const CookiePtr& cookie) - { - getCookie(cookie)->ice_response(); - } - - void - exceptionCallbackEx(const Ice::Exception& ex, const CookiePtr& cookie) - { - getCookie(cookie)->ice_exception(ex); - } - - void - responseConcurrentCallback(Int number, const CookiePtr& cookie) - { - getCookie(cookie)->ice_response(number); - } - - void - exceptionConcurrentCallback(const Ice::Exception& ex, const CookiePtr& cookie) - { - getCookie(cookie)->ice_exception(ex); - } - - void - responseWaitCallback(const CookiePtr& cookie) - { - getCookie(cookie)->ice_response(); - } - - void - exceptionWaitCallback(const Ice::Exception& ex, const CookiePtr& cookie) - { - getCookie(cookie)->ice_exception(ex); - } - - void - responseCallbackWithPayload(const CookiePtr& cookie) - { - getCookie(cookie)->ice_response(); - } - - void - exceptionCallbackWithPayload(const Ice::Exception& ex, const CookiePtr& cookie) - { - getCookie(cookie)->ice_exception(ex); - } -}; -typedef IceUtil::Handle AsyncCBPtr; - -CallbackReceiverI::CallbackReceiverI() : - _callback(0), - _waitCallback(false), - _callbackWithPayload(false), - _finishWaitCallback(false) -{ -} - void CallbackReceiverI::callback(const Current&) { - Lock sync(*this); - ++_callback; - notifyAll(); + { + lock_guard lg(_mutex); + ++_callback; + } + _condVar.notify_all(); } void @@ -130,56 +33,54 @@ CallbackReceiverI::callbackEx(const Current& current) } void -CallbackReceiverI::concurrentCallback_async(const AMD_CallbackReceiver_concurrentCallbackPtr& cb, - Int number, - const Current&) +CallbackReceiverI::concurrentCallbackAsync(int number, function response, + function error, + const Current&) { - Lock sync(*this); - - pair p; - p.first = cb; - p.second = number; - _callbacks.push_back(p); - notifyAll(); + { + lock_guard lg(_mutex); + _callbacks.emplace_back(std::move(response), std::move(error), number); + } + _condVar.notify_all(); } void CallbackReceiverI::waitCallback(const Current&) { { - Lock sync(*this); + lock_guard lg(_mutex); assert(!_waitCallback); _waitCallback = true; - notifyAll(); } + _condVar.notify_all(); + unique_lock lock(_mutex); + while(!_finishWaitCallback) { - Lock sync(*this); - while(!_finishWaitCallback) - { - wait(); - } - _finishWaitCallback = false; + _condVar.wait(lock); } + _finishWaitCallback = false; } void -CallbackReceiverI::callbackWithPayload(const Ice::ByteSeq&, const Current&) +CallbackReceiverI::callbackWithPayload(Ice::ByteSeq, const Current&) { - Lock sync(*this); - assert(!_callbackWithPayload); - _callbackWithPayload = true; - notifyAll(); + { + lock_guard lg(_mutex); + assert(!_callbackWithPayload); + _callbackWithPayload = true; + } + _condVar.notify_all(); } void CallbackReceiverI::callbackOK(int expected) { - Lock sync(*this); + unique_lock lock(_mutex); while(_callback != expected) { - wait(); + _condVar.wait(lock); } _callback = 0; } @@ -187,10 +88,10 @@ CallbackReceiverI::callbackOK(int expected) void CallbackReceiverI::waitCallbackOK() { - Lock sync(*this); + unique_lock lock(_mutex); while(!_waitCallback) { - timedWait(IceUtil::Time::seconds(30)); + _condVar.wait_for(lock, 30s); test(_waitCallback); } @@ -200,11 +101,11 @@ CallbackReceiverI::waitCallbackOK() void CallbackReceiverI::callbackWithPayloadOK() { - Lock sync(*this); + unique_lock lock(_mutex); while(!_callbackWithPayload) { - wait(); + _condVar.wait(lock); } _callbackWithPayload = false; @@ -213,105 +114,90 @@ CallbackReceiverI::callbackWithPayloadOK() void CallbackReceiverI::notifyWaitCallback() { - Lock sync(*this); - _finishWaitCallback = true; - notifyAll(); + { + lock_guard lg(_mutex); + _finishWaitCallback = true; + } + _condVar.notify_all(); }; void CallbackReceiverI::answerConcurrentCallbacks(unsigned int num) { - Lock sync(*this); + unique_lock lock(_mutex); while(_callbacks.size() != num) { - wait(); + _condVar.wait(lock); } - for(vector >::const_iterator p = _callbacks.begin(); - p != _callbacks.end(); - ++p) + for(const auto& p : _callbacks) { - p->first->ice_response(p->second); + get<0>(p)(get<2>(p)); } _callbacks.clear(); } -CallbackI::CallbackI() -{ -} - void -CallbackI::initiateCallback_async(const AMD_Callback_initiateCallbackPtr& cb, - const CallbackReceiverPrx& proxy, const Current& current) +CallbackI::initiateCallbackAsync(shared_ptr proxy, + function response, + function error, + const Current& current) { if(proxy->ice_isTwoway()) { - AsyncCBPtr acb = new AsyncCB(); - proxy->begin_callback(current.ctx, - newCallback_CallbackReceiver_callback(acb, &AsyncCB::responseCallback, &AsyncCB::exceptionCallback), - newCookie(cb)); + proxy->callbackAsync(std::move(response), std::move(error), nullptr, current.ctx); } else { proxy->callback(current.ctx); - cb->ice_response(); + response(); } } void -CallbackI::initiateCallbackEx_async(const AMD_Callback_initiateCallbackExPtr& cb, - const CallbackReceiverPrx& proxy, const Current& current) +CallbackI::initiateCallbackExAsync(shared_ptr proxy, + function response, + function error, + const Current& current) { if(proxy->ice_isTwoway()) { - AsyncCBPtr acb = new AsyncCB(); - proxy->begin_callbackEx(current.ctx, - newCallback_CallbackReceiver_callbackEx(acb, &AsyncCB::responseCallbackEx, &AsyncCB::exceptionCallbackEx), - newCookie(cb)); + proxy->callbackExAsync(std::move(response), std::move(error), nullptr, current.ctx); } else { proxy->callbackEx(current.ctx); - cb->ice_response(); + response(); } } void -CallbackI::initiateConcurrentCallback_async(const AMD_Callback_initiateConcurrentCallbackPtr& cb, - Int number, - const CallbackReceiverPrx& proxy, - const Current& current) +CallbackI::initiateConcurrentCallbackAsync(int number, shared_ptr proxy, + function response, + function error, + const Current& current) { - AsyncCBPtr acb = new AsyncCB(); - proxy->begin_concurrentCallback(number, current.ctx, - newCallback_CallbackReceiver_concurrentCallback(acb, &AsyncCB::responseConcurrentCallback, - &AsyncCB::exceptionConcurrentCallback), - newCookie(cb)); + proxy->concurrentCallbackAsync(number, std::move(response), std::move(error), nullptr, current.ctx); } void -CallbackI::initiateWaitCallback_async(const AMD_Callback_initiateWaitCallbackPtr& cb, - const CallbackReceiverPrx& proxy, - const Current& current) +CallbackI::initiateWaitCallbackAsync(shared_ptr proxy, + function response, + function error, + const Current& current) { - AsyncCBPtr acb = new AsyncCB(); - proxy->begin_waitCallback(current.ctx, - newCallback_CallbackReceiver_waitCallback(acb, &AsyncCB::responseWaitCallback, &AsyncCB::exceptionWaitCallback), - newCookie(cb)); + proxy->waitCallbackAsync(std::move(response), std::move(error), nullptr, current.ctx); } void -CallbackI::initiateCallbackWithPayload_async(const AMD_Callback_initiateCallbackWithPayloadPtr& cb, - const CallbackReceiverPrx& proxy, - const Current& current) +CallbackI::initiateCallbackWithPayloadAsync(shared_ptr proxy, + function response, + function error, + const Current& current) { Ice::ByteSeq seq(1000 * 1024, 0); - AsyncCBPtr acb = new AsyncCB(); - proxy->begin_callbackWithPayload(seq, current.ctx, - newCallback_CallbackReceiver_callbackWithPayload(acb, &AsyncCB::responseCallbackWithPayload, - &AsyncCB::exceptionCallbackWithPayload), - newCookie(cb)); + proxy->callbackWithPayloadAsync(seq, std::move(response), std::move(error), nullptr, current.ctx); } void diff --git a/cpp/test/Glacier2/router/CallbackI.h b/cpp/test/Glacier2/router/CallbackI.h index 31ea2c3ecd3..a8380d3fe2a 100644 --- a/cpp/test/Glacier2/router/CallbackI.h +++ b/cpp/test/Glacier2/router/CallbackI.h @@ -5,25 +5,20 @@ #ifndef CALLBACK_I_H #define CALLBACK_I_H -#include -#include #include #include -class CallbackReceiverI : public ::Test::CallbackReceiver, public IceUtil::Monitor +class CallbackReceiverI final : public Test::CallbackReceiver { public: - CallbackReceiverI(); + void callback(const Ice::Current&) override; + void callbackEx(const Ice::Current&) override; + void concurrentCallbackAsync(int, std::function, std::function, + const ::Ice::Current&) override; - virtual void callback(const Ice::Current&); - virtual void callbackEx(const Ice::Current&); - virtual void concurrentCallback_async(const ::Test::AMD_CallbackReceiver_concurrentCallbackPtr&, - Ice::Int, - const ::Ice::Current&); - - virtual void waitCallback(const ::Ice::Current&); - virtual void callbackWithPayload(const Ice::ByteSeq&, const ::Ice::Current&); + void waitCallback(const ::Ice::Current&) override; + void callbackWithPayload(Ice::ByteSeq, const ::Ice::Current&) override; void callbackOK(int = 1); void waitCallbackOK(); @@ -33,36 +28,41 @@ class CallbackReceiverI : public ::Test::CallbackReceiver, public IceUtil::Monit private: - int _callback; - bool _waitCallback; - bool _callbackWithPayload; - bool _finishWaitCallback; - std::vector > _callbacks; + int _callback = 0; + bool _waitCallback = false; + bool _callbackWithPayload = false; + bool _finishWaitCallback = false; + std::vector, std::function, int>> _callbacks; + + std::mutex _mutex; + std::condition_variable _condVar; }; -typedef IceUtil::Handle CallbackReceiverIPtr; -class CallbackI : public ::Test::Callback +class CallbackI final : public ::Test::Callback { public: - CallbackI(); - - virtual void initiateCallback_async(const ::Test::AMD_Callback_initiateCallbackPtr&, - const ::Test::CallbackReceiverPrx&, const Ice::Current&); - virtual void initiateCallbackEx_async(const ::Test::AMD_Callback_initiateCallbackExPtr&, - const ::Test::CallbackReceiverPrx&, const Ice::Current&); - virtual void initiateConcurrentCallback_async(const ::Test::AMD_Callback_initiateConcurrentCallbackPtr&, - Ice::Int, - const ::Test::CallbackReceiverPrx&, - const ::Ice::Current&); - virtual void initiateWaitCallback_async(const ::Test::AMD_Callback_initiateWaitCallbackPtr&, - const ::Test::CallbackReceiverPrx&, - const ::Ice::Current&); - virtual void initiateCallbackWithPayload_async(const ::Test::AMD_Callback_initiateCallbackWithPayloadPtr&, - const ::Test::CallbackReceiverPrx&, - const ::Ice::Current&); - - virtual void shutdown(const Ice::Current&); + void initiateCallbackAsync(std::shared_ptr, + std::function, std::function, + const Ice::Current&) override; + + void initiateCallbackExAsync(std::shared_ptr, + std::function, std::function, + const Ice::Current&) override; + + void initiateConcurrentCallbackAsync(int, std::shared_ptr, + std::function, std::function, + const Ice::Current&) override; + + void initiateWaitCallbackAsync(std::shared_ptr, + std::function, std::function, + const Ice::Current&) override; + + void initiateCallbackWithPayloadAsync(std::shared_ptr, + std::function, std::function, + const Ice::Current&) override; + + void shutdown(const Ice::Current&) override; }; #endif diff --git a/cpp/test/Glacier2/router/Client.cpp b/cpp/test/Glacier2/router/Client.cpp index 44c2b214d2e..fd1977e96e3 100644 --- a/cpp/test/Glacier2/router/Client.cpp +++ b/cpp/test/Glacier2/router/Client.cpp @@ -2,113 +2,108 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include -#include #include #include #include #include +#include +#include +#include using namespace std; +using namespace std::chrono_literals; using namespace Ice; using namespace Test; static Ice::InitializationData initData; -class AsyncCallback : public IceUtil::Monitor, public IceUtil::Shared +class AsyncCallback final { public: - AsyncCallback() : - _haveResponse(false) - { - } - void - response(Int response) + response(int val) { - Lock sync(*this); - _haveResponse = true; - _response = response; - notify(); + { + lock_guard lg(_mutex); + _haveResponse = true; + _response = val; + } + _condVar.notify_one(); } void - exception(const Exception& e) + error(exception_ptr e) { - Lock sync(*this); - _haveResponse = true; - _ex.reset(e.ice_clone()); - notify(); + { + lock_guard lg(_mutex); + _haveResponse = true; + _exception = e; + } + _condVar.notify_one(); } int - waitResponse() const + waitResponse() { - Lock sync(*this); + unique_lock lock(_mutex); while(!_haveResponse) { - wait(); + _condVar.wait(lock); } - if(_ex.get()) + if(_exception) { - _ex->ice_throw(); + rethrow_exception(_exception); } return _response; } private: - bool _haveResponse; - IceInternal::UniquePtr _ex; - Int _response; + bool _haveResponse = false; + exception_ptr _exception = nullptr; + int _response = -1; + mutex _mutex; + condition_variable _condVar; }; -typedef IceUtil::Handle AsyncCallbackPtr; -class MisbehavedClient : public IceUtil::Thread, public IceUtil::Monitor +class MisbehavedClient final { public: - MisbehavedClient(int id) : _id(id), _callback(false) + explicit MisbehavedClient(int id) : _id(id) { } - virtual void run() { - CommunicatorPtr communicator = initialize(initData); - ObjectPrx routerBase = communicator->stringToProxy( + auto communicator = initialize(initData); + auto routerBase = communicator->stringToProxy( "Glacier2/router:" + TestHelper::getTestEndpoint(communicator->getProperties(), 50)); - Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(routerBase); + auto router = checkedCast(routerBase); communicator->setDefaultRouter(router); ostringstream os; os << "userid-" << _id; - Glacier2::SessionPrx session = router->createSession(os.str(), "abc123"); + auto session = router->createSession(os.str(), "abc123"); communicator->getProperties()->setProperty("Ice.PrintAdapterReady", ""); - ObjectAdapterPtr adapter = communicator->createObjectAdapterWithRouter("CallbackReceiverAdapter", router); + auto adapter = communicator->createObjectAdapterWithRouter("CallbackReceiverAdapter", router); adapter->activate(); - // - // Verify that the generated end_ method is exported properly - see bug 4719. - // - Ice::AsyncResultPtr r = router->begin_getCategoryForClient(); - string category = router->end_getCategoryForClient(r); + string category = router->getCategoryForClient(); { - Lock sync(*this); - _callbackReceiver = new CallbackReceiverI; - notify(); + lock_guard lg(_mutex); + _callbackReceiver = make_shared(); } + _condVar.notify_one(); - Identity ident; - ident.name = "callbackReceiver"; - ident.category = category; - CallbackReceiverPrx receiver = CallbackReceiverPrx::uncheckedCast(adapter->add(_callbackReceiver, ident)); + Identity ident = {"callbackReceiver", category}; + auto receiver = uncheckedCast(adapter->add(_callbackReceiver, ident)); - ObjectPrx base = communicator->stringToProxy( + auto base = communicator->stringToProxy( "c1/callback:" + TestHelper::getTestEndpoint(communicator->getProperties())); base = base->ice_oneway(); - CallbackPrx callback = CallbackPrx::uncheckedCast(base); + auto callback = uncheckedCast(base); // // Block the CallbackReceiver in wait() to prevent the client from @@ -121,10 +116,10 @@ class MisbehavedClient : public IceUtil::Thread, public IceUtil::Monitor lg(_mutex); _callback = true; - notify(); } + _condVar.notify_one(); // // Callback the client with a large payload. This should cause @@ -156,96 +151,90 @@ class MisbehavedClient : public IceUtil::Thread, public IceUtil::Monitor lock(_mutex); + while(!_callback) { - Lock sync(*this); - while(!_callback) - { - wait(); - } + _condVar.wait(lock); } } private: int _id; - CallbackReceiverIPtr _callbackReceiver; - bool _callback; + shared_ptr _callbackReceiver; + bool _callback = false; + mutex _mutex; + condition_variable _condVar; }; -typedef IceUtil::Handle MisbehavedClientPtr; -class StressClient : public IceUtil::Thread, public IceUtil::Monitor +class StressClient { public: - StressClient(int id) : _id(id), _initialized(false), _notified(false) + explicit StressClient(int id) : _id(id) { } - virtual void run() { - CommunicatorPtr communicator = initialize(initData); - ObjectPrx routerBase = communicator->stringToProxy( + auto communicator = initialize(initData); + auto routerBase = communicator->stringToProxy( "Glacier2/router:" + TestHelper::getTestEndpoint(communicator->getProperties(), 50)); - _router = Glacier2::RouterPrx::checkedCast(routerBase); + _router = checkedCast(routerBase); communicator->setDefaultRouter(_router); ostringstream os; os << "userid-" << _id; - Glacier2::SessionPrx session = _router->createSession(os.str(), "abc123"); + auto session = _router->createSession(os.str(), "abc123"); communicator->getProperties()->setProperty("Ice.PrintAdapterReady", ""); - ObjectAdapterPtr adapter = communicator->createObjectAdapterWithRouter("CallbackReceiverAdapter", _router); + auto adapter = communicator->createObjectAdapterWithRouter("CallbackReceiverAdapter", _router); adapter->activate(); string category = _router->getCategoryForClient(); - _callbackReceiver = new CallbackReceiverI; - Identity ident; - ident.name = "callbackReceiver"; - ident.category = category; - CallbackReceiverPrx receiver = CallbackReceiverPrx::uncheckedCast(adapter->add(_callbackReceiver, ident)); + _callbackReceiver = make_shared(); + Identity ident = {"callbackReceiver", category}; + auto receiver = uncheckedCast(adapter->add(_callbackReceiver, ident)); - ObjectPrx base = communicator->stringToProxy( + auto base = communicator->stringToProxy( "c1/callback:" + TestHelper::getTestEndpoint(communicator->getProperties())); base = base->ice_oneway(); - CallbackPrx callback = CallbackPrx::uncheckedCast(base); + auto callback = uncheckedCast(base); { - Lock sync(*this); + lock_guard lg(_mutex); _initialized = true; - notifyAll(); } + _condVar.notify_all(); + { - Lock sync(*this); + unique_lock lock(_mutex); while(!_notified) { - wait(); + _condVar.wait(lock); } } // // Stress the router until the connection is closed. // - stress(callback, receiver); + stress(std::move(callback), std::move(receiver)); communicator->destroy(); } - virtual void stress(const CallbackPrx& callback, const CallbackReceiverPrx&) = 0; + virtual void stress(shared_ptr callback, shared_ptr) = 0; void notifyThread() { { - Lock sync(*this); + unique_lock lock(_mutex); while(!_initialized) { - wait(); + _condVar.wait(lock); } - } - { - Lock sync(*this); _notified = true; - notify(); } + _condVar.notify_one(); } void @@ -272,34 +261,35 @@ class StressClient : public IceUtil::Thread, public IceUtil::Monitor _router; int _id; - CallbackReceiverIPtr _callbackReceiver; - bool _initialized; - bool _notified; + shared_ptr _callbackReceiver; + bool _initialized = false; + bool _notified = false; + mutex _mutex; + condition_variable _condVar; }; -typedef IceUtil::Handle StressClientPtr; -class PingStressClient : public StressClient +class PingStressClient final : public StressClient { public: - PingStressClient(int id) : StressClient(id) + explicit PingStressClient(int id) : StressClient(id) { } - virtual void - stress(const CallbackPrx& callback, const CallbackReceiverPrx&) + void + stress(shared_ptr callback, shared_ptr) override { try { - CallbackPrx cb = CallbackPrx::uncheckedCast(callback->ice_twoway()); + auto cb = callback->ice_twoway(); Context context; context["_fwd"] = "t"; while(true) { cb->ice_ping(context); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(1)); + this_thread::sleep_for(1ms); } } catch(const Ice::ConnectionLostException&) @@ -319,27 +309,27 @@ class PingStressClient : public StressClient } }; -class CallbackStressClient : public StressClient +class CallbackStressClient final : public StressClient { public: - CallbackStressClient(int id) : StressClient(id) + explicit CallbackStressClient(int id) : StressClient(id) { } - virtual void - stress(const CallbackPrx& callback, const CallbackReceiverPrx& receiver) + void + stress(shared_ptr callback, shared_ptr receiver) override { try { - CallbackPrx cb = CallbackPrx::uncheckedCast(callback->ice_twoway()); + auto cb = callback->ice_twoway(); Context context; context["_fwd"] = "t"; while(true) { cb->initiateCallback(receiver, context); _callbackReceiver->callbackOK(); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(1)); + this_thread::sleep_for(1ms); } } catch(const Ice::ConnectionLostException&) @@ -363,27 +353,27 @@ class CallbackStressClient : public StressClient } }; -class CallbackWithPayloadStressClient : public StressClient +class CallbackWithPayloadStressClient final : public StressClient { public: - CallbackWithPayloadStressClient(int id) : StressClient(id) + explicit CallbackWithPayloadStressClient(int id) : StressClient(id) { } - virtual void - stress(const CallbackPrx& callback, const CallbackReceiverPrx& receiver) + void + stress(shared_ptr callback, shared_ptr receiver) override { try { - CallbackPrx cb = CallbackPrx::uncheckedCast(callback->ice_twoway()); + auto cb = callback->ice_twoway(); Context context; context["_fwd"] = "t"; while(true) { cb->initiateCallbackWithPayload(receiver, context); _callbackReceiver->callbackWithPayloadOK(); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(10)); + this_thread::sleep_for(10ms); } } catch(const Ice::ConnectionLostException&) @@ -407,11 +397,11 @@ class CallbackWithPayloadStressClient : public StressClient } }; -class CallbackClient : public Test::TestHelper +class CallbackClient final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -426,26 +416,26 @@ CallbackClient::run(int argc, char** argv) initData.properties->setProperty("Ice.Warn.Connections", "0"); Ice::CommunicatorHolder communicator = initialize(argc, argv, initData); - ObjectPrx routerBase; + shared_ptr routerBase; { cout << "testing stringToProxy for router... " << flush; routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50)); cout << "ok" << endl; } - Glacier2::RouterPrx router; + shared_ptr router; { cout << "testing checked cast for router... " << flush; - router = Glacier2::RouterPrx::checkedCast(routerBase); + router = checkedCast(routerBase); test(router); cout << "ok" << endl; } { cout << "testing router finder... " << flush; - Ice::RouterFinderPrx finder = - RouterFinderPrx::uncheckedCast(communicator->stringToProxy("Ice/RouterFinder:" + getTestEndpoint(50))); + auto finder = + uncheckedCast(communicator->stringToProxy("Ice/RouterFinder:" + getTestEndpoint(50))); test(finder->getRouter()->ice_getIdentity() == router->ice_getIdentity()); cout << "ok" << endl; } @@ -458,13 +448,13 @@ CallbackClient::run(int argc, char** argv) { cout << "getting the session timeout... " << flush; - Ice::Long sessionTimeout = router->getSessionTimeout(); - Ice::Long acmTimeout = router->getACMTimeout(); + auto sessionTimeout = router->getSessionTimeout(); + auto acmTimeout = router->getACMTimeout(); test(sessionTimeout == 30 && sessionTimeout == acmTimeout); cout << "ok" << endl; } - ObjectPrx base; + shared_ptr base; { cout << "testing stringToProxy for server object... " << flush; @@ -485,7 +475,7 @@ CallbackClient::run(int argc, char** argv) } } - Glacier2::SessionPrx session; + shared_ptr session; { cout << "trying to create session with wrong password... " << flush; @@ -548,7 +538,7 @@ CallbackClient::run(int argc, char** argv) { cout << "pinging object with client endpoint... " << flush; - Ice::ObjectPrx baseC = communicator->stringToProxy("collocated:" + getTestEndpoint(50)); + auto baseC = communicator->stringToProxy("collocated:" + getTestEndpoint(50)); try { baseC->ice_ping(); @@ -559,16 +549,16 @@ CallbackClient::run(int argc, char** argv) cout << "ok" << endl; } - CallbackPrx twoway; + shared_ptr twoway; { cout << "testing checked cast for server object... " << flush; - twoway = CallbackPrx::checkedCast(base); + twoway = checkedCast(base); test(twoway); cout << "ok" << endl; } - ObjectAdapterPtr adapter; + shared_ptr adapter; { cout << "creating and activating callback receiver adapter with router... " << flush; @@ -586,37 +576,31 @@ CallbackClient::run(int argc, char** argv) cout << "ok" << endl; } - CallbackReceiverI* callbackReceiverImpl; - ObjectPtr callbackReceiver; - CallbackReceiverPrx twowayR; - CallbackReceiverPrx fakeTwowayR; + shared_ptr callbackReceiver; + shared_ptr twowayR; + shared_ptr fakeTwowayR; { cout << "creating and adding callback receiver object... " << flush; - callbackReceiverImpl = new CallbackReceiverI; - callbackReceiver = callbackReceiverImpl; - Identity callbackReceiverIdent; - callbackReceiverIdent.name = "callbackReceiver"; - callbackReceiverIdent.category = category; - twowayR = CallbackReceiverPrx::uncheckedCast(adapter->add(callbackReceiver, callbackReceiverIdent)); - Identity fakeCallbackReceiverIdent; - fakeCallbackReceiverIdent.name = "callbackReceiver"; - fakeCallbackReceiverIdent.category = "dummy"; - fakeTwowayR = CallbackReceiverPrx::uncheckedCast(adapter->add(callbackReceiver, fakeCallbackReceiverIdent)); + callbackReceiver = make_shared(); + Identity callbackReceiverIdent = {"callbackReceiver", category}; + twowayR = uncheckedCast(adapter->add(callbackReceiver, callbackReceiverIdent)); + Identity fakeCallbackReceiverIdent = {"callbackReceiver", "dummy"}; + fakeTwowayR = uncheckedCast(adapter->add(callbackReceiver, fakeCallbackReceiverIdent)); cout << "ok" << endl; } { cout << "testing oneway callback... " << flush; - CallbackPrx oneway = CallbackPrx::uncheckedCast(twoway->ice_oneway()); - CallbackReceiverPrx onewayR = CallbackReceiverPrx::uncheckedCast(twowayR->ice_oneway()); + auto oneway = twoway->ice_oneway(); + auto onewayR = twowayR->ice_oneway(); Context context; context["_fwd"] = "o"; oneway->initiateCallback(onewayR, context); oneway->initiateCallback(onewayR, context); oneway->initiateCallback(onewayR, context); oneway->initiateCallback(onewayR, context); - callbackReceiverImpl->callbackOK(4); + callbackReceiver->callbackOK(4); cout << "ok" << endl; } @@ -628,7 +612,7 @@ CallbackClient::run(int argc, char** argv) twoway->initiateCallback(twowayR, context); twoway->initiateCallback(twowayR, context); twoway->initiateCallback(twowayR, context); - callbackReceiverImpl->callbackOK(4); + callbackReceiver->callbackOK(4); cout << "ok" << endl; } @@ -636,8 +620,8 @@ CallbackClient::run(int argc, char** argv) cout << "testing batch oneway callback... " << flush; Context context; context["_fwd"] = "O"; - CallbackPrx batchOneway = CallbackPrx::uncheckedCast(twoway->ice_batchOneway()); - CallbackReceiverPrx onewayR = CallbackReceiverPrx::uncheckedCast(twowayR->ice_oneway()); + auto batchOneway = twoway->ice_batchOneway(); + auto onewayR = twowayR->ice_oneway(); batchOneway->initiateCallback(onewayR, context); batchOneway->initiateCallback(onewayR, context); batchOneway->initiateCallback(onewayR, context); @@ -645,7 +629,7 @@ CallbackClient::run(int argc, char** argv) batchOneway->initiateCallback(onewayR, context); batchOneway->initiateCallback(onewayR, context); batchOneway->ice_flushBatchRequests(); - callbackReceiverImpl->callbackOK(6); + callbackReceiver->callbackOK(6); cout << "ok" << endl; } @@ -659,19 +643,28 @@ CallbackClient::run(int argc, char** argv) cout << "testing concurrent twoway callback... " << flush; Context context; context["_fwd"] = "t"; - AsyncCallbackPtr cb0 = new AsyncCallback(); - twoway->begin_initiateConcurrentCallback(0, twowayR, context, - newCallback_Callback_initiateConcurrentCallback(cb0, &AsyncCallback::response, &AsyncCallback::exception)); - AsyncCallbackPtr cb1 = new AsyncCallback(); - twoway->begin_initiateConcurrentCallback(1, twowayR, context, - newCallback_Callback_initiateConcurrentCallback(cb1, &AsyncCallback::response, &AsyncCallback::exception)); - AsyncCallbackPtr cb2 = new AsyncCallback(); - twoway->begin_initiateConcurrentCallback(2, twowayR, context, - newCallback_Callback_initiateConcurrentCallback(cb2, &AsyncCallback::response, &AsyncCallback::exception)); - callbackReceiverImpl->answerConcurrentCallbacks(3); - test(cb0->waitResponse() == 0); - test(cb1->waitResponse() == 1); - test(cb2->waitResponse() == 2); + AsyncCallback cb0; + twoway->initiateConcurrentCallbackAsync(0, twowayR, + [&cb0](int val){ cb0.response(val); }, + [&cb0](exception_ptr e){ cb0.error(e); }, + nullptr, context); + + AsyncCallback cb1; + twoway->initiateConcurrentCallbackAsync(1, twowayR, + [&cb1](int val){ cb1.response(val); }, + [&cb1](exception_ptr e){ cb1.error(e); }, + nullptr, context); + + AsyncCallback cb2; + twoway->initiateConcurrentCallbackAsync(2, twowayR, + [&cb2](int val){ cb2.response(val); }, + [&cb2](exception_ptr e){ cb2.error(e); }, + nullptr, context); + + callbackReceiver->answerConcurrentCallbacks(3); + test(cb0.waitResponse() == 0); + test(cb1.waitResponse() == 1); + test(cb2.waitResponse() == 2); cout << "ok" << endl; } @@ -689,7 +682,7 @@ CallbackClient::run(int argc, char** argv) test(ex.someValue == 3.14); test(ex.someString == "3.14"); } - callbackReceiverImpl->callbackOK(); + callbackReceiver->callbackOK(); cout << "ok" << endl; } @@ -712,10 +705,10 @@ CallbackClient::run(int argc, char** argv) cout << "testing whether other allowed category is accepted... " << flush; Context context; context["_fwd"] = "t"; - CallbackPrx otherCategoryTwoway = CallbackPrx::uncheckedCast( + auto otherCategoryTwoway = uncheckedCast( twoway->ice_identity(stringToIdentity("c2/callback"))); otherCategoryTwoway->initiateCallback(twowayR, context); - callbackReceiverImpl->callbackOK(); + callbackReceiver->callbackOK(); cout << "ok" << endl; } @@ -725,7 +718,7 @@ CallbackClient::run(int argc, char** argv) context["_fwd"] = "t"; try { - CallbackPrx otherCategoryTwoway = CallbackPrx::uncheckedCast( + auto otherCategoryTwoway = uncheckedCast( twoway->ice_identity(stringToIdentity("c3/callback"))); otherCategoryTwoway->initiateCallback(twowayR, context); test(false); @@ -740,10 +733,10 @@ CallbackClient::run(int argc, char** argv) cout << "testing whether user-id as category is accepted... " << flush; Context context; context["_fwd"] = "t"; - CallbackPrx otherCategoryTwoway = CallbackPrx::uncheckedCast( + auto otherCategoryTwoway = uncheckedCast( twoway->ice_identity(stringToIdentity("_userid/callback"))); otherCategoryTwoway->initiateCallback(twowayR, context); - callbackReceiverImpl->callbackOK(); + callbackReceiver->callbackOK(); cout << "ok" << endl; } @@ -753,21 +746,21 @@ CallbackClient::run(int argc, char** argv) // // Start 3 misbehaving clients. // + MisbehavedClient clients[] = {MisbehavedClient(0), MisbehavedClient(1), MisbehavedClient(2)}; + std::future futures[3] = {}; const int nClients = 3; // Passwords need to be added to the password file if more clients are needed. - int i; - vector clients; - for(i = 0; i < nClients; ++i) + for(int i = 0; i < nClients; ++i) { - clients.push_back(new MisbehavedClient(i)); - clients.back()->start(); - clients.back()->waitForCallback(); + auto& client = clients[i]; + futures[i] = std::async(launch::async, [&client]{ client.run(); }); + client.waitForCallback(); } // // Sleep for one second to make sure the router starts sending // the callback with the payload to the clients. // - IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(1)); + this_thread::sleep_for(1s); // // Initiate few callbacks with a large payload. Because of @@ -778,18 +771,18 @@ CallbackClient::run(int argc, char** argv) Context context; context["_fwd"] = "t"; twoway->initiateCallbackWithPayload(twowayR, context); - callbackReceiverImpl->callbackWithPayloadOK(); + callbackReceiver->callbackWithPayloadOK(); twoway->initiateCallbackWithPayload(twowayR, context); - callbackReceiverImpl->callbackWithPayloadOK(); + callbackReceiver->callbackWithPayloadOK(); twoway->initiateCallbackWithPayload(twowayR, context); - callbackReceiverImpl->callbackWithPayloadOK(); + callbackReceiver->callbackWithPayloadOK(); twoway->initiateCallbackWithPayload(twowayR, context); - callbackReceiverImpl->callbackWithPayloadOK(); + callbackReceiver->callbackWithPayloadOK(); - for(vector::const_iterator p = clients.begin(); p != clients.end(); ++p) + for(int i = 0; i < nClients; ++i) { - (*p)->notifyWaitCallback(); - (*p)->getThreadControl().join(); + clients[i].notifyWaitCallback(); + futures[i].get(); } cout << "ok" << endl; @@ -798,36 +791,38 @@ CallbackClient::run(int argc, char** argv) { cout << "stress test... " << flush; const int nClients = 3; // Passwords need to be added to the password file if more clients are needed. - int i; - vector clients; - for(i = 0; i < nClients; ++i) + vector> clients; + vector> futures; + random_device rd; + for(int i = 0; i < nClients; ++i) { - switch(IceUtilInternal::random(3)) + switch(rd() % 3) { case 0: - clients.push_back(new PingStressClient(i)); + clients.push_back(make_shared(i)); break; case 1: - clients.push_back(new CallbackStressClient(i)); + clients.push_back(make_shared(i)); break; case 2: - clients.push_back(new CallbackWithPayloadStressClient(i)); + clients.push_back(make_shared(i)); break; default: assert(false); break; } - clients.back()->start(); + auto client = clients.back(); + futures.push_back(std::async(launch::async, [client = std::move(client)]{ client->run(); })); } - for(vector::const_iterator p = clients.begin(); p != clients.end(); ++p) + for(const auto& p: clients) { - (*p)->notifyThread(); + p->notifyThread(); } // // Let the stress client run for a bit. // - IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(3)); + this_thread::sleep_for(3s); // // Send some callbacks. @@ -835,15 +830,18 @@ CallbackClient::run(int argc, char** argv) Context context; context["_fwd"] = "t"; twoway->initiateCallback(twowayR); - callbackReceiverImpl->callbackOK(); + callbackReceiver->callbackOK(); // // Kill the stress clients. // - for(vector::const_iterator q = clients.begin(); q != clients.end(); ++q) + for(const auto& p: clients) + { + p->kill(); + } + for(auto& f: futures) { - (*q)->kill(); - (*q)->getThreadControl().join(); + f.get(); } cout << "ok" << endl; @@ -906,7 +904,7 @@ CallbackClient::run(int argc, char** argv) cout << "ok" << endl; } - ObjectPrx processBase; + shared_ptr processBase; { cout << "testing stringToProxy for admin process facet... " << flush; @@ -914,11 +912,11 @@ CallbackClient::run(int argc, char** argv) cout << "ok" << endl; } - Ice::ProcessPrx process; + shared_ptr process; { cout << "testing checked cast for process facet... " << flush; - process = Ice::ProcessPrx::checkedCast(processBase); + process = checkedCast(processBase); test(process); cout << "ok" << endl; } diff --git a/cpp/test/Glacier2/router/Server.cpp b/cpp/test/Glacier2/router/Server.cpp index 3b7afc5a76b..c0021b7591b 100644 --- a/cpp/test/Glacier2/router/Server.cpp +++ b/cpp/test/Glacier2/router/Server.cpp @@ -10,26 +10,26 @@ using namespace std; using namespace Ice; using namespace Test; -class CallbackServer : public Test::TestHelper +class CallbackServer final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void CallbackServer::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); properties->setProperty("Ice.Warn.Connections", "0"); properties->setProperty("Ice.Warn.Dispatch", "0"); Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); communicator->getProperties()->setProperty("CallbackAdapter.Endpoints", getTestEndpoint()); - ObjectAdapterPtr adapter = communicator->createObjectAdapter("CallbackAdapter"); - adapter->add(new CallbackI(), Ice::stringToIdentity("c1/callback")); // The test allows "c1" as category. - adapter->add(new CallbackI(), Ice::stringToIdentity("c2/callback")); // The test allows "c2" as category. - adapter->add(new CallbackI(), Ice::stringToIdentity("c3/callback")); // The test rejects "c3" as category. - adapter->add(new CallbackI(), Ice::stringToIdentity("_userid/callback")); // The test allows the prefixed userid. + auto adapter = communicator->createObjectAdapter("CallbackAdapter"); + adapter->add(make_shared(), Ice::stringToIdentity("c1/callback")); // The test allows "c1" as category. + adapter->add(make_shared(), Ice::stringToIdentity("c2/callback")); // The test allows "c2" as category. + adapter->add(make_shared(), Ice::stringToIdentity("c3/callback")); // The test rejects "c3" as category. + adapter->add(make_shared(), Ice::stringToIdentity("_userid/callback")); // The test allows the prefixed userid. adapter->activate(); communicator->waitForShutdown(); } diff --git a/cpp/test/Glacier2/sessionControl/Client.cpp b/cpp/test/Glacier2/sessionControl/Client.cpp index b6592cde343..711e17056bd 100644 --- a/cpp/test/Glacier2/sessionControl/Client.cpp +++ b/cpp/test/Glacier2/sessionControl/Client.cpp @@ -12,17 +12,17 @@ using namespace std; using namespace Ice; using namespace Test; -class SessionControlClient : public Test::TestHelper +class SessionControlClient final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void SessionControlClient::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); // // We want to check whether the client retries for evicted @@ -34,15 +34,15 @@ SessionControlClient::run(int argc, char** argv) Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); cout << "getting router... " << flush; - ObjectPrx routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50)); - Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(routerBase); + auto routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50)); + auto router = checkedCast(routerBase); test(router); communicator->setDefaultRouter(router); cout << "ok" << endl; cout << "creating session... " << flush; - Glacier2::SessionPrx sessionBase = router->createSession("userid", "abc123"); - Test::SessionPrx session = Test::SessionPrx::uncheckedCast(sessionBase); + auto sessionBase = router->createSession("userid", "abc123"); + auto session = uncheckedCast(sessionBase); test(session); cout << "ok" << endl; @@ -85,11 +85,11 @@ SessionControlClient::run(int argc, char** argv) cout << "ok" << endl; cout << "testing shutdown... " << flush; - session = Test::SessionPrx::uncheckedCast(router->createSession("userid", "abc123")); + session = uncheckedCast(router->createSession("userid", "abc123")); session->shutdown(); communicator->setDefaultRouter(0); - ObjectPrx processBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51)); - Ice::ProcessPrx process = Ice::ProcessPrx::checkedCast(processBase); + auto processBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51)); + auto process = checkedCast(processBase); test(process); process->shutdown(); try diff --git a/cpp/test/Glacier2/sessionControl/Server.cpp b/cpp/test/Glacier2/sessionControl/Server.cpp index 0e05292edc4..b64881f095c 100644 --- a/cpp/test/Glacier2/sessionControl/Server.cpp +++ b/cpp/test/Glacier2/sessionControl/Server.cpp @@ -11,11 +11,11 @@ using namespace std; using namespace Ice; using namespace Test; -class SessionControlServer : public Test::TestHelper +class SessionControlServer final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -23,8 +23,8 @@ SessionControlServer::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); communicator->getProperties()->setProperty("SessionControlAdapter.Endpoints", getTestEndpoint()); - ObjectAdapterPtr adapter = communicator->createObjectAdapter("SessionControlAdapter"); - adapter->add(new SessionManagerI, Ice::stringToIdentity("SessionManager")); + auto adapter = communicator->createObjectAdapter("SessionControlAdapter"); + adapter->add(make_shared(), Ice::stringToIdentity("SessionManager")); adapter->activate(); communicator->waitForShutdown(); } diff --git a/cpp/test/Glacier2/sessionControl/SessionI.cpp b/cpp/test/Glacier2/sessionControl/SessionI.cpp index 5d25ab239ae..6c6e7422b58 100644 --- a/cpp/test/Glacier2/sessionControl/SessionI.cpp +++ b/cpp/test/Glacier2/sessionControl/SessionI.cpp @@ -9,35 +9,8 @@ using namespace std; using namespace Test; -class DestroyCB : public virtual IceUtil::Shared -{ -public: - - DestroyCB(const Test::AMD_Session_destroyFromClientPtr& cb) : _cb(cb) - { - } - - void - response() - { - _cb->ice_response(); - } - - void - exception(const IceUtil::Exception&) - { - test(false); - } - -private: - - Test::AMD_Session_destroyFromClientPtr _cb; -}; - -typedef IceUtil::Handle DestroyCBPtr; - -Glacier2::SessionPrx -SessionManagerI::create(const string& userId, const Glacier2::SessionControlPrx& sessionControl, +shared_ptr +SessionManagerI::create(string userId, shared_ptr sessionControl, const Ice::Current& current) { if(userId == "rejectme") @@ -48,23 +21,19 @@ SessionManagerI::create(const string& userId, const Glacier2::SessionControlPrx& { throw Ice::ObjectNotExistException(__FILE__, __LINE__); } - return Glacier2::SessionPrx::uncheckedCast(current.adapter->addWithUUID(new SessionI(sessionControl))); + return Ice::uncheckedCast(current.adapter->addWithUUID(make_shared(sessionControl))); } -SessionI::SessionI(const Glacier2::SessionControlPrx& sessionControl) : - _sessionControl(sessionControl) +SessionI::SessionI(shared_ptr sessionControl) : + _sessionControl(std::move(sessionControl)) { - assert(sessionControl); + assert(_sessionControl); } void -SessionI::destroyFromClient_async(const Test::AMD_Session_destroyFromClientPtr& cb, const Ice::Current&) +SessionI::destroyFromClientAsync(function response, function, const Ice::Current&) { - DestroyCBPtr asyncCB = new DestroyCB(cb); - Glacier2::Callback_SessionControl_destroyPtr amiCB = Glacier2::newCallback_SessionControl_destroy(asyncCB, - &DestroyCB::response, - &DestroyCB::exception); - _sessionControl->begin_destroy(amiCB); + _sessionControl->destroyAsync(std::move(response), [](exception_ptr){ test(false); }); } void diff --git a/cpp/test/Glacier2/sessionControl/SessionI.h b/cpp/test/Glacier2/sessionControl/SessionI.h index d325ea3ff7d..831f04679b0 100644 --- a/cpp/test/Glacier2/sessionControl/SessionI.h +++ b/cpp/test/Glacier2/sessionControl/SessionI.h @@ -7,27 +7,29 @@ #include -class SessionManagerI : public Glacier2::SessionManager +class SessionManagerI final : public Glacier2::SessionManager { public: - virtual Glacier2::SessionPrx create(const std::string&, const Glacier2::SessionControlPrx&, const Ice::Current&); + std::shared_ptr + create(std::string, std::shared_ptr, const Ice::Current&) override; }; -class SessionI : public Test::Session +class SessionI final : public Test::Session { public: - SessionI(const Glacier2::SessionControlPrx&); + explicit SessionI(std::shared_ptr); - virtual void destroyFromClient_async(const Test::AMD_Session_destroyFromClientPtr&, const Ice::Current&); - virtual void shutdown(const Ice::Current&); + void + destroyFromClientAsync(std::function, std::function, const Ice::Current&) override; - virtual void destroy(const Ice::Current&); + void shutdown(const Ice::Current&) override; + void destroy(const Ice::Current&) override; private: - Glacier2::SessionControlPrx _sessionControl; + std::shared_ptr _sessionControl; }; #endif diff --git a/cpp/test/Glacier2/sessionHelper/Client.cpp b/cpp/test/Glacier2/sessionHelper/Client.cpp index be2b034caae..1777d7bbe99 100644 --- a/cpp/test/Glacier2/sessionHelper/Client.cpp +++ b/cpp/test/Glacier2/sessionHelper/Client.cpp @@ -2,7 +2,6 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include #include #include @@ -11,177 +10,135 @@ #include #include #include +#include +#include #include using namespace std; +using namespace std::chrono_literals; using namespace Test; +class Client; +void notifyClient(); + namespace { -class Notify -{ -public: +Client* instance = nullptr; - virtual ~Notify() - { - } - - virtual void notify() = 0; -}; - -Notify* instance = 0; - -class Dispatcher : -#ifndef ICE_CPP11_MAPPING - public Ice::Dispatcher, -#endif - public IceUtil::Thread +class Dispatcher final { - public: - Dispatcher(): - _destroyed(false) - { - } - - virtual void dispatch( -#ifdef ICE_CPP11_MAPPING - std::function call, -#else - const Ice::DispatcherCallPtr& call, -#endif - const Ice::ConnectionPtr&) + void dispatch(std::function call, const shared_ptr&) { - IceUtil::Monitor::Lock lock(_monitor); - if(_queue.empty()) + bool wasEmpty = false; { - _monitor.notify(); + lock_guard lg(_mutex); + wasEmpty = _queue.empty(); + _queue.push_back(std::move(call)); + } + if(wasEmpty) + { + _condVar.notify_one(); } - _queue.push_back(call); } - virtual void - destroy() + void destroy() { - IceUtil::Monitor::Lock lock(_monitor); - _destroyed = true; - _monitor.notify(); + { + lock_guard lg(_mutex); + _destroyed = true; + } + _condVar.notify_one(); } - virtual void - run() + void run() { - while(1) + for(;;) { -#ifdef ICE_CPP11_MAPPING auto item = nextItem(); - if (!item) - { - break; - } - item(); -#else - Ice::DispatcherCallPtr item = nextItem(); if(!item) { break; } - item->run(); -#endif + item(); } } private: -#ifdef ICE_CPP11_MAPPING - std::function -#else - Ice::DispatcherCallPtr -#endif - nextItem() + std::function nextItem() { - IceUtil::Monitor::Lock lock(_monitor); + unique_lock lock(_mutex); while(_queue.empty()) { if(_destroyed) { - return ICE_NULLPTR; + return nullptr; } - _monitor.wait(); + _condVar.wait(lock); } -#ifdef ICE_CPP11_MAPPING auto item = _queue.front(); -#else - Ice::DispatcherCallPtr item = _queue.front(); -#endif _queue.pop_front(); return item; } - IceUtil::Monitor _monitor; -#ifdef ICE_CPP11_MAPPING list> _queue; -#else - list _queue; -#endif - bool _destroyed; + bool _destroyed = false; + mutex _mutex; + condition_variable _condVar; }; -typedef IceUtil::Handle DispatcherPtr; -class SuccessSessionCallback : public Glacier2::SessionCallback +class SuccessSessionCallback final : public Glacier2::SessionCallback { - public: - virtual void - connected(const Glacier2::SessionHelperPtr&) + void connected(const shared_ptr&) override { cout << "ok" << endl; - instance->notify(); + notifyClient(); } - virtual void - disconnected(const Glacier2::SessionHelperPtr&) + void + disconnected(const shared_ptr&) override { cout << "ok" << endl; - instance->notify(); + notifyClient(); } - virtual void - connectFailed(const Glacier2::SessionHelperPtr&, const Ice::Exception&) + void + connectFailed(const shared_ptr&, const Ice::Exception&) override { test(false); } - virtual void - createdCommunicator(const Glacier2::SessionHelperPtr& session) + void + createdCommunicator(const shared_ptr& session) override { test(session->communicator()); } }; -class AfterShutdownSessionCallback : public Glacier2::SessionCallback +class AfterShutdownSessionCallback final : public Glacier2::SessionCallback { - public: - virtual void - connected(const Glacier2::SessionHelperPtr&) + void + connected(const shared_ptr&) override { test(false); } - virtual void - disconnected(const Glacier2::SessionHelperPtr&) + void + disconnected(const shared_ptr&) override { test(false); } - virtual void - connectFailed(const Glacier2::SessionHelperPtr&, const Ice::Exception& ex) + void + connectFailed(const shared_ptr&, const Ice::Exception& ex) override { try { @@ -190,7 +147,7 @@ class AfterShutdownSessionCallback : public Glacier2::SessionCallback catch(const Ice::ConnectFailedException&) { cout << "ok" << endl; - instance->notify(); + notifyClient(); } catch(...) { @@ -198,32 +155,31 @@ class AfterShutdownSessionCallback : public Glacier2::SessionCallback } } - virtual void - createdCommunicator(const Glacier2::SessionHelperPtr& session) + void + createdCommunicator(const shared_ptr& session) override { test(session->communicator()); } }; -class FailSessionCallback : public Glacier2::SessionCallback +class FailSessionCallback final : public Glacier2::SessionCallback { - public: - virtual void - connected(const Glacier2::SessionHelperPtr&) + void + connected(const shared_ptr&) override { test(false); } - virtual void - disconnected(const Glacier2::SessionHelperPtr&) + void + disconnected(const shared_ptr&) override { test(false); } - virtual void - connectFailed(const Glacier2::SessionHelperPtr&, const Ice::Exception& ex) + void + connectFailed(const shared_ptr&, const Ice::Exception& ex) override { try { @@ -232,7 +188,7 @@ class FailSessionCallback : public Glacier2::SessionCallback catch(const Glacier2::PermissionDeniedException&) { cout << "ok" << endl; - instance->notify(); + notifyClient(); } catch(const Ice::LocalException&) { @@ -240,32 +196,31 @@ class FailSessionCallback : public Glacier2::SessionCallback } } - virtual void - createdCommunicator(const Glacier2::SessionHelperPtr& session) + void + createdCommunicator(const shared_ptr& session) override { test(session->communicator()); } }; -class InterruptConnectCallback : public Glacier2::SessionCallback +class InterruptConnectCallback final : public Glacier2::SessionCallback { - public: - virtual void - connected(const Glacier2::SessionHelperPtr&) + void + connected(const shared_ptr&) override { test(false); } - virtual void - disconnected(const Glacier2::SessionHelperPtr&) + void + disconnected(const shared_ptr&) override { test(false); } - virtual void - connectFailed(const Glacier2::SessionHelperPtr&, const Ice::Exception& ex) + void + connectFailed(const shared_ptr&, const Ice::Exception& ex) override { try { @@ -274,7 +229,7 @@ class InterruptConnectCallback : public Glacier2::SessionCallback catch(const Ice::CommunicatorDestroyedException&) { cout << "ok" << endl; - instance->notify(); + notifyClient(); } catch(...) { @@ -282,8 +237,8 @@ class InterruptConnectCallback : public Glacier2::SessionCallback } } - virtual void - createdCommunicator(const Glacier2::SessionHelperPtr& session) + void + createdCommunicator(const shared_ptr& session) override { test(session->communicator()); } @@ -291,28 +246,32 @@ class InterruptConnectCallback : public Glacier2::SessionCallback } // Anonymous namespace end -class Client : public Test::TestHelper, - public Notify +class Client final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; void notify() { - IceUtil::Monitor::Lock lock(_monitor); - _monitor.notify(); + _condVar.notify_one(); } private: - Glacier2::SessionHelperPtr _session; - Glacier2::SessionFactoryHelperPtr _factory; + shared_ptr _session; + shared_ptr _factory; Ice::InitializationData _initData; - IceUtil::Monitor _monitor; + mutex _mutex; + condition_variable _condVar; }; +void notifyClient() +{ + instance->notify(); +} + void Client::run(int argc, char** argv) { @@ -323,24 +282,21 @@ Client::run(int argc, char** argv) _initData.properties = Ice::createProperties(argc, argv, communicator->getProperties()); _initData.properties->setProperty("Ice.Default.Router", "Glacier2/router:" + getTestEndpoint(50)); - DispatcherPtr dispatcher = new Dispatcher(); - dispatcher->start(); -#ifdef ICE_CPP11_MAPPING - _initData.dispatcher = [dispatcher](std::function call, const std::shared_ptr& conn) - { - dispatcher->dispatch(call, conn); - }; -#else - _initData.dispatcher = dispatcher; -#endif - _factory = ICE_MAKE_SHARED(Glacier2::SessionFactoryHelper, _initData, ICE_MAKE_SHARED(FailSessionCallback)); + Dispatcher dispatcher; + auto dfut = std::async(launch::async, [&dispatcher]{ dispatcher.run(); }); + + _initData.dispatcher = [&dispatcher](std::function call, const std::shared_ptr& conn) + { + dispatcher.dispatch(call, conn); + }; + _factory = make_shared(_initData, make_shared()); // // Test to create a session with wrong userid/password // { - IceUtil::Monitor::Lock lock(_monitor); + unique_lock lock(_mutex); cout << "testing SessionHelper connect with wrong userid/password... " << flush; @@ -348,8 +304,7 @@ Client::run(int argc, char** argv) // // Wait for connectFailed callback // - _monitor.timedWait(IceUtil::Time::seconds(30)); - + _condVar.wait_for(lock, 30s); test(!_session->isConnected()); } _factory->destroy(); @@ -359,31 +314,31 @@ Client::run(int argc, char** argv) // _initData.properties->setProperty("Ice.Default.Router", ""); - _factory = ICE_MAKE_SHARED(Glacier2::SessionFactoryHelper, _initData, ICE_MAKE_SHARED(InterruptConnectCallback)); + _factory = make_shared(_initData, make_shared()); { - IceUtil::Monitor::Lock lock(_monitor); + unique_lock lock(_mutex); cout << "testing SessionHelper connect interrupt... " << flush; _factory->setRouterHost(host); _factory->setPort(getTestPort(_initData.properties, 1)); _factory->setProtocol(protocol); _session = _factory->connect("userid", "abc123"); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100)); + this_thread::sleep_for(100ms); _session->destroy(); // // Wait for connectFailed callback // - _monitor.timedWait(IceUtil::Time::seconds(30)); + _condVar.wait_for(lock, 30s); test(!_session->isConnected()); } _factory->destroy(); - _factory = ICE_MAKE_SHARED(Glacier2::SessionFactoryHelper, _initData, ICE_MAKE_SHARED(SuccessSessionCallback)); + _factory = make_shared(_initData, make_shared()); { - IceUtil::Monitor::Lock lock(_monitor); + unique_lock lock(_mutex); cout << "testing SessionHelper connect... " << flush; _factory->setRouterHost(host); _factory->setPort(getTestPort(_initData.properties, 50)); @@ -393,7 +348,7 @@ Client::run(int argc, char** argv) // // Wait for connect callback // - _monitor.timedWait(IceUtil::Time::seconds(30)); + _condVar.wait_for(lock, 30s); cout << "testing SessionHelper isConnected after connect... " << flush; test(_session->isConnected()); @@ -413,7 +368,7 @@ Client::run(int argc, char** argv) test(!_session->session()); cout << "testing stringToProxy for server object... " << flush; - Ice::ObjectPrxPtr base = + auto base = _session->communicator()->stringToProxy("callback:" + getTestEndpoint(_session->communicator()->getProperties())); cout << "ok" << endl; @@ -422,7 +377,7 @@ Client::run(int argc, char** argv) cout << "ok" << endl; cout << "testing checked cast for server object... " << flush; - CallbackPrxPtr twoway = ICE_CHECKED_CAST(CallbackPrx, base); + auto twoway = Ice::checkedCast(base); test(twoway); cout << "ok" << endl; @@ -437,7 +392,7 @@ Client::run(int argc, char** argv) // // Wait for disconnected callback // - _monitor.wait(); + _condVar.wait(lock); cout << "testing SessionHelper isConnected after destroy... " << flush; test(_session->isConnected() == false); @@ -455,7 +410,7 @@ Client::run(int argc, char** argv) cout << "ok" << endl; cout << "testing SessionHelper session after destroy... " << flush; - test(_session->session() == ICE_NULLPTR); + test(_session->session() == nullptr); cout << "ok" << endl; cout << "testing SessionHelper communicator after destroy... " << flush; @@ -471,20 +426,20 @@ Client::run(int argc, char** argv) cout << "ok" << endl; cout << "uninstalling router with communicator... " << flush; - communicator->setDefaultRouter(0); + communicator->setDefaultRouter(nullptr); cout << "ok" << endl; - Ice::ObjectPrxPtr processBase; + shared_ptr processBase; { cout << "testing stringToProxy for process object... " << flush; processBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51)); cout << "ok" << endl; } - Ice::ProcessPrxPtr process; + shared_ptr process; { cout << "testing checked cast for admin object... " << flush; - process = ICE_CHECKED_CAST(Ice::ProcessPrx, processBase); + process = Ice::checkedCast(processBase); test(process != 0); cout << "ok" << endl; } @@ -504,15 +459,15 @@ Client::run(int argc, char** argv) _factory->destroy(); - _factory = ICE_MAKE_SHARED(Glacier2::SessionFactoryHelper, _initData, ICE_MAKE_SHARED(AfterShutdownSessionCallback)); + _factory = make_shared( _initData, make_shared()); // // Wait a bit to ensure glaci2router has been shutdown. // - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100)); + this_thread::sleep_for(100ms); { - IceUtil::Monitor::Lock lock(_monitor); + unique_lock lock(_mutex); cout << "testing SessionHelper connect after router shutdown... " << flush; _factory->setRouterHost(host); _factory->setPort(getTestPort(_initData.properties, 50)); @@ -522,7 +477,7 @@ Client::run(int argc, char** argv) // // Wait for connectFailed callback // - _monitor.wait(); + _condVar.wait(lock); cout << "testing SessionHelper isConnect after connect failure... " << flush; test(_session->isConnected() == false); @@ -547,11 +502,9 @@ Client::run(int argc, char** argv) _factory->destroy(); - if(dispatcher) - { - dispatcher->destroy(); - dispatcher->getThreadControl().join(); - } + // Wait for std::async thread to complete: + dispatcher.destroy(); + dfut.get(); } DEFINE_TEST(Client) diff --git a/cpp/test/Glacier2/sessionHelper/Server.cpp b/cpp/test/Glacier2/sessionHelper/Server.cpp index dd510c28337..df94ef27022 100644 --- a/cpp/test/Glacier2/sessionHelper/Server.cpp +++ b/cpp/test/Glacier2/sessionHelper/Server.cpp @@ -2,7 +2,6 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include #include #include #include @@ -13,25 +12,24 @@ using namespace Test; namespace { -class CallbackI : public Callback +class CallbackI final : public Callback { - public: - virtual void - initiateCallback(ICE_IN(CallbackReceiverPrxPtr) proxy, const Ice::Current& current) + void + initiateCallback(shared_ptr proxy, const Ice::Current& current) override { proxy->callback(current.ctx); } - virtual void - initiateCallbackEx(ICE_IN(CallbackReceiverPrxPtr) proxy, const Ice::Current& current) + void + initiateCallbackEx(shared_ptr proxy, const Ice::Current& current) override { proxy->callbackEx(current.ctx); } - virtual void - shutdown(const Ice::Current& current) + void + shutdown(const Ice::Current& current) override { current.adapter->getCommunicator()->shutdown(); } @@ -39,11 +37,11 @@ class CallbackI : public Callback } -class Server : public Test::TestHelper +class Server final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -54,7 +52,7 @@ Server::run(int argc, char** argv) communicator->createObjectAdapter("DeactivatedAdapter"); communicator->getProperties()->setProperty("CallbackAdapter.Endpoints", getTestEndpoint()); - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("CallbackAdapter"); + auto adapter = communicator->createObjectAdapter("CallbackAdapter"); adapter->add(ICE_MAKE_SHARED(CallbackI), Ice::stringToIdentity("callback")); adapter->activate(); communicator->waitForShutdown(); diff --git a/cpp/test/Glacier2/ssl/Client.cpp b/cpp/test/Glacier2/ssl/Client.cpp index bace1ce9100..0f6147c2e72 100644 --- a/cpp/test/Glacier2/ssl/Client.cpp +++ b/cpp/test/Glacier2/ssl/Client.cpp @@ -10,21 +10,21 @@ using namespace std; using namespace Ice; using namespace Test; -class Client : public Test::TestHelper +class Client final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Client::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); properties->setProperty("Ice.Warn.Connections", "0"); Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); - Glacier2::RouterPrx router = Glacier2::RouterPrx::uncheckedCast( + auto router = uncheckedCast( communicator->stringToProxy("Glacier2/router:" + getTestEndpoint("tcp"))); communicator->setDefaultRouter(router); @@ -34,7 +34,7 @@ Client::run(int argc, char** argv) cout << "creating non-ssl session with tcp connection... "; try { - Glacier2::SessionPrx session = router->createSession("nossl", ""); + auto session = router->createSession("nossl", ""); session->ice_ping(); router->destroySession(); } @@ -47,7 +47,7 @@ Client::run(int argc, char** argv) cout << "creating ssl session with tcp connection... "; try { - Glacier2::SessionPrx session = router->createSessionFromSecureConnection(); + auto session = router->createSessionFromSecureConnection(); test(false); } catch(const Glacier2::PermissionDeniedException&) @@ -59,8 +59,8 @@ Client::run(int argc, char** argv) // Switch to using the SSL router. First, clear the router. Then // set a new SSL based router. // - communicator->setDefaultRouter(Glacier2::RouterPrx()); - router = Glacier2::RouterPrx::uncheckedCast( + communicator->setDefaultRouter(nullptr); + router = uncheckedCast( communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(1, "ssl"))); communicator->setDefaultRouter(router); @@ -70,7 +70,7 @@ Client::run(int argc, char** argv) cout << "creating non-ssl session with ssl connection... "; try { - Glacier2::SessionPrx session = router->createSession("ssl", ""); + auto session = router->createSession("ssl", ""); session->ice_ping(); router->destroySession(); } @@ -83,7 +83,7 @@ Client::run(int argc, char** argv) cout << "creating ssl session with ssl connection... "; try { - Glacier2::SessionPrx session = router->createSessionFromSecureConnection(); + auto session = router->createSessionFromSecureConnection(); session->ice_ping(); router->destroySession(); } @@ -93,8 +93,8 @@ Client::run(int argc, char** argv) } cout << "ok" << endl; - communicator->setDefaultRouter(0); - Ice::ProcessPrx process = Ice::ProcessPrx::checkedCast( + communicator->setDefaultRouter(nullptr); + auto process = checkedCast( communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(2, "tcp"))); process->shutdown(); } diff --git a/cpp/test/Glacier2/ssl/Server.cpp b/cpp/test/Glacier2/ssl/Server.cpp index cec0703fe1a..5f7d0744da4 100644 --- a/cpp/test/Glacier2/ssl/Server.cpp +++ b/cpp/test/Glacier2/ssl/Server.cpp @@ -14,7 +14,7 @@ using namespace Test; namespace { -void testContext(bool ssl, const Ice::CommunicatorPtr& communicator, const Ice::Context& context) +void testContext(bool ssl, const shared_ptr& communicator, const Ice::Context& context) { Ice::Context ctx = context; if(!ssl) @@ -38,28 +38,28 @@ void testContext(bool ssl, const Ice::CommunicatorPtr& communicator, const Ice:: } -class PermissionsVerifierI : public Glacier2::PermissionsVerifier +class PermissionsVerifierI final : public Glacier2::PermissionsVerifier { public: - virtual bool - checkPermissions(const string& userId, const string&, string&, const Ice::Current& current) const + bool + checkPermissions(string userId, string, string&, const Ice::Current& current) const override { testContext(userId == "ssl", current.adapter->getCommunicator(), current.ctx); return true; } }; -class SSLPermissionsVerifierI : public Glacier2::SSLPermissionsVerifier +class SSLPermissionsVerifierI final : public Glacier2::SSLPermissionsVerifier { public: - virtual bool - authorize(const Glacier2::SSLInfo& info, string&, const Ice::Current& current) const + bool + authorize(Glacier2::SSLInfo info, string&, const Ice::Current& current) const override { testContext(true, current.adapter->getCommunicator(), current.ctx); - IceSSL::CertificatePtr cert = IceSSL::Certificate::decode(info.certs[0]); + auto cert = IceSSL::Certificate::decode(info.certs[0]); test(cert->getIssuerDN() == IceSSL::DistinguishedName( "emailAddress=info@zeroc.com,C=US,ST=Florida,L=Jupiter,O=ZeroC\\, Inc.,OU=Ice,CN=Ice Tests CA")); test(cert->getSubjectDN() == IceSSL::DistinguishedName( @@ -70,7 +70,7 @@ class SSLPermissionsVerifierI : public Glacier2::SSLPermissionsVerifier } }; -class SessionI : public Glacier2::Session +class SessionI final : public Glacier2::Session { public: @@ -78,8 +78,8 @@ class SessionI : public Glacier2::Session { } - virtual void - destroy(const Ice::Current& current) + void + destroy(const Ice::Current& current) override { testContext(_ssl, current.adapter->getCommunicator(), current.ctx); @@ -90,8 +90,8 @@ class SessionI : public Glacier2::Session } } - virtual void - ice_ping(const Ice::Current& current) const + void + ice_ping(const Ice::Current& current) const override { testContext(_ssl, current.adapter->getCommunicator(), current.ctx); } @@ -102,26 +102,26 @@ class SessionI : public Glacier2::Session const bool _ssl; }; -class SessionManagerI : public Glacier2::SessionManager +class SessionManagerI final : public Glacier2::SessionManager { public: - virtual Glacier2::SessionPrx - create(const string& userId, const Glacier2::SessionControlPrx&, const Ice::Current& current) + shared_ptr + create(string userId, shared_ptr, const Ice::Current& current) override { testContext(userId == "ssl", current.adapter->getCommunicator(), current.ctx); - Glacier2::SessionPtr session = new SessionI(false, userId == "ssl"); - return Glacier2::SessionPrx::uncheckedCast(current.adapter->addWithUUID(session)); + auto session = make_shared(false, userId == "ssl"); + return Ice::uncheckedCast(current.adapter->addWithUUID(session)); } }; -class SSLSessionManagerI : public Glacier2::SSLSessionManager +class SSLSessionManagerI final : public Glacier2::SSLSessionManager { public: - virtual Glacier2::SessionPrx - create(const Glacier2::SSLInfo& info, const Glacier2::SessionControlPrx&, const Ice::Current& current) + shared_ptr + create(Glacier2::SSLInfo info, shared_ptr, const Ice::Current& current) override { testContext(true, current.adapter->getCommunicator(), current.ctx); @@ -131,7 +131,7 @@ class SSLSessionManagerI : public Glacier2::SSLSessionManager try { - IceSSL::CertificatePtr cert = IceSSL::Certificate::decode(info.certs[0]); + auto cert = IceSSL::Certificate::decode(info.certs[0]); test(cert->getIssuerDN() == IceSSL::DistinguishedName( "emailAddress=info@zeroc.com,C=US,ST=Florida,L=Jupiter,O=ZeroC\\, Inc.,OU=Ice,CN=Ice Tests CA")); test(cert->getSubjectDN() == IceSSL::DistinguishedName( @@ -143,28 +143,28 @@ class SSLSessionManagerI : public Glacier2::SSLSessionManager test(false); } - Glacier2::SessionPtr session = new SessionI(true, true); - return Glacier2::SessionPrx::uncheckedCast(current.adapter->addWithUUID(session)); + auto session = make_shared(true, true); + return Ice::uncheckedCast(current.adapter->addWithUUID(session)); } }; -class Server : public Test::TestHelper +class Server final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Server::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SessionServer", + auto adapter = communicator->createObjectAdapterWithEndpoints("SessionServer", getTestEndpoint(3, "tcp")); - adapter->add(new PermissionsVerifierI, Ice::stringToIdentity("verifier")); - adapter->add(new SSLPermissionsVerifierI, Ice::stringToIdentity("sslverifier")); - adapter->add(new SessionManagerI, Ice::stringToIdentity("sessionmanager")); - adapter->add(new SSLSessionManagerI, Ice::stringToIdentity("sslsessionmanager")); + adapter->add(make_shared(), Ice::stringToIdentity("verifier")); + adapter->add(make_shared(), Ice::stringToIdentity("sslverifier")); + adapter->add(make_shared(), Ice::stringToIdentity("sessionmanager")); + adapter->add(make_shared(), Ice::stringToIdentity("sslsessionmanager")); adapter->activate(); communicator->waitForShutdown(); } diff --git a/cpp/test/Glacier2/staticFiltering/BackendI.h b/cpp/test/Glacier2/staticFiltering/BackendI.h index a22383abb94..9ac0cb658db 100644 --- a/cpp/test/Glacier2/staticFiltering/BackendI.h +++ b/cpp/test/Glacier2/staticFiltering/BackendI.h @@ -7,11 +7,11 @@ #include -class BackendI : public Test::Backend +class BackendI final : public Test::Backend { public: - virtual void shutdown(const Ice::Current&); + void shutdown(const Ice::Current&) override; }; #endif diff --git a/cpp/test/Glacier2/staticFiltering/Client.cpp b/cpp/test/Glacier2/staticFiltering/Client.cpp index 6d50ee00c89..1c397a7e660 100644 --- a/cpp/test/Glacier2/staticFiltering/Client.cpp +++ b/cpp/test/Glacier2/staticFiltering/Client.cpp @@ -11,17 +11,17 @@ using namespace std; using namespace Ice; using namespace Test; -class AttackClient : public Test::TestHelper +class AttackClient final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void AttackClient::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); // // We want to check whether the client retries for evicted // proxies, even with regular retries disabled. @@ -30,29 +30,27 @@ AttackClient::run(int argc, char** argv) Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); - ObjectPrx routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50)); - Glacier2::RouterPrx router = Glacier2::RouterPrx::checkedCast(routerBase); + auto routerBase = communicator->stringToProxy("Glacier2/router:" + getTestEndpoint(50)); + auto router = checkedCast(routerBase); test(router); communicator->setDefaultRouter(router); - PropertyDict::const_iterator p; - - PropertyDict badProxies = communicator->getProperties()->getPropertiesForPrefix("Reject.Proxy."); - for(p = badProxies.begin(); p != badProxies.end(); ++p) + auto badProxies = communicator->getProperties()->getPropertiesForPrefix("Reject.Proxy."); + for(const auto& p : badProxies) { try { - Glacier2::SessionPrx session = router->createSession("userid", "abc123"); + auto session = router->createSession("userid", "abc123"); } catch(const Glacier2::CannotCreateSessionException&) { test(false); } - BackendPrx backend = BackendPrx::uncheckedCast(communicator->stringToProxy(p->second)); + auto backend = uncheckedCast(communicator->stringToProxy(p.second)); try { backend->ice_ping(); - cerr << "Test failed on : " << p->second << endl; + cerr << "Test failed on : " << p.second << endl; test(false); } catch(const ConnectionLostException&) @@ -87,25 +85,25 @@ AttackClient::run(int argc, char** argv) } } - PropertyDict goodProxies = communicator->getProperties()->getPropertiesForPrefix("Accept.Proxy."); - for(p = goodProxies.begin(); p != goodProxies.end(); ++p) + auto goodProxies = communicator->getProperties()->getPropertiesForPrefix("Accept.Proxy."); + for(const auto& p : goodProxies) { try { - Glacier2::SessionPrx session = router->createSession("userid", "abc123"); + auto session = router->createSession("userid", "abc123"); } catch(const Glacier2::CannotCreateSessionException&) { test(false); } - BackendPrx backend = BackendPrx::uncheckedCast(communicator->stringToProxy(p->second)); + auto backend = uncheckedCast(communicator->stringToProxy(p.second)); try { backend->ice_ping(); } catch(const LocalException& ex) { - cerr << p->second << endl; + cerr << p.second << endl; cerr << ex << endl; test(false); } @@ -125,10 +123,10 @@ AttackClient::run(int argc, char** argv) // Stop using router and communicate with backend and router directly // to shut things down. // - communicator->setDefaultRouter(0); + communicator->setDefaultRouter(nullptr); try { - BackendPrx backend = BackendPrx::checkedCast(communicator->stringToProxy("dummy:tcp -p 12010")); + auto backend = checkedCast(communicator->stringToProxy("dummy:tcp -p 12010")); backend->shutdown(); } catch(const Ice::LocalException&) @@ -136,8 +134,8 @@ AttackClient::run(int argc, char** argv) test(false); } - ObjectPrx processBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51)); - Ice::ProcessPrx process = Ice::ProcessPrx::checkedCast(processBase); + auto processBase = communicator->stringToProxy("Glacier2/admin -f Process:" + getTestEndpoint(51)); + auto process = checkedCast(processBase); test(process); process->shutdown(); try diff --git a/cpp/test/Glacier2/staticFiltering/Server.cpp b/cpp/test/Glacier2/staticFiltering/Server.cpp index 93446b0575f..9d452773bdf 100644 --- a/cpp/test/Glacier2/staticFiltering/Server.cpp +++ b/cpp/test/Glacier2/staticFiltering/Server.cpp @@ -15,100 +15,79 @@ using namespace Test; // simplicity, we essentially 'alias' all possible requests to a single // object adapter and a single servant. // -class ServerLocatorRegistry : public virtual LocatorRegistry +class ServerLocatorRegistry final : public LocatorRegistry { public: - virtual void - setAdapterDirectProxy_async(const AMD_LocatorRegistry_setAdapterDirectProxyPtr& cb, const string&, - const ObjectPrx&, const Current&) + void + setAdapterDirectProxyAsync(string, shared_ptr, function response, function, + const Current&) override { - cb->ice_response(); + response(); } - virtual void - setReplicatedAdapterDirectProxy_async(const AMD_LocatorRegistry_setReplicatedAdapterDirectProxyPtr& cb, - const string&, const string&, const ObjectPrx&, const Current&) + void + setReplicatedAdapterDirectProxyAsync(string, string, shared_ptr, + function response, function, + const Current&) override { - cb->ice_response(); + response(); } - virtual void - setServerProcessProxy_async(const AMD_LocatorRegistry_setServerProcessProxyPtr& cb, - const string&, const ProcessPrx&, const Current&) + void + setServerProcessProxyAsync(string, shared_ptr, + function response, function, + const Current&) override { - cb->ice_response(); + response(); } }; -class ServerLocatorI : public virtual Locator +class ServerLocatorI final : public Locator { public: - ServerLocatorI(const BackendPtr& backend, const ObjectAdapterPtr& adapter) : - _backend(backend), + + ServerLocatorI(shared_ptr backend, const shared_ptr& adapter) : + _backend(std::move(backend)), _adapter(adapter), - _registryPrx( - LocatorRegistryPrx::uncheckedCast( - adapter->add(new ServerLocatorRegistry, Ice::stringToIdentity("registry")))) + _registryPrx(uncheckedCast( + adapter->add(make_shared(), Ice::stringToIdentity("registry")))) { } - virtual void - findObjectById_async(const AMD_Locator_findObjectByIdPtr& cb, const Identity& id, const Current&) const + void + findObjectByIdAsync(Identity id, + function&)> response, function, + const Current&) const override { - cb->ice_response(_adapter->createProxy(id)); + response(_adapter->createProxy(id)); } - virtual void - findAdapterById_async(const AMD_Locator_findAdapterByIdPtr& cb, const string&, const Current&) const + void + findAdapterByIdAsync(string, + function&)> response, function, + const Current&) const override { - cb->ice_response(_adapter->createDirectProxy(stringToIdentity("dummy"))); + response(_adapter->createDirectProxy(stringToIdentity("dummy"))); } - virtual LocatorRegistryPrx - getRegistry(const Current&) const + shared_ptr + getRegistry(const Current&) const override { return _registryPrx; } private: - const BackendPtr _backend; - const ObjectAdapterPtr _adapter; - const LocatorRegistryPrx _registryPrx; -}; - -class ServantLocatorI : public virtual ServantLocator -{ -public: - - ServantLocatorI(const BackendPtr& backend) : - _backend(backend) - { - } - - virtual ObjectPtr locate(const Current&, LocalObjectPtr&) - { - return _backend; - } - - virtual void finished(const Current&, const ObjectPtr&, const LocalObjectPtr&) - { - } - - virtual void deactivate(const string&) - { - } - -private: - - const BackendPtr _backend; + const shared_ptr _backend; + const shared_ptr _adapter; + const shared_ptr _registryPrx; }; -class BackendServer : public Test::TestHelper +class BackendServer final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -119,11 +98,11 @@ BackendServer::run(int argc, char** argv) "tcp -p 12010:ssl -p 12011"); communicator->getProperties()->setProperty("BackendAdapter.Endpoints", endpoints); - ObjectAdapterPtr adapter = communicator->createObjectAdapter("BackendAdapter"); - BackendPtr backend = new BackendI; - Ice::LocatorPtr locator = new ServerLocatorI(backend, adapter); + auto adapter = communicator->createObjectAdapter("BackendAdapter"); + auto backend = make_shared(); + auto locator = make_shared(backend, adapter); adapter->add(locator, Ice::stringToIdentity("locator")); - adapter->addServantLocator(new ServantLocatorI(backend), ""); + adapter->addDefaultServant(backend, ""); adapter->activate(); communicator->waitForShutdown(); } diff --git a/cpp/test/IceBridge/simple/AllTests.cpp b/cpp/test/IceBridge/simple/AllTests.cpp index 0f66b77f277..a3e19d5c8a9 100644 --- a/cpp/test/IceBridge/simple/AllTests.cpp +++ b/cpp/test/IceBridge/simple/AllTests.cpp @@ -5,74 +5,50 @@ #include #include #include +#include +#include +#include +#include using namespace std; +using namespace std::chrono_literals; namespace { -class CallbackI : public Test::Callback +class CallbackI final : public Test::Callback { public: - CallbackI() : _count(0), _datagramCount(0) - { - } - - virtual void - ping(const Ice::Current&) + void + ping(const Ice::Current&) override { ++_count; } - virtual int - getCount(const Ice::Current&) + int + getCount(const Ice::Current&) override { return _count; } - virtual void - datagram(const Ice::Current& c) + void + datagram(const Ice::Current& c) override { test(c.con->getEndpoint()->getInfo()->datagram()); ++_datagramCount; } - virtual int - getDatagramCount(const Ice::Current&) + int + getDatagramCount(const Ice::Current&) override { return _datagramCount; } private: - int _count; - int _datagramCount; -}; - -class HeartbeatCallbackI : public Ice::HeartbeatCallback, private IceUtil::Mutex -{ -public: - - HeartbeatCallbackI() : _count(0) - { - } - - virtual void heartbeat(const Ice::ConnectionPtr&) - { - Lock sync(*this); - ++_count; - } - - int getCount() const - { - Lock sync(*this); - return _count; - } - -private: - - int _count; + int _count = 0; + int _datagramCount = 0; }; } @@ -80,12 +56,12 @@ class HeartbeatCallbackI : public Ice::HeartbeatCallback, private IceUtil::Mutex void allTests(Test::TestHelper* helper) { - Ice::CommunicatorPtr communicator = helper->communicator(); + auto communicator = helper->communicator(); cout << "testing connection to bridge... " << flush; - Ice::ObjectPrx prx = communicator->stringToProxy("test:" + helper->getTestEndpoint(1) + ":" + - helper->getTestEndpoint(1, "udp")); + auto prx = communicator->stringToProxy("test:" + helper->getTestEndpoint(1) + ":" + + helper->getTestEndpoint(1, "udp")); test(prx); - Test::MyClassPrx cl = Ice::checkedCast(prx); + auto cl = Ice::checkedCast(prx); cl->ice_ping(); cout << "ok" << endl; @@ -98,7 +74,7 @@ allTests(Test::TestHelper* helper) int nRetry = 20; while(cl->getDatagramCount() < 10 && --nRetry > 0) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(50)); + this_thread::sleep_for(50ms); } test(cl->getDatagramCount() >= 10); } @@ -106,7 +82,7 @@ allTests(Test::TestHelper* helper) cout << "testing connection close... " << flush; { - Test::MyClassPrx clc = + auto clc = Ice::checkedCast(cl->ice_getConnection()->createProxy(cl->ice_getIdentity())); clc->ice_ping(); clc->closeConnection(false); @@ -130,7 +106,7 @@ allTests(Test::TestHelper* helper) // of the connection close. test(ex.unknown.find("CloseConnectionException") != string::npos); } - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(1)); + this_thread::sleep_for(1ms); } try { @@ -149,16 +125,16 @@ allTests(Test::TestHelper* helper) int nRetry = 20; while(cl->getConnectionCount() != 2 && --nRetry > 0) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(50)); + this_thread::sleep_for(50ms); } test(cl->getConnectionCount() == 2); test(cl->ice_connectionId("other")->getConnectionInfo() != cl->getConnectionInfo()); test(cl->getConnectionCount() == 3); - cl->ice_connectionId("other")->ice_getConnection()->close(Ice::ConnectionCloseGracefully); + cl->ice_connectionId("other")->ice_getConnection()->close(Ice::ConnectionClose::Gracefully); nRetry = 20; while(cl->getConnectionCount() != 2 && --nRetry > 0) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(50)); + this_thread::sleep_for(50ms); } test(cl->getConnectionCount() == 2); } @@ -174,10 +150,10 @@ allTests(Test::TestHelper* helper) { ostringstream os; os << i; - Test::MyClassPrx p = cl->ice_connectionId(os.str()); + auto p = cl->ice_connectionId(os.str()); for(int j = 0; j < 20; ++j) { - p->begin_incCounter(++counter); + p->incCounterAsync(++counter, nullptr); } cl->waitCounter(counter); p->closeConnection(false); @@ -186,10 +162,10 @@ allTests(Test::TestHelper* helper) { ostringstream os; os << i; - Test::MyClassPrx p = cl->ice_connectionId(os.str())->ice_oneway(); + auto p = cl->ice_connectionId(os.str())->ice_oneway(); for(int j = 0; j < 20; ++j) { - p->begin_incCounter(++counter); + p->incCounterAsync(++counter, nullptr); } cl->waitCounter(counter); p->closeConnection(false); @@ -197,10 +173,10 @@ allTests(Test::TestHelper* helper) } cout << "ok" << endl; - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter(""); + auto adapter = communicator->createObjectAdapter(""); Ice::Identity id; id.name = "callback"; - adapter->add(new CallbackI(), id); + adapter->add(make_shared(), id); cout << "testing bi-dir callbacks... " << flush; { @@ -216,7 +192,7 @@ allTests(Test::TestHelper* helper) cout << "testing datagram bi-dir callbacks... " << flush; { - Test::MyClassPrx p = cl->ice_datagram(); + auto p = cl->ice_datagram(); p->ice_getConnection()->setAdapter(adapter); for(int i = 0; i < 20; i++) { @@ -225,7 +201,7 @@ allTests(Test::TestHelper* helper) int nRetry = 20; while(cl->getCallbackDatagramCount() < 10 && --nRetry > 0) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(50)); + this_thread::sleep_for(50ms); } test(cl->getCallbackDatagramCount() >= 10); } @@ -233,11 +209,11 @@ allTests(Test::TestHelper* helper) cout << "testing router... " << flush; { - Ice::ObjectPrx base = communicator->stringToProxy("Ice/RouterFinder:" + helper->getTestEndpoint(1)); - Ice::RouterFinderPrx finder = Ice::checkedCast(base); - Ice::RouterPrx router = finder->getRouter(); + auto base = communicator->stringToProxy("Ice/RouterFinder:" + helper->getTestEndpoint(1)); + auto finder = Ice::checkedCast(base); + auto router = finder->getRouter(); base = communicator->stringToProxy("test")->ice_router(router); - Test::MyClassPrx p = Ice::checkedCast(base); + auto p = Ice::checkedCast(base); p->ice_ping(); } cout << "ok" << endl; @@ -246,20 +222,23 @@ allTests(Test::TestHelper* helper) { test(cl->getHeartbeatCount() == 0); // No heartbeats enabled by default - Test::MyClassPrx p = cl->ice_connectionId("heartbeat"); - p->ice_getConnection()->setACM(1, IceUtil::None, Ice::HeartbeatAlways); + auto p = cl->ice_connectionId("heartbeat"); + p->ice_getConnection()->setACM(1, Ice::nullopt, Ice::ACMHeartbeat::HeartbeatAlways); - Test::MyClassPrx p2 = cl->ice_connectionId("heartbeat2"); - HeartbeatCallbackI* heartbeat = new HeartbeatCallbackI(); - p2->ice_getConnection()->setHeartbeatCallback(heartbeat); + auto p2 = cl->ice_connectionId("heartbeat2"); + atomic_int counter = 0; + p2->ice_getConnection()->setHeartbeatCallback([&counter](const auto&) + { + counter++; + }); p2->enableHeartbeats(); int nRetry = 20; - while((p->getHeartbeatCount() < 1 || heartbeat->getCount() < 1) && --nRetry > 0) + while((p->getHeartbeatCount() < 1 || counter.load() < 1) && --nRetry > 0) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); + this_thread::sleep_for(500ms); // TODO: check sleep time } - test(p->getHeartbeatCount() > 0 && heartbeat->getCount() > 0); + test(p->getHeartbeatCount() > 0 && counter.load() > 0); } cout << "ok" << endl; @@ -268,8 +247,8 @@ allTests(Test::TestHelper* helper) cout << "ok" << endl; cout << "testing bridge shutdown... " << flush; - Ice::ObjectPrx admin = communicator->stringToProxy("IceBridge/admin:" + helper->getTestEndpoint(2, "tcp")); - Ice::ProcessPrx process = Ice::checkedCast(admin->ice_facet("Process")); + auto admin = communicator->stringToProxy("IceBridge/admin:" + helper->getTestEndpoint(2, "tcp")); + auto process = Ice::checkedCast(admin->ice_facet("Process")); process->shutdown(); cout << "ok" << endl; } diff --git a/cpp/test/IceBridge/simple/Client.cpp b/cpp/test/IceBridge/simple/Client.cpp index 392150634e3..3fecc885ffa 100644 --- a/cpp/test/IceBridge/simple/Client.cpp +++ b/cpp/test/IceBridge/simple/Client.cpp @@ -8,19 +8,19 @@ using namespace std; -class Client : public Test::TestHelper +class Client final : public Test::TestHelper { public: - void run(int argc, char** argv); + void run(int argc, char** argv) override; }; void Client::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); properties->setProperty("Ice.RetryIntervals", "-1"); - Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); + Ice::CommunicatorHolder communicatorHolder = initialize(argc, argv, properties); void allTests(Test::TestHelper*); allTests(this); } diff --git a/cpp/test/IceBridge/simple/Server.cpp b/cpp/test/IceBridge/simple/Server.cpp index 4b51e5d132b..c75ae99363b 100644 --- a/cpp/test/IceBridge/simple/Server.cpp +++ b/cpp/test/IceBridge/simple/Server.cpp @@ -8,31 +8,31 @@ using namespace std; -class Server : public Test::TestHelper +class Server final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Server::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); properties->setProperty("Ice.Warn.Dispatch", "0"); // Make sure requests are serialized, this is required for the ordering test. properties->setProperty("Ice.ThreadPool.Server.Serialize", "1"); - Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); - communicator->getProperties()->setProperty("TestAdapter.Endpoints", - getTestEndpoint() + ":" + - getTestEndpoint("udp")); - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TestAdapter"); - adapter->add(ICE_MAKE_SHARED(MyClassI), Ice::stringToIdentity("test")); + Ice::CommunicatorHolder communicatorHolder = initialize(argc, argv, properties); + communicatorHolder->getProperties()->setProperty("TestAdapter.Endpoints", + getTestEndpoint() + ":" + + getTestEndpoint("udp")); + auto adapter = communicatorHolder->createObjectAdapter("TestAdapter"); + adapter->add(make_shared(), Ice::stringToIdentity("test")); adapter->activate(); serverReady(); - communicator->waitForShutdown(); + communicatorHolder->waitForShutdown(); } DEFINE_TEST(Server) diff --git a/cpp/test/IceBridge/simple/TestI.cpp b/cpp/test/IceBridge/simple/TestI.cpp index 23166c77a91..2998a960d06 100644 --- a/cpp/test/IceBridge/simple/TestI.cpp +++ b/cpp/test/IceBridge/simple/TestI.cpp @@ -12,240 +12,158 @@ using namespace Test; namespace { -class CloseCallbackI : public Ice::CloseCallback -{ -public: - - CloseCallbackI(const MyClassIPtr& cl) : _cl(cl) - { - } - - void - closed(const Ice::ConnectionPtr& connection) - { - _cl->removeConnection(connection); - } - -private: - - MyClassIPtr _cl; -}; - -class HeartbeatCallbackI : public Ice::HeartbeatCallback -{ -public: - - HeartbeatCallbackI(const MyClassIPtr& cl) : _cl(cl) - { - } - - void - heartbeat(const Ice::ConnectionPtr& connection) - { - _cl->incHeartbeatCount(connection); - } - -private: - - MyClassIPtr _cl; -}; - -class CallbackI : public IceUtil::Shared -{ -public: - - CallbackI(const AMD_MyClass_callCallbackPtr& amdCB) : _amdCB(amdCB) - { - } - - void response() - { - _amdCB->ice_response(); - } - - void exception(const Ice::Exception& ex) - { - _amdCB->ice_exception(ex); - } - -private: - - const AMD_MyClass_callCallbackPtr _amdCB; -}; - -template class GetCount : public IceUtil::Shared -{ -public: - - GetCount(const T& amdCB) : _amdCB(amdCB) - { - } - - void response(int count) - { - _amdCB->ice_response(count); - } - - void exception(const Ice::Exception& ex) - { - _amdCB->ice_exception(ex); - } - -private: - - const T _amdCB; -}; -typedef GetCount GetCallbackCount; -typedef GetCount GetCallbackDatagramCount; - Ice::Identity callbackId = { "callback" , "" }; } -MyClassI::MyClassI() : _datagramCount(0), _counter(0) -{ -} - void -MyClassI::callCallback_async(const AMD_MyClass_callCallbackPtr& amdCB, const Ice::Current& c) +MyClassI::callCallbackAsync(function response, + function error, + const Ice::Current& current) { - checkConnection(c.con); - Callback_Callback_pingPtr cb = newCallback_Callback_ping(new CallbackI(amdCB), - &CallbackI::response, - &CallbackI::exception); - Ice::uncheckedCast(c.con->createProxy(callbackId))->begin_ping(cb); + checkConnection(current.con); + auto prx = Ice::uncheckedCast(current.con->createProxy(callbackId)); + + prx->pingAsync([response = std::move(response)](){ response(); }, + [error = std::move(error)](exception_ptr e){ error(e); }); } void -MyClassI::getCallbackCount_async(const AMD_MyClass_getCallbackCountPtr& amdCB, const Ice::Current& c) +MyClassI::getCallbackCountAsync(function response, + function error, + const Ice::Current& current) { - checkConnection(c.con); - Callback_Callback_getCountPtr cb = newCallback_Callback_getCount(new GetCallbackCount(amdCB), - &GetCallbackCount::response, - &GetCallbackCount::exception); - Ice::uncheckedCast(c.con->createProxy(callbackId))->begin_getCount(cb); + checkConnection(current.con); + auto prx = Ice::uncheckedCast(current.con->createProxy(callbackId)); + + prx->getCountAsync([response = std::move(response)](int count){ response(count); }, + [error = std::move(error)](exception_ptr e){ error(e); }); } void -MyClassI::incCounter(int expected, const Ice::Current& c) +MyClassI::incCounter(int expected, const Ice::Current& current) { - checkConnection(c.con); + checkConnection(current.con); - IceUtil::Monitor::Lock sync(_monitor); - if(_counter + 1 != expected) { - cout << _counter << " " << expected << endl; + lock_guard lg(_lock); + if(_counter + 1 != expected) + { + cout << _counter << " " << expected << endl; + } + test(++_counter == expected); } - test(++_counter == expected); - _monitor.notifyAll(); + _condVar.notify_all(); } void MyClassI::waitCounter(int value, const Ice::Current&) { - IceUtil::Monitor::Lock sync(_monitor); + unique_lock lock(_lock); while(_counter != value) { - _monitor.wait(); + _condVar.wait(lock); } } int -MyClassI::getConnectionCount(const Ice::Current& c) +MyClassI::getConnectionCount(const Ice::Current& current) { - checkConnection(c.con); + checkConnection(current.con); return static_cast(_connections.size()); } string -MyClassI::getConnectionInfo(const Ice::Current& c) +MyClassI::getConnectionInfo(const Ice::Current& current) { - checkConnection(c.con); - return c.con->toString(); + checkConnection(current.con); + return current.con->toString(); } void -MyClassI::closeConnection(bool forceful, const Ice::Current& c) +MyClassI::closeConnection(bool forceful, const Ice::Current& current) { - checkConnection(c.con); + checkConnection(current.con); if(forceful) { - c.con->close(Ice::ConnectionCloseForcefully); + current.con->close(Ice::ConnectionClose::Forcefully); } else { - c.con->close(Ice::ConnectionCloseGracefully); + current.con->close(Ice::ConnectionClose::Gracefully); } } void -MyClassI::datagram(const Ice::Current& c) +MyClassI::datagram(const Ice::Current& current) { - checkConnection(c.con); - test(c.con->getEndpoint()->getInfo()->datagram()); + checkConnection(current.con); + test(current.con->getEndpoint()->getInfo()->datagram()); ++_datagramCount; } int -MyClassI::getDatagramCount(const Ice::Current& c) +MyClassI::getDatagramCount(const Ice::Current& current) { - checkConnection(c.con); + checkConnection(current.con); return _datagramCount; } void -MyClassI::callDatagramCallback(const Ice::Current& c) +MyClassI::callDatagramCallback(const Ice::Current& current) { - checkConnection(c.con); - test(c.con->getEndpoint()->getInfo()->datagram()); - Ice::uncheckedCast(c.con->createProxy(callbackId))->datagram(); + checkConnection(current.con); + test(current.con->getEndpoint()->getInfo()->datagram()); + Ice::uncheckedCast(current.con->createProxy(callbackId))->datagram(); } void -MyClassI::getCallbackDatagramCount_async(const AMD_MyClass_getCallbackDatagramCountPtr& amdCB, const Ice::Current& c) +MyClassI::getCallbackDatagramCountAsync(function response, + function error, + const Ice::Current& current) { - checkConnection(c.con); - Callback_Callback_getDatagramCountPtr cb = newCallback_Callback_getDatagramCount(new GetCallbackDatagramCount(amdCB), - &GetCallbackDatagramCount::response, - &GetCallbackDatagramCount::exception); - Ice::uncheckedCast(c.con->createProxy(callbackId))->begin_getDatagramCount(cb); + checkConnection(current.con); + auto prx = Ice::uncheckedCast(current.con->createProxy(callbackId)); + + prx->getDatagramCountAsync([response = std::move(response)](int count){ response(count); }, + [error = std::move(error)](auto e){ error(e); }); } int -MyClassI::getHeartbeatCount(const Ice::Current& c) +MyClassI::getHeartbeatCount(const Ice::Current& current) { - checkConnection(c.con); + checkConnection(current.con); - IceUtil::Monitor::Lock sync(_monitor); - return _connections[c.con]; + lock_guard lg(_lock); + return _connections[current.con]; } void -MyClassI::enableHeartbeats(const Ice::Current& c) +MyClassI::enableHeartbeats(const Ice::Current& current) { - checkConnection(c.con); - c.con->setACM(1, IceUtil::None, Ice::HeartbeatAlways); + checkConnection(current.con); + current.con->setACM(1, Ice::nullopt, Ice::ACMHeartbeat::HeartbeatAlways); } void -MyClassI::shutdown(const Ice::Current& c) +MyClassI::shutdown(const Ice::Current& current) { - checkConnection(c.con); - c.adapter->getCommunicator()->shutdown(); + checkConnection(current.con); + current.adapter->getCommunicator()->shutdown(); } void -MyClassI::removeConnection(const Ice::ConnectionPtr& c) +MyClassI::removeConnection(const shared_ptr& con) { - IceUtil::Monitor::Lock sync(_monitor); - _connections.erase(c); + lock_guard lg(_lock); + _connections.erase(con); } void -MyClassI::incHeartbeatCount(const Ice::ConnectionPtr& c) +MyClassI::incHeartbeatCount(const shared_ptr& con) { - IceUtil::Monitor::Lock sync(_monitor); - map::iterator p = _connections.find(c); + lock_guard lg(_lock); + auto p = _connections.find(con); if(p == _connections.end()) { return; @@ -254,13 +172,13 @@ MyClassI::incHeartbeatCount(const Ice::ConnectionPtr& c) } void -MyClassI::checkConnection(const Ice::ConnectionPtr& c) +MyClassI::checkConnection(const shared_ptr& con) { - IceUtil::Monitor::Lock sync(_monitor); - if(_connections.find(c) == _connections.end()) + lock_guard lg(_lock); + if(_connections.find(con) == _connections.end()) { - _connections.insert(make_pair(c, 0)); - c->setCloseCallback(new CloseCallbackI(this)); - c->setHeartbeatCallback(new HeartbeatCallbackI(this)); + _connections.insert(make_pair(con, 0)); + con->setCloseCallback([self = shared_from_this()](const auto& c){ self->removeConnection(c); }); + con->setHeartbeatCallback([self = shared_from_this()](const auto& c){ self->incHeartbeatCount(c); }); } } diff --git a/cpp/test/IceBridge/simple/TestI.h b/cpp/test/IceBridge/simple/TestI.h index 7ad0dec1b88..f3f45e5a3bc 100644 --- a/cpp/test/IceBridge/simple/TestI.h +++ b/cpp/test/IceBridge/simple/TestI.h @@ -7,45 +7,51 @@ #include -class MyClassI : public Test::MyClass +class MyClassI final : public Test::MyClass, public std::enable_shared_from_this { public: - MyClassI(); + void callCallbackAsync(std::function, + std::function, + const Ice::Current&) override; - virtual void callCallback_async(const Test::AMD_MyClass_callCallbackPtr&, const Ice::Current&); - virtual void getCallbackCount_async(const Test::AMD_MyClass_getCallbackCountPtr&, const Ice::Current&); + void getCallbackCountAsync(std::function, + std::function, + const Ice::Current& current) override; - virtual void incCounter(int, const Ice::Current&); - virtual void waitCounter(int, const Ice::Current&); + void incCounter(int, const Ice::Current&) override; + void waitCounter(int, const Ice::Current&) override; - virtual int getConnectionCount(const Ice::Current&); - virtual std::string getConnectionInfo(const Ice::Current&); - virtual void closeConnection(bool, const Ice::Current&); + int getConnectionCount(const Ice::Current&) override; + std::string getConnectionInfo(const Ice::Current&) override; + void closeConnection(bool, const Ice::Current&) override; - virtual void datagram(const Ice::Current&); - virtual int getDatagramCount(const Ice::Current&); + void datagram(const Ice::Current&) override; + int getDatagramCount(const Ice::Current&) override; - virtual void callDatagramCallback(const Ice::Current&); - virtual void getCallbackDatagramCount_async(const Test::AMD_MyClass_getCallbackDatagramCountPtr&, const Ice::Current&); + void callDatagramCallback(const Ice::Current&) override; - virtual int getHeartbeatCount(const Ice::Current&); - virtual void enableHeartbeats(const Ice::Current&); + void getCallbackDatagramCountAsync(std::function, + std::function, + const Ice::Current&) override; - virtual void shutdown(const Ice::Current&); + int getHeartbeatCount(const Ice::Current&) override; + void enableHeartbeats(const Ice::Current&) override; - void removeConnection(const Ice::ConnectionPtr&); - void incHeartbeatCount(const Ice::ConnectionPtr&); + void shutdown(const Ice::Current&) override; + + void removeConnection(const std::shared_ptr&); + void incHeartbeatCount(const std::shared_ptr&); private: - void checkConnection(const Ice::ConnectionPtr&); + void checkConnection(const std::shared_ptr&); - IceUtil::Monitor _monitor; - int _datagramCount; - std::map _connections; - int _counter; + std::mutex _lock; + std::condition_variable _condVar; + int _datagramCount = 0; + std::map, int> _connections; + int _counter = 0; }; -typedef IceUtil::Handle MyClassIPtr; #endif diff --git a/cpp/test/IceGrid/activation/AllTests.cpp b/cpp/test/IceGrid/activation/AllTests.cpp index fbeda45eb40..445117adab3 100644 --- a/cpp/test/IceGrid/activation/AllTests.cpp +++ b/cpp/test/IceGrid/activation/AllTests.cpp @@ -7,12 +7,15 @@ #include #include #include +#include using namespace std; using namespace Test; -void -waitForServerState(const IceGrid::AdminPrx& admin, const std::string& server, IceGrid::ServerState state) +void waitForServerState( + shared_ptr admin, + std::string server, + IceGrid::ServerState state) { int nRetry = 0; while(admin->getServerState(server) != state && nRetry < 15) @@ -24,19 +27,23 @@ waitForServerState(const IceGrid::AdminPrx& admin, const std::string& server, Ic { cerr << "server state change timed out:" << endl; cerr << "server: " << server << endl; - cerr << "state: " << state << endl; + cerr << "state: " << static_cast(state) << endl; } } -class PingThread : public IceUtil::Thread, IceUtil::Monitor +class Pinger { public: - PingThread(const Ice::ObjectPrx& proxy, int nRepetitions) : - _proxy(proxy), _finished(false), _nRepetitions(nRepetitions) + Pinger(shared_ptr proxy, int nRepetitions) : + _proxy(std::move(proxy)), + _finished(false), + _nRepetitions(nRepetitions) { } + virtual ~Pinger() {} + virtual void run() { for(int i = 0; i < _nRepetitions; ++i) @@ -45,9 +52,9 @@ class PingThread : public IceUtil::Thread, IceUtil::Monitor { _proxy->ice_ping(); } - catch(const Ice::LocalException& ex) + catch(const Ice::LocalException&) { - _exception.reset(ex.ice_clone()); + _exception = current_exception(); } catch(...) { @@ -55,49 +62,49 @@ class PingThread : public IceUtil::Thread, IceUtil::Monitor } } - Lock sync(*this); + unique_lock lock(_mutex); _finished = true; - notifyAll(); + _condVar.notify_all(); } - Ice::LocalException* - waitUntilFinished() + exception_ptr waitUntilFinished() { - Lock sync(*this); + unique_lock lock(_mutex); while(!_finished) { - wait(); + _condVar.wait(lock); } - return _exception.release(); + return _exception; } private: - Ice::ObjectPrx _proxy; - IceInternal::UniquePtr _exception; + shared_ptr _proxy; + exception_ptr _exception; bool _finished; int _nRepetitions; + mutex _mutex; + condition_variable _condVar; }; -typedef IceUtil::Handle PingThreadPtr; void allTests(Test::TestHelper* helper) { Ice::CommunicatorPtr communicator = helper->communicator(); - IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::checkedCast( + shared_ptr registry = Ice::checkedCast( communicator->stringToProxy(communicator->getDefaultLocator()->ice_getIdentity().category + "/Registry")); test(registry); - IceGrid::QueryPrx query = IceGrid::QueryPrx::checkedCast( + shared_ptr query = Ice::checkedCast( communicator->stringToProxy(communicator->getDefaultLocator()->ice_getIdentity().category + "/Query")); - IceGrid::AdminSessionPrx adminSession = registry->createAdminSession("foo", "bar"); + shared_ptr adminSession = registry->createAdminSession("foo", "bar"); adminSession->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::ICE_ENUM(ACMHeartbeat, HeartbeatAlways)); - IceGrid::AdminPrx admin = adminSession->getAdmin(); + shared_ptr admin = adminSession->getAdmin(); test(admin); admin->startServer("node-1"); @@ -120,17 +127,17 @@ allTests(Test::TestHelper* helper) cout << "testing on-demand activation... " << flush; try { - test(admin->getServerState("server") == IceGrid::Inactive); - TestIntfPrx obj = TestIntfPrx::checkedCast(communicator->stringToProxy("server")); - waitForServerState(admin, "server", IceGrid::Active); + test(admin->getServerState("server") == IceGrid::ServerState::Inactive); + shared_ptr obj = Ice::checkedCast(communicator->stringToProxy("server")); + waitForServerState(admin, "server", IceGrid::ServerState::Active); obj->shutdown(); - waitForServerState(admin, "server", IceGrid::Inactive); + waitForServerState(admin, "server", IceGrid::ServerState::Inactive); nRetry = 4; while(--nRetry > 0) { obj->shutdown(); } - waitForServerState(admin, "server", IceGrid::Inactive); + waitForServerState(admin, "server", IceGrid::ServerState::Inactive); } catch(const Ice::LocalException& ex) { @@ -142,23 +149,23 @@ allTests(Test::TestHelper* helper) cout << "testing manual activation... " << flush; try { - test(admin->getServerState("server-manual") == IceGrid::Inactive); - TestIntfPrx obj; + test(admin->getServerState("server-manual") == IceGrid::ServerState::Inactive); + shared_ptr obj; try { - obj = TestIntfPrx::checkedCast(communicator->stringToProxy("server-manual")); + obj = Ice::checkedCast(communicator->stringToProxy("server-manual")); test(false); } catch(const Ice::NoEndpointException&) { } - test(admin->getServerState("server-manual") == IceGrid::Inactive); + test(admin->getServerState("server-manual") == IceGrid::ServerState::Inactive); admin->startServer("server-manual"); - test(admin->getServerState("server-manual") == IceGrid::Active); - obj = TestIntfPrx::checkedCast(communicator->stringToProxy("server-manual")); - test(admin->getServerState("server-manual") == IceGrid::Active); + test(admin->getServerState("server-manual") == IceGrid::ServerState::Active); + obj = Ice::checkedCast< TestIntfPrx>(communicator->stringToProxy("server-manual")); + test(admin->getServerState("server-manual") == IceGrid::ServerState::Active); obj->shutdown(); - waitForServerState(admin, "server-manual", IceGrid::Inactive); + waitForServerState(admin, "server-manual", IceGrid::ServerState::Inactive); } catch(const Ice::LocalException& ex) { @@ -170,18 +177,18 @@ allTests(Test::TestHelper* helper) cout << "testing always activation... " << flush; try { - waitForServerState(admin, "server-always", IceGrid::Active); - TestIntfPrx obj = TestIntfPrx::checkedCast(communicator->stringToProxy("server-always")); + waitForServerState(admin, "server-always", IceGrid::ServerState::Active); + shared_ptr obj = Ice::checkedCast(communicator->stringToProxy("server-always")); admin->stopServer("server-always"); - waitForServerState(admin, "server-always", IceGrid::Active); + waitForServerState(admin, "server-always", IceGrid::ServerState::Active); obj->shutdown(); - waitForServerState(admin, "server-always", IceGrid::Active); + waitForServerState(admin, "server-always", IceGrid::ServerState::Active); nRetry = 4; while(--nRetry > 0) { obj->shutdown(); } - waitForServerState(admin, "server-always", IceGrid::Active); + waitForServerState(admin, "server-always", IceGrid::ServerState::Active); } catch(const Ice::LocalException& ex) { @@ -193,10 +200,10 @@ allTests(Test::TestHelper* helper) cout << "testing session activation... " << flush; try { - IceGrid::SessionPrx session = registry->createSession("test", ""); + shared_ptr session = registry->createSession("test", ""); - test(admin->getServerState("server-session") == IceGrid::Inactive); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server-session")); + test(admin->getServerState("server-session") == IceGrid::ServerState::Inactive); + shared_ptr obj = Ice::uncheckedCast(communicator->stringToProxy("server-session")); try { obj->ice_ping(); @@ -207,18 +214,18 @@ allTests(Test::TestHelper* helper) } session->allocateObjectById(obj->ice_getIdentity()); obj->ice_ping(); - waitForServerState(admin, "server-session", IceGrid::Active); + waitForServerState(admin, "server-session", IceGrid::ServerState::Active); obj->shutdown(); - waitForServerState(admin, "server-session", IceGrid::Inactive); + waitForServerState(admin, "server-session", IceGrid::ServerState::Inactive); obj->ice_ping(); - waitForServerState(admin, "server-session", IceGrid::Active); + waitForServerState(admin, "server-session", IceGrid::ServerState::Active); nRetry = 4; while(--nRetry > 0) { obj->shutdown(); } obj->ice_ping(); - waitForServerState(admin, "server-session", IceGrid::Active); + waitForServerState(admin, "server-session", IceGrid::ServerState::Active); session->releaseObject(obj->ice_getIdentity()); try { @@ -228,11 +235,11 @@ allTests(Test::TestHelper* helper) catch(const Ice::NoEndpointException&) { } - waitForServerState(admin, "server-session", IceGrid::Inactive); + waitForServerState(admin, "server-session", IceGrid::ServerState::Inactive); session->allocateObjectById(obj->ice_getIdentity()); obj->ice_ping(); - waitForServerState(admin, "server-session", IceGrid::Active); + waitForServerState(admin, "server-session", IceGrid::ServerState::Active); session->destroy(); try { @@ -242,7 +249,7 @@ allTests(Test::TestHelper* helper) catch(const Ice::NoEndpointException&) { } - waitForServerState(admin, "server-session", IceGrid::Inactive); + waitForServerState(admin, "server-session", IceGrid::ServerState::Inactive); } catch(const Ice::LocalException& ex) { @@ -256,7 +263,7 @@ allTests(Test::TestHelper* helper) { size_t count = query->findAllObjectsByType("Test").size(); - test(admin->getServerState("server") == IceGrid::Inactive); + test(admin->getServerState("server") == IceGrid::ServerState::Inactive); admin->enableServer("server", false); try { @@ -282,9 +289,9 @@ allTests(Test::TestHelper* helper) catch(const IceGrid::ServerStartException&) { } - test(admin->getServerState("server") == IceGrid::Inactive); + test(admin->getServerState("server") == IceGrid::ServerState::Inactive); - test(admin->getServerState("server-manual") == IceGrid::Inactive); + test(admin->getServerState("server-manual") == IceGrid::ServerState::Inactive); admin->enableServer("server-manual", false); try { @@ -302,7 +309,7 @@ allTests(Test::TestHelper* helper) catch(const IceGrid::ServerStartException&) { } - test(admin->getServerState("server-manual") == IceGrid::Inactive); + test(admin->getServerState("server-manual") == IceGrid::ServerState::Inactive); while(query->findAllObjectsByType("Test").size() != count - 2) { // The notification of the server being disabled is asynchronous and might @@ -310,10 +317,10 @@ allTests(Test::TestHelper* helper) IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100)); } - test(admin->getServerState("server-always") == IceGrid::Active); + test(admin->getServerState("server-always") == IceGrid::ServerState::Active); admin->enableServer("server-always", false); admin->stopServer("server-always"); - test(admin->getServerState("server-always") == IceGrid::Inactive); + test(admin->getServerState("server-always") == IceGrid::ServerState::Inactive); try { communicator->stringToProxy("server-always")->ice_ping(); @@ -330,7 +337,7 @@ allTests(Test::TestHelper* helper) catch(const IceGrid::ServerStartException&) { } - test(admin->getServerState("server-always") == IceGrid::Inactive); + test(admin->getServerState("server-always") == IceGrid::ServerState::Inactive); while(query->findAllObjectsByType("Test").size() != count - 3) { // The notification of the server being disabled is asynchronous and might @@ -338,12 +345,12 @@ allTests(Test::TestHelper* helper) IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100)); } - test(admin->getServerState("server") == IceGrid::Inactive); + test(admin->getServerState("server") == IceGrid::ServerState::Inactive); admin->enableServer("server", true); communicator->stringToProxy("server")->ice_locatorCacheTimeout(0)->ice_ping(); int pid = admin->getServerPid("server"); admin->enableServer("server", false); - test(admin->getServerState("server") == IceGrid::Active); + test(admin->getServerState("server") == IceGrid::ServerState::Active); try { communicator->stringToProxy("server")->ice_locatorCacheTimeout(0)->ice_ping(); @@ -356,7 +363,7 @@ allTests(Test::TestHelper* helper) communicator->stringToProxy("server")->ice_locatorCacheTimeout(0)->ice_ping(); test(admin->getServerPid("server") == pid); admin->stopServer("server"); - test(admin->getServerState("server") == IceGrid::Inactive); + test(admin->getServerState("server") == IceGrid::ServerState::Inactive); while(query->findAllObjectsByType("Test").size() != count - 2) { @@ -375,17 +382,17 @@ allTests(Test::TestHelper* helper) cout << "testing server enable... " << flush; try { - test(admin->getServerState("server") == IceGrid::Inactive); + test(admin->getServerState("server") == IceGrid::ServerState::Inactive); admin->enableServer("server", true); communicator->stringToProxy("server")->ice_ping(); admin->stopServer("server"); - test(admin->getServerState("server") == IceGrid::Inactive); + test(admin->getServerState("server") == IceGrid::ServerState::Inactive); admin->startServer("server"); - test(admin->getServerState("server") == IceGrid::Active); + test(admin->getServerState("server") == IceGrid::ServerState::Active); admin->stopServer("server"); - test(admin->getServerState("server") == IceGrid::Inactive); + test(admin->getServerState("server") == IceGrid::ServerState::Inactive); - test(admin->getServerState("server-manual") == IceGrid::Inactive); + test(admin->getServerState("server-manual") == IceGrid::ServerState::Inactive); admin->enableServer("server-manual", true); try { @@ -395,15 +402,15 @@ allTests(Test::TestHelper* helper) catch(const Ice::NoEndpointException&) { } - test(admin->getServerState("server-manual") == IceGrid::Inactive); + test(admin->getServerState("server-manual") == IceGrid::ServerState::Inactive); admin->startServer("server-manual"); - test(admin->getServerState("server-manual") == IceGrid::Active); + test(admin->getServerState("server-manual") == IceGrid::ServerState::Active); admin->stopServer("server-manual"); - test(admin->getServerState("server-manual") == IceGrid::Inactive); + test(admin->getServerState("server-manual") == IceGrid::ServerState::Inactive); - test(admin->getServerState("server-always") == IceGrid::Inactive); + test(admin->getServerState("server-always") == IceGrid::ServerState::Inactive); admin->enableServer("server-always", true); - waitForServerState(admin, "server-always", IceGrid::Active); + waitForServerState(admin, "server-always", IceGrid::ServerState::Active); admin->stopServer("server-always"); try { @@ -413,7 +420,7 @@ allTests(Test::TestHelper* helper) catch(const IceGrid::ServerStartException&) { } - test(admin->getServerState("server-always") == IceGrid::Active); + test(admin->getServerState("server-always") == IceGrid::ServerState::Active); } catch(const Ice::LocalException& ex) { @@ -427,69 +434,108 @@ allTests(Test::TestHelper* helper) { int i; const int nThreads = 3; - Ice::ObjectPrx invalid = communicator->stringToProxy("invalid-exe"); - - vector threads; - threads.reserve(nThreads); - vector::const_iterator p; + shared_ptr invalid = communicator->stringToProxy("invalid-exe"); + vector, thread>> pingers; for(i = 0; i < nThreads; i++) { - threads.push_back(new PingThread(invalid, 10)); - } - for(p = threads.begin(); p != threads.end(); ++p) - { - (*p)->start(); + auto pinger = make_shared(invalid, 10); + auto t = thread( + [pinger]() + { + pinger->run(); + }); + pingers.push_back(make_pair(pinger, std::move(t))); } - for(p = threads.begin(); p != threads.end(); ++p) + + for(const auto& p : pingers) { - IceInternal::UniquePtr ex((*p)->waitUntilFinished()); - test(dynamic_cast(ex.get())); + exception_ptr ex = p.first->waitUntilFinished(); + try + { + rethrow_exception(ex); + } + catch (const Ice::NoEndpointException&) + { + } + catch (...) + { + test(false); + } } - for(p = threads.begin(); p != threads.end(); ++p) + + for (auto& p : pingers) { - (*p)->getThreadControl().join(); + p.second.join(); } - threads.resize(0); + pingers.clear(); invalid = communicator->stringToProxy("invalid-pwd"); for(i = 0; i < nThreads; i++) { - threads.push_back(new PingThread(invalid, 10)); - } - for(p = threads.begin(); p != threads.end(); ++p) - { - (*p)->start(); + auto pinger = make_shared(invalid, 10); + auto t = thread( + [pinger]() + { + pinger->run(); + }); + pingers.push_back(make_pair(pinger, std::move(t))); } - for(p = threads.begin(); p != threads.end(); ++p) + + for (const auto& p : pingers) { - IceInternal::UniquePtr ex((*p)->waitUntilFinished()); - test(dynamic_cast(ex.get())); + exception_ptr ex = p.first->waitUntilFinished(); + try + { + rethrow_exception(ex); + } + catch (const Ice::NoEndpointException&) + { + } + catch (...) + { + test(false); + } } - for(p = threads.begin(); p != threads.end(); ++p) + + for (auto& p : pingers) { - (*p)->getThreadControl().join(); + p.second.join(); } - threads.resize(0); + pingers.clear(); invalid = communicator->stringToProxy("fail-on-startup"); - for(i = 0; i < nThreads; i++) - { - threads.push_back(new PingThread(invalid, 5)); - } - for(p = threads.begin(); p != threads.end(); ++p) + for (i = 0; i < nThreads; i++) { - (*p)->start(); + auto pinger = make_shared(invalid, 5); + auto t = thread( + [pinger]() + { + pinger->run(); + }); + pingers.push_back(make_pair(pinger, std::move(t))); } - for(p = threads.begin(); p != threads.end(); ++p) + + for (const auto& p : pingers) { - IceInternal::UniquePtr ex((*p)->waitUntilFinished()); - test(dynamic_cast(ex.get())); + exception_ptr ex = p.first->waitUntilFinished(); + try + { + rethrow_exception(ex); + } + catch (const Ice::NoEndpointException&) + { + } + catch (...) + { + test(false); + } } - for(p = threads.begin(); p != threads.end(); ++p) + + for (auto& p : pingers) { - (*p)->getThreadControl().join(); + p.second.join(); } - threads.resize(0); + pingers.resize(0); try { @@ -521,29 +567,40 @@ allTests(Test::TestHelper* helper) cout << "testing activation timeout... " << flush; try { - test(admin->getServerState("server-activation-timeout") == IceGrid::Inactive); + test(admin->getServerState("server-activation-timeout") == IceGrid::ServerState::Inactive); const int nThreads = 5; - Ice::ObjectPrx proxy = communicator->stringToProxy("server-activation-timeout"); - vector threads; - threads.reserve(nThreads); - vector::const_iterator p; - int i; - for(i = 0; i < nThreads; i++) - { - threads.push_back(new PingThread(proxy, 1)); - } - for(p = threads.begin(); p != threads.end(); ++p) + shared_ptr proxy = communicator->stringToProxy("server-activation-timeout"); + vector, thread>> pingers; + for (int i = 0; i < nThreads; i++) { - (*p)->start(); + auto pinger = make_shared(proxy, 1); + auto t = thread( + [pinger]() + { + pinger->run(); + }); + pingers.push_back(make_pair(pinger, std::move(t))); } - for(p = threads.begin(); p != threads.end(); ++p) + + for (const auto& p : pingers) { - IceInternal::UniquePtr ex((*p)->waitUntilFinished()); - test(dynamic_cast(ex.get())); + exception_ptr ex = p.first->waitUntilFinished(); + try + { + rethrow_exception(ex); + } + catch (const Ice::NoEndpointException&) + { + } + catch (...) + { + test(false); + } } - for(p = threads.begin(); p != threads.end(); ++p) + + for (auto& p : pingers) { - (*p)->getThreadControl().join(); + p.second.join(); } admin->stopServer("server-activation-timeout"); } @@ -562,7 +619,7 @@ allTests(Test::TestHelper* helper) cout << "testing deactivation timeout... " << flush; try { - test(admin->getServerState("server-deactivation-timeout") == IceGrid::Inactive); + test(admin->getServerState("server-deactivation-timeout") == IceGrid::ServerState::Inactive); communicator->stringToProxy("server-deactivation-timeout")->ice_ping(); admin->stopServer("server-deactivation-timeout"); } @@ -576,11 +633,11 @@ allTests(Test::TestHelper* helper) cout << "testing permanent disable on failure... " << flush; try { - test(admin->getServerState("server1") == IceGrid::Inactive); - TestIntfPrx obj = TestIntfPrx::checkedCast(communicator->stringToProxy("server1")); - waitForServerState(admin, "server1", IceGrid::Active); + test(admin->getServerState("server1") == IceGrid::ServerState::Inactive); + shared_ptr obj = Ice::checkedCast(communicator->stringToProxy("server1")); + waitForServerState(admin, "server1", IceGrid::ServerState::Active); obj->fail(); - waitForServerState(admin, "server1", IceGrid::Inactive); + waitForServerState(admin, "server1", IceGrid::ServerState::Inactive); try { obj->ice_ping(); @@ -591,19 +648,19 @@ allTests(Test::TestHelper* helper) } test(!admin->isServerEnabled("server1")); - test(admin->getServerState("server1-manual") == IceGrid::Inactive); + test(admin->getServerState("server1-manual") == IceGrid::ServerState::Inactive); admin->startServer("server1-manual"); - test(admin->getServerState("server1-manual") == IceGrid::Active); - obj = TestIntfPrx::checkedCast(communicator->stringToProxy("server1-manual")); - test(admin->getServerState("server1-manual") == IceGrid::Active); + test(admin->getServerState("server1-manual") == IceGrid::ServerState::Active); + obj = Ice::checkedCast(communicator->stringToProxy("server1-manual")); + test(admin->getServerState("server1-manual") == IceGrid::ServerState::Active); obj->fail(); - waitForServerState(admin, "server1-manual", IceGrid::Inactive); + waitForServerState(admin, "server1-manual", IceGrid::ServerState::Inactive); test(!admin->isServerEnabled("server1-manual")); - test(admin->getServerState("server1-always") == IceGrid::Active); - obj = TestIntfPrx::checkedCast(communicator->stringToProxy("server1-always")); + test(admin->getServerState("server1-always") == IceGrid::ServerState::Active); + obj = Ice::checkedCast(communicator->stringToProxy("server1-always")); obj->fail(); - waitForServerState(admin, "server1-always", IceGrid::Inactive); + waitForServerState(admin, "server1-always", IceGrid::ServerState::Inactive); test(!admin->isServerEnabled("server1-always")); } catch(const Ice::LocalException& ex) @@ -616,19 +673,20 @@ allTests(Test::TestHelper* helper) cout << "testing temporary disable on failure... " << flush; try { - test(admin->getServerState("server2") == IceGrid::Inactive); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server2")); + test(admin->getServerState("server2") == IceGrid::ServerState::Inactive); + auto obj = Ice::uncheckedCast(communicator->stringToProxy("server2")); + obj = obj->ice_locatorCacheTimeout(0); while(true) { obj->ice_ping(); - waitForServerState(admin, "server2", IceGrid::Active); - IceUtil::Time now = IceUtil::Time::now(); + waitForServerState(admin, "server2", IceGrid::ServerState::Active); + auto now = std::chrono::steady_clock::now(); obj->fail(); - waitForServerState(admin, "server2", IceGrid::Inactive); + waitForServerState(admin, "server2", IceGrid::ServerState::Inactive); try { obj->ice_ping(); - test(IceUtil::Time::now() - now >= IceUtil::Time::seconds(3)); + test(chrono::steady_clock::now() - now >= 3s); } catch (const Ice::NoEndpointException&) { @@ -653,36 +711,38 @@ allTests(Test::TestHelper* helper) } } test(admin->isServerEnabled("server2")); - waitForServerState(admin, "server2", IceGrid::Active); + waitForServerState(admin, "server2", IceGrid::ServerState::Active); obj->ice_ping(); admin->stopServer("server2"); - test(admin->getServerState("server2-manual") == IceGrid::Inactive); + test(admin->getServerState("server2-manual") == IceGrid::ServerState::Inactive); admin->startServer("server2-manual"); - test(admin->getServerState("server2-manual") == IceGrid::Active); - obj = TestIntfPrx::checkedCast(communicator->stringToProxy("server2-manual")); + test(admin->getServerState("server2-manual") == IceGrid::ServerState::Active); + obj = Ice::checkedCast(communicator->stringToProxy("server2-manual")); obj->fail(); - waitForServerState(admin, "server2-manual", IceGrid::Inactive); + waitForServerState(admin, "server2-manual", IceGrid::ServerState::Inactive); test(!admin->isServerEnabled("server2-manual")); admin->startServer("server2-manual"); test(admin->isServerEnabled("server2-manual")); - test(admin->getServerState("server2-manual") == IceGrid::Active); + test(admin->getServerState("server2-manual") == IceGrid::ServerState::Active); admin->stopServer("server2-manual"); - test(admin->getServerState("server2-always") == IceGrid::Active); - obj = TestIntfPrx::checkedCast(communicator->stringToProxy("server2-always")); + test(admin->getServerState("server2-always") == IceGrid::ServerState::Active); + obj = Ice::checkedCast(communicator->stringToProxy("server2-always")); obj->fail(); - waitForServerState(admin, "server2-always", IceGrid::Inactive); + waitForServerState(admin, "server2-always", IceGrid::ServerState::Inactive); test(!admin->isServerEnabled("server2-always")); nRetry = 0; while((!admin->isServerEnabled("server2-always") || - admin->getServerState("server2-always") != IceGrid::Active) && + admin->getServerState("server2-always") != IceGrid::ServerState::Active) && nRetry < 15) { IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); ++nRetry; } - test(admin->isServerEnabled("server2-always") && admin->getServerState("server2-always") == IceGrid::Active); + test( + admin->isServerEnabled("server2-always") && admin->getServerState("server2-always") == + IceGrid::ServerState::Active); obj->ice_ping(); } catch(const Ice::LocalException& ex) diff --git a/cpp/test/IceGrid/activation/TestI.h b/cpp/test/IceGrid/activation/TestI.h index 35dc14c474c..ecd362da3f7 100644 --- a/cpp/test/IceGrid/activation/TestI.h +++ b/cpp/test/IceGrid/activation/TestI.h @@ -7,7 +7,7 @@ #include -class TestI : public ::Test::TestIntf +class TestI final : public Test::TestIntf { public: diff --git a/cpp/test/IceGrid/allocation/AllTests.cpp b/cpp/test/IceGrid/allocation/AllTests.cpp index 3543e07e67c..aa4033a9652 100644 --- a/cpp/test/IceGrid/allocation/AllTests.cpp +++ b/cpp/test/IceGrid/allocation/AllTests.cpp @@ -2,65 +2,67 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include -#include #include #include #include #include #include +#include +#include using namespace std; using namespace Test; using namespace IceGrid; -class Callback : public IceUtil::Monitor, public virtual IceUtil::Shared +class Callback { public: - Callback() : _response(false), _exception(false) + Callback() : + _response(false), + _exception(false) { } void - response(const Ice::ObjectPrx& obj) + response(shared_ptr obj) { - Lock sync(*this); - _response = true; - _obj = obj; - notify(); - } + { + lock_guard lg(_mutex); + _response = true; + _obj = std::move(obj); + } - void - exception(const Ice::Exception&) - { - Lock sync(*this); - _exception = true; - notify(); + _condVar.notify_one(); } void - waitResponse(const char*, int) + exception() { - Lock sync(*this); - while(!_response && !_exception) { - wait(); + lock_guard lg(_mutex); + _exception = true; } + _condVar.notify_one(); + } + + void waitResponse(const char*, int) + { + unique_lock lock(_mutex); + _condVar.wait(lock, [&] { return _response || _exception; }); } bool - hasResponse(Ice::ObjectPrx& obj) + hasResponse(shared_ptr& obj) { - Lock sync(*this); + lock_guard lg(_mutex); obj = _obj; return _response; } - bool - hasException() + bool hasException() { - Lock sync(*this); + lock_guard lg(_mutex); return _exception; } @@ -68,50 +70,45 @@ class Callback : public IceUtil::Monitor, public virtual IceUtil bool _response; bool _exception; - Ice::ObjectPrx _obj; + mutex _mutex; + condition_variable _condVar; + shared_ptr _obj; }; -typedef IceUtil::Handle CallbackPtr; -class StressClient : public IceUtil::Thread, public IceUtil::Monitor +class StressClient { public: - StressClient(int id, const RegistryPrx& registry, bool destroySession) : - _communicator(registry->ice_getCommunicator()), + StressClient(int id, shared_ptr registry, bool destroySession) : _id(id), - _registry(registry), + _registry(std::move(registry)), _notified(false), _terminated(false), _destroySession(destroySession) { } - StressClient(int id, const SessionPrx& session) : - _communicator(session->ice_getCommunicator()), + StressClient(int id, shared_ptr session) : _id(id), - _session(session), + _session(std::move(session)), _notified(false), _terminated(false), _destroySession(false) { } - virtual void run() { { - Lock sync(*this); - while(!_notified) - { - wait(); - } + unique_lock lock(_mutex); + _condVar.wait(lock, [&] { return _notified == true; }); } - SessionPrx session; + shared_ptr session; while(true) { { - Lock sync(*this); + lock_guard lg(_mutex); if(_terminated) { if(!_session && session) @@ -133,15 +130,15 @@ class StressClient : public IceUtil::Thread, public IceUtil::MonitorcreateSession(os.str(), ""); - session->setAllocationTimeout(static_cast(IceUtilInternal::random(200))); // 200ms timeout + session->setAllocationTimeout(static_cast(_rd() % 200)); // 200ms timeout } } assert(session); session->keepAlive(); - Ice::ObjectPrx object; - switch(IceUtilInternal::random(_destroySession ? 4 : 2)) + shared_ptr object; + switch( _rd() % (_destroySession ? 4 : 2)) { case 0: object = allocate(session); @@ -163,8 +160,8 @@ class StressClient : public IceUtil::Thread, public IceUtil::MonitorreleaseObject(object->ice_getIdentity()); @@ -179,11 +176,11 @@ class StressClient : public IceUtil::Thread, public IceUtil::Monitor + allocate(const shared_ptr& session) { ostringstream os; - os << "stress-" << IceUtilInternal::random(6) + 1; + os << "stress-" << (_rd() % 6) + 1; try { return session->allocateObjectById(Ice::stringToIdentity(os.str())); @@ -197,11 +194,11 @@ class StressClient : public IceUtil::Thread, public IceUtil::Monitor + allocateByType(const shared_ptr& session) { try { @@ -210,72 +207,76 @@ class StressClient : public IceUtil::Thread, public IceUtil::Monitor& session) { ostringstream os; - os << "stress-" << IceUtilInternal::random(3); - CallbackPtr asyncCB = new Callback(); - IceGrid::Callback_Session_allocateObjectByIdPtr cb = - IceGrid::newCallback_Session_allocateObjectById(asyncCB, &Callback::response, &Callback::exception); - session->begin_allocateObjectById(Ice::stringToIdentity(os.str()), cb); + os << "stress-" << (_rd() % 3); + + auto cb = make_shared(); + session->allocateObjectByIdAsync(Ice::stringToIdentity(os.str()), + [cb](shared_ptr o) { cb->response(std::move(o)); }, + [cb](exception_ptr) { cb->exception(); }); session->destroy(); } void - allocateByTypeAndDestroy(const SessionPrx& session) + allocateByTypeAndDestroy(const shared_ptr& session) { - CallbackPtr asyncCB = new Callback(); - IceGrid::Callback_Session_allocateObjectByTypePtr cb = - IceGrid::newCallback_Session_allocateObjectByType(asyncCB, &Callback::response, &Callback::exception); - session->begin_allocateObjectByType("::StressTest", cb); + auto cb = make_shared(); + session->allocateObjectByTypeAsync("::StressTest", + [cb](shared_ptr o) { cb->response(std::move(o)); }, + [cb](exception_ptr) { cb->exception(); }); session->destroy(); } - void - notifyThread() + void notifyThread() { - Lock sync(*this); - _notified = true; - notify(); + { + lock_guard lg(_mutex); + _notified = true; + } + _condVar.notify_one(); } - void - terminate() + void terminate() { - Lock sync(*this); - _terminated = true; - notify(); + { + lock_guard lg(_mutex); + _terminated = true; + } + _condVar.notify_one(); } protected: - const Ice::CommunicatorPtr _communicator; const int _id; - const RegistryPrx _registry; - const SessionPrx _session; + const shared_ptr _registry; + const shared_ptr _session; bool _notified; bool _terminated; const bool _destroySession; + mutex _mutex; + condition_variable _condVar; + random_device _rd; }; -typedef IceUtil::Handle StressClientPtr; void allTests(Test::TestHelper* helper) { - Ice::CommunicatorPtr communicator = helper->communicator(); - IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::checkedCast( + auto communicator = helper->communicator(); + auto registry = Ice::checkedCast( communicator->stringToProxy(communicator->getDefaultLocator()->ice_getIdentity().category + "/Registry")); test(registry); - AdminSessionPrx session = registry->createAdminSession("foo", "bar"); + auto session = registry->createAdminSession("foo", "bar"); session->ice_getConnection()->setACM(registry->getACMTimeout(), - IceUtil::None, - Ice::ICE_ENUM(ACMHeartbeat, HeartbeatAlways)); + Ice::nullopt, + Ice::ACMHeartbeat::HeartbeatAlways); - AdminPrx admin = session->getAdmin(); + auto admin = session->getAdmin(); test(admin); cout << "starting router... " << flush; @@ -292,20 +293,20 @@ allTests(Test::TestHelper* helper) const int allocationTimeout = 5000; - Ice::ObjectPrx obj; - Ice::ObjectPrx dummy; + shared_ptr obj; + shared_ptr dummy; try { cout << "testing create session... " << flush; - SessionPrx session1 = registry->createSession("Client1", ""); - SessionPrx session2 = registry->createSession("Client2", ""); + auto session1 = registry->createSession("Client1", ""); + auto session2 = registry->createSession("Client2", ""); cout << "ok" << endl; cout << "testing allocate object by identity... " << flush; - Ice::Identity allocatable = Ice::stringToIdentity("allocatable"); - Ice::Identity allocatablebis = Ice::stringToIdentity("allocatablebis"); + auto allocatable = Ice::stringToIdentity("allocatable"); + auto allocatablebis = Ice::stringToIdentity("allocatablebis"); try { @@ -427,17 +428,15 @@ allTests(Test::TestHelper* helper) session2->setAllocationTimeout(allocationTimeout); - CallbackPtr asyncCB1 = new Callback(); - IceGrid::Callback_Session_allocateObjectByIdPtr cb1 = IceGrid::newCallback_Session_allocateObjectById(asyncCB1, - &Callback::response, - &Callback::exception); - - session2->begin_allocateObjectById(allocatable, cb1); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); - test(!asyncCB1->hasResponse(dummy)); + auto cb1 = make_shared(); + session2->allocateObjectByIdAsync(allocatable, + [&cb1](shared_ptr o) { cb1->response(o); }, + [&cb1](exception_ptr) { cb1->exception(); }); + this_thread::sleep_for(500ms); + test(!cb1->hasResponse(dummy)); session1->releaseObject(allocatable); - asyncCB1->waitResponse(__FILE__, __LINE__); - test(asyncCB1->hasResponse(dummy)); + cb1->waitResponse(__FILE__, __LINE__); + test(cb1->hasResponse(dummy)); session1->setAllocationTimeout(0); try @@ -457,16 +456,15 @@ allTests(Test::TestHelper* helper) { } session1->setAllocationTimeout(allocationTimeout); - asyncCB1 = new Callback(); - cb1 = IceGrid::newCallback_Session_allocateObjectById(asyncCB1, - &Callback::response, - &Callback::exception); - session1->begin_allocateObjectById(allocatable, cb1); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); - test(!asyncCB1->hasResponse(dummy)); + cb1 = make_shared(); + session1->allocateObjectByIdAsync(allocatable, + [&cb1](shared_ptr o) { cb1->response(o); }, + [&cb1](exception_ptr) { cb1->exception(); }); + this_thread::sleep_for(500ms); + test(!cb1->hasResponse(dummy)); session2->releaseObject(allocatable); - asyncCB1->waitResponse(__FILE__, __LINE__); - test(asyncCB1->hasResponse(dummy)); + cb1->waitResponse(__FILE__, __LINE__); + test(cb1->hasResponse(dummy)); session1->releaseObject(allocatable); @@ -578,16 +576,15 @@ allTests(Test::TestHelper* helper) session2->releaseObject(allocatablebis); session1->setAllocationTimeout(allocationTimeout); - CallbackPtr asyncCB3 = new Callback(); - IceGrid::Callback_Session_allocateObjectByTypePtr cb3 = - IceGrid::newCallback_Session_allocateObjectByType(asyncCB3, &Callback::response, &Callback::exception); - - session1->begin_allocateObjectByType("::Test", cb3); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); - test(!asyncCB3->hasResponse(dummy)); + auto cb3 = make_shared(); + session1->allocateObjectByTypeAsync("::Test", + [&cb3](shared_ptr o) { cb3->response(o); }, + [&cb3](exception_ptr) { cb3->exception(); }); + this_thread::sleep_for(500ms); + test(!cb3->hasResponse(dummy)); session2->releaseObject(obj->ice_getIdentity()); - asyncCB3->waitResponse(__FILE__, __LINE__); - test(asyncCB3->hasResponse(obj)); + cb3->waitResponse(__FILE__, __LINE__); + test(cb3->hasResponse(obj)); session1->releaseObject(obj->ice_getIdentity()); @@ -600,7 +597,7 @@ allTests(Test::TestHelper* helper) // not be visible to the allocation system immediately. session1->allocateObjectByType("::Test"); session1->releaseObject(obj->ice_getIdentity()); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100)); + this_thread::sleep_for(100ms); } test(false); } @@ -614,7 +611,7 @@ allTests(Test::TestHelper* helper) cout << "testing object allocation timeout... " << flush; session1->allocateObjectById(allocatable); - IceUtil::Time time = IceUtil::Time::now(); + auto time = chrono::system_clock::now(); session2->setAllocationTimeout(500); try { @@ -623,9 +620,9 @@ allTests(Test::TestHelper* helper) } catch(const AllocationTimeoutException&) { - test(time + IceUtil::Time::milliSeconds(100) < IceUtil::Time::now()); + test(time + 100ms < chrono::system_clock::now()); } - time = IceUtil::Time::now(); + time = chrono::system_clock::now(); try { session2->allocateObjectById(allocatable); @@ -634,8 +631,8 @@ allTests(Test::TestHelper* helper) catch(const AllocationTimeoutException&) { } - test(time + IceUtil::Time::milliSeconds(100) < IceUtil::Time::now()); - time = IceUtil::Time::now(); + test(time + 100ms < chrono::system_clock::now()); + time = chrono::system_clock::now(); try { session2->allocateObjectByType("::Test"); @@ -644,7 +641,7 @@ allTests(Test::TestHelper* helper) catch(const AllocationTimeoutException&) { } - test(time + IceUtil::Time::milliSeconds(100) < IceUtil::Time::now()); + test(time + 100ms < chrono::system_clock::now()); session1->releaseObject(allocatable); session2->setAllocationTimeout(0); @@ -755,28 +752,30 @@ allTests(Test::TestHelper* helper) session1->allocateObjectById(allocatable4); session2->setAllocationTimeout(allocationTimeout); - asyncCB1 = new Callback(); - cb1 = IceGrid::newCallback_Session_allocateObjectById(asyncCB1, &Callback::response, &Callback::exception); - session2->begin_allocateObjectById(allocatable3, cb1); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); - test(!asyncCB1->hasResponse(dummy)); + cb1 = make_shared(); + session2->allocateObjectByIdAsync(allocatable3, + [&cb1](shared_ptr o) { cb1->response(o); }, + [&cb1](exception_ptr) { cb1->exception(); }); + this_thread::sleep_for(500ms); + test(!cb1->hasResponse(dummy)); session1->releaseObject(allocatable3); - test(!asyncCB1->hasResponse(dummy)); + test(!cb1->hasResponse(dummy)); session1->releaseObject(allocatable4); - asyncCB1->waitResponse(__FILE__, __LINE__); - test(asyncCB1->hasResponse(dummy)); + cb1->waitResponse(__FILE__, __LINE__); + test(cb1->hasResponse(dummy)); session2->releaseObject(allocatable3); session1->setAllocationTimeout(allocationTimeout); test(session2->allocateObjectByType("::TestServer1")); - asyncCB3 = new Callback(); - cb3 = IceGrid::newCallback_Session_allocateObjectByType(asyncCB3, &Callback::response, &Callback::exception); - session1->begin_allocateObjectByType("::TestServer2", cb3); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); - test(!asyncCB3->hasResponse(dummy)); + cb3 = make_shared(); + session1->allocateObjectByTypeAsync("::TestServer2", + [&cb3](shared_ptr o) { cb3->response(o); }, + [&cb3](exception_ptr) { cb3->exception(); }); + this_thread::sleep_for(500ms); + test(!cb3->hasResponse(dummy)); session2->releaseObject(allocatable3); - asyncCB3->waitResponse(__FILE__, __LINE__); - test(asyncCB3->hasResponse(dummy)); + cb3->waitResponse(__FILE__, __LINE__); + test(cb3->hasResponse(dummy)); session1->releaseObject(allocatable4); session1->setAllocationTimeout(0); @@ -806,9 +805,9 @@ allTests(Test::TestHelper* helper) session2->releaseObject(Ice::stringToIdentity("allocatable31")); session2->releaseObject(Ice::stringToIdentity("allocatable41")); - Ice::ObjectPrx obj1 = session1->allocateObjectByType("::TestMultipleServer"); + auto obj1 = session1->allocateObjectByType("::TestMultipleServer"); test(obj1); - Ice::ObjectPrx obj2 = session2->allocateObjectByType("::TestMultipleServer"); + auto obj2 = session2->allocateObjectByType("::TestMultipleServer"); test(obj2); try { @@ -840,7 +839,7 @@ allTests(Test::TestHelper* helper) // not be visible to the allocation system immediately. session1->allocateObjectByType("::TestServer1"); session1->releaseObject(allocatable3); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100)); + this_thread::sleep_for(100ms); } test(false); } @@ -857,119 +856,125 @@ allTests(Test::TestHelper* helper) session2->setAllocationTimeout(allocationTimeout); session2->allocateObjectById(allocatable); - CallbackPtr asyncCB11 = new Callback(); - IceGrid::Callback_Session_allocateObjectByIdPtr cb11 = - IceGrid::newCallback_Session_allocateObjectById(asyncCB11, &Callback::response, &Callback::exception); - CallbackPtr asyncCB12 = new Callback(); - IceGrid::Callback_Session_allocateObjectByIdPtr cb12 = - IceGrid::newCallback_Session_allocateObjectById(asyncCB12, &Callback::response, &Callback::exception); - session1->begin_allocateObjectById(allocatable, cb11); - session1->begin_allocateObjectById(allocatable, cb12); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); - test(!asyncCB11->hasResponse(dummy)); - test(!asyncCB12->hasResponse(dummy)); + auto cb11 = make_shared(); + auto cb12 = make_shared(); + session1->allocateObjectByIdAsync(allocatable, + [&cb11](shared_ptr o) { cb11->response(o); }, + [&cb11](exception_ptr) { cb11->exception(); }); + session1->allocateObjectByIdAsync(allocatable, + [&cb12](shared_ptr o) { cb12->response(o); }, + [&cb12](exception_ptr) { cb12->exception(); }); + this_thread::sleep_for(500ms); + test(!cb11->hasResponse(dummy)); + test(!cb12->hasResponse(dummy)); session2->releaseObject(allocatable); - asyncCB11->waitResponse(__FILE__, __LINE__); - asyncCB12->waitResponse(__FILE__, __LINE__); - test(asyncCB11->hasResponse(dummy) ? asyncCB12->hasException() : asyncCB12->hasResponse(dummy)); - test(asyncCB12->hasResponse(dummy) ? asyncCB11->hasException() : asyncCB11->hasResponse(dummy)); + cb11->waitResponse(__FILE__, __LINE__); + cb12->waitResponse(__FILE__, __LINE__); + test(cb11->hasResponse(dummy) ? cb12->hasException() : cb12->hasResponse(dummy)); + test(cb12->hasResponse(dummy) ? cb11->hasException() : cb11->hasResponse(dummy)); session1->releaseObject(allocatable); session2->allocateObjectById(allocatable); - CallbackPtr asyncCB31 = new Callback(); - IceGrid::Callback_Session_allocateObjectByTypePtr cb31 = - IceGrid::newCallback_Session_allocateObjectByType(asyncCB31, &Callback::response, &Callback::exception); - CallbackPtr asyncCB32 = new Callback(); - IceGrid::Callback_Session_allocateObjectByTypePtr cb32 = - IceGrid::newCallback_Session_allocateObjectByType(asyncCB32, &Callback::response, &Callback::exception); - session1->begin_allocateObjectByType("::Test", cb31); - session1->begin_allocateObjectByType("::Test", cb32); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); - test(!asyncCB31->hasResponse(dummy)); - test(!asyncCB32->hasResponse(dummy)); + auto cb31 = make_shared(); + auto cb32 = make_shared(); + session1->allocateObjectByTypeAsync("::Test", + [&cb31](shared_ptr o) { cb31->response(o); }, + [&cb31](exception_ptr) { cb31->exception(); }); + session1->allocateObjectByTypeAsync("::Test", + [&cb32](shared_ptr o) { cb32->response(o); }, + [&cb32](exception_ptr) { cb32->exception(); }); + this_thread::sleep_for(500ms); + test(!cb31->hasResponse(dummy)); + test(!cb32->hasResponse(dummy)); session2->releaseObject(allocatable); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(300)); + this_thread::sleep_for(300ms); do { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); + this_thread::sleep_for(200ms); } - while(!asyncCB31->hasResponse(dummy) && !asyncCB32->hasResponse(dummy)); - test((asyncCB31->hasResponse(dummy) && dummy && !asyncCB32->hasResponse(dummy)) || - (asyncCB32->hasResponse(dummy) && dummy && !asyncCB31->hasResponse(dummy))); + while(!cb31->hasResponse(dummy) && !cb32->hasResponse(dummy)); + test((cb31->hasResponse(dummy) && dummy && !cb32->hasResponse(dummy)) || + (cb32->hasResponse(dummy) && dummy && !cb31->hasResponse(dummy))); session1->releaseObject(allocatable); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(300)); - CallbackPtr asyncCB33 = asyncCB31->hasResponse(dummy) ? asyncCB32 : asyncCB31; - asyncCB33->waitResponse(__FILE__, __LINE__); - test(asyncCB33->hasResponse(dummy) && dummy); + this_thread::sleep_for(300ms); + auto cb33 = cb31->hasResponse(dummy) ? cb32 : cb31; + cb33->waitResponse(__FILE__, __LINE__); + test(cb33->hasResponse(dummy) && dummy); session1->releaseObject(allocatable); session2->allocateObjectById(allocatable3); - asyncCB11 = new Callback(); - cb11 = IceGrid::newCallback_Session_allocateObjectById(asyncCB11, &Callback::response, &Callback::exception); - asyncCB12 = new Callback(); - cb12 = IceGrid::newCallback_Session_allocateObjectById(asyncCB12, &Callback::response, &Callback::exception); - session1->begin_allocateObjectById(allocatable3, cb11); - session1->begin_allocateObjectById(allocatable3, cb12); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); - test(!asyncCB11->hasResponse(dummy)); - test(!asyncCB12->hasResponse(dummy)); + cb11 = make_shared(); + cb12 = make_shared(); + session1->allocateObjectByIdAsync(allocatable3, + [&cb11](shared_ptr o) { cb11->response(o); }, + [&cb11](exception_ptr) { cb11->exception(); }); + session1->allocateObjectByIdAsync(allocatable3, + [&cb12](shared_ptr o) { cb12->response(o); }, + [&cb12](exception_ptr) { cb12->exception(); }); + this_thread::sleep_for(500ms); + test(!cb11->hasResponse(dummy)); + test(!cb12->hasResponse(dummy)); session2->releaseObject(allocatable3); - asyncCB11->waitResponse(__FILE__, __LINE__); - asyncCB12->waitResponse(__FILE__, __LINE__); - test(asyncCB11->hasResponse(dummy) ? asyncCB12->hasException() : asyncCB12->hasResponse(dummy)); - test(asyncCB12->hasResponse(dummy) ? asyncCB11->hasException() : asyncCB11->hasResponse(dummy)); + cb11->waitResponse(__FILE__, __LINE__); + cb12->waitResponse(__FILE__, __LINE__); + test(cb11->hasResponse(dummy) ? cb12->hasException() : cb12->hasResponse(dummy)); + test(cb12->hasResponse(dummy) ? cb11->hasException() : cb11->hasResponse(dummy)); session1->releaseObject(allocatable3); session2->allocateObjectById(allocatable3); - asyncCB31 = new Callback(); - cb31 = IceGrid::newCallback_Session_allocateObjectByType(asyncCB31, &Callback::response, &Callback::exception); - asyncCB32 = new Callback(); - cb32 = IceGrid::newCallback_Session_allocateObjectByType(asyncCB32, &Callback::response, &Callback::exception); - session1->begin_allocateObjectByType("::TestServer1", cb31); - session1->begin_allocateObjectByType("::TestServer1", cb32); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); - test(!asyncCB31->hasResponse(dummy)); - test(!asyncCB32->hasResponse(dummy)); + cb31 = make_shared(); + cb32 = make_shared(); + session1->allocateObjectByTypeAsync("::TestServer1", + [&cb31](shared_ptr o) { cb31->response(o); }, + [&cb31](exception_ptr) { cb31->exception(); }); + session1->allocateObjectByTypeAsync("::TestServer1", + [&cb32](shared_ptr o) { cb32->response(o); }, + [&cb32](exception_ptr) { cb32->exception(); }); + this_thread::sleep_for(500ms); + test(!cb31->hasResponse(dummy)); + test(!cb32->hasResponse(dummy)); session2->releaseObject(allocatable3); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(300)); + this_thread::sleep_for(300ms); do { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); + this_thread::sleep_for(200ms); } - while(!asyncCB31->hasResponse(dummy) && !asyncCB32->hasResponse(dummy)); - test((asyncCB31->hasResponse(dummy) && dummy && !asyncCB32->hasResponse(dummy)) || - (asyncCB32->hasResponse(dummy) && dummy && !asyncCB31->hasResponse(dummy))); + while(!cb31->hasResponse(dummy) && !cb32->hasResponse(dummy)); + test((cb31->hasResponse(dummy) && dummy && !cb32->hasResponse(dummy)) || + (cb32->hasResponse(dummy) && dummy && !cb31->hasResponse(dummy))); session1->releaseObject(allocatable3); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(300)); - asyncCB33 = asyncCB31->hasResponse(dummy) ? asyncCB32 : asyncCB31; - asyncCB33->waitResponse(__FILE__, __LINE__); - test(asyncCB33->hasResponse(dummy) && dummy); + this_thread::sleep_for(300ms); + cb33 = cb31->hasResponse(dummy) ? cb32 : cb31; + cb33->waitResponse(__FILE__, __LINE__); + test(cb33->hasResponse(dummy) && dummy); session1->releaseObject(allocatable3); session1->allocateObjectById(allocatable3); - asyncCB31 = new Callback(); - cb31 = IceGrid::newCallback_Session_allocateObjectByType(asyncCB31, &Callback::response, &Callback::exception); - asyncCB32 = new Callback(); - cb32 = IceGrid::newCallback_Session_allocateObjectByType(asyncCB32, &Callback::response, &Callback::exception); - session1->begin_allocateObjectByType("::TestServer1", cb31); - session1->begin_allocateObjectByType("::TestServer1", cb32); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); - test(!asyncCB31->hasResponse(dummy)); - test(!asyncCB32->hasResponse(dummy)); + cb31 = make_shared(); + cb32 = make_shared(); + session1->allocateObjectByTypeAsync("::TestServer1", + [&cb31](shared_ptr o) { cb31->response(o); }, + [&cb31](exception_ptr) { cb31->exception(); }); + session1->allocateObjectByTypeAsync("::TestServer1", + [&cb32](shared_ptr o) { cb32->response(o); }, + [&cb32](exception_ptr) { cb32->exception(); }); + this_thread::sleep_for(500ms); + test(!cb31->hasResponse(dummy)); + test(!cb32->hasResponse(dummy)); session1->releaseObject(allocatable3); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(300)); + this_thread::sleep_for(300ms); do { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); + this_thread::sleep_for(200ms); } - while(!asyncCB31->hasResponse(dummy) && !asyncCB32->hasResponse(dummy)); - test((asyncCB31->hasResponse(dummy) && dummy && !asyncCB32->hasResponse(dummy)) || - (asyncCB32->hasResponse(dummy) && dummy && !asyncCB31->hasResponse(dummy))); + while(!cb31->hasResponse(dummy) && !cb32->hasResponse(dummy)); + test((cb31->hasResponse(dummy) && dummy && !cb32->hasResponse(dummy)) || + (cb32->hasResponse(dummy) && dummy && !cb31->hasResponse(dummy))); session1->releaseObject(allocatable3); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(300)); - asyncCB33 = asyncCB31->hasResponse(dummy) ? asyncCB32 : asyncCB31; - asyncCB33->waitResponse(__FILE__, __LINE__); - test(asyncCB33->hasResponse(dummy) && dummy); + this_thread::sleep_for(300ms); + cb33 = cb31->hasResponse(dummy) ? cb32 : cb31; + cb33->waitResponse(__FILE__, __LINE__); + test(cb33->hasResponse(dummy) && dummy); session1->releaseObject(allocatable3); cout << "ok" << endl; @@ -980,17 +985,18 @@ allTests(Test::TestHelper* helper) test(obj && obj->ice_getIdentity().name == "allocatable"); session1->setAllocationTimeout(allocationTimeout); - asyncCB3 = new Callback(); - cb3 = IceGrid::newCallback_Session_allocateObjectByType(asyncCB3, &Callback::response, &Callback::exception); - session1->begin_allocateObjectByType("::Test", cb3); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(500)); - test(!asyncCB3->hasResponse(dummy)); + cb3 = make_shared(); + session1->allocateObjectByTypeAsync("::Test", + [&cb3](shared_ptr o) { cb3->response(o); }, + [&cb3](exception_ptr) { cb3->exception(); }); + this_thread::sleep_for(500ms); + test(!cb3->hasResponse(dummy)); session2->destroy(); - asyncCB3->waitResponse(__FILE__, __LINE__); - test(asyncCB3->hasResponse(obj)); + cb3->waitResponse(__FILE__, __LINE__); + test(cb3->hasResponse(obj)); session1->destroy(); - session2 = SessionPrx::uncheckedCast(registry->createSession("Client2", "")); + session2 = Ice::uncheckedCast(registry->createSession("Client2", "")); session2->setAllocationTimeout(0); session2->allocateObjectById(allocatable); session2->destroy(); @@ -1001,11 +1007,11 @@ allTests(Test::TestHelper* helper) session1 = registry->createSession("Client1", ""); session2 = registry->createSession("Client2", ""); - ServerDescriptorPtr objectAllocOriginal = admin->getServerInfo("ObjectAllocation").descriptor; - ServerDescriptorPtr objectAllocUpdate = ServerDescriptorPtr::dynamicCast(objectAllocOriginal->ice_clone()); + auto objectAllocOriginal = admin->getServerInfo("ObjectAllocation").descriptor; + auto objectAllocUpdate = dynamic_pointer_cast(objectAllocOriginal->ice_clone()); - ServerDescriptorPtr serverAllocOriginal = admin->getServerInfo("ServerAllocation").descriptor; - ServerDescriptorPtr serverAllocUpdate = ServerDescriptorPtr::dynamicCast(serverAllocOriginal->ice_clone()); + auto serverAllocOriginal = admin->getServerInfo("ServerAllocation").descriptor; + auto serverAllocUpdate = dynamic_pointer_cast(serverAllocOriginal->ice_clone()); NodeUpdateDescriptor nodeUpdate; nodeUpdate.name = "localnode"; @@ -1018,19 +1024,19 @@ allTests(Test::TestHelper* helper) { session1->allocateObjectById(allocatable3); - Ice::AsyncResultPtr r2 = session2->begin_allocateObjectById(allocatable4); + auto r2 = session2->allocateObjectByIdAsync(allocatable4); session1->allocateObjectById(allocatable4); session1->releaseObject(allocatable4); - test(!r2->isCompleted()); + test(r2.wait_for(chrono::milliseconds(0)) != future_status::ready); serverAllocUpdate->allocatable = false; admin->updateApplication(appUpdate); - test(!r2->isCompleted()); + test(r2.wait_for(chrono::milliseconds(0)) != future_status::ready); session1->releaseObject(allocatable3); - session2->end_allocateObjectById(r2); + r2.get(); session2->releaseObject(allocatable4); serverAllocUpdate->allocatable = true; @@ -1039,19 +1045,19 @@ allTests(Test::TestHelper* helper) { session1->allocateObjectById(allocatable); - Ice::AsyncResultPtr r2 = session2->begin_allocateObjectById(allocatable); + auto r2 = session2->allocateObjectByIdAsync(allocatable); objectAllocUpdate->deactivationTimeout = "23"; admin->updateApplication(appUpdate); session1->releaseObject(allocatable); - session2->end_allocateObjectById(r2); + r2.get(); session2->releaseObject(allocatable); } { session1->allocateObjectById(allocatable); - Ice::AsyncResultPtr r2 = session2->begin_allocateObjectById(allocatable); + auto r2 = session2->allocateObjectByIdAsync(allocatable); vector allocatables = objectAllocUpdate->adapters[0].allocatables; objectAllocUpdate->adapters[0].allocatables.clear(); // Remove the allocatable object @@ -1059,12 +1065,13 @@ allTests(Test::TestHelper* helper) try { - session2->end_allocateObjectById(r2); + r2.get(); test(false); } catch(const ObjectNotRegisteredException&) { } + try { session1->releaseObject(allocatable); @@ -1084,14 +1091,14 @@ allTests(Test::TestHelper* helper) cout << "ok" << endl; cout << "testing allocation with Glacier2 session... " << flush; - Ice::ObjectPrx routerBase = communicator->stringToProxy("Glacier2/router:default -p 12347"); - Glacier2::RouterPrx router1 = Glacier2::RouterPrx::checkedCast(routerBase->ice_connectionId("client1")); + auto routerBase = communicator->stringToProxy("Glacier2/router:default -p 12347"); + auto router1 = Ice::checkedCast(routerBase->ice_connectionId("client1")); test(router1); - Glacier2::SessionPrx sessionBase = router1->createSession("test1", "abc123"); + auto sessionBase = router1->createSession("test1", "abc123"); try { - session1 = IceGrid::SessionPrx::checkedCast(sessionBase->ice_connectionId("client1")->ice_router(router1)); + session1 = Ice::checkedCast(sessionBase->ice_connectionId("client1")->ice_router(router1)); test(session1); session1->ice_ping(); @@ -1136,45 +1143,50 @@ allTests(Test::TestHelper* helper) cout << "stress test... " << flush; - SessionPrx stressSession = registry->createSession("StressSession", ""); + auto stressSession = registry->createSession("StressSession", ""); const int nClients = 10; - int i; - vector clients; - for(i = 0; i < nClients - 2; ++i) + map, future> clients; + random_device rd; + + for(int i = 0; i < nClients - 2; ++i) { - if(IceUtilInternal::random(2) == 1) + shared_ptr client; + if(rd() % 2 == 1) { - clients.push_back(new StressClient(i, registry, false)); + client = make_shared(i, registry, false); } else { - clients.push_back(new StressClient(i, stressSession)); + client = make_shared(i, stressSession); } - clients.back()->start(); + clients.insert(make_pair(client, async(launch::async, [=] { client->run(); }))); + } + + { + auto client8 = make_shared(8, registry, true); + clients.insert(make_pair(client8, async(launch::async, [=] { client8->run(); }))); + auto client9 = make_shared(9, registry, true); + clients.insert(make_pair(client9, async(launch::async, [=] { client9->run(); }))); } - clients.push_back(new StressClient(i++, registry, true)); - clients.back()->start(); - clients.push_back(new StressClient(i++, registry, true)); - clients.back()->start(); - for(vector::const_iterator p = clients.begin(); p != clients.end(); ++p) + for(const auto& c : clients) { - (*p)->notifyThread(); + c.first->notifyThread(); } // // Let the stress client run for a bit. // - IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(8)); + this_thread::sleep_for(8s); // // Terminate the stress clients. // - for(vector::const_iterator q = clients.begin(); q != clients.end(); ++q) + for(auto& c : clients) { - (*q)->terminate(); - (*q)->getThreadControl().join(); + c.first->terminate(); + c.second.get(); } stressSession->destroy(); diff --git a/cpp/test/IceGrid/allocation/PermissionsVerifier.cpp b/cpp/test/IceGrid/allocation/PermissionsVerifier.cpp index 6e15bad1c0d..a7087847a96 100644 --- a/cpp/test/IceGrid/allocation/PermissionsVerifier.cpp +++ b/cpp/test/IceGrid/allocation/PermissionsVerifier.cpp @@ -4,37 +4,33 @@ #include #include +#include using namespace std; -class PermissionsVerifierI : public Glacier2::PermissionsVerifier +class PermissionsVerifierI final : public Glacier2::PermissionsVerifier { public: - virtual bool - checkPermissions(const string&, const string&, string&, const Ice::Current&) const + bool + checkPermissions(string, string, string&, const Ice::Current&) const override { return true; } }; -class PermissionsVerifierServer : public Ice::Application +class Server : public Test::TestHelper { public: - virtual int run(int, char*[]) + void run(int argc, char** argv) override { - Ice::ObjectAdapterPtr adapter = communicator()->createObjectAdapter("PermissionsVerifier"); - adapter->add(new PermissionsVerifierI, Ice::stringToIdentity("PermissionsVerifier")); + Ice::CommunicatorHolder communicator = initialize(argc, argv); + auto adapter = communicator->createObjectAdapter("PermissionsVerifier"); + adapter->add(make_shared(), Ice::stringToIdentity("PermissionsVerifier")); adapter->activate(); - communicator()->waitForShutdown(); - return EXIT_SUCCESS; + communicator->waitForShutdown(); } }; -int -main(int argc, char* argv[]) -{ - PermissionsVerifierServer app; - return app.main(argc, argv); -} +DEFINE_TEST(Server) \ No newline at end of file diff --git a/cpp/test/IceGrid/allocation/Server.cpp b/cpp/test/IceGrid/allocation/Server.cpp index 5b45a7e7468..b3fb5db6296 100644 --- a/cpp/test/IceGrid/allocation/Server.cpp +++ b/cpp/test/IceGrid/allocation/Server.cpp @@ -12,28 +12,28 @@ class Server : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Server::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); - Ice::PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); string name = properties->getProperty("Ice.ProgramName"); - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("Server"); - adapter->add(new TestI(properties), Ice::stringToIdentity("allocatable")); - adapter->add(new TestI(properties), Ice::stringToIdentity("nonallocatable")); - adapter->add(new TestI(properties), Ice::stringToIdentity("allocatable1")); - adapter->add(new TestI(properties), Ice::stringToIdentity("allocatable2")); - adapter->add(new TestI(properties), Ice::stringToIdentity("allocatable3")); - adapter->add(new TestI(properties), Ice::stringToIdentity("allocatable4")); - adapter->add(new TestI(properties), Ice::stringToIdentity("allocatable11")); - adapter->add(new TestI(properties), Ice::stringToIdentity("allocatable21")); - adapter->add(new TestI(properties), Ice::stringToIdentity("allocatable31")); - adapter->add(new TestI(properties), Ice::stringToIdentity("allocatable41")); + auto adapter = communicator->createObjectAdapter("Server"); + adapter->add(make_shared(properties), Ice::stringToIdentity("allocatable")); + adapter->add(make_shared(properties), Ice::stringToIdentity("nonallocatable")); + adapter->add(make_shared(properties), Ice::stringToIdentity("allocatable1")); + adapter->add(make_shared(properties), Ice::stringToIdentity("allocatable2")); + adapter->add(make_shared(properties), Ice::stringToIdentity("allocatable3")); + adapter->add(make_shared(properties), Ice::stringToIdentity("allocatable4")); + adapter->add(make_shared(properties), Ice::stringToIdentity("allocatable11")); + adapter->add(make_shared(properties), Ice::stringToIdentity("allocatable21")); + adapter->add(make_shared(properties), Ice::stringToIdentity("allocatable31")); + adapter->add(make_shared(properties), Ice::stringToIdentity("allocatable41")); try { diff --git a/cpp/test/IceGrid/allocation/TestI.cpp b/cpp/test/IceGrid/allocation/TestI.cpp index f91a7ac44b2..f2aff630cfa 100644 --- a/cpp/test/IceGrid/allocation/TestI.cpp +++ b/cpp/test/IceGrid/allocation/TestI.cpp @@ -5,8 +5,8 @@ #include #include -TestI::TestI(const Ice::PropertiesPtr& properties) : - _properties(properties) +TestI::TestI(std::shared_ptr properties) : + _properties(std::move(properties)) { } @@ -17,7 +17,7 @@ TestI::shutdown(const Ice::Current& current) } std::string -TestI::getProperty(const std::string& name, const Ice::Current&) +TestI::getProperty(std::string name, const Ice::Current&) { return _properties->getProperty(name); } diff --git a/cpp/test/IceGrid/allocation/TestI.h b/cpp/test/IceGrid/allocation/TestI.h index 1fcf402f93d..e6edeef7abd 100644 --- a/cpp/test/IceGrid/allocation/TestI.h +++ b/cpp/test/IceGrid/allocation/TestI.h @@ -7,18 +7,18 @@ #include -class TestI : public ::Test::TestIntf +class TestI final : public Test::TestIntf { public: - TestI(const Ice::PropertiesPtr&); + TestI(std::shared_ptr); - virtual void shutdown(const Ice::Current&); - virtual std::string getProperty(const std::string&, const Ice::Current&); + void shutdown(const Ice::Current&) override; + std::string getProperty(std::string, const ::Ice::Current&) override; private: - Ice::PropertiesPtr _properties; + std::shared_ptr _properties; }; #endif diff --git a/cpp/test/IceGrid/deployer/AllTests.cpp b/cpp/test/IceGrid/deployer/AllTests.cpp index d6885bd6e2d..37899d4d03d 100644 --- a/cpp/test/IceGrid/deployer/AllTests.cpp +++ b/cpp/test/IceGrid/deployer/AllTests.cpp @@ -3,6 +3,7 @@ // #include +#include #include #include #include @@ -50,34 +51,17 @@ bool isLongLineEnd(const string& line) } -#ifdef ICE_CPP11_COMPILER -function +function&)> proxyIdentityEqual(const string& strId) { - return [id = Ice::stringToIdentity(strId)](const Ice::ObjectPrxPtr& obj) + return [id = Ice::stringToIdentity(strId)](const shared_ptr& obj) { return obj->ice_getIdentity() == id; }; } -#else -struct ProxyEqualIdentity : public std::binary_function -{ - bool - operator()(const Ice::ObjectPrx& p1, const string& id) const - { - return p1->ice_getIdentity() == Ice::stringToIdentity(id); - } -}; - -binder2nd -proxyIdentityEqual(const string& strId) -{ - return bind2nd(ProxyEqualIdentity(), strId); -} -#endif void -logTests(const Ice::CommunicatorPtr& comm, const AdminSessionPrx& session) +logTests(const shared_ptr& comm, const shared_ptr& session) { cout << "testing stderr/stdout/log files... " << flush; string testDir = comm->getProperties()->getProperty("TestDir"); @@ -107,7 +91,7 @@ logTests(const Ice::CommunicatorPtr& comm, const AdminSessionPrx& session) { } - Ice::ObjectPrx obj = TestIntfPrx::checkedCast(comm->stringToProxy("LogServer")); + shared_ptr obj = Ice::checkedCast(comm->stringToProxy("LogServer")); try { session->openServerStdErr("LogServer", -1)->destroy(); @@ -119,7 +103,7 @@ logTests(const Ice::CommunicatorPtr& comm, const AdminSessionPrx& session) test(false); } - FileIteratorPrx it; + shared_ptr it; Ice::StringSeq lines; try { @@ -379,20 +363,20 @@ void allTests(Test::TestHelper* helper) { Ice::CommunicatorPtr comm = helper->communicator(); - IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::checkedCast( + shared_ptr registry = Ice::checkedCast( comm->stringToProxy(comm->getDefaultLocator()->ice_getIdentity().category + "/Registry")); test(registry); - IceGrid::QueryPrx query = IceGrid::QueryPrx::checkedCast( + shared_ptr query = Ice::checkedCast( comm->stringToProxy(comm->getDefaultLocator()->ice_getIdentity().category + "/Query")); test(query); - AdminSessionPrx session = registry->createAdminSession("foo", "bar"); + shared_ptr session = registry->createAdminSession("foo", "bar"); session->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::ICE_ENUM(ACMHeartbeat, HeartbeatAlways)); - AdminPrx admin = session->getAdmin(); + shared_ptr admin = session->getAdmin(); test(admin); cout << "testing server registration... " << flush; @@ -420,7 +404,8 @@ allTests(Test::TestHelper* helper) cout << "ok" << endl; cout << "testing object registration... " << flush; - Ice::ObjectProxySeq objs = query->findAllObjectsByType("::Test"); + + auto objs = query->findAllObjectsByType("::Test"); test(find_if(objs.begin(), objs.end(), proxyIdentityEqual("Server1")) != objs.end()); test(find_if(objs.begin(), objs.end(), proxyIdentityEqual("Server2")) != objs.end()); test(find_if(objs.begin(), objs.end(), proxyIdentityEqual("SimpleServer")) != objs.end()); @@ -440,24 +425,24 @@ allTests(Test::TestHelper* helper) } { - Ice::ObjectPrx obj = query->findObjectByType("::Test"); + shared_ptr obj = query->findObjectByType("::Test"); string id = comm->identityToString(obj->ice_getIdentity()); test(id.find("Server") == 0 || id.find("IceBox") == 0 || id == "SimpleServer" || id == "SimpleIceBox-SimpleService" || id == "ReplicatedObject"); } { - Ice::ObjectPrx obj = query->findObjectByTypeOnLeastLoadedNode("::Test", LoadSample5); + shared_ptr obj = query->findObjectByTypeOnLeastLoadedNode("::Test", LoadSample::LoadSample5); string id = comm->identityToString(obj->ice_getIdentity()); test(id.find("Server") == 0 || id.find("IceBox") == 0 || id == "SimpleServer" || id == "SimpleIceBox-SimpleService" || id == "ReplicatedObject"); } { - Ice::ObjectPrx obj = query->findObjectByType("::Foo"); + shared_ptr obj = query->findObjectByType("::Foo"); test(!obj); - obj = query->findObjectByTypeOnLeastLoadedNode("::Foo", LoadSample15); + obj = query->findObjectByTypeOnLeastLoadedNode("::Foo", LoadSample::LoadSample15); test(!obj); } @@ -490,15 +475,15 @@ allTests(Test::TestHelper* helper) replicated14.name = "ReplicatedObject14"; test(query->findObjectById(replicated14)->ice_getEncodingVersion() == Ice::stringToEncodingVersion("1.4")); - Ice::LocatorPrx locator = comm->getDefaultLocator(); - test(query->findObjectById(encoding10_oneway) == locator->findObjectById(encoding10_oneway)); - test(query->findObjectById(encoding10_secure) == locator->findObjectById(encoding10_secure)); - test(query->findObjectById(oaoptions) == locator->findObjectById(oaoptions)); - test(query->findObjectById(comoptions) == locator->findObjectById(comoptions)); - test(query->findObjectById(options34) == locator->findObjectById(options34)); - test(query->findObjectById(simpleServer) == locator->findObjectById(simpleServer)); - test(query->findObjectById(replicated15) == locator->findObjectById(replicated15)); - test(query->findObjectById(replicated14) == locator->findObjectById(replicated14)); + shared_ptr locator = comm->getDefaultLocator(); + test(Ice::targetEqualTo(query->findObjectById(encoding10_oneway), locator->findObjectById(encoding10_oneway))); + test(Ice::targetEqualTo(query->findObjectById(encoding10_secure), locator->findObjectById(encoding10_secure))); + test(Ice::targetEqualTo(query->findObjectById(oaoptions), locator->findObjectById(oaoptions))); + test(Ice::targetEqualTo(query->findObjectById(comoptions), locator->findObjectById(comoptions))); + test(Ice::targetEqualTo(query->findObjectById(options34), locator->findObjectById(options34))); + test(Ice::targetEqualTo(query->findObjectById(simpleServer), locator->findObjectById(simpleServer))); + test(Ice::targetEqualTo(query->findObjectById(replicated15), locator->findObjectById(replicated15))); + test(Ice::targetEqualTo(query->findObjectById(replicated14), locator->findObjectById(replicated14))); cout << "ok" << endl; @@ -511,20 +496,20 @@ allTests(Test::TestHelper* helper) // server. Ensure we can reach each object. // cout << "pinging server objects... " << flush; - TestIntfPrx obj; - obj = TestIntfPrx::checkedCast(comm->stringToProxy("Server1@Server1.Server")); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("Server2@Server2.Server")); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("SimpleServer@SimpleServer.Server")); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox1-Service2@IceBox1Service2Adapter")); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox2-Service1@IceBox2.Service1.Service1")); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox2-Service2@IceBox2Service2Adapter")); - obj = TestIntfPrx::checkedCast( + shared_ptr obj; + obj = Ice::checkedCast(comm->stringToProxy("Server1@Server1.Server")); + obj = Ice::checkedCast(comm->stringToProxy("Server2@Server2.Server")); + obj = Ice::checkedCast(comm->stringToProxy("SimpleServer@SimpleServer.Server")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox1-Service2@IceBox1Service2Adapter")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox2-Service1@IceBox2.Service1.Service1")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox2-Service2@IceBox2Service2Adapter")); + obj = Ice::checkedCast( comm->stringToProxy("SimpleIceBox-SimpleService@SimpleIceBox.SimpleService.SimpleService")); cout << "ok" << endl; cout << "testing server configuration... " << flush; - obj = TestIntfPrx::checkedCast(comm->stringToProxy("Server1@Server1.Server")); + obj = Ice::checkedCast(comm->stringToProxy("Server1@Server1.Server")); test(obj->getProperty("Type") == "Server"); test(obj->getProperty("Name") == "Server1"); test(obj->getProperty("NameName") == "Server1Server1"); @@ -547,7 +532,7 @@ allTests(Test::TestHelper* helper) cout << "ok" << endl; cout << "testing service configuration... " << flush; - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); test(obj->getProperty("Service1.Type") == "standard"); test(obj->getProperty("Service1.ServiceName") == "Service1"); test(obj->getProperty("TestService1Identity") == "IceBox1-Service1"); @@ -563,7 +548,7 @@ allTests(Test::TestHelper* helper) test(obj->getProperty("PropertyWithEscapeSpace") == "foo\\ "); test(obj->getProperty("PropertyWithProperty") == "Plugin.EntryPoint=foo:bar --Ice.Config=\\\\\\server\\foo bar\\file.cfg"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox2-Service2@IceBox2Service2Adapter")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox2-Service2@IceBox2Service2Adapter")); test(obj->getProperty("Service2.Type") == "nonstandard"); test(obj->getProperty("Service2.ServiceName") == "Service2"); test(obj->getProperty("Service2.DebugProperty") == ""); @@ -571,41 +556,41 @@ allTests(Test::TestHelper* helper) cout << "ok" << endl; cout << "testing server options... " << flush; - obj = TestIntfPrx::checkedCast(comm->stringToProxy("Server1@Server1.Server")); + obj = Ice::checkedCast(comm->stringToProxy("Server1@Server1.Server")); test(obj->getProperty("Test.Test") == "2"); test(obj->getProperty("Test.Test1") == "0"); cout << "ok" << endl; cout << "testing variables... " << flush; - vector proxies; - obj = TestIntfPrx::checkedCast(comm->stringToProxy("Server1@Server1.Server")); + vector> proxies; + obj = Ice::checkedCast(comm->stringToProxy("Server1@Server1.Server")); proxies.push_back(obj); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); proxies.push_back(obj); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("SimpleServer@SimpleServer.Server")); + obj = Ice::checkedCast(comm->stringToProxy("SimpleServer@SimpleServer.Server")); proxies.push_back(obj); - obj = TestIntfPrx::checkedCast( + obj = Ice::checkedCast( comm->stringToProxy("SimpleIceBox-SimpleService@SimpleIceBox.SimpleService.SimpleService")); proxies.push_back(obj); - for(vector::const_iterator p = proxies.begin(); p != proxies.end(); ++p) + for(const auto& p : proxies) { - test((*p)->getProperty("AppVarProp") == "AppVar"); - test((*p)->getProperty("NodeVarProp") == "NodeVar"); - test((*p)->getProperty("RecursiveAppVarProp") == "Test"); - test((*p)->getProperty("AppVarOverridedProp") == "OverridedInNode"); - test((*p)->getProperty("AppVarDefinedInNodeProp") == "localnode"); - test((*p)->getProperty("EscapedAppVarProp") == "${escaped}"); - test((*p)->getProperty("RecursiveEscapedAppVarProp") == "${escaped}"); - test((*p)->getProperty("Recursive2EscapedAppVarProp") == "${escaped}"); - test((*p)->getProperty("RecursiveNodeVarProp") == "localnode"); - test((*p)->getProperty("TestDirProp") != "NotThisValue"); + test(p->getProperty("AppVarProp") == "AppVar"); + test(p->getProperty("NodeVarProp") == "NodeVar"); + test(p->getProperty("RecursiveAppVarProp") == "Test"); + test(p->getProperty("AppVarOverridedProp") == "OverridedInNode"); + test(p->getProperty("AppVarDefinedInNodeProp") == "localnode"); + test(p->getProperty("EscapedAppVarProp") == "${escaped}"); + test(p->getProperty("RecursiveEscapedAppVarProp") == "${escaped}"); + test(p->getProperty("Recursive2EscapedAppVarProp") == "${escaped}"); + test(p->getProperty("RecursiveNodeVarProp") == "localnode"); + test(p->getProperty("TestDirProp") != "NotThisValue"); } cout << "ok" << endl; cout << "testing parameters... " << flush; - obj = TestIntfPrx::checkedCast(comm->stringToProxy("Server1@Server1.Server")); + obj = Ice::checkedCast(comm->stringToProxy("Server1@Server1.Server")); test(obj->getProperty("Param1Prop") == "Param1"); test(obj->getProperty("Param2Prop") == "AppVar"); test(obj->getProperty("ParamEscapedProp") == "${escaped}"); @@ -613,7 +598,7 @@ allTests(Test::TestHelper* helper) test(obj->getProperty("AppVarOverridedByParamProp") == "Overrided"); test(obj->getProperty("NodeVarOverridedByParamProp") == "Test"); test(obj->getProperty("DefaultParamProp") == "VALUE"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("Server2@Server2.Server")); + obj = Ice::checkedCast(comm->stringToProxy("Server2@Server2.Server")); test(obj->getProperty("Param1Prop") == "Param12"); test(obj->getProperty("Param2Prop") == "OverridedInNode"); test(obj->getProperty("ParamEscapedProp") == "${escaped}"); @@ -622,16 +607,16 @@ allTests(Test::TestHelper* helper) test(obj->getProperty("NodeVarOverridedByParamProp") == "Test"); test(obj->getProperty("DefaultParamProp") == "OTHERVALUE"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); test(obj->getProperty("AppVarOverridedByParamProp") == "Test"); test(obj->getProperty("NodeVarOverridedByParamProp") == "Overrided"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox1-Service2@IceBox1Service2Adapter")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox1-Service2@IceBox1Service2Adapter")); test(obj->getProperty("AppVarOverridedByParamProp") == "Test"); test(obj->getProperty("NodeVarOverridedByParamProp") == "Test"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox2-Service1@IceBox2.Service1.Service1")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox2-Service1@IceBox2.Service1.Service1")); test(obj->getProperty("AppVarOverridedByParamProp") == "Test"); test(obj->getProperty("NodeVarOverridedByParamProp") == "Overrided"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox2-Service2@IceBox2Service2Adapter")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox2-Service2@IceBox2Service2Adapter")); test(obj->getProperty("AppVarOverridedByParamProp") == "Test"); test(obj->getProperty("NodeVarOverridedByParamProp") == "Test"); @@ -656,33 +641,33 @@ allTests(Test::TestHelper* helper) cout << "ok" << endl; cout << "testing property sets..." << flush; - obj = TestIntfPrx::checkedCast(comm->stringToProxy("Server1@Server1.Server")); + obj = Ice::checkedCast(comm->stringToProxy("Server1@Server1.Server")); test(obj->getProperty("AppProperty") == "AppVar"); test(obj->getProperty("AppProperty2") == "OverrideMe"); test(obj->getProperty("AppProperty21") == "Override"); test(obj->getProperty("NodeProperty") == "NodeVar"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("Server2@Server2.Server")); + obj = Ice::checkedCast(comm->stringToProxy("Server2@Server2.Server")); test(obj->getProperty("AppProperty") == "AppVar"); test(obj->getProperty("AppProperty2") == "OverrideMe"); test(obj->getProperty("AppProperty21") == "Override"); test(obj->getProperty("NodeProperty") == "NodeVar"); test(obj->getProperty("ServerInstanceProperty") == "Server2"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); test(obj->getProperty("AppProperty") == ""); // IceBox server properties aren't inherited for IceBox1 test(obj->getProperty("AppProperty2") == ""); test(obj->getProperty("AppProperty21") == ""); test(obj->getProperty("NodeProperty") == ""); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox2-Service1@IceBox2.Service1.Service1")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox2-Service1@IceBox2.Service1.Service1")); test(obj->getProperty("AppProperty") == "AppVar"); test(obj->getProperty("AppProperty2") == "OverrideMe"); test(obj->getProperty("AppProperty21") == "Override"); test(obj->getProperty("NodeProperty") == "NodeVar"); test(obj->getProperty("IceBoxInstanceProperty") == "IceBox2"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox2-Service2@IceBox2Service2Adapter")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox2-Service2@IceBox2Service2Adapter")); test(obj->getProperty("AppProperty") == "AppVar"); test(obj->getProperty("AppProperty2") == "OverrideMe"); test(obj->getProperty("AppProperty21") == "Override"); @@ -690,17 +675,17 @@ allTests(Test::TestHelper* helper) test(obj->getProperty("IceBoxInstanceProperty") == "IceBox2"); test(obj->getProperty("ServiceInstanceProperty") == "Service2"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("SimpleServer@SimpleServer.Server")); + obj = Ice::checkedCast(comm->stringToProxy("SimpleServer@SimpleServer.Server")); test(obj->getProperty("AppProperty") == "AppVar"); test(obj->getProperty("AppProperty2") == "OverrideMe"); test(obj->getProperty("AppProperty21") == "Override"); test(obj->getProperty("NodeProperty") == "NodeVar"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox1-Service1@IceBox1.Service1.Service1")); test(obj->getProperty("ServerInstanceServiceProperty") == "service1"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox1-Service4@IceBox1.Service4.Service4")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox1-Service4@IceBox1.Service4.Service4")); test(obj->getProperty("ServerInstanceServiceProperty") == "service4"); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox2-Service4@IceBox2.Service4.Service4")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox2-Service4@IceBox2.Service4.Service4")); test(obj->getProperty("IceBoxInstanceProperty") == "overridden"); cout << "ok" << endl; @@ -711,8 +696,8 @@ allTests(Test::TestHelper* helper) templ.parameters.push_back("nam3"); templ.parameters.push_back("nam2"); templ.parameters.push_back("nam3"); - templ.descriptor = new ServerDescriptor(); - ServerDescriptorPtr server = ServerDescriptorPtr::dynamicCast(templ.descriptor); + templ.descriptor = make_shared(); + ServerDescriptorPtr server = dynamic_pointer_cast(templ.descriptor); server->id = "test"; server->exe = "${test.dir}/server"; server->applicationDistrib = false; @@ -745,25 +730,25 @@ void allTestsWithTarget(Test::TestHelper* helper) { Ice::CommunicatorPtr comm = helper->communicator(); - RegistryPrx registry = IceGrid::RegistryPrx::checkedCast( + shared_ptr registry = Ice::checkedCast( comm->stringToProxy(comm->getDefaultLocator()->ice_getIdentity().category + "/Registry")); test(registry); - AdminSessionPrx session = registry->createAdminSession("foo", "bar"); + shared_ptr session = registry->createAdminSession("foo", "bar"); - session->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::HeartbeatOnIdle); + session->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::ACMHeartbeat::HeartbeatOnIdle); - AdminPrx admin = session->getAdmin(); + shared_ptr admin = session->getAdmin(); test(admin); cout << "testing targets... " << flush; - TestIntfPrx obj = TestIntfPrx::checkedCast(comm->stringToProxy("Server3@Server3.Server")); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox3-Service1@IceBox3.Service1.Service1")); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox3-Service3@IceBox3.Service3.Service3")); + shared_ptr obj = Ice::checkedCast(comm->stringToProxy("Server3@Server3.Server")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox3-Service1@IceBox3.Service1.Service1")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox3-Service3@IceBox3.Service3.Service3")); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("IceBox3-Service4@IceBox3.Service4.Service4")); + obj = Ice::checkedCast(comm->stringToProxy("IceBox3-Service4@IceBox3.Service4.Service4")); - obj = TestIntfPrx::checkedCast(comm->stringToProxy("Server3@Server3.Server")); + obj = Ice::checkedCast(comm->stringToProxy("Server3@Server3.Server")); test(obj->getProperty("TargetProp") == "1"); cout << "ok" << endl; diff --git a/cpp/test/IceGrid/deployer/Server.cpp b/cpp/test/IceGrid/deployer/Server.cpp index f3e3fd320de..11ecae316f6 100644 --- a/cpp/test/IceGrid/deployer/Server.cpp +++ b/cpp/test/IceGrid/deployer/Server.cpp @@ -80,8 +80,7 @@ Server::run(int argc, char** argv) } adapter = communicator->createObjectAdapter("Server"); - Ice::ObjectPtr object = new TestI(properties); - adapter->add(object, Ice::stringToIdentity(name)); + adapter->add(make_shared(properties), Ice::stringToIdentity(name)); try { adapter->activate(); diff --git a/cpp/test/IceGrid/deployer/Service.cpp b/cpp/test/IceGrid/deployer/Service.cpp index 2071fde15cd..e572c544908 100644 --- a/cpp/test/IceGrid/deployer/Service.cpp +++ b/cpp/test/IceGrid/deployer/Service.cpp @@ -30,7 +30,7 @@ extern "C" // Factory function // ICE_DECLSPEC_EXPORT ::IceBox::Service* -create(CommunicatorPtr) +create(const CommunicatorPtr&) { return new ServiceI; } @@ -52,8 +52,9 @@ ServiceI::start(const string& name, { Ice::PropertiesPtr properties = communicator->getProperties(); Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter(name); - Ice::ObjectPtr object = new TestI(properties); - adapter->add(object, stringToIdentity(properties->getProperty(name + ".Identity"))); + adapter->add( + make_shared(properties), + stringToIdentity(properties->getProperty(name + ".Identity"))); adapter->activate(); } diff --git a/cpp/test/IceGrid/deployer/TestI.cpp b/cpp/test/IceGrid/deployer/TestI.cpp index f91a7ac44b2..ecd4c4224fb 100644 --- a/cpp/test/IceGrid/deployer/TestI.cpp +++ b/cpp/test/IceGrid/deployer/TestI.cpp @@ -17,7 +17,7 @@ TestI::shutdown(const Ice::Current& current) } std::string -TestI::getProperty(const std::string& name, const Ice::Current&) +TestI::getProperty(std::string name, const Ice::Current&) { return _properties->getProperty(name); } diff --git a/cpp/test/IceGrid/deployer/TestI.h b/cpp/test/IceGrid/deployer/TestI.h index 1fcf402f93d..44096e406ff 100644 --- a/cpp/test/IceGrid/deployer/TestI.h +++ b/cpp/test/IceGrid/deployer/TestI.h @@ -14,7 +14,7 @@ class TestI : public ::Test::TestIntf TestI(const Ice::PropertiesPtr&); virtual void shutdown(const Ice::Current&); - virtual std::string getProperty(const std::string&, const Ice::Current&); + virtual std::string getProperty(std::string, const Ice::Current&); private: diff --git a/cpp/test/IceGrid/distribution/AllTests.cpp b/cpp/test/IceGrid/distribution/AllTests.cpp index 7aede6e5ba2..329a86423e0 100644 --- a/cpp/test/IceGrid/distribution/AllTests.cpp +++ b/cpp/test/IceGrid/distribution/AllTests.cpp @@ -18,16 +18,16 @@ void allTests(Test::TestHelper* helper) { Ice::CommunicatorPtr communicator = helper->communicator(); - IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::checkedCast( + shared_ptr registry = Ice::checkedCast( communicator->stringToProxy(communicator->getDefaultLocator()->ice_getIdentity().category + "/Registry")); test(registry); - AdminSessionPrx session = registry->createAdminSession("foo", "bar"); + shared_ptr session = registry->createAdminSession("foo", "bar"); session->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::ICE_ENUM(ACMHeartbeat, HeartbeatAlways)); - AdminPrx admin = session->getAdmin(); + shared_ptr admin = session->getAdmin(); test(admin); cout << "testing distributions... " << flush; @@ -35,8 +35,7 @@ allTests(Test::TestHelper* helper) admin->startServer("Test.IcePatch2"); admin->startServer("IcePatch2-Direct"); - TestIntfPrx test; - test = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server-all")); + shared_ptr test = Ice::uncheckedCast(communicator->stringToProxy("server-all")); test(test->getServerFile("rootfile") == ""); try @@ -59,7 +58,7 @@ allTests(Test::TestHelper* helper) test(test->getApplicationFile("dir1/file2") == ""); test(test->getApplicationFile("dir2/file3") == "dummy-file3"); - test = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server-all-direct")); + test = Ice::uncheckedCast(communicator->stringToProxy("server-all-direct")); test(test->getServerFile("rootfile") == ""); test(test->getServerFile("dir1/file1") == ""); @@ -100,7 +99,7 @@ allTests(Test::TestHelper* helper) copy(ex.reasons.begin(), ex.reasons.end(), ostream_iterator(cerr, "\n")); test(false); } - test = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server-dir1")); + test = Ice::uncheckedCast(communicator->stringToProxy("server-dir1")); test(test->getServerFile("rootfile") == ""); test(test->getServerFile("dir1/file1") == "dummy-file1"); @@ -127,8 +126,7 @@ allTests(Test::TestHelper* helper) admin->startServer("Test.IcePatch2"); admin->startServer("IcePatch2-Direct"); - TestIntfPrx test; - test = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server-all")); + shared_ptr test = Ice::uncheckedCast(communicator->stringToProxy("server-all")); test(test->getServerFile("rootfile") == "rootfile"); try @@ -162,7 +160,7 @@ allTests(Test::TestHelper* helper) copy(ex.reasons.begin(), ex.reasons.end(), ostream_iterator(cerr, "\n")); test(false); } - test = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server-all-direct")); + test = Ice::uncheckedCast(communicator->stringToProxy("server-all-direct")); test(test->getServerFile("rootfile") == "rootfile-updated!"); test(test->getServerFile("dir1/file1") == ""); @@ -185,7 +183,7 @@ allTests(Test::TestHelper* helper) copy(ex.reasons.begin(), ex.reasons.end(), ostream_iterator(cerr, "\n")); test(false); } - test = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server-dir1")); + test = Ice::uncheckedCast(communicator->stringToProxy("server-dir1")); test(test->getServerFile("rootfile") == ""); test(test->getServerFile("dir1/file1") == ""); @@ -227,7 +225,7 @@ allTests(Test::TestHelper* helper) test(false); } - TestIntfPrx test = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server-dir1")); + shared_ptr test = Ice::uncheckedCast(communicator->stringToProxy("server-dir1")); test(test->getServerFile("rootfile") == ""); test(test->getServerFile("dir1/file1") == "dummy-file1"); @@ -255,7 +253,7 @@ allTests(Test::TestHelper* helper) test(false); } - test = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server-dir1")); + test = Ice::uncheckedCast(communicator->stringToProxy("server-dir1")); test(test->getServerFile("rootfile") == ""); test(test->getServerFile("dir1/file1") == "dummy-file1"); @@ -285,7 +283,7 @@ allTests(Test::TestHelper* helper) test(false); } - test = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server-dir1")); + test = Ice::uncheckedCast(communicator->stringToProxy("server-dir1")); test(test->getServerFile("rootfile") == ""); test(test->getServerFile("dir1/file1") == "dummy-file1"); @@ -297,7 +295,7 @@ allTests(Test::TestHelper* helper) test(test->getApplicationFile("dir1/file2") == ""); test(test->getApplicationFile("dir2/file3") == ""); - test = TestIntfPrx::uncheckedCast(communicator->stringToProxy("server-all")); + test = Ice::uncheckedCast(communicator->stringToProxy("server-all")); test(test->getServerFile("rootfile") == ""); test(test->getServerFile("dir1/file1") == ""); diff --git a/cpp/test/IceGrid/distribution/Server.cpp b/cpp/test/IceGrid/distribution/Server.cpp index b1335eb7399..450aff7b5fb 100644 --- a/cpp/test/IceGrid/distribution/Server.cpp +++ b/cpp/test/IceGrid/distribution/Server.cpp @@ -22,8 +22,7 @@ Server::run(int argc, char** argv) Ice::PropertiesPtr properties = communicator->getProperties(); string name = properties->getProperty("Ice.ProgramName"); Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("Server"); - Ice::ObjectPtr object = new TestI(properties); - adapter->add(object, Ice::stringToIdentity(name)); + adapter->add(make_shared(properties), Ice::stringToIdentity(name)); try { diff --git a/cpp/test/IceGrid/distribution/TestI.cpp b/cpp/test/IceGrid/distribution/TestI.cpp index bd591ac5046..612079bd3b3 100644 --- a/cpp/test/IceGrid/distribution/TestI.cpp +++ b/cpp/test/IceGrid/distribution/TestI.cpp @@ -15,7 +15,7 @@ TestI::TestI(const Ice::PropertiesPtr& properties) : } string -TestI::getServerFile(const string& path, const Ice::Current&) +TestI::getServerFile(string path, const Ice::Current&) { string file = _properties->getProperty("ServerDistrib") + "/" + path; ifstream is(file.c_str()); @@ -28,7 +28,7 @@ TestI::getServerFile(const string& path, const Ice::Current&) } string -TestI::getApplicationFile(const string& path, const Ice::Current&) +TestI::getApplicationFile(string path, const Ice::Current&) { string file = _properties->getProperty("ApplicationDistrib") + "/" + path; ifstream is(file.c_str()); diff --git a/cpp/test/IceGrid/distribution/TestI.h b/cpp/test/IceGrid/distribution/TestI.h index 2eedcb913b5..43edc0b6991 100644 --- a/cpp/test/IceGrid/distribution/TestI.h +++ b/cpp/test/IceGrid/distribution/TestI.h @@ -13,8 +13,8 @@ class TestI : public ::Test::TestIntf TestI(const Ice::PropertiesPtr&); - virtual std::string getServerFile(const std::string&, const Ice::Current&); - virtual std::string getApplicationFile(const std::string&, const Ice::Current&); + virtual std::string getServerFile(std::string, const Ice::Current&) override; + virtual std::string getApplicationFile(std::string, const Ice::Current&) override; private: diff --git a/cpp/test/IceGrid/noRestartUpdate/AllTests.cpp b/cpp/test/IceGrid/noRestartUpdate/AllTests.cpp index 09c854baf1d..6b3ed5b67e6 100644 --- a/cpp/test/IceGrid/noRestartUpdate/AllTests.cpp +++ b/cpp/test/IceGrid/noRestartUpdate/AllTests.cpp @@ -2,18 +2,18 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include #include #include #include #include +#include using namespace std; using namespace Test; using namespace IceGrid; void -addProperty(const CommunicatorDescriptorPtr& communicator, const string& name, const string& value) +addProperty(const shared_ptr& communicator, const string& name, const string& value) { PropertyDescriptor prop; prop.name = name; @@ -22,58 +22,49 @@ addProperty(const CommunicatorDescriptorPtr& communicator, const string& name, c } string -getProperty(const CommunicatorDescriptorPtr& communicator, const string& name) +getProperty(const shared_ptr& communicator, const string& name) { PropertyDescriptorSeq& properties = communicator->propertySet.properties; - for(PropertyDescriptorSeq::const_iterator q = properties.begin(); q != properties.end(); ++q) + for(const auto& prop : properties) { - if(q->name == name) + if(prop.name == name) { - return q->value; + return prop.value; } } return ""; } void -removeProperty(const CommunicatorDescriptorPtr& communicator, const string& name) +removeProperty(const shared_ptr& communicator, const string& name) { PropertyDescriptorSeq& properties = communicator->propertySet.properties; - for(PropertyDescriptorSeq::iterator q = properties.begin(); q != properties.end(); ++q) - { - if(q->name == name) - { - properties.erase(q); - break; - } - } + properties.erase(remove_if(properties.begin(), properties.end(),[&name](const auto& p) { return p.name == name; })); } PropertyDescriptor createProperty(const string& name, const string& value) { - PropertyDescriptor prop; - prop.name = name; - prop.value = value; - return prop; + return { name, value}; } bool -hasProperty(const CommunicatorDescriptorPtr& desc, const string& name, const string& value) +hasProperty(const shared_ptr& communicator, const string& name, const string& value) { - for(PropertyDescriptorSeq::const_iterator p = desc->propertySet.properties.begin(); - p != desc->propertySet.properties.end(); ++p) + PropertyDescriptorSeq& properties = communicator->propertySet.properties; + for(const auto& prop : properties) { - if(p->name == name) + if(prop.name == name) { - return p->value == value; + return prop.value == value; } } return false; } void -updateServerRuntimeProperties(const AdminPrx& admin, const string&, const ServerDescriptorPtr& desc) +updateServerRuntimeProperties(const shared_ptr& admin, const string&, + const shared_ptr& desc) { ApplicationUpdateDescriptor update; update.name = "TestApp"; @@ -92,33 +83,34 @@ updateServerRuntimeProperties(const AdminPrx& admin, const string&, const Server } } -ServiceDescriptorPtr -getServiceDescriptor(const AdminPrx& admin, const string& service) +shared_ptr +getServiceDescriptor(const shared_ptr& admin, const string& service) { - ServerInfo info = admin->getServerInfo("IceBox"); + auto info = admin->getServerInfo("IceBox"); test(info.descriptor); - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); - for(ServiceInstanceDescriptorSeq::const_iterator p = iceBox->services.begin(); p != iceBox->services.end(); ++p) + auto iceBox = dynamic_pointer_cast(info.descriptor); + for(const auto& serviceInstance : iceBox->services) { - if(p->descriptor->name == service) + if(serviceInstance.descriptor->name == service) { - return p->descriptor; + return serviceInstance.descriptor; } } - return 0; + return nullptr; } void -updateServiceRuntimeProperties(const AdminPrx& admin, const ServiceDescriptorPtr& desc) +updateServiceRuntimeProperties(const shared_ptr& admin, const shared_ptr& desc) { - ServerInfo info = admin->getServerInfo("IceBox"); + auto info = admin->getServerInfo("IceBox"); test(info.descriptor); - IceBoxDescriptorPtr iceBox = IceBoxDescriptorPtr::dynamicCast(info.descriptor); - for(ServiceInstanceDescriptorSeq::const_iterator p = iceBox->services.begin(); p != iceBox->services.end(); ++p) + + auto iceBox = dynamic_pointer_cast(info.descriptor); + for(const auto& serviceInstance : iceBox->services) { - if(p->descriptor->name == desc->name) + if(serviceInstance.descriptor->name == desc->name) { - p->descriptor->propertySet.properties = desc->propertySet.properties; + serviceInstance.descriptor->propertySet.properties = desc->propertySet.properties; } } ApplicationUpdateDescriptor update; @@ -146,20 +138,20 @@ updateServiceRuntimeProperties(const AdminPrx& admin, const ServiceDescriptorPtr void allTests(Test::TestHelper* helper) { - Ice::CommunicatorPtr communicator = helper->communicator(); - IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::checkedCast( + auto communicator = helper->communicator(); + auto registry = Ice::checkedCast( communicator->stringToProxy(communicator->getDefaultLocator()->ice_getIdentity().category + "/Registry")); test(registry); - AdminSessionPrx session = registry->createAdminSession("foo", "bar"); + auto session = registry->createAdminSession("foo", "bar"); session->ice_getConnection()->setACM(registry->getACMTimeout(), - IceUtil::None, - Ice::ICE_ENUM(ACMHeartbeat, HeartbeatAlways)); + Ice::nullopt, + Ice::ACMHeartbeat::HeartbeatAlways); - AdminPrx admin = session->getAdmin(); + auto admin = session->getAdmin(); test(admin); - Ice::PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); { ApplicationDescriptor testApp; @@ -176,7 +168,7 @@ allTests(Test::TestHelper* helper) cout << "testing server add... " << flush; - ServerDescriptorPtr server = new ServerDescriptor(); + auto server = make_shared(); server->id = "Server"; server->exe = properties->getProperty("ServerDir") + "/server"; server->pwd = "."; @@ -222,8 +214,8 @@ allTests(Test::TestHelper* helper) TemplateDescriptor templ; templ.parameters.push_back("name"); - templ.descriptor = new ServerDescriptor(); - server = ServerDescriptorPtr::dynamicCast(templ.descriptor); + templ.descriptor = make_shared(); + server = dynamic_pointer_cast(templ.descriptor); server->id = "${name}"; server->exe = "${server.dir}/server"; server->pwd = "."; @@ -349,39 +341,39 @@ allTests(Test::TestHelper* helper) test(info.descriptor); addProperty(info.descriptor, "test", "test"); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test") == ""); + test(Ice::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test") == ""); updateServerRuntimeProperties(admin, "Server", info.descriptor); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test") == "test"); + test(Ice::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test") == "test"); test(serverPid == admin->getServerPid("Server")); admin->stopServer("Server"); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test") == "test"); + test(Ice::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test") == "test"); test((serverPid = admin->getServerPid("Server")) > 0); test(hasProperty(admin->getServerInfo("Server").descriptor, "test", "test")); addProperty(info.descriptor, "test2", "test2"); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test2") == ""); + test(Ice::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test2") == ""); updateServerRuntimeProperties(admin, "Server", info.descriptor); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test2") == "test2"); + test(Ice::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test2") == "test2"); test(serverPid == admin->getServerPid("Server")); test(hasProperty(admin->getServerInfo("Server").descriptor, "test2", "test2")); removeProperty(info.descriptor, "test2"); updateServerRuntimeProperties(admin, "Server", info.descriptor); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test2") == ""); + test(Ice::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test2") == ""); test(serverPid == admin->getServerPid("Server")); test(!hasProperty(admin->getServerInfo("Server").descriptor, "test2", "test2")); addProperty(info.descriptor, "test3", "test3"); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test3") == ""); + test(Ice::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test3") == ""); updateServerRuntimeProperties(admin, "Server", info.descriptor); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test3") == "test3"); + test(Ice::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test3") == "test3"); test(serverPid == admin->getServerPid("Server")); test(hasProperty(admin->getServerInfo("Server").descriptor, "test3", "test3")); admin->stopServer("Server"); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test") == "test"); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test2") == ""); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test3") == "test3"); + test(Ice::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test") == "test"); + test(Ice::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test2") == ""); + test(Ice::uncheckedCast(communicator->stringToProxy("Server"))->getProperty("test3") == "test3"); test((serverPid = admin->getServerPid("Server")) > 0); test(hasProperty(admin->getServerInfo("Server").descriptor, "test", "test")); test(!hasProperty(admin->getServerInfo("Server").descriptor, "test2", "")); @@ -410,12 +402,12 @@ allTests(Test::TestHelper* helper) addProperty(server, "test", "test"); assert(templ.descriptor == server); update.serverTemplates["ServerTemplate"] = templ; - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server1"))->getProperty("test") == ""); + test(Ice::uncheckedCast(communicator->stringToProxy("Server1"))->getProperty("test") == ""); admin->updateApplicationWithoutRestart(update); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server1"))->getProperty("test") == "test"); + test(Ice::uncheckedCast(communicator->stringToProxy("Server1"))->getProperty("test") == "test"); test(server1Pid == admin->getServerPid("Server1")); admin->stopServer("Server1"); - test(TestIntfPrx::uncheckedCast(communicator->stringToProxy("Server1"))->getProperty("test") == "test"); + test(Ice::uncheckedCast(communicator->stringToProxy("Server1"))->getProperty("test") == "test"); server1Pid = admin->getServerPid("Server1"); test(hasProperty(admin->getServerInfo("Server1").descriptor, "test", "test")); } @@ -498,7 +490,7 @@ allTests(Test::TestHelper* helper) cout << "testing icebox server add... " << flush; - ServiceDescriptorPtr service = new ServiceDescriptor(); + auto service = make_shared(); addProperty(service, "Ice.Warn.UnknownProperties", "0"); //addProperty(service, "Ice.Trace.Admin.Properties", "1"); service->name = "Service1"; @@ -516,7 +508,7 @@ allTests(Test::TestHelper* helper) adapter.objects.push_back(object); service->adapters.push_back(adapter); - IceBoxDescriptorPtr icebox = new IceBoxDescriptor(); + auto icebox = make_shared(); icebox->id = "IceBox"; icebox->exe = properties->getProperty("IceBoxExe"); icebox->activation = "on-demand"; @@ -524,14 +516,14 @@ allTests(Test::TestHelper* helper) icebox->allocatable = false; addProperty(icebox, "Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); icebox->services.resize(3); - icebox->services[0].descriptor = ServiceDescriptorPtr::dynamicCast(service->ice_clone()); + icebox->services[0].descriptor = dynamic_pointer_cast(service->ice_clone()); service->name = "Service2"; - icebox->services[1].descriptor = ServiceDescriptorPtr::dynamicCast(service->ice_clone()); + icebox->services[1].descriptor = dynamic_pointer_cast(service->ice_clone()); service->name = "Service3"; // Test also with shared communicator because it uses different proxy name // and thus different branches in code. addProperty(icebox, "IceBox.UseSharedCommunicator.Service3", "1"); - icebox->services[2].descriptor = ServiceDescriptorPtr::dynamicCast(service->ice_clone()); + icebox->services[2].descriptor = dynamic_pointer_cast(service->ice_clone()); try { @@ -569,7 +561,7 @@ allTests(Test::TestHelper* helper) { // can't add service without restart test(iceBoxPid == admin->getServerPid("IceBox")); - icebox = IceBoxDescriptorPtr::dynamicCast(admin->getServerInfo("IceBox").descriptor); + icebox = dynamic_pointer_cast(admin->getServerInfo("IceBox").descriptor); } catch(const Ice::Exception& ex) { @@ -589,7 +581,7 @@ allTests(Test::TestHelper* helper) { // can't remove service without restart test(iceBoxPid == admin->getServerPid("IceBox")); - icebox = IceBoxDescriptorPtr::dynamicCast(admin->getServerInfo("IceBox").descriptor); + icebox = dynamic_pointer_cast(admin->getServerInfo("IceBox").descriptor); } catch(const Ice::Exception& ex) { @@ -609,7 +601,7 @@ allTests(Test::TestHelper* helper) { // can't update service entry point without restart test(iceBoxPid == admin->getServerPid("IceBox")); - icebox = IceBoxDescriptorPtr::dynamicCast(admin->getServerInfo("IceBox").descriptor); + icebox = dynamic_pointer_cast(admin->getServerInfo("IceBox").descriptor); } catch(const Ice::Exception& ex) { @@ -617,14 +609,14 @@ allTests(Test::TestHelper* helper) test(false); } - ServiceDescriptorPtr svc1 = icebox->services[0].descriptor; - TestIntfPrx svc1Prx = TestIntfPrx::checkedCast(communicator->stringToProxy("IceBox.Service1")); + auto svc1 = icebox->services[0].descriptor; + auto svc1Prx = Ice::checkedCast(communicator->stringToProxy("IceBox.Service1")); - ServiceDescriptorPtr svc2 = icebox->services[1].descriptor; - TestIntfPrx svc2Prx = TestIntfPrx::checkedCast(communicator->stringToProxy("IceBox.Service2")); + auto svc2 = icebox->services[1].descriptor; + auto svc2Prx = Ice::checkedCast(communicator->stringToProxy("IceBox.Service2")); - ServiceDescriptorPtr svc3 = icebox->services[2].descriptor; - TestIntfPrx svc3Prx = TestIntfPrx::checkedCast(communicator->stringToProxy("IceBox.Service3")); + auto svc3 = icebox->services[2].descriptor; + auto svc3Prx = Ice::checkedCast(communicator->stringToProxy("IceBox.Service3")); addProperty(svc1, "test", "test"); test(svc1Prx->getProperty("test") == ""); @@ -665,9 +657,9 @@ allTests(Test::TestHelper* helper) // Wait for the server to be active to have the guarantee that // the property update will return once the properties are // updated. - while(admin->getServerState("IceBox") != IceGrid::Active) + while(admin->getServerState("IceBox") != IceGrid::ServerState::Active) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100)); + this_thread::sleep_for(100ms); } test(hasProperty(getServiceDescriptor(admin, "Service1"), "test", "test")); test(!hasProperty(getServiceDescriptor(admin, "Service1"), "test2", "")); diff --git a/cpp/test/IceGrid/noRestartUpdate/Client.cpp b/cpp/test/IceGrid/noRestartUpdate/Client.cpp index 0d88f5c27be..cd37c6411ed 100644 --- a/cpp/test/IceGrid/noRestartUpdate/Client.cpp +++ b/cpp/test/IceGrid/noRestartUpdate/Client.cpp @@ -8,11 +8,11 @@ using namespace std; -class Client : public Test::TestHelper +class Client final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void diff --git a/cpp/test/IceGrid/noRestartUpdate/Server.cpp b/cpp/test/IceGrid/noRestartUpdate/Server.cpp index db88ace71a7..bea873f9998 100644 --- a/cpp/test/IceGrid/noRestartUpdate/Server.cpp +++ b/cpp/test/IceGrid/noRestartUpdate/Server.cpp @@ -8,7 +8,7 @@ using namespace std; -class Server : public Test::TestHelper +class Server final : public Test::TestHelper { public: @@ -19,13 +19,12 @@ void Server::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); - Ice::PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); string name = properties->getProperty("Ice.ProgramName"); - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("Server"); - Ice::ObjectPtr object = new TestI(adapter, properties); - adapter->add(object, Ice::stringToIdentity(name)); + auto adapter = communicator->createObjectAdapter("Server"); + adapter->add(make_shared(adapter, properties), Ice::stringToIdentity(name)); try { diff --git a/cpp/test/IceGrid/noRestartUpdate/Service.cpp b/cpp/test/IceGrid/noRestartUpdate/Service.cpp index 847edb5b2af..8619d938614 100644 --- a/cpp/test/IceGrid/noRestartUpdate/Service.cpp +++ b/cpp/test/IceGrid/noRestartUpdate/Service.cpp @@ -9,18 +9,15 @@ using namespace std; using namespace Ice; -class ServiceI : public ::IceBox::Service +class ServiceI final : public IceBox::Service { public: - ServiceI(); - virtual ~ServiceI(); + void start(const string&, + const shared_ptr&, + const StringSeq&) override; - virtual void start(const string&, - const CommunicatorPtr&, - const StringSeq&); - - virtual void stop(); + void stop() override; }; extern "C" @@ -30,30 +27,21 @@ extern "C" // Factory function // ICE_DECLSPEC_EXPORT ::IceBox::Service* -create(CommunicatorPtr) +create(const shared_ptr&) { return new ServiceI; } } -ServiceI::ServiceI() -{ -} - -ServiceI::~ServiceI() -{ -} - void ServiceI::start(const string& name, - const CommunicatorPtr& communicator, + const shared_ptr& communicator, const StringSeq&) { - Ice::PropertiesPtr properties = communicator->getProperties(); - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter(name); - Ice::ObjectPtr object = new TestI(adapter, properties); - adapter->add(object, stringToIdentity(properties->getProperty(name + ".Identity"))); + auto properties = communicator->getProperties(); + auto adapter = communicator->createObjectAdapter(name); + adapter->add(make_shared(adapter, properties), stringToIdentity(properties->getProperty(name + ".Identity"))); adapter->activate(); } diff --git a/cpp/test/IceGrid/noRestartUpdate/TestI.cpp b/cpp/test/IceGrid/noRestartUpdate/TestI.cpp index 06688e08685..4149e08d307 100644 --- a/cpp/test/IceGrid/noRestartUpdate/TestI.cpp +++ b/cpp/test/IceGrid/noRestartUpdate/TestI.cpp @@ -5,9 +5,9 @@ #include #include -TestI::TestI(const Ice::ObjectAdapterPtr& adapter, const Ice::PropertiesPtr& properties) : - _adapter(adapter), - _properties(properties) +TestI::TestI(std::shared_ptr adapter, std::shared_ptr properties) : + _adapter(std::move(adapter)), + _properties(std::move(properties)) { } @@ -18,7 +18,7 @@ TestI::shutdown(const Ice::Current&) } std::string -TestI::getProperty(const std::string& name, const Ice::Current&) +TestI::getProperty(std::string name, const Ice::Current&) { return _properties->getProperty(name); } diff --git a/cpp/test/IceGrid/noRestartUpdate/TestI.h b/cpp/test/IceGrid/noRestartUpdate/TestI.h index 98cd86156ce..6a8ab0bf7b4 100644 --- a/cpp/test/IceGrid/noRestartUpdate/TestI.h +++ b/cpp/test/IceGrid/noRestartUpdate/TestI.h @@ -7,19 +7,19 @@ #include -class TestI : public ::Test::TestIntf +class TestI final : public ::Test::TestIntf { public: - TestI(const Ice::ObjectAdapterPtr&, const Ice::PropertiesPtr&); + TestI(std::shared_ptr, std::shared_ptr); - virtual void shutdown(const Ice::Current&); - virtual std::string getProperty(const std::string&, const Ice::Current&); + void shutdown(const Ice::Current&) override; + std::string getProperty(std::string, const Ice::Current&) override; private: - Ice::ObjectAdapterPtr _adapter; - Ice::PropertiesPtr _properties; + std::shared_ptr _adapter; + std::shared_ptr _properties; }; #endif diff --git a/cpp/test/IceGrid/replicaGroup/AllTests.cpp b/cpp/test/IceGrid/replicaGroup/AllTests.cpp index ab0d3913df3..45b68bbb36e 100644 --- a/cpp/test/IceGrid/replicaGroup/AllTests.cpp +++ b/cpp/test/IceGrid/replicaGroup/AllTests.cpp @@ -15,7 +15,8 @@ using namespace Test; using namespace IceGrid; void -instantiateServer(const AdminPrx& admin, const string& templ, const string& node, const map& params, +instantiateServer(const shared_ptr& admin, const string& templ, const string& node, + const map& params, const string& application = string("Test"), bool startServer = true) { ServerInstanceDescriptor desc; @@ -61,7 +62,7 @@ instantiateServer(const AdminPrx& admin, const string& templ, const string& node } void -removeServer(const AdminPrx& admin, const string& id) +removeServer(const shared_ptr& admin, const string& id) { try { @@ -102,20 +103,20 @@ removeServer(const AdminPrx& admin, const string& id) void allTests(Test::TestHelper* helper) { - Ice::CommunicatorPtr comm = helper->communicator(); - IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::checkedCast( + auto comm = helper->communicator(); + auto registry = Ice::checkedCast( comm->stringToProxy(comm->getDefaultLocator()->ice_getIdentity().category + "/Registry")); test(registry); - IceGrid::QueryPrx query = IceGrid::QueryPrx::checkedCast( + auto query = Ice::checkedCast( comm->stringToProxy(comm->getDefaultLocator()->ice_getIdentity().category + "/Query")); test(query); - AdminSessionPrx session = registry->createAdminSession("foo", "bar"); + auto session = registry->createAdminSession("foo", "bar"); session->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, - Ice::ICE_ENUM(ACMHeartbeat, HeartbeatAlways)); + Ice::ACMHeartbeat::HeartbeatAlways); - AdminPrx admin = session->getAdmin(); + auto admin = session->getAdmin(); test(admin); set serverReplicaIds; @@ -138,33 +139,33 @@ allTests(Test::TestHelper* helper) params["id"] = "Server3"; instantiateServer(admin, "Server", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("dummy@RoundRobin")); + auto obj = Ice::uncheckedCast(comm->stringToProxy("dummy@RoundRobin")); Ice::ObjectProxySeq objs = query->findAllReplicas(obj); test(objs.size() == 3); test(serverReplicaIds.find(objs[0]->ice_getAdapterId()) != serverReplicaIds.end()); test(serverReplicaIds.find(objs[1]->ice_getAdapterId()) != serverReplicaIds.end()); test(serverReplicaIds.find(objs[2]->ice_getAdapterId()) != serverReplicaIds.end()); - obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("RoundRobin")); + obj = Ice::uncheckedCast(comm->stringToProxy("RoundRobin")); objs = query->findAllReplicas(obj); test(objs.size() == 3); test(serverReplicaIds.find(objs[0]->ice_getAdapterId()) != serverReplicaIds.end()); test(serverReplicaIds.find(objs[1]->ice_getAdapterId()) != serverReplicaIds.end()); test(serverReplicaIds.find(objs[2]->ice_getAdapterId()) != serverReplicaIds.end()); - obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("dummy@dummy")); + obj = Ice::uncheckedCast(comm->stringToProxy("dummy@dummy")); objs = query->findAllReplicas(obj); test(objs.empty()); - obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("dummy@Server1.ReplicatedAdapter")); + obj = Ice::uncheckedCast(comm->stringToProxy("dummy@Server1.ReplicatedAdapter")); objs = query->findAllReplicas(obj); test(objs.empty()); - obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("dummy:tcp")); + obj = Ice::uncheckedCast(comm->stringToProxy("dummy:tcp")); objs = query->findAllReplicas(obj); test(objs.empty()); - obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("dummy@Ordered")); + obj = Ice::uncheckedCast(comm->stringToProxy("dummy@Ordered")); objs = query->findAllReplicas(obj); test(objs.empty()); @@ -184,9 +185,9 @@ allTests(Test::TestHelper* helper) instantiateServer(admin, "Server", "localnode", params); params["id"] = "Server3"; instantiateServer(admin, "Server", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("RoundRobin")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(0)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("RoundRobin")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(0)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); try { test(obj->getReplicaIdAndShutdown() == "Server1.ReplicatedAdapter"); @@ -261,9 +262,9 @@ allTests(Test::TestHelper* helper) params["replicaGroup"] = "RoundRobin"; params["id"] = "IceBox1"; instantiateServer(admin, "IceBox", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("RoundRobin")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(0)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("RoundRobin")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(0)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); try { test(obj->getReplicaIdAndShutdown() == "IceBox1.Service1.Service1"); @@ -292,7 +293,7 @@ allTests(Test::TestHelper* helper) params["id"] = "Server3"; params["priority"] = "2"; instantiateServer(admin, "Server", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Ordered")); + auto obj = Ice::uncheckedCast(comm->stringToProxy("Ordered")); try { test(obj->getReplicaIdAndShutdown() == "Server2.ReplicatedAdapter"); @@ -315,9 +316,9 @@ allTests(Test::TestHelper* helper) params["replicaGroup"] = "Ordered"; params["id"] = "IceBox1"; instantiateServer(admin, "IceBox", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Ordered")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(0)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("Ordered")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(0)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); try { test(obj->getReplicaIdAndShutdown() == "IceBox1.Service3.Service3"); @@ -343,9 +344,9 @@ allTests(Test::TestHelper* helper) instantiateServer(admin, "Server", "localnode", params); params["id"] = "Server3"; instantiateServer(admin, "Server", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Random")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(0)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("Random")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(0)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); set replicaIds = serverReplicaIds; while(!replicaIds.empty()) { @@ -404,9 +405,9 @@ allTests(Test::TestHelper* helper) params["replicaGroup"] = "Random"; params["id"] = "IceBox1"; instantiateServer(admin, "IceBox", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Random")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(0)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("Random")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(0)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); set replicaIds = svcReplicaIds; while(!replicaIds.empty()) { @@ -437,9 +438,9 @@ allTests(Test::TestHelper* helper) instantiateServer(admin, "Server", "localnode", params); params["id"] = "Server3"; instantiateServer(admin, "Server", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Adaptive")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(0)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("Adaptive")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(0)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); set replicaIds = serverReplicaIds; while(!replicaIds.empty()) { @@ -462,9 +463,9 @@ allTests(Test::TestHelper* helper) params["replicaGroup"] = "Adaptive"; params["id"] = "IceBox1"; instantiateServer(admin, "IceBox", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Adaptive")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(0)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("Adaptive")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(0)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); set replicaIds = svcReplicaIds; while(!replicaIds.empty()) { @@ -496,14 +497,14 @@ allTests(Test::TestHelper* helper) params["id"] = "Server3"; instantiateServer(admin, "IceBox1", "localnode", params); - Ice::LocatorPrx locator = comm->getDefaultLocator(); + auto locator = comm->getDefaultLocator(); Ice::Context ctx; ctx["server"] = "Server3"; locator->ice_context(ctx); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Ordered-Filtered")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(0)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("Ordered-Filtered")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(0)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); try { ctx["server"] = "Server3"; @@ -548,13 +549,13 @@ allTests(Test::TestHelper* helper) ctx["server"] = "Server3"; test(query->ice_context(ctx)->findObjectByTypeOnLeastLoadedNode( - "::Test::TestIntf2", LoadSample5)->ice_getAdapterId() == "Server3.Service.Service"); + "::Test::TestIntf2", LoadSample::LoadSample5)->ice_getAdapterId() == "Server3.Service.Service"); ctx["server"] = "Server1"; test(query->ice_context(ctx)->findObjectByTypeOnLeastLoadedNode( - "::Test::TestIntf2", LoadSample5)->ice_getAdapterId() == "Server1.ReplicatedAdapter"); + "::Test::TestIntf2", LoadSample::LoadSample5)->ice_getAdapterId() == "Server1.ReplicatedAdapter"); ctx["server"] = "Server2"; test(query->ice_context(ctx)->findObjectByTypeOnLeastLoadedNode( - "::Test::TestIntf2", LoadSample5)->ice_getAdapterId() == "Server2.ReplicatedAdapter"); + "::Test::TestIntf2", LoadSample::LoadSample5)->ice_getAdapterId() == "Server2.ReplicatedAdapter"); ctx["server"] = "Server3"; test(query->ice_context(ctx)->findAllObjectsByType("::Test::TestIntf2")[0]->ice_getAdapterId() == @@ -582,7 +583,7 @@ allTests(Test::TestHelper* helper) params["id"] = "UnknownServer"; instantiateServer(admin, "Server", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Unknown")); + auto obj = Ice::uncheckedCast(comm->stringToProxy("Unknown")); obj->getReplicaId(); removeServer(admin, "UnknownServer"); @@ -593,9 +594,9 @@ allTests(Test::TestHelper* helper) params["id"] = "ExcludeServer"; instantiateServer(admin, "Server", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Exclude")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(0)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("Exclude")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(0)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); try { obj->getReplicaId(); @@ -605,7 +606,7 @@ allTests(Test::TestHelper* helper) { } - Ice::LocatorPrx locator = comm->getDefaultLocator(); + auto locator = comm->getDefaultLocator(); try { Ice::Context ctx; @@ -637,9 +638,9 @@ allTests(Test::TestHelper* helper) cout << "testing load balancing n-replicas... " << flush; { - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("RoundRobin-2")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(-1)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("RoundRobin-2")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(-1)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); try { obj->ice_ping(); @@ -714,9 +715,9 @@ allTests(Test::TestHelper* helper) } { - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("RoundRobin-All")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(-1)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("RoundRobin-All")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(-1)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); try { obj->ice_ping(); @@ -781,13 +782,14 @@ allTests(Test::TestHelper* helper) instantiateServer(admin, "Server", "inactivenode", params); params["id"] = "Server2"; instantiateServer(admin, "Server", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Random")); + auto obj = Ice::uncheckedCast(comm->stringToProxy("Random")); test(obj->getReplicaId() == "Server2.ReplicatedAdapter"); // // Also make sure that findObjectByTypeOnLeastLoadedNode still work. // - obj = TestIntfPrx::uncheckedCast(query->findObjectByTypeOnLeastLoadedNode("::Test::TestIntf", LoadSample1)); + obj = Ice::uncheckedCast(query->findObjectByTypeOnLeastLoadedNode("::Test::TestIntf", + LoadSample::LoadSample1)); test(obj->getReplicaId() == "Server2.ReplicatedAdapter"); removeServer(admin, "Server1"); @@ -798,7 +800,7 @@ allTests(Test::TestHelper* helper) instantiateServer(admin, "Server", "inactivenode", params); params["id"] = "Server2"; instantiateServer(admin, "Server", "localnode", params); - obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("RoundRobin")); + obj = Ice::uncheckedCast(comm->stringToProxy("RoundRobin")); test(obj->getReplicaId() == "Server2.ReplicatedAdapter"); removeServer(admin, "Server1"); removeServer(admin, "Server2"); @@ -808,7 +810,7 @@ allTests(Test::TestHelper* helper) instantiateServer(admin, "Server", "inactivenode", params); params["id"] = "Server2"; instantiateServer(admin, "Server", "localnode", params); - obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Adaptive")); + obj = Ice::uncheckedCast(comm->stringToProxy("Adaptive")); test(obj->getReplicaId() == "Server2.ReplicatedAdapter"); removeServer(admin, "Server1"); removeServer(admin, "Server2"); @@ -818,7 +820,7 @@ allTests(Test::TestHelper* helper) instantiateServer(admin, "IceBox", "localnode", params); params["id"] = "Server1"; instantiateServer(admin, "Server", "inactivenode", params); - obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Random")); + obj = Ice::uncheckedCast(comm->stringToProxy("Random")); test(svcReplicaIds.find(obj->getReplicaId()) != svcReplicaIds.end()); removeServer(admin, "IceBox1"); removeServer(admin, "Server1"); @@ -875,9 +877,9 @@ allTests(Test::TestHelper* helper) // Test has a replica group referenced by the Test1 application. } - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("Random")); - obj = TestIntfPrx::uncheckedCast(obj->ice_locatorCacheTimeout(0)); - obj = TestIntfPrx::uncheckedCast(obj->ice_connectionCached(false)); + auto obj = Ice::uncheckedCast(comm->stringToProxy("Random")); + obj = Ice::uncheckedCast(obj->ice_locatorCacheTimeout(0)); + obj = Ice::uncheckedCast(obj->ice_connectionCached(false)); set replicaIds; replicaIds.insert("Server1.ReplicatedAdapter"); replicaIds.insert("Server2.ReplicatedAdapter"); @@ -899,7 +901,7 @@ allTests(Test::TestHelper* helper) ReplicaGroupDescriptor replicaGroup; replicaGroup.id = "ReplicatedAdapterFromTest1"; - replicaGroup.loadBalancing = new RandomLoadBalancingPolicy(); + replicaGroup.loadBalancing = make_shared(); replicaGroup.loadBalancing->nReplicas = "0"; update = ApplicationUpdateDescriptor(); update.name = "Test1"; @@ -978,7 +980,7 @@ allTests(Test::TestHelper* helper) params["encoding"] = "1.0"; instantiateServer(admin, "Server", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy(*p)); + auto obj = Ice::uncheckedCast(comm->stringToProxy(*p)); obj = obj->ice_locatorCacheTimeout(0); obj = obj->ice_connectionCached(false); @@ -1021,7 +1023,7 @@ allTests(Test::TestHelper* helper) params["encoding"] = "1.0"; instantiateServer(admin, "DynamicallyRegisteredServer", "localnode", params); - TestIntfPrx obj = TestIntfPrx::uncheckedCast(comm->stringToProxy("DynamicRandom@DynamicRandom")); + auto obj = Ice::uncheckedCast(comm->stringToProxy("DynamicRandom@DynamicRandom")); obj = obj->ice_locatorCacheTimeout(0); obj = obj->ice_connectionCached(false); obj = obj->ice_encodingVersion(Ice::Encoding_1_1); @@ -1117,7 +1119,7 @@ allTests(Test::TestHelper* helper) app.descriptor.nodes.clear(); ReplicaGroupDescriptor replicaGroup; replicaGroup.id = "DynamicRandomRG"; - replicaGroup.loadBalancing = new RandomLoadBalancingPolicy("1"); + replicaGroup.loadBalancing = make_shared("1"); app.descriptor.replicaGroups.push_back(replicaGroup); try { diff --git a/cpp/test/IceGrid/replicaGroup/RegistryPlugin.cpp b/cpp/test/IceGrid/replicaGroup/RegistryPlugin.cpp index e5254890f9a..a8b8168ca94 100644 --- a/cpp/test/IceGrid/replicaGroup/RegistryPlugin.cpp +++ b/cpp/test/IceGrid/replicaGroup/RegistryPlugin.cpp @@ -13,34 +13,34 @@ using namespace IceGrid; namespace { -class RegistryPluginI : public Ice::Plugin +class RegistryPluginI final : public Ice::Plugin { public: - RegistryPluginI(const Ice::CommunicatorPtr&); + RegistryPluginI(const shared_ptr&); - virtual void initialize(); - virtual void destroy(); + void initialize() override; + void destroy() override; private: - const Ice::CommunicatorPtr _communicator; - ReplicaGroupFilterPtr _filterByServer; - ReplicaGroupFilterPtr _excludeServer2; - ReplicaGroupFilterPtr _excludeServer3; - TypeFilterPtr _type; + const shared_ptr _communicator; + shared_ptr _filterByServer; + shared_ptr _excludeServer2; + shared_ptr _excludeServer3; + shared_ptr _type; }; -class ReplicaGroupFilterI : public IceGrid::ReplicaGroupFilter +class ReplicaGroupFilterI final : public IceGrid::ReplicaGroupFilter { public: - ReplicaGroupFilterI(const RegistryPluginFacadePtr& facade) : _facade(facade), _testFacade(true) + ReplicaGroupFilterI(const shared_ptr& facade) : _facade(facade), _testFacade(true) { } - virtual Ice::StringSeq - filter(const string& id, const Ice::StringSeq& adpts, const Ice::ConnectionPtr&, const Ice::Context& ctx) + Ice::StringSeq + filter(const string& id, const Ice::StringSeq& adpts, const shared_ptr&, const Ice::Context& ctx) override { if(_testFacade) { @@ -67,7 +67,7 @@ class ReplicaGroupFilterI : public IceGrid::ReplicaGroupFilter } } - Ice::Context::const_iterator p = ctx.find("server"); + auto p = ctx.find("server"); if(p == ctx.end()) { return adpts; @@ -75,11 +75,11 @@ class ReplicaGroupFilterI : public IceGrid::ReplicaGroupFilter string server = p->second; Ice::StringSeq filteredAdapters; - for(Ice::StringSeq::const_iterator q = adpts.begin(); q != adpts.end(); ++q) + for(const auto& adapter : adpts) { - if(_facade->getAdapterServer(*q) == server) + if(_facade->getAdapterServer(adapter) == server) { - filteredAdapters.push_back(*q); + filteredAdapters.push_back(adapter); } } return filteredAdapters; @@ -87,22 +87,23 @@ class ReplicaGroupFilterI : public IceGrid::ReplicaGroupFilter private: - RegistryPluginFacadePtr _facade; + shared_ptr _facade; bool _testFacade; }; -class TypeFilterI : public IceGrid::TypeFilter +class TypeFilterI final : public IceGrid::TypeFilter { public: - TypeFilterI(const RegistryPluginFacadePtr& facade) : _facade(facade) + TypeFilterI(const shared_ptr& facade) : _facade(facade) { } - virtual Ice::ObjectProxySeq - filter(const string& /*type*/, const Ice::ObjectProxySeq& objects, const Ice::ConnectionPtr&, const Ice::Context& ctx) + Ice::ObjectProxySeq + filter(const string&, const Ice::ObjectProxySeq& objects, const shared_ptr&, + const Ice::Context& ctx) override { - Ice::Context::const_iterator p = ctx.find("server"); + auto p = ctx.find("server"); if(p == ctx.end()) { return objects; @@ -110,11 +111,11 @@ class TypeFilterI : public IceGrid::TypeFilter string server = p->second; Ice::ObjectProxySeq filteredObjects; - for(Ice::ObjectProxySeq::const_iterator q = objects.begin(); q != objects.end(); ++q) + for(const auto& object : objects) { - if(_facade->getAdapterServer((*q)->ice_getAdapterId()) == server) + if(_facade->getAdapterServer(object->ice_getAdapterId()) == server) { - filteredObjects.push_back(*q); + filteredObjects.push_back(object); } } return filteredObjects; @@ -122,22 +123,23 @@ class TypeFilterI : public IceGrid::TypeFilter private: - RegistryPluginFacadePtr _facade; + shared_ptr _facade; }; -class ExcludeReplicaGroupFilterI : public IceGrid::ReplicaGroupFilter +class ExcludeReplicaGroupFilterI final : public IceGrid::ReplicaGroupFilter { public: - ExcludeReplicaGroupFilterI(const RegistryPluginFacadePtr& facade, const string& exclude) : + ExcludeReplicaGroupFilterI(const shared_ptr& facade, const string& exclude) : _facade(facade), _exclude(exclude) { } - virtual Ice::StringSeq - filter(const string& /*id*/, const Ice::StringSeq& adapters, const Ice::ConnectionPtr& /*con*/, const Ice::Context& ctx) + Ice::StringSeq + filter(const string&, const Ice::StringSeq& adapters, const shared_ptr& , + const Ice::Context& ctx) override { - Ice::Context::const_iterator p = ctx.find("server"); + auto p = ctx.find("server"); if(p == ctx.end() || p->second == _exclude) { return Ice::StringSeq(); @@ -147,7 +149,7 @@ class ExcludeReplicaGroupFilterI : public IceGrid::ReplicaGroupFilter private: - const RegistryPluginFacadePtr _facade; + const shared_ptr _facade; const string _exclude; }; @@ -158,27 +160,27 @@ extern "C" { ICE_DECLSPEC_EXPORT Ice::Plugin* -createRegistryPlugin(const Ice::CommunicatorPtr& communicator, const string&, const Ice::StringSeq&) +createRegistryPlugin(const shared_ptr& communicator, const string&, const Ice::StringSeq&) { return new RegistryPluginI(communicator); } } -RegistryPluginI::RegistryPluginI(const Ice::CommunicatorPtr& communicator) : _communicator(communicator) +RegistryPluginI::RegistryPluginI(const shared_ptr& communicator) : _communicator(communicator) { } void RegistryPluginI::initialize() { - IceGrid::RegistryPluginFacadePtr facade = IceGrid::getRegistryPluginFacade(); + auto facade = IceGrid::getRegistryPluginFacade(); assert(facade); - _filterByServer = new ReplicaGroupFilterI(facade); - _excludeServer2 = new ExcludeReplicaGroupFilterI(facade, "Server2"); - _excludeServer3 = new ExcludeReplicaGroupFilterI(facade, "Server3"); - _type = new TypeFilterI(facade); + _filterByServer = make_shared(facade); + _excludeServer2 = make_shared(facade, "Server2"); + _excludeServer3 = make_shared(facade, "Server3"); + _type = make_shared(facade); facade->addReplicaGroupFilter("filterByServer", _filterByServer); test(facade->removeReplicaGroupFilter("filterByServer", _filterByServer)); @@ -193,7 +195,7 @@ RegistryPluginI::initialize() void RegistryPluginI::destroy() { - IceGrid::RegistryPluginFacadePtr facade = IceGrid::getRegistryPluginFacade(); + auto facade = IceGrid::getRegistryPluginFacade(); assert(facade); facade->removeReplicaGroupFilter("filterByServer", _filterByServer); diff --git a/cpp/test/IceGrid/replicaGroup/Server.cpp b/cpp/test/IceGrid/replicaGroup/Server.cpp index d397d9ad8e7..6ec653b5e73 100644 --- a/cpp/test/IceGrid/replicaGroup/Server.cpp +++ b/cpp/test/IceGrid/replicaGroup/Server.cpp @@ -19,9 +19,9 @@ void Server::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); - Ice::ObjectAdapterPtr adpt = communicator->createObjectAdapter("ReplicatedAdapter"); - Ice::PropertiesPtr properties = communicator->getProperties(); - Ice::ObjectPtr object = new TestI(properties); + auto adpt = communicator->createObjectAdapter("ReplicatedAdapter"); + auto properties = communicator->getProperties(); + auto object = make_shared(properties); adpt->add(object, Ice::stringToIdentity(properties->getProperty("Ice.ProgramName"))); adpt->add(object, Ice::stringToIdentity(properties->getProperty("Identity"))); try diff --git a/cpp/test/IceGrid/replicaGroup/Service.cpp b/cpp/test/IceGrid/replicaGroup/Service.cpp index c5954bcf7dc..c14058a5de1 100644 --- a/cpp/test/IceGrid/replicaGroup/Service.cpp +++ b/cpp/test/IceGrid/replicaGroup/Service.cpp @@ -9,18 +9,15 @@ using namespace std; using namespace Ice; -class ServiceI : public ::IceBox::Service +class ServiceI final : public IceBox::Service { public: - ServiceI(); - virtual ~ServiceI(); + void start(const string&, + const shared_ptr&, + const StringSeq&) override; - virtual void start(const string&, - const CommunicatorPtr&, - const StringSeq&); - - virtual void stop(); + void stop() override; }; extern "C" @@ -30,28 +27,20 @@ extern "C" // Factory function // ICE_DECLSPEC_EXPORT ::IceBox::Service* -create(CommunicatorPtr) +create(const shared_ptr&) { return new ServiceI; } } -ServiceI::ServiceI() -{ -} - -ServiceI::~ServiceI() -{ -} - void ServiceI::start(const string& name, - const CommunicatorPtr& communicator, + const shared_ptr& communicator, const StringSeq&) { - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter(name); - Ice::ObjectPtr object = new TestI(communicator->getProperties()); + auto adapter = communicator->createObjectAdapter(name); + auto object = make_shared(communicator->getProperties()); adapter->add(object, stringToIdentity(name)); adapter->add(object, stringToIdentity(communicator->getProperties()->getProperty("Identity"))); adapter->activate(); diff --git a/cpp/test/IceGrid/replication/AllTests.cpp b/cpp/test/IceGrid/replication/AllTests.cpp index acb9ae5e4fe..64d0e5923ba 100644 --- a/cpp/test/IceGrid/replication/AllTests.cpp +++ b/cpp/test/IceGrid/replication/AllTests.cpp @@ -6,9 +6,9 @@ #include #include #include -#include #include #include +#include using namespace std; using namespace Test; @@ -17,37 +17,28 @@ using namespace IceGrid; namespace { -const int sleepTime = 100; // 100ms -const int maxRetry = 240000 / sleepTime; // 4 minutes +const auto sleepTime = 100ms; +const int maxRetry = static_cast(120000 / sleepTime.count()); // 2 minutes void -addProperty(const CommunicatorDescriptorPtr& communicator, const string& name, const string& value) -{ - PropertyDescriptor prop; - prop.name = name; - prop.value = value; - communicator->propertySet.properties.push_back(prop); -} - -void -waitForServerState(const IceGrid::AdminPrx& admin, const std::string& server, bool up) +waitForServerState(const shared_ptr& admin, const string& server, bool up) { int nRetry = 0; - while(nRetry < maxRetry) // One minute + while(nRetry < maxRetry) { - if(admin->getServerState(server) == (up ? Active : Inactive)) + if(admin->getServerState(server) == (up ? ServerState::Active : ServerState::Inactive)) { return; } - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(sleepTime)); + this_thread::sleep_for(sleepTime); ++nRetry; } test(false); } void -waitForReplicaState(const IceGrid::AdminPrx& admin, const std::string& replica, bool up) +waitForReplicaState(const shared_ptr& admin, const string& replica, bool up) { int nRetry = 0; while(nRetry < maxRetry) @@ -67,7 +58,7 @@ waitForReplicaState(const IceGrid::AdminPrx& admin, const std::string& replica, } } - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(sleepTime)); + this_thread::sleep_for(sleepTime); ++nRetry; } @@ -93,7 +84,7 @@ waitForReplicaState(const IceGrid::AdminPrx& admin, const std::string& replica, } void -waitForNodeState(const IceGrid::AdminPrx& admin, const std::string& node, bool up) +waitForNodeState(const shared_ptr& admin, const string& node, bool up) { int nRetry = 0; while(nRetry < maxRetry) @@ -113,7 +104,7 @@ waitForNodeState(const IceGrid::AdminPrx& admin, const std::string& node, bool u } } - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(sleepTime)); + this_thread::sleep_for(sleepTime); ++nRetry; } try @@ -137,10 +128,10 @@ waitForNodeState(const IceGrid::AdminPrx& admin, const std::string& node, bool u } void -instantiateServer(const AdminPrx& admin, const string& templ, const map& params) +instantiateServer(const shared_ptr& admin, string templ, const map& params) { ServerInstanceDescriptor desc; - desc._cpp_template = templ; + desc._cpp_template = std::move(templ); desc.parameterValues = params; NodeUpdateDescriptor nodeUpdate; nodeUpdate.name = "localnode"; @@ -165,7 +156,7 @@ instantiateServer(const AdminPrx& admin, const string& templ, const map& admin, const string& id) { try { @@ -201,7 +192,7 @@ removeServer(const AdminPrx& admin, const string& id) } bool -waitAndPing(const Ice::ObjectPrx& obj) +waitAndPing(const shared_ptr& obj) { int nRetry = 0; while(nRetry < maxRetry) @@ -213,15 +204,15 @@ waitAndPing(const Ice::ObjectPrx& obj) } catch(const Ice::LocalException&) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(sleepTime)); + this_thread::sleep_for(sleepTime); ++nRetry; } } return false; } -AdminPrx -createAdminSession(const Ice::LocatorPrx& locator, const string& replica) +shared_ptr +createAdminSession(const shared_ptr& locator, string replica) { test(waitAndPing(locator)); @@ -230,31 +221,43 @@ createAdminSession(const Ice::LocatorPrx& locator, const string& replica) { registryStr += "-" + replica; } - Ice::ObjectPrx obj = locator->ice_getCommunicator()->stringToProxy(registryStr)->ice_locator(locator); - RegistryPrx registry = RegistryPrx::checkedCast(obj); + auto obj = locator->ice_getCommunicator()->stringToProxy(registryStr)->ice_locator(locator); + auto registry = Ice::checkedCast(obj); test(registry); - AdminSessionPrx session = AdminSessionPrx::checkedCast(registry->createAdminSession("foo", "bar")); + auto session = Ice::checkedCast(registry->createAdminSession("foo", "bar")); test(session); return session->getAdmin(); } +bool +isObjectInfoEqual(const ObjectInfo& info1, const ObjectInfo& info2) +{ + return (info1.type == info2.type) && Ice::targetEqualTo(info1.proxy, info2.proxy); +} + +bool +isAdapterInfoEqual(const AdapterInfo& adpt1, const AdapterInfo& adpt2) +{ + return (adpt1.id == adpt2.id) && (adpt1.replicaGroupId == adpt2.replicaGroupId) && Ice::targetEqualTo(adpt1.proxy, adpt2.proxy); +} + } void allTests(Test::TestHelper* helper) { - Ice::CommunicatorPtr comm = helper->communicator(); - IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::checkedCast( - comm->stringToProxy(comm->getDefaultLocator()->ice_getIdentity().category + "/Registry")); + auto communicator = helper->communicator(); + auto registry = Ice::checkedCast(communicator->stringToProxy( + communicator->getDefaultLocator()->ice_getIdentity().category + "/Registry")); - AdminSessionPrx adminSession = registry->createAdminSession("foo", "bar"); + auto adminSession = registry->createAdminSession("foo", "bar"); adminSession->ice_getConnection()->setACM(registry->getACMTimeout(), - IceUtil::None, - Ice::ICE_ENUM(ACMHeartbeat, HeartbeatAlways)); + Ice::nullopt, + Ice::ACMHeartbeat::HeartbeatAlways); - AdminPrx admin = adminSession->getAdmin(); + auto admin = adminSession->getAdmin(); test(admin); map params; @@ -277,17 +280,17 @@ allTests(Test::TestHelper* helper) params["port"] = "12052"; instantiateServer(admin, "IceGridRegistry", params); - Ice::LocatorPrx masterLocator = - Ice::LocatorPrx::uncheckedCast(comm->stringToProxy("RepTestIceGrid/Locator-Master:default -p 12050")); - Ice::LocatorPrx slave1Locator = - Ice::LocatorPrx::uncheckedCast(comm->stringToProxy("RepTestIceGrid/Locator-Slave1:default -p 12051")); - Ice::LocatorPrx slave2Locator = - Ice::LocatorPrx::uncheckedCast(comm->stringToProxy("RepTestIceGrid/Locator-Slave2:default -p 12052")); + auto masterLocator = Ice::uncheckedCast( + communicator->stringToProxy("RepTestIceGrid/Locator-Master:default -p 12050")); + auto slave1Locator = Ice::uncheckedCast( + communicator->stringToProxy("RepTestIceGrid/Locator-Slave1:default -p 12051")); + auto slave2Locator = Ice::uncheckedCast( + communicator->stringToProxy("RepTestIceGrid/Locator-Slave2:default -p 12052")); - Ice::LocatorPrx replicatedLocator = - Ice::LocatorPrx::uncheckedCast(comm->stringToProxy("RepTestIceGrid/Locator:default -p 12050:default -p 12051")); + auto replicatedLocator = Ice::uncheckedCast( + communicator->stringToProxy("RepTestIceGrid/Locator:default -p 12050:default -p 12051")); - AdminPrx masterAdmin, slave1Admin, slave2Admin; + shared_ptr masterAdmin, slave1Admin, slave2Admin; admin->startServer("Master"); masterAdmin = createAdminSession(masterLocator, ""); @@ -310,52 +313,47 @@ allTests(Test::TestHelper* helper) { Ice::EndpointSeq endpoints; ObjectInfo info; - info = masterAdmin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")); - ObjectInfo info1 = slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")); - test(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")) == info); + auto info1 = slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")); + test(isObjectInfoEqual(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")), info)); test(info.type == Ice::Locator::ice_staticId()); endpoints = info.proxy->ice_getEndpoints(); test(endpoints.size() == 2); test(endpoints[0]->toString().find("-p 12050") != string::npos); test(endpoints[1]->toString().find("-p 12051") != string::npos); - info = masterAdmin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")); - test(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")) == info); + test(isObjectInfoEqual(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")), info)); test(info.type == IceGrid::Query::ice_staticId()); endpoints = info.proxy->ice_getEndpoints(); test(endpoints.size() == 2); test(endpoints[0]->toString().find("-p 12050") != string::npos); test(endpoints[1]->toString().find("-p 12051") != string::npos); - admin->startServer("Slave2"); slave2Admin = createAdminSession(slave2Locator, "Slave2"); - info = masterAdmin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")); // We eventually need to wait here for the update of the replicated objects to propagate to the replica. int nRetry = 0; - while(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")) != info && nRetry < maxRetry) + while(!isObjectInfoEqual(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")), info) && nRetry < maxRetry) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(sleepTime)); + this_thread::sleep_for(sleepTime); ++nRetry; } - test(slave2Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")) == info); + test(isObjectInfoEqual(slave2Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")), info)); test(info.type == Ice::Locator::ice_staticId()); endpoints = info.proxy->ice_getEndpoints(); test(endpoints.size() == 3); test(endpoints[0]->toString().find("-p 12050") != string::npos); test(endpoints[1]->toString().find("-p 12051") != string::npos); test(endpoints[2]->toString().find("-p 12052") != string::npos); - info = masterAdmin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")); // We eventually need to wait here for the update of the replicated objects to propagate to the replica. nRetry = 0; - while(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")) != info && nRetry < maxRetry) + while(!isObjectInfoEqual(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")), info) && nRetry < maxRetry) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(sleepTime)); + this_thread::sleep_for(sleepTime); ++nRetry; } - test(slave2Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")) == info); + test(isObjectInfoEqual(slave2Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")), info)); test(info.type == IceGrid::Query::ice_staticId()); endpoints = info.proxy->ice_getEndpoints(); test(endpoints.size() == 3); @@ -369,12 +367,12 @@ allTests(Test::TestHelper* helper) info = masterAdmin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")); // We eventually need to wait here for the update of the replicated objects to propagate to the replica. nRetry = 0; - while(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")) != info && nRetry < maxRetry) + while(!isObjectInfoEqual(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")), info) && nRetry < maxRetry) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(sleepTime)); + this_thread::sleep_for(sleepTime); ++nRetry; } - test(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")) == info); + test(isObjectInfoEqual(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Locator")), info)); test(info.type == Ice::Locator::ice_staticId()); endpoints = info.proxy->ice_getEndpoints(); test(endpoints.size() == 2); @@ -383,24 +381,31 @@ allTests(Test::TestHelper* helper) info = masterAdmin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")); nRetry = 0; - while(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")) != info && nRetry < maxRetry) + while(!isObjectInfoEqual(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")), info) && nRetry < maxRetry) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(sleepTime)); + this_thread::sleep_for(sleepTime); ++nRetry; } - test(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")) == info); + test(isObjectInfoEqual(slave1Admin->getObjectInfo(Ice::stringToIdentity("RepTestIceGrid/Query")), info)); test(info.type == IceGrid::Query::ice_staticId()); endpoints = info.proxy->ice_getEndpoints(); test(endpoints.size() == 2); test(endpoints[0]->toString().find("-p 12050") != string::npos); test(endpoints[1]->toString().find("-p 12051") != string::npos); - QueryPrx query; - query = QueryPrx::uncheckedCast(comm->stringToProxy("RepTestIceGrid/Query:" + endpoints[0]->toString())); - Ice::ObjectProxySeq objs = query->findAllObjectsByType("::IceGrid::Registry"); - test(objs.size() == 2); - query = QueryPrx::uncheckedCast(comm->stringToProxy("RepTestIceGrid/Query:" + endpoints[1]->toString())); - test(objs == query->findAllObjectsByType("::IceGrid::Registry")); + shared_ptr query; + query = Ice::uncheckedCast( + communicator->stringToProxy("RepTestIceGrid/Query:" + endpoints[0]->toString())); + auto objs1 = query->findAllObjectsByType("::IceGrid::Registry"); + test(objs1.size() == 2); + + query = Ice::uncheckedCast( + communicator->stringToProxy("RepTestIceGrid/Query:" + endpoints[1]->toString())); + auto objs2 = query->findAllObjectsByType("::IceGrid::Registry"); + for(vector::size_type i = 0; i < objs1.size(); i++) + { + test(Ice::targetEqualTo(objs1[i], objs2[i])); + } } cout << "ok" << endl; @@ -411,14 +416,14 @@ allTests(Test::TestHelper* helper) // admin session creation for the creation of the admin // session above!) // - RegistryPrx masterRegistry = RegistryPrx::checkedCast( - comm->stringToProxy("RepTestIceGrid/Registry")->ice_locator(replicatedLocator)); - RegistryPrx slave1Registry = RegistryPrx::checkedCast( - comm->stringToProxy("RepTestIceGrid/Registry-Slave1")->ice_locator(replicatedLocator)); + auto masterRegistry = Ice::checkedCast( + communicator->stringToProxy("RepTestIceGrid/Registry")->ice_locator(replicatedLocator)); + auto slave1Registry = Ice::checkedCast( + communicator->stringToProxy("RepTestIceGrid/Registry-Slave1")->ice_locator(replicatedLocator)); - SessionPrx session = masterRegistry->createSession("dummy", "dummy"); + auto session = masterRegistry->createSession("dummy", "dummy"); session->destroy(); - if(comm->getProperties()->getProperty("Ice.Default.Protocol") == "ssl") + if(communicator->getProperties()->getProperty("Ice.Default.Protocol") == "ssl") { session = masterRegistry->createSessionFromSecureConnection(); session->destroy(); @@ -452,10 +457,10 @@ allTests(Test::TestHelper* helper) // // Test registry user-account mapper. // - UserAccountMapperPrx masterMapper = UserAccountMapperPrx::checkedCast( - comm->stringToProxy("RepTestIceGrid/RegistryUserAccountMapper")->ice_locator(replicatedLocator)); - UserAccountMapperPrx slave1Mapper = UserAccountMapperPrx::checkedCast( - comm->stringToProxy("RepTestIceGrid/RegistryUserAccountMapper-Slave1")->ice_locator(replicatedLocator)); + auto masterMapper = Ice::checkedCast( + communicator->stringToProxy("RepTestIceGrid/RegistryUserAccountMapper")->ice_locator(replicatedLocator)); + auto slave1Mapper = Ice::checkedCast( + communicator->stringToProxy("RepTestIceGrid/RegistryUserAccountMapper-Slave1")->ice_locator(replicatedLocator)); test(masterMapper->getUserAccount("Dummy User Account1") == "dummy1"); test(masterMapper->getUserAccount("Dummy User Account2") == "dummy2"); @@ -482,11 +487,11 @@ allTests(Test::TestHelper* helper) // Test SessionManager, SSLSessionManager, // AdminSessionManager, AdminSSLSessionManager // - comm->stringToProxy("RepTestIceGrid/SessionManager")->ice_locator(replicatedLocator)->ice_ping(); - comm->stringToProxy("RepTestIceGrid/SSLSessionManager")->ice_locator(replicatedLocator)->ice_ping(); + communicator->stringToProxy("RepTestIceGrid/SessionManager")->ice_locator(replicatedLocator)->ice_ping(); + communicator->stringToProxy("RepTestIceGrid/SSLSessionManager")->ice_locator(replicatedLocator)->ice_ping(); try { - comm->stringToProxy("RepTestIceGrid/SessionManager-Slave1")->ice_locator(replicatedLocator)->ice_ping(); + communicator->stringToProxy("RepTestIceGrid/SessionManager-Slave1")->ice_locator(replicatedLocator)->ice_ping(); test(false); } catch(const Ice::NotRegisteredException&) @@ -494,17 +499,17 @@ allTests(Test::TestHelper* helper) } try { - comm->stringToProxy("RepTestIceGrid/SSLSessionManager-Slave1")->ice_locator(replicatedLocator)->ice_ping(); + communicator->stringToProxy("RepTestIceGrid/SSLSessionManager-Slave1")->ice_locator(replicatedLocator)->ice_ping(); test(false); } catch(const Ice::NotRegisteredException&) { } - comm->stringToProxy("RepTestIceGrid/AdminSessionManager")->ice_locator(replicatedLocator)->ice_ping(); - comm->stringToProxy("RepTestIceGrid/AdminSSLSessionManager")->ice_locator(replicatedLocator)->ice_ping(); - comm->stringToProxy("RepTestIceGrid/AdminSessionManager-Slave1")->ice_locator(replicatedLocator)->ice_ping(); - comm->stringToProxy("RepTestIceGrid/AdminSSLSessionManager-Slave1")->ice_locator(replicatedLocator)->ice_ping(); + communicator->stringToProxy("RepTestIceGrid/AdminSessionManager")->ice_locator(replicatedLocator)->ice_ping(); + communicator->stringToProxy("RepTestIceGrid/AdminSSLSessionManager")->ice_locator(replicatedLocator)->ice_ping(); + communicator->stringToProxy("RepTestIceGrid/AdminSessionManager-Slave1")->ice_locator(replicatedLocator)->ice_ping(); + communicator->stringToProxy("RepTestIceGrid/AdminSSLSessionManager-Slave1")->ice_locator(replicatedLocator)->ice_ping(); } cout << "ok" << endl; @@ -525,10 +530,10 @@ allTests(Test::TestHelper* helper) AdapterInfo adpt; adpt.id = "TestAdpt"; - adpt.proxy = comm->stringToProxy("dummy:tcp -p 12345 -h 127.0.0.1"); + adpt.proxy = communicator->stringToProxy("dummy:tcp -p 12345 -h 127.0.0.1"); ObjectInfo obj; - obj.proxy = comm->stringToProxy("dummy:tcp -p 12345 -h 127.0.0.1"); + obj.proxy = communicator->stringToProxy("dummy:tcp -p 12345 -h 127.0.0.1"); obj.type = "::Hello"; // @@ -536,7 +541,7 @@ allTests(Test::TestHelper* helper) // forwarding to the master work (the slave locator registry // forwards everything to the master). // - Ice::LocatorRegistryPrx locatorRegistry = slave1Locator->getRegistry(); + auto locatorRegistry = slave1Locator->getRegistry(); // // Test addition of application, adapter, object. @@ -573,13 +578,13 @@ allTests(Test::TestHelper* helper) test(slave1Admin->getApplicationInfo("TestApp").descriptor.description == "added application"); test(slave2Admin->getApplicationInfo("TestApp").descriptor.description == "added application"); - test(masterAdmin->getAdapterInfo("TestAdpt")[0] == adpt); - test(slave1Admin->getAdapterInfo("TestAdpt")[0] == adpt); - test(slave2Admin->getAdapterInfo("TestAdpt")[0] == adpt); + test(isAdapterInfoEqual(masterAdmin->getAdapterInfo("TestAdpt")[0], adpt)); + test(isAdapterInfoEqual(slave1Admin->getAdapterInfo("TestAdpt")[0], adpt)); + test(isAdapterInfoEqual(slave2Admin->getAdapterInfo("TestAdpt")[0], adpt)); - test(masterAdmin->getObjectInfo(obj.proxy->ice_getIdentity()) == obj); - test(slave1Admin->getObjectInfo(obj.proxy->ice_getIdentity()) == obj); - test(slave2Admin->getObjectInfo(obj.proxy->ice_getIdentity()) == obj); + test(isObjectInfoEqual(masterAdmin->getObjectInfo(obj.proxy->ice_getIdentity()), obj)); + test(isObjectInfoEqual(slave1Admin->getObjectInfo(obj.proxy->ice_getIdentity()), obj)); + test(isObjectInfoEqual(slave2Admin->getObjectInfo(obj.proxy->ice_getIdentity()), obj)); slave2Admin->shutdown(); waitForServerState(admin, "Slave2", false); @@ -614,7 +619,7 @@ allTests(Test::TestHelper* helper) ApplicationUpdateDescriptor appUpdate; appUpdate.name = "TestApp"; - appUpdate.description = new BoxedString("updated2 application"); + appUpdate.description = make_shared("updated2 application"); try { slave1Admin->updateApplication(appUpdate); @@ -629,7 +634,7 @@ allTests(Test::TestHelper* helper) adpt.replicaGroupId = "TestReplicaGroup"; locatorRegistry->setReplicatedAdapterDirectProxy(adpt.id, adpt.replicaGroupId, adpt.proxy); - obj.proxy = comm->stringToProxy("dummy:tcp -p 12346 -h 127.0.0.1"); + obj.proxy = communicator->stringToProxy("dummy:tcp -p 12346 -h 127.0.0.1"); try { slave1Admin->updateObject(obj.proxy); @@ -648,13 +653,13 @@ allTests(Test::TestHelper* helper) test(slave1Admin->getApplicationInfo("TestApp").descriptor.description == "updated2 application"); test(slave2Admin->getApplicationInfo("TestApp").descriptor.description == "updated2 application"); - test(masterAdmin->getAdapterInfo("TestAdpt")[0] == adpt); - test(slave1Admin->getAdapterInfo("TestAdpt")[0] == adpt); - test(slave2Admin->getAdapterInfo("TestAdpt")[0] == adpt); + test(isAdapterInfoEqual(masterAdmin->getAdapterInfo("TestAdpt")[0], adpt)); + test(isAdapterInfoEqual(slave1Admin->getAdapterInfo("TestAdpt")[0], adpt)); + test(isAdapterInfoEqual(slave2Admin->getAdapterInfo("TestAdpt")[0], adpt)); - test(masterAdmin->getObjectInfo(obj.proxy->ice_getIdentity()) == obj); - test(slave1Admin->getObjectInfo(obj.proxy->ice_getIdentity()) == obj); - test(slave2Admin->getObjectInfo(obj.proxy->ice_getIdentity()) == obj); + test(isObjectInfoEqual(masterAdmin->getObjectInfo(obj.proxy->ice_getIdentity()), obj)); + test(isObjectInfoEqual(slave1Admin->getObjectInfo(obj.proxy->ice_getIdentity()), obj)); + test(isObjectInfoEqual(slave2Admin->getObjectInfo(obj.proxy->ice_getIdentity()), obj)); slave2Admin->shutdown(); waitForServerState(admin, "Slave2", false); @@ -780,7 +785,7 @@ allTests(Test::TestHelper* helper) { // // Add an application which is using Node1. Otherwise, when a - // registry restarts it would throw aways the proxy of the nodes + // registry restarts it would throw away the proxy of the nodes // because the node isn't used by any application. // ApplicationDescriptor app; @@ -834,7 +839,7 @@ allTests(Test::TestHelper* helper) // if(!slave1Admin->pingNode("Node1")) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); + this_thread::sleep_for(200ms); } test(slave1Admin->pingNode("Node1")); // Node should be re-connected. } @@ -855,7 +860,7 @@ allTests(Test::TestHelper* helper) { if(!slave2Admin->pingNode("Node1")) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); + this_thread::sleep_for(200ms); } test(slave2Admin->pingNode("Node1")); // Node should be re-connected even if the master is down. } @@ -874,7 +879,7 @@ allTests(Test::TestHelper* helper) { if(!masterAdmin->pingNode("Node1")) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); + this_thread::sleep_for(200ms); } test(masterAdmin->pingNode("Node1")); // Node should be re-connected. } @@ -890,7 +895,7 @@ allTests(Test::TestHelper* helper) { if(!slave1Admin->pingNode("Node1")) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); + this_thread::sleep_for(200ms); } test(slave1Admin->pingNode("Node1")); // Node should be re-connected. } @@ -903,7 +908,7 @@ allTests(Test::TestHelper* helper) { if(!masterAdmin->pingNode("Node1")) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); + this_thread::sleep_for(200ms); } test(masterAdmin->pingNode("Node1")); } @@ -916,7 +921,7 @@ allTests(Test::TestHelper* helper) { if(!slave2Admin->pingNode("Node1")) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); + this_thread::sleep_for(200ms); } test(slave2Admin->pingNode("Node1")); } @@ -933,7 +938,7 @@ allTests(Test::TestHelper* helper) { if(!slave2Admin->pingNode("Node1")) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); + this_thread::sleep_for(200ms); } test(slave2Admin->pingNode("Node1")); } @@ -953,13 +958,14 @@ allTests(Test::TestHelper* helper) app.name = "TestApp"; app.description = "added application"; - ServerDescriptorPtr server = new ServerDescriptor(); + auto server = make_shared(); server->id = "Server"; - server->exe = comm->getProperties()->getProperty("ServerDir") + "/server"; + server->exe = communicator->getProperties()->getProperty("ServerDir") + "/server"; server->pwd = "."; server->applicationDistrib = false; server->allocatable = false; - addProperty(server, "Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + PropertyDescriptor prop{ "Ice.Admin.Endpoints", "tcp -h 127.0.0.1" }; + server->propertySet.properties.push_back(prop); server->activation = "on-demand"; AdapterDescriptor adapter; adapter.name = "TestAdapter"; @@ -984,21 +990,21 @@ allTests(Test::TestHelper* helper) try { - comm->stringToProxy("test")->ice_locator(masterLocator)->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(masterLocator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); } catch(const Ice::LocalException& ex) { cerr << ex << endl; - ApplicationInfo appInfo = admin->getApplicationInfo("Test"); + auto appInfo = admin->getApplicationInfo("Test"); cerr << "properties-override = " << appInfo.descriptor.variables["properties-override"] << endl; - PropertyDescriptorSeq& seq = admin->getServerInfo("Node1").descriptor->propertySet.properties; - for(PropertyDescriptorSeq::const_iterator p = seq.begin(); p != seq.end(); ++p) + auto propertySeq = admin->getServerInfo("Node1").descriptor->propertySet.properties; + for(const auto& p : propertySeq) { - cerr << p->name << " = " << p->value << endl; + cerr << p.name << " = " << p.value << endl; } test(false); } @@ -1024,8 +1030,8 @@ allTests(Test::TestHelper* helper) try { - comm->stringToProxy("test")->ice_locator(masterLocator)->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(masterLocator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); } catch(const Ice::LocalException& ex) { @@ -1050,7 +1056,7 @@ allTests(Test::TestHelper* helper) } try { - comm->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); test(false); } catch(const Ice::NoEndpointException&) @@ -1067,7 +1073,7 @@ allTests(Test::TestHelper* helper) try { - comm->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); } catch(const Ice::LocalException& ex) { @@ -1110,7 +1116,7 @@ allTests(Test::TestHelper* helper) try { - comm->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); } catch(const Ice::LocalException& ex) { @@ -1123,7 +1129,7 @@ allTests(Test::TestHelper* helper) try { - comm->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); } catch(const Ice::NoEndpointException&) { @@ -1131,7 +1137,7 @@ allTests(Test::TestHelper* helper) try { - comm->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); } catch(const Ice::LocalException& ex) { @@ -1167,9 +1173,9 @@ allTests(Test::TestHelper* helper) try { - comm->stringToProxy("test")->ice_locator(masterLocator)->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(masterLocator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); } catch(const Ice::LocalException& ex) { @@ -1189,13 +1195,14 @@ allTests(Test::TestHelper* helper) app.name = "TestApp"; app.description = "added application"; - ServerDescriptorPtr server = new ServerDescriptor(); + auto server = make_shared(); server->id = "Server"; - server->exe = comm->getProperties()->getProperty("ServerDir") + "/server"; + server->exe = communicator->getProperties()->getProperty("ServerDir") + "/server"; server->pwd = "."; server->applicationDistrib = false; server->allocatable = false; - addProperty(server, "Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + PropertyDescriptor prop{ "Ice.Admin.Endpoints", "tcp -h 127.0.0.1" }; + server->propertySet.properties.push_back(prop); server->activation = "on-demand"; AdapterDescriptor adapter; adapter.name = "TestAdapter"; @@ -1218,9 +1225,9 @@ allTests(Test::TestHelper* helper) masterAdmin->addApplication(app); - comm->stringToProxy("test")->ice_locator(masterLocator)->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(masterLocator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); masterAdmin->stopServer("Server"); // @@ -1238,8 +1245,8 @@ allTests(Test::TestHelper* helper) instantiateServer(admin, "IceGridRegistry", params); admin->startServer("Slave1"); - slave1Locator = - Ice::LocatorPrx::uncheckedCast(comm->stringToProxy("RepTestIceGrid/Locator-Master:default -p 12051")); + slave1Locator = Ice::uncheckedCast( + communicator->stringToProxy("RepTestIceGrid/Locator-Master:default -p 12051")); slave1Admin = createAdminSession(slave1Locator, ""); waitForReplicaState(slave1Admin, "Slave2", true); @@ -1255,8 +1262,8 @@ allTests(Test::TestHelper* helper) server->propertySet.properties.push_back(property); slave1Admin->updateApplication(update); - comm->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); slave1Admin->shutdown(); waitForServerState(admin, "Slave1", false); @@ -1278,20 +1285,20 @@ allTests(Test::TestHelper* helper) masterAdmin = createAdminSession(masterLocator, ""); admin->startServer("Slave1"); - slave1Locator = - Ice::LocatorPrx::uncheckedCast(comm->stringToProxy("RepTestIceGrid/Locator-Slave1:default -p 12051")); + slave1Locator = Ice::uncheckedCast( + communicator->stringToProxy("RepTestIceGrid/Locator-Slave1:default -p 12051")); slave1Admin = createAdminSession(slave1Locator, "Slave1"); - comm->stringToProxy("test")->ice_locator(masterLocator)->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(masterLocator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave1Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test")->ice_locator(slave2Locator)->ice_locatorCacheTimeout(0)->ice_ping(); masterAdmin->stopServer("Server"); waitForReplicaState(masterAdmin, "Slave1", true); waitForReplicaState(masterAdmin, "Slave2", true); - ApplicationInfo info = masterAdmin->getApplicationInfo("TestApp"); + auto info = masterAdmin->getApplicationInfo("TestApp"); test(info.revision == 2); masterAdmin->removeApplication("TestApp"); @@ -1319,23 +1326,23 @@ allTests(Test::TestHelper* helper) admin->startServer("Node2"); waitForNodeState(masterAdmin, "Node2", true); - Ice::LocatorPrx slave3Locator = - Ice::LocatorPrx::uncheckedCast( - comm->stringToProxy("RepTestIceGrid/Locator-Slave3 -e 1.0:default -p 12053")); - IceGrid::AdminPrx slave3Admin = createAdminSession(slave3Locator, "Slave3"); + auto slave3Locator = Ice::uncheckedCast( + communicator->stringToProxy("RepTestIceGrid/Locator-Slave3 -e 1.0:default -p 12053")); + auto slave3Admin = createAdminSession(slave3Locator, "Slave3"); waitForNodeState(slave3Admin, "Node2", true); ApplicationDescriptor app; app.name = "TestApp"; app.description = "added application"; - ServerDescriptorPtr server = new ServerDescriptor(); + auto server = make_shared(); server->id = "Server"; - server->exe = comm->getProperties()->getProperty("ServerDir") + "/server"; + server->exe = communicator->getProperties()->getProperty("ServerDir") + "/server"; server->pwd = "."; server->applicationDistrib = false; server->allocatable = false; - addProperty(server, "Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + PropertyDescriptor prop{ "Ice.Admin.Endpoints", "tcp -h 127.0.0.1" }; + server->propertySet.properties.push_back(prop); server->activation = "on-demand"; AdapterDescriptor adapter; adapter.name = "TestAdapter"; @@ -1358,11 +1365,11 @@ allTests(Test::TestHelper* helper) masterAdmin->addApplication(app); - comm->stringToProxy("test -e 1.0")->ice_locator( + communicator->stringToProxy("test -e 1.0")->ice_locator( masterLocator->ice_encodingVersion(Ice::Encoding_1_0))->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test -e 1.0")->ice_locator( + communicator->stringToProxy("test -e 1.0")->ice_locator( slave1Locator->ice_encodingVersion(Ice::Encoding_1_0))->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test -e 1.0")->ice_locator(slave3Locator)->ice_locatorCacheTimeout(0)->ice_ping(); + communicator->stringToProxy("test -e 1.0")->ice_locator(slave3Locator)->ice_locatorCacheTimeout(0)->ice_ping(); masterAdmin->stopServer("Server"); masterAdmin->removeApplication("TestApp"); @@ -1378,20 +1385,20 @@ allTests(Test::TestHelper* helper) app.replicaGroups.resize(1); app.replicaGroups[0].id = "TestReplicaGroup"; - app.replicaGroups[0].loadBalancing = new IceGrid::RandomLoadBalancingPolicy("2"); + app.replicaGroups[0].loadBalancing = make_shared("2"); ObjectDescriptor object; object.id = Ice::stringToIdentity("test"); object.type = "::Test::TestIntf"; app.replicaGroups[0].objects.push_back(object); - ServerDescriptorPtr server = new ServerDescriptor(); + auto server = make_shared(); server->id = "Server1"; - server->exe = comm->getProperties()->getProperty("ServerDir") + "/server"; + server->exe = communicator->getProperties()->getProperty("ServerDir") + "/server"; server->pwd = "."; server->applicationDistrib = false; server->allocatable = false; - addProperty(server, "Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + server->propertySet.properties.push_back(PropertyDescriptor{ "Ice.Admin.Endpoints", "tcp -h 127.0.0.1" }); server->activation = "on-demand"; AdapterDescriptor adapter; adapter.name = "TestAdapter"; @@ -1410,7 +1417,7 @@ allTests(Test::TestHelper* helper) server->adapters.push_back(adapter); app.nodes["Node1"].servers.push_back(server); - ServerDescriptorPtr server2 = ServerDescriptorPtr::dynamicCast(server->ice_clone()); + auto server2 = dynamic_pointer_cast(server->ice_clone()); server2->id = "Server2"; app.nodes["Node2"].servers.push_back(server2); @@ -1423,16 +1430,16 @@ allTests(Test::TestHelper* helper) cerr << ex.reason << endl; } - comm->stringToProxy("test -e 1.0@TestReplicaGroup")->ice_locator( + communicator->stringToProxy("test -e 1.0@TestReplicaGroup")->ice_locator( masterLocator->ice_encodingVersion(Ice::Encoding_1_0))->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test -e 1.0@TestAdapter.Server1")->ice_locator( + communicator->stringToProxy("test -e 1.0@TestAdapter.Server1")->ice_locator( masterLocator->ice_encodingVersion(Ice::Encoding_1_0))->ice_locatorCacheTimeout(0)->ice_ping(); - comm->stringToProxy("test -e 1.0@TestAdapter.Server2")->ice_locator( + communicator->stringToProxy("test -e 1.0@TestAdapter.Server2")->ice_locator( masterLocator->ice_encodingVersion(Ice::Encoding_1_0))->ice_locatorCacheTimeout(0)->ice_ping(); - QueryPrx query = QueryPrx::uncheckedCast( - comm->stringToProxy("RepTestIceGrid/Query")->ice_locator(masterLocator)); - test(query->findAllReplicas(comm->stringToProxy("test")).size() == 2); + auto query = Ice::uncheckedCast( + communicator->stringToProxy("RepTestIceGrid/Query")->ice_locator(masterLocator)); + test(query->findAllReplicas(communicator->stringToProxy("test")).size() == 2); test(masterAdmin->getAdapterInfo("TestReplicaGroup").size() == 2); admin->sendSignal("Node2", "SIGSTOP"); @@ -1448,7 +1455,7 @@ allTests(Test::TestHelper* helper) { } - test(query->findAllReplicas(comm->stringToProxy("test")).size() == 2); + test(query->findAllReplicas(communicator->stringToProxy("test")).size() == 2); try { masterAdmin->ice_invocationTimeout(1000)->getAdapterInfo("TestReplicaGroup"); @@ -1460,7 +1467,7 @@ allTests(Test::TestHelper* helper) admin->sendSignal("Node2", "SIGCONT"); } - test(query->findAllReplicas(comm->stringToProxy("test")).size() == 2); + test(query->findAllReplicas(communicator->stringToProxy("test")).size() == 2); test(masterAdmin->ice_invocationTimeout(1000)->getAdapterInfo("TestReplicaGroup").size() == 2); masterAdmin->removeApplication("TestApp"); diff --git a/cpp/test/IceGrid/replication/Client.cpp b/cpp/test/IceGrid/replication/Client.cpp index b95771b42fb..472adec97a1 100644 --- a/cpp/test/IceGrid/replication/Client.cpp +++ b/cpp/test/IceGrid/replication/Client.cpp @@ -8,22 +8,20 @@ using namespace std; -class Client : public Test::TestHelper +class Client final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Client::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); properties->setProperty("Ice.Warn.Connections", "0"); - properties->setProperty("Ice.Default.Timeout", "100"); - properties->setProperty("Ice.Trace.Retry", "1"); - Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); - communicator->getProperties()->parseCommandLineOptions("", Ice::argsToStringSeq(argc, argv)); + Ice::CommunicatorHolder communicatorHolder = initialize(argc, argv, properties); + communicatorHolder->getProperties()->parseCommandLineOptions("", Ice::argsToStringSeq(argc, argv)); void allTests(Test::TestHelper*); allTests(this); } diff --git a/cpp/test/IceGrid/replication/Server.cpp b/cpp/test/IceGrid/replication/Server.cpp index d21343f8f68..a0979fb2694 100644 --- a/cpp/test/IceGrid/replication/Server.cpp +++ b/cpp/test/IceGrid/replication/Server.cpp @@ -8,19 +8,19 @@ using namespace std; -class Server : public Test::TestHelper +class Server final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Server::run(int argc, char** argv) { - Ice::CommunicatorHolder communicator = initialize(argc, argv); - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("TestAdapter"); - adapter->add(new TestI(), Ice::stringToIdentity(communicator->getProperties()->getProperty("Identity"))); + Ice::CommunicatorHolder communicatorHolder = initialize(argc, argv); + auto adapter = communicatorHolder->createObjectAdapter("TestAdapter"); + adapter->add(make_shared(), Ice::stringToIdentity(communicatorHolder->getProperties()->getProperty("Identity"))); try { adapter->activate(); @@ -28,7 +28,7 @@ Server::run(int argc, char** argv) catch(const Ice::ObjectAdapterDeactivatedException&) { } - communicator->waitForShutdown(); + communicatorHolder->waitForShutdown(); } DEFINE_TEST(Server) diff --git a/cpp/test/IceGrid/replication/TestI.h b/cpp/test/IceGrid/replication/TestI.h index ec90fc41e3e..e92772c0574 100644 --- a/cpp/test/IceGrid/replication/TestI.h +++ b/cpp/test/IceGrid/replication/TestI.h @@ -7,7 +7,7 @@ #include -class TestI : public ::Test::TestIntf +class TestI final : public ::Test::TestIntf { public: diff --git a/cpp/test/IceGrid/session/AllTests.cpp b/cpp/test/IceGrid/session/AllTests.cpp index 52324845f15..95e699bba71 100644 --- a/cpp/test/IceGrid/session/AllTests.cpp +++ b/cpp/test/IceGrid/session/AllTests.cpp @@ -2,26 +2,18 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include #include #include #include #include #include +#include using namespace std; using namespace IceGrid; +using namespace Test; -void -addProperty(const CommunicatorDescriptorPtr& communicator, const string& name, const string& value) -{ - PropertyDescriptor prop; - prop.name = name; - prop.value = value; - communicator->propertySet.properties.push_back(prop); -} - -class ObserverBase : public IceUtil::Monitor +class ObserverBase { public: @@ -38,42 +30,32 @@ class ObserverBase : public IceUtil::Monitor static void printStack() { - map::const_iterator p; - for(p = _observers.begin(); p != _observers.end(); ++p) + for(const auto& p : _observers) { - vector::const_iterator q = p->second->_stack.begin(); - if(p->second->_stack.size() > 10) + vector::const_iterator q = p.second->_stack.begin(); + if (p.second->_stack.size() > 10) { - q = p->second->_stack.begin() + - static_cast::difference_type>(p->second->_stack.size() - 10); + q = p.second->_stack.begin() + + static_cast::difference_type>(p.second->_stack.size() - 10); } - cerr << "Last 10 updates of observer `" << p->second->_name << "':" << endl; - for(; q != p->second->_stack.end(); ++q) + cerr << "Last 10 updates of observer `" << p.second->_name << "':" << endl; + for (; q != p.second->_stack.end(); ++q) { cerr << " " << *q << endl; } - p->second->_stack.clear(); + p.second->_stack.clear(); } } void - trace(const string& msg) - { - _stack.push_back(msg); - } - - void - waitForUpdate(const char*, int line) + waitForUpdate(int line) { - Lock sync(*this); - - ostringstream os; - os << "wait for update from line " << line; - trace(os.str()); + unique_lock lg(_mutex); + _stack.push_back("wait for update from line " + to_string(line)); while(!_updated) { - wait(); + _condVar.wait(lg); } --_updated; } @@ -83,19 +65,25 @@ class ObserverBase : public IceUtil::Monitor void updated(const string& update) { - trace(update); + _stack.push_back(update); ++_updated; - notifyAll(); + _condVar.notify_all(); } string _name; vector _stack; int _updated; + mutex _mutex; + static map _observers; + +private: + + condition_variable _condVar; }; map ObserverBase::_observers; -class ApplicationObserverI : public ApplicationObserver, public ObserverBase +class ApplicationObserverI final : public ApplicationObserver, public ObserverBase { public: @@ -103,48 +91,48 @@ class ApplicationObserverI : public ApplicationObserver, public ObserverBase { } - virtual void - applicationInit(int serialP, const ApplicationInfoSeq& apps, const Ice::Current&) + void + applicationInit(int serialP, ApplicationInfoSeq apps, const Ice::Current&) override { - Lock sync(*this); - for(ApplicationInfoSeq::const_iterator p = apps.begin(); p != apps.end(); ++p) + lock_guard lg(_mutex); + for(const auto& p : apps) { - if(p->descriptor.name != "Test") // Ignore the test application from application.xml! + if(p.descriptor.name != "Test") // Ignore the test application from application.xml! { - this->applications.insert(make_pair(p->descriptor.name, *p)); + applications.insert(make_pair(p.descriptor.name, p)); } } updated(updateSerial(serialP, "init update")); } - virtual void - applicationAdded(int serialP, const ApplicationInfo& app, const Ice::Current&) + void + applicationAdded(int serialP, ApplicationInfo app, const Ice::Current&) override { - Lock sync(*this); - this->applications.insert(make_pair(app.descriptor.name, app)); + lock_guard lg(_mutex); + applications.insert(make_pair(app.descriptor.name, app)); updated(updateSerial(serialP, "application added `" + app.descriptor.name + "'")); } - virtual void - applicationRemoved(int serialP, const std::string& name, const Ice::Current&) + void + applicationRemoved(int serialP, std::string name, const Ice::Current&) override { - Lock sync(*this); - this->applications.erase(name); + lock_guard lg(_mutex); + applications.erase(name); updated(updateSerial(serialP, "application removed `" + name + "'")); } - virtual void - applicationUpdated(int serialP, const ApplicationUpdateInfo& info, const Ice::Current&) + void + applicationUpdated(int serialP, ApplicationUpdateInfo info, const Ice::Current&) override { - Lock sync(*this); + lock_guard lg(_mutex); const ApplicationUpdateDescriptor& desc = info.descriptor; - for(Ice::StringSeq::const_iterator q = desc.removeVariables.begin(); q != desc.removeVariables.end(); ++q) + for(const auto& p : desc.removeVariables) { - this->applications[desc.name].descriptor.variables.erase(*q); + applications[desc.name].descriptor.variables.erase(p); } - for(map::const_iterator p = desc.variables.begin(); p != desc.variables.end(); ++p) + for(const auto& p : desc.variables) { - this->applications[desc.name].descriptor.variables[p->first] = p->second; + applications[desc.name].descriptor.variables[p.first] = p.second; } updated(updateSerial(serialP, "application updated `" + desc.name + "'")); } @@ -163,9 +151,8 @@ class ApplicationObserverI : public ApplicationObserver, public ObserverBase return os.str(); } }; -typedef IceUtil::Handle ApplicationObserverIPtr; -class AdapterObserverI : public AdapterObserver, public ObserverBase +class AdapterObserverI final : public AdapterObserver, public ObserverBase { public: @@ -173,37 +160,37 @@ class AdapterObserverI : public AdapterObserver, public ObserverBase { } - virtual void - adapterInit(const AdapterInfoSeq& adaptersP, const Ice::Current&) + void + adapterInit(AdapterInfoSeq adaptersP, const Ice::Current&) override { - Lock sync(*this); - for(AdapterInfoSeq::const_iterator q = adaptersP.begin(); q != adaptersP.end(); ++q) + lock_guard lg(_mutex); + for(const auto& p : adaptersP) { - adapters.insert(make_pair(q->id, *q)); + adapters.insert(make_pair(p.id, p)); } updated(updateSerial(0, "init update")); } void - adapterAdded(const AdapterInfo& info, const Ice::Current&) + adapterAdded(AdapterInfo info, const Ice::Current&) override { - Lock sync(*this); + lock_guard lg(_mutex); adapters.insert(make_pair(info.id, info)); updated(updateSerial(0, "adapter added `" + info.id + "'")); } void - adapterUpdated(const AdapterInfo& info, const Ice::Current&) + adapterUpdated(AdapterInfo info, const Ice::Current&) override { - Lock sync(*this); + lock_guard lg(_mutex); adapters[info.id] = info; updated(updateSerial(0, "adapter updated `" + info.id + "'")); } void - adapterRemoved(const string& id, const Ice::Current&) + adapterRemoved(string id, const Ice::Current&) override { - Lock sync(*this); + lock_guard lg(_mutex); adapters.erase(id); updated(updateSerial(0, "adapter removed `" + id + "'")); } @@ -222,9 +209,8 @@ class AdapterObserverI : public AdapterObserver, public ObserverBase return os.str(); } }; -typedef IceUtil::Handle AdapterObserverIPtr; -class ObjectObserverI : public ObjectObserver, public ObserverBase +class ObjectObserverI final : public ObjectObserver, public ObserverBase { public: @@ -232,37 +218,37 @@ class ObjectObserverI : public ObjectObserver, public ObserverBase { } - virtual void - objectInit(const ObjectInfoSeq& objectsP, const Ice::Current&) + void + objectInit(ObjectInfoSeq objectsP, const Ice::Current&) override { - Lock sync(*this); - for(ObjectInfoSeq::const_iterator r = objectsP.begin(); r != objectsP.end(); ++r) + lock_guard lg(_mutex); + for(const auto& p : objectsP) { - objects.insert(make_pair(r->proxy->ice_getIdentity(), *r)); + objects.insert(make_pair(p.proxy->ice_getIdentity(), p)); } updated(updateSerial(0, "init update")); } void - objectAdded(const ObjectInfo& info, const Ice::Current&) + objectAdded(ObjectInfo info, const Ice::Current&) override { - Lock sync(*this); + lock_guard lg(_mutex); objects.insert(make_pair(info.proxy->ice_getIdentity(), info)); updated(updateSerial(0, "object added `" + info.proxy->ice_toString() + "'")); } void - objectUpdated(const ObjectInfo& info, const Ice::Current&) + objectUpdated(ObjectInfo info, const Ice::Current&) override { - Lock sync(*this); + lock_guard lg(_mutex); objects[info.proxy->ice_getIdentity()] = info; updated(updateSerial(0, "object updated `" + info.proxy->ice_toString() + "'")); } void - objectRemoved(const Ice::Identity& id, const Ice::Current& current) + objectRemoved(Ice::Identity id, const Ice::Current& current) override { - Lock sync(*this); + lock_guard lg(_mutex); objects.erase(id); updated(updateSerial(0, "object removed `" + current.adapter->getCommunicator()->identityToString(id) + "'")); @@ -282,9 +268,8 @@ class ObjectObserverI : public ObjectObserver, public ObserverBase return os.str(); } }; -typedef IceUtil::Handle ObjectObserverIPtr; -class NodeObserverI : public NodeObserver, public ObserverBase +class NodeObserverI final : public NodeObserver, public ObserverBase { public: @@ -292,50 +277,51 @@ class NodeObserverI : public NodeObserver, public ObserverBase { } - virtual void - nodeInit(const NodeDynamicInfoSeq& info, const Ice::Current&) + void + nodeInit(NodeDynamicInfoSeq info, const Ice::Current&) override { - Lock sync(*this); - for(NodeDynamicInfoSeq::const_iterator p = info.begin(); p != info.end(); ++p) + lock_guard lg(_mutex); + for(const auto& p : info) { - this->nodes[p->info.name] = filter(*p); + nodes[p.info.name] = filter(p); } updated("init"); } - virtual void - nodeUp(const NodeDynamicInfo& info, const Ice::Current&) + void + nodeUp(NodeDynamicInfo info, const Ice::Current&) override { - Lock sync(*this); - this->nodes[info.info.name] = filter(info); + lock_guard lg(_mutex); + nodes[info.info.name] = filter(info); updated("node `" + info.info.name + "' up"); } - virtual void - nodeDown(const string& name, const Ice::Current&) + void + nodeDown(string name, const Ice::Current&) override { - Lock sync(*this); - this->nodes.erase(name); + lock_guard lg(_mutex); + nodes.erase(name); updated("node `" + name + "' down"); } - virtual void - updateServer(const string& node, const ServerDynamicInfo& info, const Ice::Current&) + void + updateServer(string node, ServerDynamicInfo info, const Ice::Current&) override { if(info.id == "Glacier2" || info.id == "Glacier2Admin" || info.id == "PermissionsVerifierServer") { return; } - Lock sync(*this); + + lock_guard lg(_mutex); //cerr << node << " " << info.id << " " << info.state << " " << info.pid << endl; - ServerDynamicInfoSeq& servers = this->nodes[node].servers; + ServerDynamicInfoSeq& servers = nodes[node].servers; ServerDynamicInfoSeq::iterator p; for(p = servers.begin(); p != servers.end(); ++p) { if(p->id == info.id) { - if(info.state == Destroyed) + if(info.state == ServerState::Destroyed) { servers.erase(p); } @@ -346,28 +332,28 @@ class NodeObserverI : public NodeObserver, public ObserverBase break; } } - if(info.state != Destroyed && p == servers.end()) + if(info.state != ServerState::Destroyed && p == servers.end()) { servers.push_back(info); } ostringstream os; - os << "server `" << info.id << "' on node `" << node << "' state updated: " << info.state + os << "server `" << info.id << "' on node `" << node << "' state updated: " << static_cast(info.state) << " (pid = " << info.pid << ")"; updated(os.str()); } - virtual void - updateAdapter(const string& node, const AdapterDynamicInfo& info, const Ice::Current&) + void + updateAdapter(string node, AdapterDynamicInfo info, const Ice::Current&) override { if(info.id == "PermissionsVerifierServer.Server") { return; } - Lock sync(*this); + lock_guard lg(_mutex); //cerr << "update adapter: " << info.id << " " << (info.proxy ? "active" : "inactive") << endl; - AdapterDynamicInfoSeq& adapters = this->nodes[node].adapters; + AdapterDynamicInfoSeq& adapters = nodes[node].adapters; AdapterDynamicInfoSeq::iterator p; for(p = adapters.begin(); p != adapters.end(); ++p) { @@ -396,7 +382,7 @@ class NodeObserverI : public NodeObserver, public ObserverBase } NodeDynamicInfo - filter(const NodeDynamicInfo& info) + filter(NodeDynamicInfo info) { if(info.info.name != "localnode") { @@ -406,22 +392,22 @@ class NodeObserverI : public NodeObserver, public ObserverBase NodeDynamicInfo filtered; filtered.info = info.info; - for(ServerDynamicInfoSeq::const_iterator p = info.servers.begin(); p != info.servers.end(); ++p) + for(const auto& p : info.servers) { - if(p->id == "Glacier2" || p->id == "Glacier2Admin" || p->id == "PermissionsVerifierServer") + if(p.id == "Glacier2" || p.id == "Glacier2Admin" || p.id == "PermissionsVerifierServer") { continue; } - filtered.servers.push_back(*p); + filtered.servers.push_back(p); } - for(AdapterDynamicInfoSeq::const_iterator a = info.adapters.begin(); a != info.adapters.end(); ++a) + for(const auto& a : info.adapters) { - if(a->id == "PermissionsVerifierServer.Server") + if(a.id == "PermissionsVerifierServer.Server") { continue; } - filtered.adapters.push_back(*a); + filtered.adapters.push_back(a); } return filtered; @@ -429,9 +415,8 @@ class NodeObserverI : public NodeObserver, public ObserverBase map nodes; }; -typedef IceUtil::Handle NodeObserverIPtr; -class RegistryObserverI : public RegistryObserver, public ObserverBase +class RegistryObserverI final : public RegistryObserver, public ObserverBase { public: @@ -439,36 +424,35 @@ class RegistryObserverI : public RegistryObserver, public ObserverBase { } - virtual void - registryInit(const RegistryInfoSeq& info, const Ice::Current&) + void + registryInit(RegistryInfoSeq info, const Ice::Current&) override { - Lock sync(*this); + lock_guard lg(_mutex); for(RegistryInfoSeq::const_iterator p = info.begin(); p != info.end(); ++p) { - this->registries[p->name] = *p; + registries[p->name] = *p; } updated("init"); } - virtual void - registryUp(const RegistryInfo& info, const Ice::Current&) + void + registryUp(RegistryInfo info, const Ice::Current&) override { - Lock sync(*this); - this->registries[info.name] = info; + lock_guard lg(_mutex); + registries[info.name] = info; updated("registry `" + info.name + "' up"); } - virtual void - registryDown(const string& name, const Ice::Current&) - { - Lock sync(*this); - this->registries.erase(name); - updated("registry `" + name + "' down"); - } + void + registryDown(string name, const Ice::Current&) override + { + lock_guard lg(_mutex); + registries.erase(name); + updated("registry `" + name + "' down"); + } map registries; }; -typedef IceUtil::Handle RegistryObserverIPtr; void testFailedAndPrintObservers(const char* expr, const char* file, unsigned int line) @@ -480,25 +464,19 @@ testFailedAndPrintObservers(const char* expr, const char* file, unsigned int lin #undef test #define test(ex) ((ex) ? ((void)0) : testFailedAndPrintObservers(#ex, __FILE__, __LINE__)) -#if defined(_AIX) && defined(__GNUC__) -// Strange optimization bug with catching ExtendedPermissionDeniedException with GCC 8.1 on AIX -__attribute__((optimize("O0"))) -#endif void -allTests(Test::TestHelper* helper) +allTests(TestHelper* helper) { - Ice::CommunicatorPtr communicator = helper->communicator(); + auto communicator = helper->communicator(); bool encoding10 = communicator->getProperties()->getProperty("Ice.Default.EncodingVersion") == "1.0"; - IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::checkedCast( - communicator->stringToProxy(communicator->getDefaultLocator()->ice_getIdentity().category + "/Registry")); + auto registry = Ice::checkedCast(communicator->stringToProxy( + communicator->getDefaultLocator()->ice_getIdentity().category + "/Registry")); - AdminSessionPrx session = registry->createAdminSession("admin3", "test3"); - session->ice_getConnection()->setACM(registry->getACMTimeout(), - IceUtil::None, - Ice::ICE_ENUM(ACMHeartbeat, HeartbeatAlways)); + auto session = registry->createAdminSession("admin3", "test3"); + session->ice_getConnection()->setACM(registry->getACMTimeout(), Ice::nullopt, Ice::ACMHeartbeat::HeartbeatAlways); - AdminPrx admin = session->getAdmin(); + auto admin = session->getAdmin(); test(admin); cout << "starting router... " << flush; @@ -525,21 +503,21 @@ allTests(Test::TestHelper* helper) } cout << "ok" << endl; - Ice::PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); - IceGrid::RegistryPrx registry1 = IceGrid::RegistryPrx::uncheckedCast(registry->ice_connectionId("reg1")); - IceGrid::RegistryPrx registry2 = IceGrid::RegistryPrx::uncheckedCast(registry->ice_connectionId("reg2")); + auto registry1 = Ice::uncheckedCast(registry->ice_connectionId("reg1")); + auto registry2 = Ice::uncheckedCast(registry->ice_connectionId("reg2")); - Glacier2::RouterPrx router = Glacier2::RouterPrx::uncheckedCast( + auto router = Ice::uncheckedCast( communicator->stringToProxy("Glacier2/router:default -p 12347 -h 127.0.0.1")); - Glacier2::RouterPrx adminRouter = Glacier2::RouterPrx::uncheckedCast( + auto adminRouter = Ice::uncheckedCast( communicator->stringToProxy("Glacier2/router:default -p 12348 -h 127.0.0.1")); - Glacier2::RouterPrx router1 = Glacier2::RouterPrx::uncheckedCast(router->ice_connectionId("router1")); - Glacier2::RouterPrx router2 = Glacier2::RouterPrx::uncheckedCast(router->ice_connectionId("router2")); + auto router1 = Ice::uncheckedCast(router->ice_connectionId("router1")); + auto router2 = Ice::uncheckedCast(router->ice_connectionId("router2")); - Glacier2::RouterPrx adminRouter1 = Glacier2::RouterPrx::uncheckedCast(adminRouter->ice_connectionId("admRouter1")); - Glacier2::RouterPrx adminRouter2 = Glacier2::RouterPrx::uncheckedCast(adminRouter->ice_connectionId("admRouter2")); + auto adminRouter1 = Ice::uncheckedCast(adminRouter->ice_connectionId("admRouter1")); + auto adminRouter2 = Ice::uncheckedCast(adminRouter->ice_connectionId("admRouter2")); // // TODO: Find a better way to wait for the Glacier2 router to be @@ -555,23 +533,22 @@ allTests(Test::TestHelper* helper) } catch(const Ice::LocalException&) { - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(100)); + this_thread::sleep_for(100ms); } } { cout << "testing username/password sessions... " << flush; + shared_ptr session1, session2; - SessionPrx session1, session2; - - session1 = SessionPrx::uncheckedCast(registry1->createSession("client1", "test1")->ice_connectionId("reg1")); - session2 = SessionPrx::uncheckedCast(registry2->createSession("client2", "test2")->ice_connectionId("reg2")); + session1 = Ice::uncheckedCast(registry1->createSession("client1", "test1")->ice_connectionId("reg1")); + session2 = Ice::uncheckedCast(registry2->createSession("client2", "test2")->ice_connectionId("reg2")); try { registry1->createSession("client3", "test1"); test(false); } - catch(const IceGrid::PermissionDeniedException&) + catch(const PermissionDeniedException&) { } try @@ -581,7 +558,7 @@ allTests(Test::TestHelper* helper) registry1->createSession("client3", "test1", ctx); test(false); } - catch(const IceGrid::PermissionDeniedException& ex) + catch(const PermissionDeniedException& ex) { test(ex.reason == "reason"); } @@ -626,18 +603,18 @@ allTests(Test::TestHelper* helper) session1->destroy(); session2->destroy(); - AdminSessionPrx adminSession1, adminSession2; + shared_ptr adminSession1, adminSession2; - adminSession1 = AdminSessionPrx::uncheckedCast( + adminSession1 = Ice::uncheckedCast( registry1->createAdminSession("admin1", "test1")->ice_connectionId("reg1")); - adminSession2 = AdminSessionPrx::uncheckedCast( + adminSession2 = Ice::uncheckedCast( registry2->createAdminSession("admin2", "test2")->ice_connectionId("reg2")); try { registry1->createAdminSession("admin3", "test1"); test(false); } - catch(const IceGrid::PermissionDeniedException&) + catch(const PermissionDeniedException&) { } try @@ -647,7 +624,7 @@ allTests(Test::TestHelper* helper) registry1->createSession("admin3", "test1", ctx); test(false); } - catch(const IceGrid::PermissionDeniedException& ex) + catch(const PermissionDeniedException& ex) { test(ex.reason == "reason"); } @@ -702,10 +679,10 @@ allTests(Test::TestHelper* helper) { cout << "testing sessions from secure connection... " << flush; - SessionPrx session1, session2; + shared_ptr session1, session2; - session1 = SessionPrx::uncheckedCast(registry1->createSessionFromSecureConnection()->ice_connectionId("reg1")); - session2 = SessionPrx::uncheckedCast(registry2->createSessionFromSecureConnection()->ice_connectionId("reg2")); + session1 = Ice::uncheckedCast(registry1->createSessionFromSecureConnection()->ice_connectionId("reg1")); + session2 = Ice::uncheckedCast(registry2->createSessionFromSecureConnection()->ice_connectionId("reg2")); session1->ice_ping(); session2->ice_ping(); @@ -717,7 +694,7 @@ allTests(Test::TestHelper* helper) registry1->createSessionFromSecureConnection(ctx); test(false); } - catch(const IceGrid::PermissionDeniedException& ex) + catch(const PermissionDeniedException& ex) { test(ex.reason == "reason"); } @@ -742,11 +719,11 @@ allTests(Test::TestHelper* helper) session1->destroy(); session2->destroy(); - AdminSessionPrx adminSession1, adminSession2; + shared_ptr adminSession1, adminSession2; - adminSession1 = AdminSessionPrx::uncheckedCast( + adminSession1 = Ice::uncheckedCast( registry1->createAdminSessionFromSecureConnection()->ice_connectionId("reg1")); - adminSession2 = AdminSessionPrx::uncheckedCast( + adminSession2 = Ice::uncheckedCast( registry2->createAdminSessionFromSecureConnection()->ice_connectionId("reg2")); adminSession1->ice_ping(); @@ -759,7 +736,7 @@ allTests(Test::TestHelper* helper) registry1->createAdminSessionFromSecureConnection(ctx); test(false); } - catch(const IceGrid::PermissionDeniedException& ex) + catch(const PermissionDeniedException& ex) { test(ex.reason == "reason"); } @@ -794,7 +771,7 @@ allTests(Test::TestHelper* helper) registry1->createSessionFromSecureConnection(); test(false); } - catch(const IceGrid::PermissionDeniedException&) + catch(const PermissionDeniedException&) { } try @@ -802,7 +779,7 @@ allTests(Test::TestHelper* helper) registry1->createAdminSessionFromSecureConnection(); test(false); } - catch(const IceGrid::PermissionDeniedException&) + catch(const PermissionDeniedException&) { } cout << "ok" << endl; @@ -811,17 +788,17 @@ allTests(Test::TestHelper* helper) { cout << "testing Glacier2 username/password sessions... " << flush; - SessionPrx session1, session2; + shared_ptr session1, session2; - Glacier2::SessionPrx base; + shared_ptr base; base = router1->createSession("client1", "test1"); test(base); - session1 = SessionPrx::uncheckedCast(base->ice_connectionId("router1")->ice_router(router1)); + session1 = Ice::uncheckedCast(base->ice_connectionId("router1")->ice_router(router1)); base = router2->createSession("client2", "test2"); test(base); - session2 = SessionPrx::uncheckedCast(base->ice_connectionId("router2")->ice_router(router2)); + session2 = Ice::uncheckedCast(base->ice_connectionId("router2")->ice_router(router2)); try { @@ -838,7 +815,7 @@ allTests(Test::TestHelper* helper) router->ice_connectionId("routerex")->createSession("client3", "test1", ctx); test(false); } - catch(const Test::ExtendedPermissionDeniedException& ex) + catch(const ExtendedPermissionDeniedException& ex) { test(!encoding10 && ex.reason == "reason"); } @@ -867,7 +844,7 @@ allTests(Test::TestHelper* helper) { } - Ice::ObjectPrx obj = communicator->stringToProxy("TestIceGrid/Query"); + auto obj = communicator->stringToProxy("TestIceGrid/Query"); obj->ice_connectionId("router1")->ice_router(router1)->ice_ping(); obj->ice_connectionId("router2")->ice_router(router2)->ice_ping(); @@ -892,13 +869,13 @@ allTests(Test::TestHelper* helper) router1->destroySession(); router2->destroySession(); - AdminSessionPrx admSession1, admSession2; + shared_ptr admSession1, admSession2; base = adminRouter1->createSession("admin1", "test1"); - admSession1 = AdminSessionPrx::uncheckedCast(base->ice_connectionId("admRouter1")->ice_router(adminRouter1)); + admSession1 = Ice::uncheckedCast(base->ice_connectionId("admRouter1")->ice_router(adminRouter1)); base = adminRouter2->createSession("admin2", "test2"); - admSession2 = AdminSessionPrx::uncheckedCast(base->ice_connectionId("admRouter2")->ice_router(adminRouter2)); + admSession2 = Ice::uncheckedCast(base->ice_connectionId("admRouter2")->ice_router(adminRouter2)); try { @@ -915,7 +892,7 @@ allTests(Test::TestHelper* helper) adminRouter->ice_connectionId("routerex")->createSession("admin3", "test1", ctx); test(false); } - catch(const Test::ExtendedPermissionDeniedException& ex) + catch(const ExtendedPermissionDeniedException& ex) { test(!encoding10 && ex.reason == "reason"); } @@ -927,8 +904,8 @@ allTests(Test::TestHelper* helper) admSession1->ice_ping(); admSession2->ice_ping(); - Ice::ObjectPrx admin1 = admSession1->getAdmin()->ice_router(adminRouter1)->ice_connectionId("admRouter1"); - Ice::ObjectPrx admin2 = admSession2->getAdmin()->ice_router(adminRouter2)->ice_connectionId("admRouter2"); + auto admin1 = admSession1->getAdmin()->ice_router(adminRouter1)->ice_connectionId("admRouter1"); + auto admin2 = admSession2->getAdmin()->ice_router(adminRouter2)->ice_connectionId("admRouter2"); admin1->ice_ping(); admin2->ice_ping(); @@ -981,21 +958,21 @@ allTests(Test::TestHelper* helper) { cout << "testing Glacier2 sessions from secure connection... " << flush; - SessionPrx session1, session2; + shared_ptr session1, session2; - Glacier2::SessionPrx base; + shared_ptr base; // // BUGFIX: We can't re-use the same router proxies because of bug 1034. // - router1 = Glacier2::RouterPrx::uncheckedCast(router1->ice_connectionId("router11")); - router2 = Glacier2::RouterPrx::uncheckedCast(router2->ice_connectionId("router21")); + router1 = Ice::uncheckedCast(router1->ice_connectionId("router11")); + router2 = Ice::uncheckedCast(router2->ice_connectionId("router21")); base = router1->createSessionFromSecureConnection(); - session1 = SessionPrx::uncheckedCast(base->ice_connectionId("router11")->ice_router(router1)); + session1 = Ice::uncheckedCast(base->ice_connectionId("router11")->ice_router(router1)); base = router2->createSessionFromSecureConnection(); - session2 = SessionPrx::uncheckedCast(base->ice_connectionId("router21")->ice_router(router2)); + session2 = Ice::uncheckedCast(base->ice_connectionId("router21")->ice_router(router2)); session1->ice_ping(); session2->ice_ping(); @@ -1007,7 +984,7 @@ allTests(Test::TestHelper* helper) router->ice_connectionId("routerex")->createSessionFromSecureConnection(ctx); test(false); } - catch(const Test::ExtendedPermissionDeniedException& ex) + catch(const ExtendedPermissionDeniedException& ex) { test(!encoding10 && ex.reason == "reason"); } @@ -1033,7 +1010,7 @@ allTests(Test::TestHelper* helper) { } - Ice::ObjectPrx obj = communicator->stringToProxy("TestIceGrid/Query"); + shared_ptr obj = communicator->stringToProxy("TestIceGrid/Query"); obj->ice_connectionId("router11")->ice_router(router1)->ice_ping(); obj->ice_connectionId("router21")->ice_router(router2)->ice_ping(); @@ -1058,19 +1035,17 @@ allTests(Test::TestHelper* helper) router1->destroySession(); router2->destroySession(); - AdminSessionPrx admSession1, admSession2; + shared_ptr admSession1, admSession2; - // // BUGFIX: We can't re-use the same router proxies because of bug 1034. - // - adminRouter1 = Glacier2::RouterPrx::uncheckedCast(adminRouter->ice_connectionId("admRouter11")); - adminRouter2 = Glacier2::RouterPrx::uncheckedCast(adminRouter->ice_connectionId("admRouter21")); + adminRouter1 = Ice::uncheckedCast(adminRouter->ice_connectionId("admRouter11")); + adminRouter2 = Ice::uncheckedCast(adminRouter->ice_connectionId("admRouter21")); base = adminRouter1->createSessionFromSecureConnection(); - admSession1 = AdminSessionPrx::uncheckedCast(base->ice_connectionId("admRouter11")->ice_router(adminRouter1)); + admSession1 = Ice::uncheckedCast(base->ice_connectionId("admRouter11")->ice_router(adminRouter1)); base = adminRouter2->createSessionFromSecureConnection(); - admSession2 = AdminSessionPrx::uncheckedCast(base->ice_connectionId("admRouter21")->ice_router(adminRouter2)); + admSession2 = Ice::uncheckedCast(base->ice_connectionId("admRouter21")->ice_router(adminRouter2)); admSession1->ice_ping(); admSession2->ice_ping(); @@ -1082,7 +1057,7 @@ allTests(Test::TestHelper* helper) adminRouter->ice_connectionId("routerex")->createSessionFromSecureConnection(ctx); test(false); } - catch(const Test::ExtendedPermissionDeniedException& ex) + catch(const ExtendedPermissionDeniedException& ex) { test(!encoding10 && ex.reason == "reason"); } @@ -1091,8 +1066,8 @@ allTests(Test::TestHelper* helper) test(encoding10 && ex.reason == "reason"); } - Ice::ObjectPrx admin1 = admSession1->getAdmin()->ice_router(adminRouter1)->ice_connectionId("admRouter11"); - Ice::ObjectPrx admin2 = admSession2->getAdmin()->ice_router(adminRouter2)->ice_connectionId("admRouter21"); + auto admin1 = admSession1->getAdmin()->ice_router(adminRouter1)->ice_connectionId("admRouter11"); + auto admin2 = admSession2->getAdmin()->ice_router(adminRouter2)->ice_connectionId("admRouter21"); admin1->ice_ping(); admin2->ice_ping(); @@ -1164,20 +1139,20 @@ allTests(Test::TestHelper* helper) { cout << "testing updates with admin sessions... " << flush; - AdminSessionPrx session1 = registry->createAdminSession("admin1", "test1"); - AdminSessionPrx session2 = registry->createAdminSession("admin2", "test2"); + auto session1 = registry->createAdminSession("admin1", "test1"); + auto session2 = registry->createAdminSession("admin2", "test2"); - session1->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::HeartbeatOnIdle); - session2->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::HeartbeatOnIdle); + session1->ice_getConnection()->setACM(registry->getACMTimeout(), Ice::nullopt, Ice::ACMHeartbeat::HeartbeatOnIdle); + session2->ice_getConnection()->setACM(registry->getACMTimeout(), Ice::nullopt, Ice::ACMHeartbeat::HeartbeatOnIdle); - AdminPrx admin1 = session1->getAdmin(); - AdminPrx admin2 = session2->getAdmin(); + auto admin1 = session1->getAdmin(); + auto admin2 = session2->getAdmin(); - Ice::ObjectAdapterPtr adpt1 = communicator->createObjectAdapter(""); - ApplicationObserverIPtr appObs1 = new ApplicationObserverI("appObs1.1"); - Ice::ObjectPrx app1 = adpt1->addWithUUID(appObs1); - NodeObserverIPtr nodeObs1 = new NodeObserverI("nodeObs1"); - Ice::ObjectPrx no1 = adpt1->addWithUUID(nodeObs1); + auto adpt1 = communicator->createObjectAdapter(""); + auto appObs1 = make_shared("appObs1.1"); + auto app1 = adpt1->addWithUUID(appObs1); + auto nodeObs1 = make_shared("nodeObs1"); + auto no1 = adpt1->addWithUUID(nodeObs1); adpt1->activate(); registry->ice_getConnection()->setAdapter(adpt1); session1->setObserversByIdentity(Ice::Identity(), @@ -1186,20 +1161,20 @@ allTests(Test::TestHelper* helper) Ice::Identity(), Ice::Identity()); - Ice::ObjectAdapterPtr adpt2 = communicator->createObjectAdapterWithEndpoints("Observer2", "tcp"); - ApplicationObserverIPtr appObs2 = new ApplicationObserverI("appObs2"); - Ice::ObjectPrx app2 = adpt2->addWithUUID(appObs2); - NodeObserverIPtr nodeObs2 = new NodeObserverI("nodeObs1"); - Ice::ObjectPrx no2 = adpt2->addWithUUID(nodeObs2); + auto adpt2 = communicator->createObjectAdapterWithEndpoints("Observer2", "default"); + auto appObs2 = make_shared("appObs2"); + auto app2 = adpt2->addWithUUID(appObs2); + auto nodeObs2 = make_shared("nodeObs1"); + auto no2 = adpt2->addWithUUID(nodeObs2); adpt2->activate(); session2->setObservers(0, - NodeObserverPrx::uncheckedCast(no2), - ApplicationObserverPrx::uncheckedCast(app2), + Ice::uncheckedCast(no2), + Ice::uncheckedCast(app2), 0, 0); - appObs1->waitForUpdate(__FILE__, __LINE__); - appObs2->waitForUpdate(__FILE__, __LINE__); + appObs1->waitForUpdate(__LINE__); + appObs2->waitForUpdate(__LINE__); int serial = appObs1->serial; test(serial == appObs2->serial); @@ -1266,7 +1241,7 @@ allTests(Test::TestHelper* helper) { ApplicationDescriptor app; app.name = "Application"; - admin2->addApplication(app); + admin2->addApplication(std::move(app)); } catch(const Ice::UserException&) { @@ -1291,8 +1266,8 @@ allTests(Test::TestHelper* helper) test(false); } - appObs1->waitForUpdate(__FILE__, __LINE__); - appObs2->waitForUpdate(__FILE__, __LINE__); + appObs1->waitForUpdate(__LINE__); + appObs2->waitForUpdate(__LINE__); test(serial + 1 == appObs1->serial); test(serial + 1 == appObs2->serial); @@ -1305,7 +1280,7 @@ allTests(Test::TestHelper* helper) ApplicationUpdateDescriptor update; update.name = "Application"; update.variables.insert(make_pair(string("test"), string("test"))); - admin1->updateApplication(update); + admin1->updateApplication(std::move(update)); session1->finishUpdate(); } catch(const Ice::UserException& ex) @@ -1314,28 +1289,13 @@ allTests(Test::TestHelper* helper) test(false); } - appObs1->waitForUpdate(__FILE__, __LINE__); - appObs2->waitForUpdate(__FILE__, __LINE__); + appObs1->waitForUpdate(__LINE__); + appObs2->waitForUpdate(__LINE__); test(serial + 1 == appObs1->serial); test(serial + 1 == appObs2->serial); ++serial; - // - // We now allow modifying the database without holding the - // exclusive lock. - // -// try -// { -// ApplicationUpdateDescriptor update; -// update.name = "Application"; -// admin1->updateApplication(update); -// test(false); -// } -// catch(const AccessDeniedException&) -// { -// } - try { int s = session2->startUpdate(); @@ -1348,8 +1308,8 @@ allTests(Test::TestHelper* helper) test(false); } - appObs1->waitForUpdate(__FILE__, __LINE__); - appObs2->waitForUpdate(__FILE__, __LINE__); + appObs1->waitForUpdate(__LINE__); + appObs2->waitForUpdate(__LINE__); test(serial + 1 == appObs1->serial); test(serial + 1 == appObs2->serial); @@ -1381,32 +1341,28 @@ allTests(Test::TestHelper* helper) adpt1->destroy(); adpt2->destroy(); - // - // TODO: test session reaping? - // - cout << "ok" << endl; } { cout << "testing invalid configuration... " << flush; - AdminSessionPrx session1 = registry->createAdminSession("admin1", "test1"); - AdminPrx admin1 = session1->getAdmin(); + auto session1 = registry->createAdminSession("admin1", "test1"); + auto admin1 = session1->getAdmin(); - Ice::LocatorRegistryPrx locatorRegistry = communicator->getDefaultLocator()->getRegistry(); + auto locatorRegistry = communicator->getDefaultLocator()->getRegistry(); try { ApplicationDescriptor app; app.name = string(512, 'A'); - admin1->addApplication(app); + admin1->addApplication(std::move(app)); test(false); } catch(const DeploymentException&) { } - Ice::ObjectPrx obj = communicator->stringToProxy("dummy:tcp -p 10000"); + auto obj = communicator->stringToProxy("dummy:tcp -p 10000"); try { locatorRegistry->setAdapterDirectProxy(string(512, 'A'), obj); @@ -1439,14 +1395,14 @@ allTests(Test::TestHelper* helper) { cout << "testing application observer... " << flush; - AdminSessionPrx session1 = registry->createAdminSession("admin1", "test1"); - AdminPrx admin1 = session1->getAdmin(); + auto session1 = registry->createAdminSession("admin1", "test1"); + auto admin1 = session1->getAdmin(); - session1->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::HeartbeatOnIdle); + session1->ice_getConnection()->setACM(registry->getACMTimeout(), Ice::nullopt, Ice::ACMHeartbeat::HeartbeatOnIdle); - Ice::ObjectAdapterPtr adpt1 = communicator->createObjectAdapter(""); - ApplicationObserverIPtr appObs1 = new ApplicationObserverI("appObs1.2"); - Ice::ObjectPrx app1 = adpt1->addWithUUID(appObs1); + auto adpt1 = communicator->createObjectAdapter(""); + auto appObs1 = make_shared("appObs1.2"); + auto app1 = adpt1->addWithUUID(appObs1); adpt1->activate(); registry->ice_getConnection()->setAdapter(adpt1); session1->setObserversByIdentity(Ice::Identity(), @@ -1455,7 +1411,7 @@ allTests(Test::TestHelper* helper) Ice::Identity(), Ice::Identity()); - appObs1->waitForUpdate(__FILE__, __LINE__); + appObs1->waitForUpdate(__LINE__); int serial = appObs1->serial; test(appObs1->applications.empty()); @@ -1466,8 +1422,8 @@ allTests(Test::TestHelper* helper) app.name = "Application"; int s = session1->startUpdate(); test(s == serial); - admin1->addApplication(app); - appObs1->waitForUpdate(__FILE__, __LINE__); + admin1->addApplication(std::move(app)); + appObs1->waitForUpdate(__LINE__); test(appObs1->applications.find("Application") != appObs1->applications.end()); test(++serial == appObs1->serial); } @@ -1482,8 +1438,8 @@ allTests(Test::TestHelper* helper) ApplicationUpdateDescriptor update; update.name = "Application"; update.variables.insert(make_pair(string("test"), string("test"))); - admin1->updateApplication(update); - appObs1->waitForUpdate(__FILE__, __LINE__); + admin1->updateApplication(std::move(update)); + appObs1->waitForUpdate(__LINE__); test(appObs1->applications.find("Application") != appObs1->applications.end()); test(appObs1->applications["Application"].descriptor.variables["test"] == "test"); test(++serial == appObs1->serial); @@ -1500,8 +1456,8 @@ allTests(Test::TestHelper* helper) app = appObs1->applications["Application"].descriptor; app.variables.clear(); app.variables["test1"] = "test"; - admin1->syncApplication(app); - appObs1->waitForUpdate(__FILE__, __LINE__); + admin1->syncApplication(std::move(app)); + appObs1->waitForUpdate(__LINE__); test(appObs1->applications.find("Application") != appObs1->applications.end()); test(appObs1->applications["Application"].descriptor.variables.size() == 1); test(appObs1->applications["Application"].descriptor.variables["test1"] == "test"); @@ -1516,7 +1472,7 @@ allTests(Test::TestHelper* helper) try { admin1->removeApplication("Application"); - appObs1->waitForUpdate(__FILE__, __LINE__); + appObs1->waitForUpdate(__LINE__); test(appObs1->applications.empty()); test(++serial == appObs1->serial); } @@ -1535,14 +1491,14 @@ allTests(Test::TestHelper* helper) { cout << "testing adapter observer... " << flush; - AdminSessionPrx session1 = AdminSessionPrx::uncheckedCast(registry->createAdminSession("admin1", "test1")); - AdminPrx admin1 = session1->getAdmin(); + auto session1 = Ice::uncheckedCast(registry->createAdminSession("admin1", "test1")); + auto admin1 = session1->getAdmin(); - session1->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::HeartbeatOnIdle); + session1->ice_getConnection()->setACM(registry->getACMTimeout(), Ice::nullopt, Ice::ACMHeartbeat::HeartbeatOnIdle); - Ice::ObjectAdapterPtr adpt1 = communicator->createObjectAdapter(""); - AdapterObserverIPtr adptObs1 = new AdapterObserverI("adptObs1"); - Ice::ObjectPrx adapter1 = adpt1->addWithUUID(adptObs1); + auto adpt1 = communicator->createObjectAdapter(""); + auto adptObs1 = make_shared("adptObs1"); + auto adapter1 = adpt1->addWithUUID(adptObs1); adpt1->activate(); registry->ice_getConnection()->setAdapter(adpt1); session1->setObserversByIdentity(Ice::Identity(), @@ -1551,57 +1507,57 @@ allTests(Test::TestHelper* helper) adapter1->ice_getIdentity(), Ice::Identity()); - adptObs1->waitForUpdate(__FILE__, __LINE__); // init + adptObs1->waitForUpdate(__LINE__); // init try { - Ice::ObjectPrx obj = communicator->stringToProxy("dummy:tcp -p 10000"); + auto obj = communicator->stringToProxy("dummy:tcp -p 10000"); - Ice::LocatorRegistryPrx locatorRegistry = communicator->getDefaultLocator()->getRegistry(); + auto locatorRegistry = communicator->getDefaultLocator()->getRegistry(); locatorRegistry->setAdapterDirectProxy("DummyAdapter", obj); - adptObs1->waitForUpdate(__FILE__, __LINE__); + adptObs1->waitForUpdate(__LINE__); test(adptObs1->adapters.find("DummyAdapter") != adptObs1->adapters.end()); - test(adptObs1->adapters["DummyAdapter"].proxy == obj); + test(Ice::targetEqualTo(adptObs1->adapters["DummyAdapter"].proxy, obj)); obj = communicator->stringToProxy("dummy:tcp -p 10000 -h localhost"); locatorRegistry->setAdapterDirectProxy("DummyAdapter", obj); - adptObs1->waitForUpdate(__FILE__, __LINE__); + adptObs1->waitForUpdate(__LINE__); test(adptObs1->adapters.find("DummyAdapter") != adptObs1->adapters.end()); - test(adptObs1->adapters["DummyAdapter"].proxy == obj); + test(Ice::targetEqualTo(adptObs1->adapters["DummyAdapter"].proxy, obj)); obj = communicator->stringToProxy("dummy:tcp -p 10000 -h localhost"); locatorRegistry->setReplicatedAdapterDirectProxy("DummyAdapter", "DummyReplicaGroup", obj); - adptObs1->waitForUpdate(__FILE__, __LINE__); + adptObs1->waitForUpdate(__LINE__); test(adptObs1->adapters.find("DummyAdapter") != adptObs1->adapters.end()); - test(adptObs1->adapters["DummyAdapter"].proxy == obj); + test(Ice::targetEqualTo(adptObs1->adapters["DummyAdapter"].proxy, obj)); test(adptObs1->adapters["DummyAdapter"].replicaGroupId == "DummyReplicaGroup"); obj = communicator->stringToProxy("dummy:tcp -p 10000 -h localhost"); locatorRegistry->setReplicatedAdapterDirectProxy("DummyAdapter1", "DummyReplicaGroup", obj); - adptObs1->waitForUpdate(__FILE__, __LINE__); + adptObs1->waitForUpdate(__LINE__); test(adptObs1->adapters.find("DummyAdapter1") != adptObs1->adapters.end()); - test(adptObs1->adapters["DummyAdapter1"].proxy == obj); + test(Ice::targetEqualTo(adptObs1->adapters["DummyAdapter1"].proxy, obj)); test(adptObs1->adapters["DummyAdapter1"].replicaGroupId == "DummyReplicaGroup"); obj = communicator->stringToProxy("dummy:tcp -p 10000 -h localhost"); locatorRegistry->setReplicatedAdapterDirectProxy("DummyAdapter2", "DummyReplicaGroup", obj); - adptObs1->waitForUpdate(__FILE__, __LINE__); + adptObs1->waitForUpdate(__LINE__); test(adptObs1->adapters.find("DummyAdapter2") != adptObs1->adapters.end()); - test(adptObs1->adapters["DummyAdapter2"].proxy == obj); + test(Ice::targetEqualTo(adptObs1->adapters["DummyAdapter2"].proxy, obj)); test(adptObs1->adapters["DummyAdapter2"].replicaGroupId == "DummyReplicaGroup"); admin->removeAdapter("DummyAdapter2"); - adptObs1->waitForUpdate(__FILE__, __LINE__); + adptObs1->waitForUpdate(__LINE__); test(adptObs1->adapters.find("DummyAdapter2") == adptObs1->adapters.end()); admin->removeAdapter("DummyReplicaGroup"); - adptObs1->waitForUpdate(__FILE__, __LINE__); - adptObs1->waitForUpdate(__FILE__, __LINE__); + adptObs1->waitForUpdate(__LINE__); + adptObs1->waitForUpdate(__LINE__); test(adptObs1->adapters["DummyAdapter"].replicaGroupId == ""); test(adptObs1->adapters["DummyAdapter1"].replicaGroupId == ""); locatorRegistry->setAdapterDirectProxy("DummyAdapter", 0); - adptObs1->waitForUpdate(__FILE__, __LINE__); + adptObs1->waitForUpdate(__LINE__); test(adptObs1->adapters.find("DummyAdapter") == adptObs1->adapters.end()); } catch(const Ice::UserException& ex) @@ -1619,14 +1575,14 @@ allTests(Test::TestHelper* helper) { cout << "testing object observer... " << flush; - AdminSessionPrx session1 = AdminSessionPrx::uncheckedCast(registry->createAdminSession("admin1", "test1")); - AdminPrx admin1 = session1->getAdmin(); + auto session1 = Ice::uncheckedCast(registry->createAdminSession("admin1", "test1")); + auto admin1 = session1->getAdmin(); - session1->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::HeartbeatOnIdle); + session1->ice_getConnection()->setACM(registry->getACMTimeout(), Ice::nullopt, Ice::ACMHeartbeat::HeartbeatOnIdle); - Ice::ObjectAdapterPtr adpt1 = communicator->createObjectAdapter(""); - ObjectObserverIPtr objectObs1 = new ObjectObserverI("objectObs1"); - Ice::ObjectPrx object1 = adpt1->addWithUUID(objectObs1); + auto adpt1 = communicator->createObjectAdapter(""); + auto objectObs1 = make_shared("objectObs1"); + auto object1 = adpt1->addWithUUID(objectObs1); adpt1->activate(); registry->ice_getConnection()->setAdapter(adpt1); session1->setObserversByIdentity(Ice::Identity(), @@ -1635,27 +1591,27 @@ allTests(Test::TestHelper* helper) Ice::Identity(), object1->ice_getIdentity()); - objectObs1->waitForUpdate(__FILE__, __LINE__); // init + objectObs1->waitForUpdate(__LINE__); // init try { - Ice::ObjectPrx obj = communicator->stringToProxy("dummy:tcp -p 10000"); + auto obj = communicator->stringToProxy("dummy:tcp -p 10000"); admin->addObjectWithType(obj, "::Dummy"); - objectObs1->waitForUpdate(__FILE__, __LINE__); + objectObs1->waitForUpdate(__LINE__); test(objectObs1->objects.find(Ice::stringToIdentity("dummy")) != objectObs1->objects.end()); test(objectObs1->objects[Ice::stringToIdentity("dummy")].type == "::Dummy"); - test(objectObs1->objects[Ice::stringToIdentity("dummy")].proxy == obj); + test(Ice::targetEqualTo(objectObs1->objects[Ice::stringToIdentity("dummy")].proxy, obj)); obj = communicator->stringToProxy("dummy:tcp -p 10000 -h localhost"); admin->updateObject(obj); - objectObs1->waitForUpdate(__FILE__, __LINE__); + objectObs1->waitForUpdate(__LINE__); test(objectObs1->objects.find(Ice::stringToIdentity("dummy")) != objectObs1->objects.end()); test(objectObs1->objects[Ice::stringToIdentity("dummy")].type == "::Dummy"); - test(objectObs1->objects[Ice::stringToIdentity("dummy")].proxy == obj); + test(Ice::targetEqualTo(objectObs1->objects[Ice::stringToIdentity("dummy")].proxy, obj)); admin->removeObject(obj->ice_getIdentity()); - objectObs1->waitForUpdate(__FILE__, __LINE__); + objectObs1->waitForUpdate(__LINE__); test(objectObs1->objects.find(Ice::stringToIdentity("dummy")) == objectObs1->objects.end()); } catch(const Ice::UserException& ex) @@ -1670,123 +1626,17 @@ allTests(Test::TestHelper* helper) cout << "ok" << endl; } - { -// cout << "???" << endl; - -// // -// // Setup a descriptor to deploy a node on the node. -// // -// ApplicationDescriptor nodeApp; -// nodeApp.name = "NodeApp"; -// ServerDescriptorPtr server = new ServerDescriptor(); -// server->id = "node-1"; -// server->exe = properties->getProperty("IceGridNodeExe"); -// server->options.push_back("--nowarn"); -// server->pwd = "."; -// addProperty(server, "IceGrid.Node.Name", "node-1"); -// addProperty(server, "IceGrid.Node.Data", properties->getProperty("TestDir") + "/db/node-1"); -// addProperty(server, "IceGrid.Node.Endpoints", "default"); -// NodeDescriptor node; -// node.servers.push_back(server); -// nodeApp.nodes["localnode"] = node; - -// try -// { -// int s = session1->startUpdate(); -// test(s == serial); -// admin1->addApplication(nodeApp); -// appObs1->waitForUpdate(__FILE__, __LINE__); // application added -// test(appObs1->applications.find("NodeApp") != appObs1->applications.end()); -// test(++serial == appObs1->serial); -// } -// catch(const DeploymentException& ex) -// { -// cerr << ex.reason << endl; -// test(false); -// } -// catch(const Ice::UserException& ex) -// { -// cerr << ex << endl; -// test(false); -// } - -// try -// { -// admin->startServer("node-1"); -// } -// catch(const NodeUnreachableException& ex) -// { -// cerr << ex << ":\n"; -// cerr << "node = " << ex.name << endl; -// cerr << "reason = " << ex.reason << endl; -// } -// appObs1->waitForUpdate(__FILE__, __LINE__); // object added (for node well-known proxy) -// test(++serial == appObs1->serial); - -// nodeObs1->waitForUpdate(__FILE__, __LINE__); // updateServer -// nodeObs1->waitForUpdate(__FILE__, __LINE__); // updateServer -// do -// { -// nodeObs1->waitForUpdate(__FILE__, __LINE__); // nodeUp -// } -// while(nodeObs1->nodes.find("node-1") == nodeObs1->nodes.end()); - -// try -// { -// admin->stopServer("node-1"); -// } -// catch(const NodeUnreachableException& ex) -// { -// cerr << ex << ":\n"; -// cerr << "node = " << ex.name << endl; -// cerr << "reason = " << ex.reason << endl; -// } -// appObs1->waitForUpdate(__FILE__, __LINE__); // object removed (for node well-known proxy) -// test(++serial == appObs1->serial); - -// nodeObs1->waitForUpdate(__FILE__, __LINE__); // updateServer -// nodeObs1->waitForUpdate(__FILE__, __LINE__); // updateServer -// nodeObs1->waitForUpdate(__FILE__, __LINE__); // nodeDown -// test(nodeObs1->nodes.find("node-1") == nodeObs1->nodes.end()); - -// try -// { -// admin1->removeApplication("NodeApp"); -// appObs1->waitForUpdate(__FILE__, __LINE__); // application removed -// test(appObs1->applications.empty()); -// test(++serial == appObs1->serial); -// } -// catch(const DeploymentException& ex) -// { -// cerr << ex.reason << endl; -// test(false); -// } -// catch(const Ice::UserException& ex) -// { -// cerr << ex << endl; -// test(false); -// } - -// nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate(Destroying) -// nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate(Destroyed) - -// session1->destroy(); -// adpt1->destroy(); - -// cout << "ok" << endl; - } - { cout << "testing node observer... " << flush; - AdminSessionPrx session1 = registry->createAdminSession("admin1", "test1"); + auto session1 = registry->createAdminSession("admin1", "test1"); - session1->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::HeartbeatOnIdle); + session1->ice_getConnection()->setACM(registry->getACMTimeout(), Ice::nullopt, Ice::ACMHeartbeat::HeartbeatOnIdle); - Ice::ObjectAdapterPtr adpt1 = communicator->createObjectAdapter(""); - ApplicationObserverIPtr appObs1 = new ApplicationObserverI("appObs1.3"); - Ice::ObjectPrx app1 = adpt1->addWithUUID(appObs1); - NodeObserverIPtr nodeObs1 = new NodeObserverI("nodeObs1"); - Ice::ObjectPrx no1 = adpt1->addWithUUID(nodeObs1); + auto adpt1 = communicator->createObjectAdapter(""); + auto appObs1 = make_shared("appObs1.3"); + auto app1 = adpt1->addWithUUID(appObs1); + auto nodeObs1 = make_shared("nodeObs1"); + auto no1 = adpt1->addWithUUID(nodeObs1); adpt1->activate(); registry->ice_getConnection()->setAdapter(adpt1); session1->setObserversByIdentity(Ice::Identity(), @@ -1795,67 +1645,68 @@ allTests(Test::TestHelper* helper) Ice::Identity(), Ice::Identity()); - appObs1->waitForUpdate(__FILE__, __LINE__); - nodeObs1->waitForUpdate(__FILE__, __LINE__); // init + appObs1->waitForUpdate(__LINE__); + nodeObs1->waitForUpdate(__LINE__); // init test(nodeObs1->nodes.find("localnode") != nodeObs1->nodes.end()); test(appObs1->applications.empty()); ApplicationDescriptor nodeApp; nodeApp.name = "NodeApp"; - ServerDescriptorPtr server = new ServerDescriptor(); + auto server = make_shared(); server->id = "node-1"; server->exe = properties->getProperty("IceGridNodeExe"); server->options.push_back("--nowarn"); server->pwd = "."; server->applicationDistrib = false; server->allocatable = false; - addProperty(server, "IceGrid.Node.Name", "node-1"); - addProperty(server, "IceGrid.Node.Data", properties->getProperty("TestDir") + "/db/node-1"); - addProperty(server, "IceGrid.Node.Endpoints", "default"); - addProperty(server, "Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + server->propertySet.properties.push_back(PropertyDescriptor{ "IceGrid.Node.Name", "node-1" }); + server->propertySet.properties.push_back( + PropertyDescriptor{ "IceGrid.Node.Data", properties->getProperty("TestDir") + "/db/node-1" }); + server->propertySet.properties.push_back(PropertyDescriptor{ "IceGrid.Node.Endpoints", "default" }); + server->propertySet.properties.push_back(PropertyDescriptor{ "Ice.Admin.Endpoints", "tcp -h 127.0.0.1" }); NodeDescriptor node; - node.servers.push_back(server); + node.servers.push_back(std::move(server)); nodeApp.nodes["localnode"] = node; session->startUpdate(); admin->addApplication(nodeApp); session->finishUpdate(); - appObs1->waitForUpdate(__FILE__, __LINE__); + appObs1->waitForUpdate(__LINE__); admin->startServer("node-1"); - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate + nodeObs1->waitForUpdate(__LINE__); // serverUpdate + nodeObs1->waitForUpdate(__LINE__); // serverUpdate do { - nodeObs1->waitForUpdate(__FILE__, __LINE__); // nodeUp + nodeObs1->waitForUpdate(__LINE__); // nodeUp } while(nodeObs1->nodes.find("node-1") == nodeObs1->nodes.end()); test(nodeObs1->nodes["localnode"].servers.size() == 1); - test(nodeObs1->nodes["localnode"].servers[0].state == Active); + test(nodeObs1->nodes["localnode"].servers[0].state == ServerState::Active); admin->stopServer("node-1"); - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate(Deactivating) - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate(Inactive) - nodeObs1->waitForUpdate(__FILE__, __LINE__); // nodeDown - test(nodeObs1->nodes["localnode"].servers[0].state == Inactive); + nodeObs1->waitForUpdate(__LINE__); // serverUpdate(Deactivating) + nodeObs1->waitForUpdate(__LINE__); // serverUpdate(Inactive) + nodeObs1->waitForUpdate(__LINE__); // nodeDown + test(nodeObs1->nodes["localnode"].servers[0].state == ServerState::Inactive); session->startUpdate(); admin->removeApplication("NodeApp"); session->finishUpdate(); - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate(Destroying) - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate(Destroyed) + nodeObs1->waitForUpdate(__LINE__); // serverUpdate(Destroying) + nodeObs1->waitForUpdate(__LINE__); // serverUpdate(Destroyed) - appObs1->waitForUpdate(__FILE__, __LINE__); + appObs1->waitForUpdate(__LINE__); test(nodeObs1->nodes.find("node-1") == nodeObs1->nodes.end()); ApplicationDescriptor testApp; testApp.name = "TestApp"; - server = new ServerDescriptor(); + server = make_shared(); server->id = "Server"; server->exe = properties->getProperty("ServerDir") + "/server"; server->pwd = properties->getProperty("TestDir"); @@ -1867,75 +1718,75 @@ allTests(Test::TestHelper* helper) adapter.id = "ServerAdapter"; adapter.registerProcess = false; adapter.serverLifetime = true; - server->adapters.push_back(adapter); - addProperty(server, "Server.Endpoints", "default"); - addProperty(server, "Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); + server->adapters.push_back(std::move(adapter)); + server->propertySet.properties.push_back(PropertyDescriptor{ "Server.Endpoints", "default" }); + server->propertySet.properties.push_back(PropertyDescriptor{ "Ice.Admin.Endpoints", "tcp -h 127.0.0.1" }); node = NodeDescriptor(); node.servers.push_back(server); testApp.nodes["localnode"] = node; session->startUpdate(); - admin->addApplication(testApp); + admin->addApplication(std::move(testApp)); session->finishUpdate(); - appObs1->waitForUpdate(__FILE__, __LINE__); + appObs1->waitForUpdate(__LINE__); session->startUpdate(); admin->startServer("Server"); session->finishUpdate(); - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate - nodeObs1->waitForUpdate(__FILE__, __LINE__); // adapterUpdate + nodeObs1->waitForUpdate(__LINE__); // serverUpdate + nodeObs1->waitForUpdate(__LINE__); // serverUpdate + nodeObs1->waitForUpdate(__LINE__); // adapterUpdate test(nodeObs1->nodes.find("localnode") != nodeObs1->nodes.end()); test(nodeObs1->nodes["localnode"].servers.size() == 1); - test(nodeObs1->nodes["localnode"].servers[0].state == Active); + test(nodeObs1->nodes["localnode"].servers[0].state == ServerState::Active); test(nodeObs1->nodes["localnode"].adapters.size() == 1); test(nodeObs1->nodes["localnode"].adapters[0].proxy); test(nodeObs1->nodes["localnode"].servers[0].enabled); admin->enableServer("Server", false); - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate + nodeObs1->waitForUpdate(__LINE__); // serverUpdate test(!nodeObs1->nodes["localnode"].servers[0].enabled); admin->enableServer("Server", true); - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate + nodeObs1->waitForUpdate(__LINE__); // serverUpdate test(nodeObs1->nodes["localnode"].servers[0].enabled); admin->stopServer("Server"); - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate - nodeObs1->waitForUpdate(__FILE__, __LINE__); // adapterUpdate + nodeObs1->waitForUpdate(__LINE__); // serverUpdate + nodeObs1->waitForUpdate(__LINE__); // serverUpdate + nodeObs1->waitForUpdate(__LINE__); // adapterUpdate test(nodeObs1->nodes.find("localnode") != nodeObs1->nodes.end()); test(nodeObs1->nodes["localnode"].servers.size() == 1); - test(nodeObs1->nodes["localnode"].servers[0].state == Inactive); + test(nodeObs1->nodes["localnode"].servers[0].state == ServerState::Inactive); test(nodeObs1->nodes["localnode"].adapters.empty()); session->startUpdate(); admin->removeApplication("TestApp"); session->finishUpdate(); - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate(Destroying) - nodeObs1->waitForUpdate(__FILE__, __LINE__); // serverUpdate(Destroyed) + nodeObs1->waitForUpdate(__LINE__); // serverUpdate(Destroying) + nodeObs1->waitForUpdate(__LINE__); // serverUpdate(Destroyed) test(nodeObs1->nodes["localnode"].servers.empty()); - appObs1->waitForUpdate(__FILE__, __LINE__); + appObs1->waitForUpdate(__LINE__); cout << "ok" << endl; } { cout << "testing registry observer... " << flush; - AdminSessionPrx session1 = registry->createAdminSession("admin1", "test1"); + auto session1 = registry->createAdminSession("admin1", "test1"); - session1->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::HeartbeatOnIdle); + session1->ice_getConnection()->setACM(registry->getACMTimeout(), Ice::nullopt, Ice::ACMHeartbeat::HeartbeatOnIdle); - Ice::ObjectAdapterPtr adpt1 = communicator->createObjectAdapter(""); - ApplicationObserverIPtr appObs1 = new ApplicationObserverI("appObs1.4"); - Ice::ObjectPrx app1 = adpt1->addWithUUID(appObs1); - RegistryObserverIPtr registryObs1 = new RegistryObserverI("registryObs1"); - Ice::ObjectPrx ro1 = adpt1->addWithUUID(registryObs1); + auto adpt1 = communicator->createObjectAdapter(""); + auto appObs1 = make_shared("appObs1.4"); + auto app1 = adpt1->addWithUUID(appObs1); + auto registryObs1 = make_shared("registryObs1"); + auto ro1 = adpt1->addWithUUID(registryObs1); adpt1->activate(); registry->ice_getConnection()->setAdapter(adpt1); session1->setObserversByIdentity(ro1->ice_getIdentity(), @@ -1944,20 +1795,20 @@ allTests(Test::TestHelper* helper) Ice::Identity(), Ice::Identity()); - appObs1->waitForUpdate(__FILE__, __LINE__); - registryObs1->waitForUpdate(__FILE__, __LINE__); // init + appObs1->waitForUpdate(__LINE__); + registryObs1->waitForUpdate(__LINE__); // init test(registryObs1->registries.find("Master") != registryObs1->registries.end()); test(appObs1->applications.empty()); - QueryPrx query = QueryPrx::uncheckedCast(communicator->stringToProxy("TestIceGrid/Query")); - Ice::ObjectProxySeq registries = query->findAllObjectsByType("::IceGrid::Registry"); + auto query = Ice::uncheckedCast(communicator->stringToProxy("TestIceGrid/Query")); + auto registries = query->findAllObjectsByType("::IceGrid::Registry"); const string prefix("Registry-"); - for(Ice::ObjectProxySeq::const_iterator p = registries.begin(); p != registries.end(); ++p) + for(const auto& p : registries) { - string name = (*p)->ice_getIdentity().name; + string name = p->ice_getIdentity().name; string::size_type pos = name.find(prefix); - if(pos != string::npos) + if (pos != string::npos) { name = name.substr(prefix.size()); test(registryObs1->registries.find(name) != registryObs1->registries.end()); @@ -1968,17 +1819,17 @@ allTests(Test::TestHelper* helper) { cout << "testing observer with direct proxy... " << flush; - AdminSessionPrx session1 = registry->createAdminSession("admin1", "test1"); + auto session1 = registry->createAdminSession("admin1", "test1"); - session1->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::HeartbeatOnIdle); + session1->ice_getConnection()->setACM(registry->getACMTimeout(), Ice::nullopt, Ice::ACMHeartbeat::HeartbeatOnIdle); - Ice::ObjectAdapterPtr adpt1 = communicator->createObjectAdapterWithEndpoints("", "tcp"); - NodeObserverIPtr nodeObs1 = new NodeObserverI("nodeObs1"); - Ice::ObjectPrx no1 = adpt1->addWithUUID(nodeObs1); + auto adpt1 = communicator->createObjectAdapterWithEndpoints("", "default"); + auto nodeObs1 = make_shared("nodeObs1"); + auto no1 = adpt1->addWithUUID(nodeObs1); adpt1->activate(); - session1->setObservers(0, NodeObserverPrx::uncheckedCast(no1), 0, 0, 0); - nodeObs1->waitForUpdate(__FILE__, __LINE__); // init + session1->setObservers(0, Ice::uncheckedCast(no1), 0, 0, 0); + nodeObs1->waitForUpdate(__LINE__); // init session1->destroy(); adpt1->destroy(); @@ -1988,18 +1839,19 @@ allTests(Test::TestHelper* helper) { cout << "testing observer with indirect proxy... " << flush; - AdminSessionPrx session1 = registry->createAdminSession("admin1", "test1"); - communicator->getProperties()->setProperty("IndirectAdpt1.Endpoints", "tcp"); + auto session1 = registry->createAdminSession("admin1", "test1"); + communicator->getProperties()->setProperty("IndirectAdpt1.Endpoints", "default"); communicator->getProperties()->setProperty("IndirectAdpt1.AdapterId", "adapter1"); - Ice::ObjectAdapterPtr adpt1 = communicator->createObjectAdapter("IndirectAdpt1"); + auto adpt1 = communicator->createObjectAdapter("IndirectAdpt1"); test(communicator->getDefaultLocator()); - NodeObserverIPtr nodeObs1 = new NodeObserverI("nodeObs1"); - Ice::ObjectPrx no1 = adpt1->addWithUUID(nodeObs1); + auto nodeObs1 = make_shared("nodeObs1"); + + auto no1 = adpt1->addWithUUID(nodeObs1); assert(no1->ice_getAdapterId() == "adapter1"); adpt1->activate(); - session1->setObservers(0, NodeObserverPrx::uncheckedCast(no1), 0, 0, 0); - nodeObs1->waitForUpdate(__FILE__, __LINE__); // init + session1->setObservers(0, Ice::uncheckedCast(no1), 0, 0, 0); + nodeObs1->waitForUpdate(__LINE__); // init session1->destroy(); adpt1->destroy(); diff --git a/cpp/test/IceGrid/session/Client.cpp b/cpp/test/IceGrid/session/Client.cpp index 882ba448080..88ac4d24d59 100644 --- a/cpp/test/IceGrid/session/Client.cpp +++ b/cpp/test/IceGrid/session/Client.cpp @@ -7,20 +7,20 @@ using namespace std; -class Client : public Test::TestHelper +class Client final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Client::run(int argc, char** argv) { - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); properties->parseCommandLineOptions("", Ice::argsToStringSeq(argc, argv)); properties->setProperty("Ice.Warn.Connections", "0"); - Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); + Ice::CommunicatorHolder communicatorHolder = initialize(argc, argv, properties); void allTests(Test::TestHelper*); allTests(this); } diff --git a/cpp/test/IceGrid/session/PermissionsVerifier.cpp b/cpp/test/IceGrid/session/PermissionsVerifier.cpp index de0951e9287..8cd13583259 100644 --- a/cpp/test/IceGrid/session/PermissionsVerifier.cpp +++ b/cpp/test/IceGrid/session/PermissionsVerifier.cpp @@ -10,12 +10,12 @@ using namespace std; -class AdminPermissionsVerifierI : public Glacier2::PermissionsVerifier +class AdminPermissionsVerifierI final : public Glacier2::PermissionsVerifier { public: - virtual bool - checkPermissions(const string& userId, const string& passwd, string&, const Ice::Current& c) const + bool + checkPermissions(string userId, string passwd, string&, const Ice::Current& c) const override { if(c.ctx.find("throw") != c.ctx.end()) { @@ -27,24 +27,24 @@ class AdminPermissionsVerifierI : public Glacier2::PermissionsVerifier } }; -class PermissionsVerifierServer : public Test::TestHelper +class PermissionsVerifierServer final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void PermissionsVerifierServer::run(int argc, char** argv) { shutdownOnInterrupt(); - Ice::PropertiesPtr properties = createTestProperties(argc, argv); + auto properties = createTestProperties(argc, argv); properties->parseCommandLineOptions("", Ice::argsToStringSeq(argc, argv)); - Ice::CommunicatorHolder communicator = initialize(argc, argv, properties); - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("PermissionsVerifier"); - adapter->add(new AdminPermissionsVerifierI, Ice::stringToIdentity("AdminPermissionsVerifier")); + Ice::CommunicatorHolder communicatorHolder = initialize(argc, argv, properties); + auto adapter = communicatorHolder->createObjectAdapter("PermissionsVerifier"); + adapter->add(make_shared(), Ice::stringToIdentity("AdminPermissionsVerifier")); adapter->activate(); - communicator->waitForShutdown(); + communicatorHolder->waitForShutdown(); } DEFINE_TEST(PermissionsVerifierServer) diff --git a/cpp/test/IceGrid/session/Server.cpp b/cpp/test/IceGrid/session/Server.cpp index c154ef61e11..62ebd18e695 100644 --- a/cpp/test/IceGrid/session/Server.cpp +++ b/cpp/test/IceGrid/session/Server.cpp @@ -10,12 +10,13 @@ using namespace std; -class ClientPermissionsVerifierI : public Glacier2::PermissionsVerifier +class ClientPermissionsVerifierI final : public Glacier2::PermissionsVerifier { public: - virtual bool - checkPermissions(const string& userId, const string& passwd, string&, const Ice::Current& current) const + + bool + checkPermissions(string userId, string passwd, string&, const Ice::Current& current) const override { if(current.ctx.find("throw") != current.ctx.end()) { @@ -25,19 +26,19 @@ class ClientPermissionsVerifierI : public Glacier2::PermissionsVerifier } }; -class SSLPermissionsVerifierI : public Glacier2::SSLPermissionsVerifier +class SSLPermissionsVerifierI final : public Glacier2::SSLPermissionsVerifier { public: - virtual bool - authorize(const Glacier2::SSLInfo& info, string&, const Ice::Current& current) const + bool + authorize(Glacier2::SSLInfo info, string&, const Ice::Current& current) const override { if(current.ctx.find("throw") != current.ctx.end()) { throw Test::ExtendedPermissionDeniedException("reason"); } test(info.certs.size() > 0); - IceSSL::CertificatePtr cert = IceSSL::Certificate::decode(info.certs[0]); + auto cert = IceSSL::Certificate::decode(info.certs[0]); test(cert->getIssuerDN() == IceSSL::DistinguishedName( "emailAddress=info@zeroc.com,C=US,ST=Florida,L=Jupiter,O=ZeroC\\, Inc.,OU=Ice,CN=Ice Tests CA")); test(cert->getSubjectDN() == IceSSL::DistinguishedName( @@ -48,22 +49,22 @@ class SSLPermissionsVerifierI : public Glacier2::SSLPermissionsVerifier } }; -class Server : public Test::TestHelper +class Server final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Server::run(int argc, char** argv) { - Ice::CommunicatorHolder communicator = initialize(argc, argv); - Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("Server"); - if(communicator->getProperties()->getPropertyAsInt("AddPermissionsVerifiers") > 0) + Ice::CommunicatorHolder communicatorHolder = initialize(argc, argv); + auto adapter = communicatorHolder->createObjectAdapter("Server"); + if(communicatorHolder->getProperties()->getPropertyAsInt("AddPermissionsVerifiers") > 0) { - adapter->add(new ClientPermissionsVerifierI(), Ice::stringToIdentity("ClientPermissionsVerifier")); - adapter->add(new SSLPermissionsVerifierI(), Ice::stringToIdentity("SSLPermissionsVerifier")); + adapter->add(make_shared(), Ice::stringToIdentity("ClientPermissionsVerifier")); + adapter->add(make_shared(), Ice::stringToIdentity("SSLPermissionsVerifier")); } adapter->activate(); @@ -74,7 +75,7 @@ Server::run(int argc, char** argv) catch(const Ice::ObjectAdapterDeactivatedException&) { } - communicator->waitForShutdown(); + communicatorHolder->waitForShutdown(); } DEFINE_TEST(Server) diff --git a/cpp/test/IceGrid/simple/AllTests.cpp b/cpp/test/IceGrid/simple/AllTests.cpp index 8ac52b2b58a..d720f881ac6 100644 --- a/cpp/test/IceGrid/simple/AllTests.cpp +++ b/cpp/test/IceGrid/simple/AllTests.cpp @@ -36,11 +36,9 @@ allTests(Test::TestHelper* helper) cout << "ok" << endl; cout << "testing locator finder... " << flush; - Ice::Identity finderId; - finderId.category = "Ice"; - finderId.name = "LocatorFinder"; - Ice::LocatorFinderPrxPtr finder = ICE_CHECKED_CAST(Ice::LocatorFinderPrx, - communicator->getDefaultLocator()->ice_identity(finderId)); + + auto finder = Ice::checkedCast( + communicator->getDefaultLocator()->ice_identity(Ice::Identity{ "LocatorFinder", "Ice" })); test(finder->getLocator()); cout << "ok" << endl; diff --git a/cpp/test/IceGrid/simple/Client.cpp b/cpp/test/IceGrid/simple/Client.cpp index e7000c958db..07bc54a1556 100644 --- a/cpp/test/IceGrid/simple/Client.cpp +++ b/cpp/test/IceGrid/simple/Client.cpp @@ -23,8 +23,7 @@ Client::run(int argc, char** argv) #ifdef ICE_STATIC_LIBS Ice::registerIceLocatorDiscovery(false); #endif - Ice::CommunicatorHolder communicator = initialize(argc, argv); - + Ice::CommunicatorHolder communicatorHolder = initialize(argc, argv); bool withDeploy = false; for(int i = 1; i < argc; ++i) diff --git a/cpp/test/IceGrid/update/AllTests.cpp b/cpp/test/IceGrid/update/AllTests.cpp index 9b4b5ce1eea..15c3f5fb8a2 100644 --- a/cpp/test/IceGrid/update/AllTests.cpp +++ b/cpp/test/IceGrid/update/AllTests.cpp @@ -61,16 +61,16 @@ void allTests(Test::TestHelper* helper) { const Ice::CommunicatorPtr& communicator = helper->communicator(); - IceGrid::RegistryPrx registry = IceGrid::RegistryPrx::checkedCast( + shared_ptr registry = Ice::checkedCast( communicator->stringToProxy(communicator->getDefaultLocator()->ice_getIdentity().category + "/Registry")); test(registry); - AdminSessionPrx session = registry->createAdminSession("foo", "bar"); + shared_ptr session = registry->createAdminSession("foo", "bar"); session->ice_getConnection()->setACM(registry->getACMTimeout(), IceUtil::None, Ice::ICE_ENUM(ACMHeartbeat, HeartbeatAlways)); - AdminPrx admin = session->getAdmin(); + shared_ptr admin = session->getAdmin(); test(admin); Ice::PropertiesPtr properties = communicator->getProperties(); @@ -90,7 +90,7 @@ allTests(Test::TestHelper* helper) cout << "testing server add... " << flush; - ServerDescriptorPtr server = new ServerDescriptor(); + auto server = make_shared(); server->id = "Server"; server->exe = properties->getProperty("ServerDir") + "/server"; server->pwd = "."; @@ -156,8 +156,8 @@ allTests(Test::TestHelper* helper) TemplateDescriptor templ; templ.parameters.push_back("name"); - templ.descriptor = new ServerDescriptor(); - server = ServerDescriptorPtr::dynamicCast(templ.descriptor); + templ.descriptor = make_shared(); + server = dynamic_pointer_cast(templ.descriptor); server->id = "${name}"; server->exe = "${test.dir}/server"; server->pwd = "."; @@ -537,7 +537,7 @@ allTests(Test::TestHelper* helper) cout << "testing icebox server add... " << flush; - ServiceDescriptorPtr service = new ServiceDescriptor(); + auto service = make_shared(); service->name = "Service1"; service->entry = "TestService:create"; AdapterDescriptor adapter; @@ -548,7 +548,7 @@ allTests(Test::TestHelper* helper) addProperty(service, "${service}.Endpoints", "default"); service->adapters.push_back(adapter); - IceBoxDescriptorPtr server = new IceBoxDescriptor(); + auto server = make_shared(); server->id = "IceBox"; server->exe = properties->getProperty("IceBoxExe"); @@ -556,11 +556,11 @@ allTests(Test::TestHelper* helper) server->allocatable = false; addProperty(server, "Ice.Admin.Endpoints", "tcp -h 127.0.0.1"); server->services.resize(3); - server->services[0].descriptor = ServiceDescriptorPtr::dynamicCast(service->ice_clone()); + server->services[0].descriptor = dynamic_pointer_cast(service->ice_clone()); service->name = "Service2"; - server->services[1].descriptor = ServiceDescriptorPtr::dynamicCast(service->ice_clone()); + server->services[1].descriptor = dynamic_pointer_cast(service->ice_clone()); service->name = "Service3"; - server->services[2].descriptor = ServiceDescriptorPtr::dynamicCast(service->ice_clone()); + server->services[2].descriptor = dynamic_pointer_cast(service->ice_clone()); update.nodes[0].servers.push_back(server); try @@ -714,7 +714,7 @@ allTests(Test::TestHelper* helper) { cout << "testing variable update... " << flush; - ServerDescriptorPtr server = new ServerDescriptor(); + auto server = make_shared(); server->id = "${name}"; server->exe = "server"; server->pwd = "."; @@ -875,7 +875,7 @@ allTests(Test::TestHelper* helper) { cout << "testing property set update... " << flush; - ServiceDescriptorPtr service = new ServiceDescriptor(); + auto service = make_shared(); service->name = "${name}"; service->entry = "dummy"; addProperty(service, "ServiceProp", "test"); @@ -889,7 +889,7 @@ allTests(Test::TestHelper* helper) serviceInstance.parameterValues["name"] = "Service"; serviceInstance.propertySet.properties.push_back(createProperty("ServiceInstanceProp", "test")); - IceBoxDescriptorPtr server = new IceBoxDescriptor(); + auto server = make_shared(); server->id = "${name}"; server->exe = "server"; server->pwd = "."; @@ -946,7 +946,7 @@ allTests(Test::TestHelper* helper) test(hasProperty(info.descriptor, "ApplicationProp", "test")); test(hasProperty(info.descriptor, "ServerInstanceProp", "test")); - ServiceDescriptorPtr svc = IceBoxDescriptorPtr::dynamicCast(info.descriptor)->services[0].descriptor; + ServiceDescriptorPtr svc = dynamic_pointer_cast(info.descriptor)->services[0].descriptor; test(hasProperty(svc, "ServiceProp", "test")); ApplicationUpdateDescriptor empty; @@ -960,7 +960,7 @@ allTests(Test::TestHelper* helper) update.serviceTemplates["ServiceTemplate"] = svcTempl; admin->updateApplication(update); info = admin->getServerInfo("Server"); - svc = IceBoxDescriptorPtr::dynamicCast(info.descriptor)->services[0].descriptor; + svc = dynamic_pointer_cast(info.descriptor)->services[0].descriptor; test(hasProperty(svc, "ServiceProp", "updated")); update = empty; @@ -972,7 +972,7 @@ allTests(Test::TestHelper* helper) update.serverTemplates["ServerTemplate"] = templ; admin->updateApplication(update); info = admin->getServerInfo("Server"); - svc = IceBoxDescriptorPtr::dynamicCast(info.descriptor)->services[0].descriptor; + svc = dynamic_pointer_cast(info.descriptor)->services[0].descriptor; test(hasProperty(svc, "ServiceInstanceProp", "updated")); update = empty; @@ -1058,7 +1058,7 @@ allTests(Test::TestHelper* helper) testApp = admin->getApplicationInfo("TestApp").descriptor; test(testApp.description == "Description"); - update.description = new BoxedString("updatedDescription"); + update.description = make_shared("updatedDescription"); try { admin->updateApplication(update); @@ -1071,7 +1071,7 @@ allTests(Test::TestHelper* helper) testApp = admin->getApplicationInfo("TestApp").descriptor; test(testApp.description == "updatedDescription"); - update.description = new BoxedString(""); + update.description = make_shared(""); try { admin->updateApplication(update); @@ -1095,7 +1095,7 @@ allTests(Test::TestHelper* helper) ApplicationDescriptor nodeApp; nodeApp.name = "NodeApp"; - ServerDescriptorPtr server = new ServerDescriptor(); + auto server = make_shared(); server->id = "node-${index}"; server->exe = properties->getProperty("IceGridNodeExe"); server->pwd = "."; @@ -1158,7 +1158,7 @@ allTests(Test::TestHelper* helper) ApplicationDescriptor testApp; testApp.name = "TestApp"; - server = new ServerDescriptor(); + server = make_shared(); server->id = "Server"; server->exe = properties->getProperty("ServerDir") + "/server"; server->pwd = "."; @@ -1187,7 +1187,7 @@ allTests(Test::TestHelper* helper) try { admin->startServer("Server"); - test(admin->getServerState("Server") == Active); + test(admin->getServerState("Server") == ServerState::Active); } catch(const ServerStartException& ex) { @@ -1225,10 +1225,12 @@ allTests(Test::TestHelper* helper) { try { - test(admin->getServerInfo("Server").node == "node-2" && admin->getServerState("Server") == Inactive); + test( + admin->getServerInfo("Server").node == "node-2" && + admin->getServerState("Server") == ServerState::Inactive); admin->startServer("Server"); - test(admin->getServerState("Server") == Active); + test(admin->getServerState("Server") == ServerState::Active); break; } catch(const DeploymentException&) diff --git a/cpp/test/IceGrid/update/Server.cpp b/cpp/test/IceGrid/update/Server.cpp index 6cb98a3566b..b99b4af76b3 100644 --- a/cpp/test/IceGrid/update/Server.cpp +++ b/cpp/test/IceGrid/update/Server.cpp @@ -23,7 +23,7 @@ Server::run(int argc, char** argv) string name = properties->getProperty("Ice.ProgramName"); Ice::ObjectAdapterPtr adapter = communicator->createObjectAdapter("Server"); - Ice::ObjectPtr object = new TestI(properties); + auto object = make_shared(properties); adapter->add(object, Ice::stringToIdentity(name)); try diff --git a/cpp/test/IceGrid/update/TestI.cpp b/cpp/test/IceGrid/update/TestI.cpp index f91a7ac44b2..ecd4c4224fb 100644 --- a/cpp/test/IceGrid/update/TestI.cpp +++ b/cpp/test/IceGrid/update/TestI.cpp @@ -17,7 +17,7 @@ TestI::shutdown(const Ice::Current& current) } std::string -TestI::getProperty(const std::string& name, const Ice::Current&) +TestI::getProperty(std::string name, const Ice::Current&) { return _properties->getProperty(name); } diff --git a/cpp/test/IceGrid/update/TestI.h b/cpp/test/IceGrid/update/TestI.h index 1fcf402f93d..44096e406ff 100644 --- a/cpp/test/IceGrid/update/TestI.h +++ b/cpp/test/IceGrid/update/TestI.h @@ -14,7 +14,7 @@ class TestI : public ::Test::TestIntf TestI(const Ice::PropertiesPtr&); virtual void shutdown(const Ice::Current&); - virtual std::string getProperty(const std::string&, const Ice::Current&); + virtual std::string getProperty(std::string, const Ice::Current&); private: diff --git a/cpp/test/IceStorm/federation/Publisher.cpp b/cpp/test/IceStorm/federation/Publisher.cpp index a08a327b0e5..6bdfbebf08c 100644 --- a/cpp/test/IceStorm/federation/Publisher.cpp +++ b/cpp/test/IceStorm/federation/Publisher.cpp @@ -12,7 +12,7 @@ using namespace Ice; using namespace IceStorm; using namespace Test; -class Publisher : public Test::TestHelper +class Publisher final : public Test::TestHelper { public: @@ -23,8 +23,8 @@ void Publisher::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); - PropertiesPtr properties = communicator->getProperties(); - const string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); + auto properties = communicator->getProperties(); + auto managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { ostringstream os; @@ -32,8 +32,8 @@ Publisher::run(int argc, char** argv) throw runtime_error(os.str()); } - ObjectPrx base = communicator->stringToProxy(managerProxy); - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); + auto base = communicator->stringToProxy(managerProxy); + auto manager = checkedCast(base); if(!manager) { ostringstream os; @@ -41,13 +41,13 @@ Publisher::run(int argc, char** argv) throw runtime_error(os.str()); } - TopicPrx fed1 = manager->retrieve("fed1"); - TopicPrx fed2 = manager->retrieve("fed2"); - TopicPrx fed3 = manager->retrieve("fed3"); + auto fed1 = manager->retrieve("fed1"); + auto fed2 = manager->retrieve("fed2"); + auto fed3 = manager->retrieve("fed3"); - EventPrx eventFed1 = EventPrx::uncheckedCast(fed1->getPublisher()->ice_oneway()); - EventPrx eventFed2 = EventPrx::uncheckedCast(fed2->getPublisher()->ice_oneway()); - EventPrx eventFed3 = EventPrx::uncheckedCast(fed3->getPublisher()->ice_oneway()); + auto eventFed1 = uncheckedCast(fed1->getPublisher()->ice_oneway()); + auto eventFed2 = uncheckedCast(fed2->getPublisher()->ice_oneway()); + auto eventFed3 = uncheckedCast(fed3->getPublisher()->ice_oneway()); Ice::Context context; @@ -91,9 +91,9 @@ Publisher::run(int argc, char** argv) // Before we exit, we ping all proxies as twoway, to make sure // that all oneways are delivered. // - EventPrx::uncheckedCast(eventFed1->ice_twoway())->ice_ping(); - EventPrx::uncheckedCast(eventFed2->ice_twoway())->ice_ping(); - EventPrx::uncheckedCast(eventFed3->ice_twoway())->ice_ping(); + eventFed1->ice_twoway()->ice_ping(); + eventFed2->ice_twoway()->ice_ping(); + eventFed3->ice_twoway()->ice_ping(); } DEFINE_TEST(Publisher) diff --git a/cpp/test/IceStorm/federation/Subscriber.cpp b/cpp/test/IceStorm/federation/Subscriber.cpp index fabd871da38..21b866dd631 100644 --- a/cpp/test/IceStorm/federation/Subscriber.cpp +++ b/cpp/test/IceStorm/federation/Subscriber.cpp @@ -5,8 +5,6 @@ #include #include #include -#include -#include #include using namespace std; @@ -14,55 +12,25 @@ using namespace Ice; using namespace IceStorm; using namespace Test; -class EventI : public Event +class EventI final : public Event { public: - virtual void - pub(const string&, const Ice::Current& current) + void + pub(string, const Ice::Current& current) override { - IceUtilInternal::MutexPtrLock sync(_countMutex); - if(++_count == 30 + 40 + 30) { current.adapter->getCommunicator()->shutdown(); } } - static IceUtil::Mutex* _countMutex; - private: - static int _count; -}; - -typedef IceUtil::Handle EventIPtr; - -int EventI::_count = 0; -IceUtil::Mutex* EventI::_countMutex = 0; - -namespace -{ - -class Init -{ -public: - - Init() - { - EventI::_countMutex = new IceUtil::Mutex; - } - - ~Init() - { - delete EventI::_countMutex; - EventI::_countMutex = 0; - } + static atomic_int _count; }; -Init init; - -} +atomic_int EventI::_count = 0; void usage(const char* appName) @@ -74,11 +42,11 @@ usage(const char* appName) "-b Use batch reliability.\n"; } -class Subscriber : public Test::TestHelper +class Subscriber final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -114,15 +82,15 @@ Subscriber::run(int argc, char** argv) } } - PropertiesPtr properties = communicator->getProperties(); - string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); + auto properties = communicator->getProperties(); + auto managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { throw runtime_error("property `IceStormAdmin.TopicManager.Default' is not set"); } - ObjectPrx base = communicator->stringToProxy(managerProxy); - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); + auto base = communicator->stringToProxy(managerProxy); + auto manager = checkedCast(base); if(!manager) { ostringstream os; @@ -130,13 +98,13 @@ Subscriber::run(int argc, char** argv) throw runtime_error(os.str()); } - ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SubscriberAdapter", "default"); + auto adapter = communicator->createObjectAdapterWithEndpoints("SubscriberAdapter", "default"); // // Activate the servants. // - ObjectPrx objFed1 = adapter->addWithUUID(new EventI()); - ObjectPrx objFed2 = adapter->addWithUUID(new EventI()); - ObjectPrx objFed3 = adapter->addWithUUID(new EventI()); + auto objFed1 = adapter->addWithUUID(make_shared()); + auto objFed2 = adapter->addWithUUID(make_shared()); + auto objFed3 = adapter->addWithUUID(make_shared()); IceStorm::QoS qos; if(batch) @@ -152,9 +120,9 @@ Subscriber::run(int argc, char** argv) objFed3 = objFed1->ice_oneway(); } - TopicPrx fed1 = manager->retrieve("fed1"); - TopicPrx fed2 = manager->retrieve("fed2"); - TopicPrx fed3 = manager->retrieve("fed3"); + auto fed1 = manager->retrieve("fed1"); + auto fed2 = manager->retrieve("fed2"); + auto fed3 = manager->retrieve("fed3"); fed1->subscribeAndGetPublisher(qos, objFed1); fed2->subscribeAndGetPublisher(qos, objFed2); diff --git a/cpp/test/IceStorm/federation2/Publisher.cpp b/cpp/test/IceStorm/federation2/Publisher.cpp index 8b2b853286e..564ee5400be 100644 --- a/cpp/test/IceStorm/federation2/Publisher.cpp +++ b/cpp/test/IceStorm/federation2/Publisher.cpp @@ -2,23 +2,23 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include #include #include #include #include #include +#include using namespace std; using namespace Ice; using namespace IceStorm; using namespace Test; -class Publisher : public Test::TestHelper +class Publisher final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -29,22 +29,22 @@ Publisher::run(int argc, char** argv) opts.addOpt("", "count", IceUtilInternal::Options::NeedArg); opts.parse(argc, (const char**)argv); - PropertiesPtr properties = communicator->getProperties(); - string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); + auto properties = communicator->getProperties(); + auto managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { throw runtime_error("property `IceStormAdmin.TopicManager.Default' is not set"); } - ObjectPrx base = communicator->stringToProxy(managerProxy); - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); + auto base = communicator->stringToProxy(managerProxy); + auto manager = checkedCast(base); if(!manager) { throw runtime_error("`" + managerProxy + "' is not running"); } - TopicPrx fed1 = manager->retrieve("fed1"); - EventPrx eventFed1 = EventPrx::uncheckedCast(fed1->getPublisher()->ice_oneway()); + auto fed1 = manager->retrieve("fed1"); + auto eventFed1 = uncheckedCast(fed1->getPublisher()->ice_oneway()); string arg = opts.optArg("count"); int count = 1; @@ -63,14 +63,14 @@ Publisher::run(int argc, char** argv) // Before we exit, we ping all proxies as twoway, to make sure // that all oneways are delivered. // - EventPrx::uncheckedCast(eventFed1->ice_twoway())->ice_ping(); + eventFed1->ice_twoway()->ice_ping(); if(count == 0) { break; } --count; - IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(1)); + this_thread::sleep_for(1s); } } diff --git a/cpp/test/IceStorm/federation2/Subscriber.cpp b/cpp/test/IceStorm/federation2/Subscriber.cpp index 510c3e61e13..9e50e410459 100644 --- a/cpp/test/IceStorm/federation2/Subscriber.cpp +++ b/cpp/test/IceStorm/federation2/Subscriber.cpp @@ -5,8 +5,6 @@ #include #include #include -#include -#include #include #include @@ -23,14 +21,14 @@ using namespace Ice; using namespace IceStorm; using namespace Test; -class EventI : public Event +class EventI final : public Event { public: - virtual void - pub(const string&, const Ice::Current& current) + void + pub(string, const Ice::Current& current) override { - IceUtilInternal::MutexPtrLock sync(_countMutex); + lock_guard lg(countMutex); if(++_count == 10) { @@ -38,40 +36,15 @@ class EventI : public Event } } - static IceUtil::Mutex* _countMutex; + static mutex countMutex; private: static int _count; }; -typedef IceUtil::Handle EventIPtr; - int EventI::_count = 0; -IceUtil::Mutex* EventI::_countMutex = 0; - -namespace -{ - -class Init -{ -public: - - Init() - { - EventI::_countMutex = new IceUtil::Mutex; - } - - ~Init() - { - delete EventI::_countMutex; - EventI::_countMutex = 0; - } -}; - -Init init; - -} +mutex EventI::countMutex; void usage(const char* appName) @@ -84,11 +57,11 @@ usage(const char* appName) ; } -class Subscriber : public Test::TestHelper +class Subscriber final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -124,8 +97,8 @@ Subscriber::run(int argc, char** argv) } } - PropertiesPtr properties = communicator->getProperties(); - const string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); + auto properties = communicator->getProperties(); + auto managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { ostringstream os; @@ -133,8 +106,8 @@ Subscriber::run(int argc, char** argv) throw invalid_argument(os.str()); } - ObjectPrx base = communicator->stringToProxy(managerProxy); - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); + auto base = communicator->stringToProxy(managerProxy); + auto manager = checkedCast(base); if(!manager) { ostringstream os; @@ -142,12 +115,12 @@ Subscriber::run(int argc, char** argv) throw invalid_argument(os.str()); } - ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SubscriberAdapter", "default"); + auto adapter = communicator->createObjectAdapterWithEndpoints("SubscriberAdapter", "default"); // // Activate the servants. // - ObjectPrx obj = adapter->addWithUUID(new EventI()); + auto obj = adapter->addWithUUID(make_shared()); IceStorm::QoS qos; if(batch) @@ -159,7 +132,7 @@ Subscriber::run(int argc, char** argv) obj = obj->ice_oneway(); } - TopicPrx fed1 = manager->retrieve("fed1"); + auto fed1 = manager->retrieve("fed1"); fed1->subscribeAndGetPublisher(qos, obj); diff --git a/cpp/test/IceStorm/persistent/Client.cpp b/cpp/test/IceStorm/persistent/Client.cpp index 4f86d352c64..94b7090e21b 100644 --- a/cpp/test/IceStorm/persistent/Client.cpp +++ b/cpp/test/IceStorm/persistent/Client.cpp @@ -11,19 +11,19 @@ using namespace Ice; using namespace IceStorm; using namespace Test; -class Client : public Test::TestHelper +class Client final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Client::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); - PropertiesPtr properties = communicator->getProperties(); - string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); + auto properties = communicator->getProperties(); + auto managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { ostringstream os; @@ -31,8 +31,8 @@ Client::run(int argc, char** argv) throw invalid_argument(os.str()); } - IceStorm::TopicManagerPrx manager = - IceStorm::TopicManagerPrx::checkedCast(communicator->stringToProxy(managerProxy)); + auto manager = + checkedCast(communicator->stringToProxy(managerProxy)); if(!manager) { ostringstream os; @@ -52,12 +52,12 @@ Client::run(int argc, char** argv) // Create topics // cerr << "creating topics and links..." << flush; - TopicPrx linkTo = 0; + shared_ptr linkTo; for(int i = 0; i < 10; ++i) { ostringstream topicName; topicName << "topic" << i; - TopicPrx topic = manager->create(topicName.str()); + auto topic = manager->create(topicName.str()); if(linkTo) { topic->link(linkTo, i + 1); @@ -74,7 +74,7 @@ Client::run(int argc, char** argv) { ostringstream topicName; topicName << "topic" << i; - TopicPrx topic = manager->retrieve(topicName.str()); + auto topic = manager->retrieve(topicName.str()); test(topic); ostringstream subscriber; diff --git a/cpp/test/IceStorm/rep1/Publisher.cpp b/cpp/test/IceStorm/rep1/Publisher.cpp index 479d0806f2c..e7200e25c47 100644 --- a/cpp/test/IceStorm/rep1/Publisher.cpp +++ b/cpp/test/IceStorm/rep1/Publisher.cpp @@ -4,7 +4,6 @@ #include #include -#include #include #include #include @@ -14,11 +13,11 @@ using namespace Ice; using namespace IceStorm; using namespace Test; -class Publisher : public Test::TestHelper +class Publisher final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -39,8 +38,8 @@ Publisher::run(int argc, char** argv) throw invalid_argument(os.str()); } - PropertiesPtr properties = communicator->getProperties(); - string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); + auto properties = communicator->getProperties(); + auto managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { ostringstream os; @@ -48,7 +47,7 @@ Publisher::run(int argc, char** argv) throw invalid_argument(os.str()); } - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast( + auto manager = checkedCast( communicator->stringToProxy(managerProxy)); if(!manager) { @@ -57,7 +56,7 @@ Publisher::run(int argc, char** argv) throw invalid_argument(os.str()); } - TopicPrx topic; + shared_ptr topic; while(true) { try @@ -86,16 +85,16 @@ Publisher::run(int argc, char** argv) // if(opts.isSet("cycle")) { - Ice::ObjectPrx prx = topic->getPublisher()->ice_twoway(); - vector single; - Ice::EndpointSeq endpoints = prx->ice_getEndpoints(); - for(Ice::EndpointSeq::const_iterator p = endpoints.begin(); p != endpoints.end(); ++p) + auto prx = uncheckedCast(topic->getPublisher()->ice_twoway()); + vector> single; + auto endpoints = prx->ice_getEndpoints(); + for(const auto& p: endpoints) { - if((*p)->toString().substr(0, 3) != "udp") + if(p->toString().substr(0, 3) != "udp") { Ice::EndpointSeq e; - e.push_back(*p); - single.push_back(SinglePrx::uncheckedCast(prx->ice_endpoints(e))); + e.push_back(p); + single.push_back(prx->ice_endpoints(e)); } } if(single.size() <= 1) @@ -107,13 +106,13 @@ Publisher::run(int argc, char** argv) size_t which = 0; for(size_t i = 0; i < 1000; ++i) { - single[which]->event(static_cast(i)); + single[which]->event(static_cast(i)); which = (which + 1) % single.size(); } } else { - SinglePrx single = SinglePrx::uncheckedCast(topic->getPublisher()->ice_twoway()); + auto single = uncheckedCast(topic->getPublisher()->ice_twoway()); for(int i = 0; i < 1000; ++i) { single->event(i); diff --git a/cpp/test/IceStorm/rep1/Sub.cpp b/cpp/test/IceStorm/rep1/Sub.cpp index f7a62cd15e8..115b8c89009 100644 --- a/cpp/test/IceStorm/rep1/Sub.cpp +++ b/cpp/test/IceStorm/rep1/Sub.cpp @@ -2,7 +2,6 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include #include #include #include @@ -14,19 +13,20 @@ using namespace Ice; using namespace IceStorm; using namespace Test; -class SingleI : public Single +class SingleI final : public Single { public: - SingleI() {} - virtual void event(int, const Current&) {} + void event(int, const Current&) override + { + } }; -class Sub : public Test::TestHelper +class Sub final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -48,8 +48,8 @@ Sub::run(int argc, char** argv) throw invalid_argument(os.str()); } - PropertiesPtr properties = communicator->getProperties(); - string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); + auto properties = communicator->getProperties(); + auto managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { ostringstream os; @@ -57,8 +57,8 @@ Sub::run(int argc, char** argv) throw invalid_argument(os.str()); } - ObjectPrx base = communicator->stringToProxy(managerProxy); - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); + auto base = communicator->stringToProxy(managerProxy); + auto manager = checkedCast(base); if(!manager) { ostringstream os; @@ -66,11 +66,11 @@ Sub::run(int argc, char** argv) throw invalid_argument(os.str()); } - ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default"); + auto adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default"); - TopicPrx topic = manager->retrieve("single"); + auto topic = manager->retrieve("single"); - Ice::ObjectPrx prx = adapter->add(new SingleI(), stringToIdentity(opts.optArg("id"))); + auto prx = adapter->add(make_shared(), stringToIdentity(opts.optArg("id"))); if(opts.isSet("unsub")) { topic->unsubscribe(prx); diff --git a/cpp/test/IceStorm/rep1/Subscriber.cpp b/cpp/test/IceStorm/rep1/Subscriber.cpp index 9f567c24b95..57167dd4f50 100644 --- a/cpp/test/IceStorm/rep1/Subscriber.cpp +++ b/cpp/test/IceStorm/rep1/Subscriber.cpp @@ -2,7 +2,6 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include #include #include #include @@ -14,11 +13,11 @@ using namespace Ice; using namespace IceStorm; using namespace Test; -class SingleI : public Single, public IceUtil::Monitor +class SingleI final : public Single { public: - SingleI(const CommunicatorPtr& communicator, const string& name, int max) : + SingleI(const shared_ptr& communicator, const string& name, int max) : _communicator(communicator), _name(name), _max(max), @@ -27,30 +26,29 @@ class SingleI : public Single, public IceUtil::Monitor { } - virtual void - event(int i, const Current&) + void + event(int i, const Current&) override { if(_name == "twoway ordered" && i != _last) { cerr << endl << "received unordered event for `" << _name << "': " << i << " " << _last; test(false); } - Lock sync(*this); + lock_guard lg(_mutex); ++_last; if(++_count == _max) { - notify(); + _condVar.notify_one(); } } - virtual void + void waitForEvents() { - Lock sync(*this); - IceUtil::Time timeout = IceUtil::Time::seconds(40); + unique_lock lock(_mutex); while(_count < _max) { - if(!timedWait(timeout)) + if(_condVar.wait_for(lock, 40s) == cv_status::timeout) { test(false); } @@ -59,19 +57,20 @@ class SingleI : public Single, public IceUtil::Monitor private: - CommunicatorPtr _communicator; + shared_ptr _communicator; const string _name; const int _max; int _count; int _last; + mutex _mutex; + condition_variable _condVar; }; -typedef IceUtil::Handle SingleIPtr; -class Subscriber : public Test::TestHelper +class Subscriber final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -94,8 +93,8 @@ Subscriber::run(int argc, char** argv) throw invalid_argument(os.str()); } - PropertiesPtr properties = communicator->getProperties(); - string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); + auto properties = communicator->getProperties(); + auto managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { ostringstream os; @@ -103,8 +102,8 @@ Subscriber::run(int argc, char** argv) throw invalid_argument(os.str()); } - ObjectPrx base = communicator->stringToProxy(managerProxy); - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); + auto base = communicator->stringToProxy(managerProxy); + auto manager = checkedCast(base); if(!manager) { ostringstream os; @@ -112,9 +111,9 @@ Subscriber::run(int argc, char** argv) throw invalid_argument(os.str()); } - ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default"); + auto adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default"); - TopicPrx topic; + shared_ptr topic; while(true) { try @@ -144,19 +143,19 @@ Subscriber::run(int argc, char** argv) // // Create subscribers with different QoS. // - SingleIPtr sub; + shared_ptr sub; IceStorm::QoS qos; if(opts.isSet("ordered")) { - sub = new SingleI(communicator.communicator(), "twoway ordered", events); + sub = make_shared(communicator.communicator(), "twoway ordered", events); qos["reliability"] = "ordered"; } else { - sub = new SingleI(communicator.communicator(), "twoway", events); + sub = make_shared(communicator.communicator(), "twoway", events); } - Ice::ObjectPrx prx = adapter->addWithUUID(sub); + auto prx = adapter->addWithUUID(sub); while(true) { diff --git a/cpp/test/IceStorm/repgrid/Client.cpp b/cpp/test/IceStorm/repgrid/Client.cpp index 12d1c751138..004945ab745 100644 --- a/cpp/test/IceStorm/repgrid/Client.cpp +++ b/cpp/test/IceStorm/repgrid/Client.cpp @@ -12,33 +12,27 @@ using namespace Ice; using namespace IceStorm; using namespace Test; -class SingleI : public Single, public IceUtil::Monitor +class SingleI final : public Single { public: - SingleI() : - _count(0) + void + event(int, const Current&) override { - } - - virtual void - event(int, const Current&) - { - Lock sync(*this); + lock_guard lg(_mutex); if(++_count == 1000) { - notify(); + _condVar.notify_one(); } } - virtual void + void waitForEvents() { - Lock sync(*this); - IceUtil::Time timeout = IceUtil::Time::seconds(20); + unique_lock lock(_mutex); while(_count < 1000) { - if(!timedWait(timeout)) + if(_condVar.wait_for(lock, 20s) == cv_status::timeout) { test(false); } @@ -47,23 +41,24 @@ class SingleI : public Single, public IceUtil::Monitor private: - int _count; + int _count = 0; + mutex _mutex; + condition_variable _condVar; }; -typedef IceUtil::Handle SingleIPtr; -class Client : public Test::TestHelper +class Client final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Client::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); - ObjectPrx base = communicator->stringToProxy("Test.IceStorm/TopicManager"); - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); + auto base = communicator->stringToProxy("Test.IceStorm/TopicManager"); + auto manager = checkedCast(base); if(!manager) { ostringstream os; @@ -71,22 +66,22 @@ Client::run(int argc, char** argv) throw invalid_argument(os.str()); } - ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default:udp"); + auto adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default:udp"); - TopicPrx topic = manager->create("single"); + auto topic = manager->create("single"); // // Create subscribers with different QoS. // - SingleIPtr sub = new SingleI; + auto sub = make_shared(); topic->subscribeAndGetPublisher(IceStorm::QoS(), adapter->addWithUUID(sub)); adapter->activate(); // Ensure that getPublisher & getNonReplicatedPublisher work // correctly. - Ice::ObjectPrx p1 = topic->getPublisher(); - Ice::ObjectPrx p2 = topic->getNonReplicatedPublisher(); + auto p1 = topic->getPublisher(); + auto p2 = topic->getNonReplicatedPublisher(); test(p1->ice_getAdapterId() == "PublishReplicaGroup"); test(p2->ice_getAdapterId() == "Test.IceStorm1.Publish" || p2->ice_getAdapterId() == "Test.IceStorm2.Publish" || @@ -96,7 +91,7 @@ Client::run(int argc, char** argv) // Get a publisher object, create a twoway proxy and then cast to // a Single object. // - SinglePrx single = SinglePrx::uncheckedCast(topic->getPublisher()->ice_twoway()); + auto single = uncheckedCast(topic->getPublisher()->ice_twoway()); for(int i = 0; i < 1000; ++i) { single->event(i); diff --git a/cpp/test/IceStorm/repstress/Control.cpp b/cpp/test/IceStorm/repstress/Control.cpp index 1f63f5bf4dc..c8da41bf746 100644 --- a/cpp/test/IceStorm/repstress/Control.cpp +++ b/cpp/test/IceStorm/repstress/Control.cpp @@ -10,11 +10,11 @@ using namespace std; using namespace Ice; using namespace Test; -class Control : public Test::TestHelper +class Control final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -28,7 +28,7 @@ Control::run(int argc, char** argv) throw invalid_argument(os.str()); } - ControllerPrx control = ControllerPrx::uncheckedCast(communicator->stringToProxy(argv[1])); + auto control = uncheckedCast(communicator->stringToProxy(argv[1])); control->stop(); } diff --git a/cpp/test/IceStorm/repstress/Publisher.cpp b/cpp/test/IceStorm/repstress/Publisher.cpp index 65fda890f83..7ebd4cf3821 100644 --- a/cpp/test/IceStorm/repstress/Publisher.cpp +++ b/cpp/test/IceStorm/repstress/Publisher.cpp @@ -3,44 +3,44 @@ // #include -#include #include #include #include #include +#include using namespace std; using namespace Ice; using namespace IceStorm; using namespace Test; -class ControllerI : public Controller +class ControllerI final : public Controller { public: - virtual void stop(const Ice::Current& c) + void stop(const Ice::Current& c) override { c.adapter->getCommunicator()->shutdown(); } }; -class PublishThread : public IceUtil::Thread, public IceUtil::Mutex +class PublishThread final { public: - PublishThread(const SinglePrx& single) : - _single(single), + explicit PublishThread(shared_ptr single) : + _single(std::move(single)), _published(0), _destroy(false) { } - virtual void run() + void run() { while(true) { { - Lock sync(*this); + lock_guard log(_mutex); if(_destroy) { cout << _published << endl; @@ -50,7 +50,7 @@ class PublishThread : public IceUtil::Thread, public IceUtil::Mutex try { _single->event(_published); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(1)); + this_thread::sleep_for(1ms); } catch(const Ice::UnknownException&) { @@ -64,31 +64,30 @@ class PublishThread : public IceUtil::Thread, public IceUtil::Mutex void destroy() { - Lock sync(*this); + lock_guard log(_mutex); _destroy = true; } private: - const SinglePrx _single; + const shared_ptr _single; int _published; bool _destroy; + mutex _mutex; }; -typedef IceUtil::Handle PublishThreadPtr; -class Publisher : public Test::TestHelper +class Publisher final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Publisher::run(int argc, char** argv) { - Ice::CommunicatorHolder communicator = initialize(argc, argv); - PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { @@ -97,7 +96,7 @@ Publisher::run(int argc, char** argv) throw invalid_argument(os.str()); } - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast( + auto manager = checkedCast( communicator->stringToProxy(managerProxy)); if(!manager) { @@ -106,27 +105,26 @@ Publisher::run(int argc, char** argv) throw invalid_argument(os.str()); } - TopicPrx topic = manager->retrieve("single"); + auto topic = manager->retrieve("single"); assert(topic); // // Get a publisher object, create a twoway proxy, disable // connection caching and then cast to a Single object. // - SinglePrx single = SinglePrx::uncheckedCast(topic->getPublisher()->ice_twoway()->ice_connectionCached(false)); - - ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("ControllerAdapter", "tcp"); - Ice::ObjectPrx controller = adapter->addWithUUID(new ControllerI); + auto single = uncheckedCast(topic->getPublisher()->ice_twoway()->ice_connectionCached(false)); + auto adapter = communicator->createObjectAdapterWithEndpoints("ControllerAdapter", "tcp"); + auto controller = adapter->addWithUUID(make_shared()); adapter->activate(); cout << communicator->proxyToString(controller) << endl; - PublishThreadPtr t = new PublishThread(single); - t->start(); + PublishThread pt(std::move(single)); + auto fut = std::async(launch::async, [&pt]{ pt.run(); }); communicator->waitForShutdown(); - t->destroy(); - t->getThreadControl().join(); + pt.destroy(); + fut.get(); } DEFINE_TEST(Publisher) diff --git a/cpp/test/IceStorm/repstress/Subscriber.cpp b/cpp/test/IceStorm/repstress/Subscriber.cpp index 10f2a028014..957893c880d 100644 --- a/cpp/test/IceStorm/repstress/Subscriber.cpp +++ b/cpp/test/IceStorm/repstress/Subscriber.cpp @@ -2,7 +2,6 @@ // Copyright (c) ZeroC, Inc. All rights reserved. // -#include #include #include #include @@ -14,57 +13,49 @@ using namespace Ice; using namespace IceStorm; using namespace Test; -class ControllerI : public Controller +class ControllerI final : public Controller { public: - virtual void stop(const Ice::Current& c) + void stop(const Ice::Current& c) override { c.adapter->getCommunicator()->shutdown(); } }; -class SingleI : public Single, public IceUtil::Monitor +class SingleI final : public Single { public: - SingleI() : - _nevents(0) + void + event(int, const Current&) override { - } - - virtual void - event(int, const Current&) - { - Lock sync(*this); ++_nevents; } int nevents() const { - Lock sync(*this); return _nevents; } private: - int _nevents; + atomic_int _nevents = 0; }; -typedef IceUtil::Handle SingleIPtr; -class Subscriber : public Test::TestHelper +class Subscriber final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Subscriber::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); - PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { @@ -73,8 +64,8 @@ Subscriber::run(int argc, char** argv) throw invalid_argument(os.str()); } - ObjectPrx base = communicator->stringToProxy(managerProxy); - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); + auto base = communicator->stringToProxy(managerProxy); + auto manager = checkedCast(base); if(!manager) { ostringstream os; @@ -82,12 +73,12 @@ Subscriber::run(int argc, char** argv) throw invalid_argument(os.str()); } - ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default"); - TopicPrx topic = manager->retrieve("single"); + auto adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default"); + auto topic = manager->retrieve("single"); - SingleIPtr sub = new SingleI(); - Ice::ObjectPrx prx = adapter->addWithUUID(sub); - Ice::ObjectPrx control = adapter->addWithUUID(new ControllerI); + auto sub = make_shared(); + auto prx = adapter->addWithUUID(sub); + auto control = adapter->addWithUUID(make_shared()); IceStorm::QoS qos; diff --git a/cpp/test/IceStorm/single/Publisher.cpp b/cpp/test/IceStorm/single/Publisher.cpp index abe715961b2..9ff0d1c8b33 100644 --- a/cpp/test/IceStorm/single/Publisher.cpp +++ b/cpp/test/IceStorm/single/Publisher.cpp @@ -12,18 +12,18 @@ using namespace Ice; using namespace IceStorm; using namespace Test; -class Publisher : public Test::TestHelper +class Publisher final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Publisher::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); - PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { @@ -32,7 +32,7 @@ Publisher::run(int argc, char** argv) throw invalid_argument(os.str()); } - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast( + auto manager = checkedCast( communicator->stringToProxy(managerProxy)); if(!manager) { @@ -41,14 +41,14 @@ Publisher::run(int argc, char** argv) throw invalid_argument(os.str()); } - TopicPrx topic = manager->retrieve("single"); + auto topic = manager->retrieve("single"); assert(topic); // // Get a publisher object, create a twoway proxy and then cast to // a Single object. // - SinglePrx single = SinglePrx::uncheckedCast(topic->getPublisher()->ice_twoway()); + auto single = uncheckedCast(topic->getPublisher()->ice_twoway()); for(int i = 0; i < 1000; ++i) { single->event(i); diff --git a/cpp/test/IceStorm/single/Subscriber.cpp b/cpp/test/IceStorm/single/Subscriber.cpp index edf4ccc0b61..9e71d9070a0 100644 --- a/cpp/test/IceStorm/single/Subscriber.cpp +++ b/cpp/test/IceStorm/single/Subscriber.cpp @@ -12,7 +12,7 @@ using namespace Ice; using namespace IceStorm; using namespace Test; -class SingleI : public Single, public IceUtil::Monitor +class SingleI final : public Single { public: @@ -23,8 +23,8 @@ class SingleI : public Single, public IceUtil::Monitor { } - virtual void - event(int i, const Current& current) + void + event(int i, const Current& current) override { if((_name == "default" || _name == "oneway" || _name == "batch" || _name == "datagram" || _name == "batch datagram") && current.requestId != 0) @@ -46,7 +46,7 @@ class SingleI : public Single, public IceUtil::Monitor cerr << endl << "expected datagram to be received over udp"; test(false); } - Lock sync(*this); + lock_guard lg(_mutex); if(_name == "per-request load balancing") { _connections.insert(current.con); @@ -54,19 +54,19 @@ class SingleI : public Single, public IceUtil::Monitor ++_last; if(++_count == 1000) { - notify(); + _condVar.notify_one(); } } - virtual void + void waitForEvents() { - Lock sync(*this); + unique_lock lock(_mutex); cout << "testing " << _name << " ... " << flush; bool datagram = _name == "datagram" || _name == "batch datagram"; while(_count < 1000) { - if(!timedWait(IceUtil::Time::seconds(30))) + if(_condVar.wait_for(lock, 30s) == cv_status::timeout) { if(datagram && _count > 0) { @@ -98,22 +98,23 @@ class SingleI : public Single, public IceUtil::Monitor const string _name; int _count; int _last; - set _connections; + set> _connections; + mutex _mutex; + condition_variable _condVar; }; -typedef IceUtil::Handle SingleIPtr; -class Subscriber : public Test::TestHelper +class Subscriber final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void Subscriber::run(int argc, char** argv) { Ice::CommunicatorHolder communicator = initialize(argc, argv); - PropertiesPtr properties = communicator->getProperties(); + auto properties = communicator->getProperties(); string managerProxy = properties->getProperty("IceStormAdmin.TopicManager.Default"); if(managerProxy.empty()) { @@ -122,8 +123,8 @@ Subscriber::run(int argc, char** argv) throw invalid_argument(os.str()); } - ObjectPrx base = communicator->stringToProxy(managerProxy); - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast(base); + auto base = communicator->stringToProxy(managerProxy); + auto manager = checkedCast(base); if(!manager) { ostringstream os; @@ -132,7 +133,7 @@ Subscriber::run(int argc, char** argv) } // Use 2 default endpoints to test per-request load balancing - ObjectAdapterPtr adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default:default:udp"); + auto adapter = communicator->createObjectAdapterWithEndpoints("SingleAdapter", "default:default:udp"); // // Test topic name that is too long @@ -149,7 +150,7 @@ Subscriber::run(int argc, char** argv) } } - TopicPrx topic = manager->retrieve("single"); + auto topic = manager->retrieve("single"); // // Test subscriber identity that is too long @@ -158,7 +159,7 @@ Subscriber::run(int argc, char** argv) { try { - Ice::ObjectPrx object = communicator->stringToProxy(string(512, 'A') + ":default -p 10000"); + auto object = communicator->stringToProxy(string(512, 'A') + ":default -p 10000"); topic->subscribeAndGetPublisher(IceStorm::QoS(), object); test(false); } @@ -170,48 +171,48 @@ Subscriber::run(int argc, char** argv) // // Create subscribers with different QoS. // - vector subscribers; + vector> subscribers; vector subscriberIdentities; { - subscribers.push_back(new SingleI("default")); - Ice::ObjectPrx object = adapter->addWithUUID(subscribers.back())->ice_oneway(); + subscribers.push_back(make_shared("default")); + auto object = adapter->addWithUUID(subscribers.back())->ice_oneway(); subscriberIdentities.push_back(object->ice_getIdentity()); topic->subscribeAndGetPublisher(IceStorm::QoS(), object); } { - subscribers.push_back(new SingleI("oneway")); - Ice::ObjectPrx object = adapter->addWithUUID(subscribers.back())->ice_oneway(); + subscribers.push_back(make_shared("oneway")); + auto object = adapter->addWithUUID(subscribers.back())->ice_oneway(); subscriberIdentities.push_back(object->ice_getIdentity()); topic->subscribeAndGetPublisher(IceStorm::QoS(), object); } { - subscribers.push_back(new SingleI("twoway")); - Ice::ObjectPrx object = adapter->addWithUUID(subscribers.back()); + subscribers.push_back(make_shared("twoway")); + auto object = adapter->addWithUUID(subscribers.back()); subscriberIdentities.push_back(object->ice_getIdentity()); topic->subscribeAndGetPublisher(IceStorm::QoS(), object); } { - subscribers.push_back(new SingleI("batch")); - Ice::ObjectPrx object = adapter->addWithUUID(subscribers.back())->ice_batchOneway(); + subscribers.push_back(make_shared("batch")); + auto object = adapter->addWithUUID(subscribers.back())->ice_batchOneway(); subscriberIdentities.push_back(object->ice_getIdentity()); topic->subscribeAndGetPublisher(IceStorm::QoS(), object); } { - subscribers.push_back(new SingleI("twoway ordered")); // Ordered + subscribers.push_back(make_shared("twoway ordered")); // Ordered IceStorm::QoS qos; qos["reliability"] = "ordered"; - Ice::ObjectPrx object = adapter->addWithUUID(subscribers.back()); + auto object = adapter->addWithUUID(subscribers.back()); subscriberIdentities.push_back(object->ice_getIdentity()); topic->subscribeAndGetPublisher(qos, object); } { - subscribers.push_back(new SingleI("per-request load balancing")); + subscribers.push_back(make_shared("per-request load balancing")); IceStorm::QoS qos; qos["locatorCacheTimeout"] = "10"; qos["connectionCached"] = "0"; - Ice::ObjectPrx object = adapter->addWithUUID(subscribers.back()); + auto object = adapter->addWithUUID(subscribers.back()); subscriberIdentities.push_back(object->ice_getIdentity()); topic->subscribeAndGetPublisher(qos, object); } @@ -220,9 +221,9 @@ Subscriber::run(int argc, char** argv) // (otherwise, if multiple UDP subscribers use the same connection we might get high // packet loss, see bug 1784). communicator->getProperties()->setProperty("UdpAdapter3.ThreadPool.Size", "1"); - ObjectAdapterPtr adpt = communicator->createObjectAdapterWithEndpoints("UdpAdapter3", "udp"); - subscribers.push_back(new SingleI("datagram")); - Ice::ObjectPrx object = adpt->addWithUUID(subscribers.back())->ice_datagram(); + auto adpt = communicator->createObjectAdapterWithEndpoints("UdpAdapter3", "udp"); + subscribers.push_back(make_shared("datagram")); + auto object = adpt->addWithUUID(subscribers.back())->ice_datagram(); subscriberIdentities.push_back(object->ice_getIdentity()); adpt->activate(); topic->subscribeAndGetPublisher(IceStorm::QoS(), object); @@ -232,9 +233,9 @@ Subscriber::run(int argc, char** argv) // (otherwise, if multiple UDP subscribers use the same connection we might get high // packet loss, see bug 1784). communicator->getProperties()->setProperty("UdpAdapter4.ThreadPool.Size", "1"); - ObjectAdapterPtr adpt = communicator->createObjectAdapterWithEndpoints("UdpAdapter4", "udp"); - subscribers.push_back(new SingleI("batch datagram")); - Ice::ObjectPrx object = adpt->addWithUUID(subscribers.back())->ice_batchDatagram(); + auto adpt = communicator->createObjectAdapterWithEndpoints("UdpAdapter4", "udp"); + subscribers.push_back(make_shared("batch datagram")); + auto object = adpt->addWithUUID(subscribers.back())->ice_batchDatagram(); subscriberIdentities.push_back(object->ice_getIdentity()); adpt->activate(); topic->subscribeAndGetPublisher(IceStorm::QoS(), object); @@ -244,14 +245,14 @@ Subscriber::run(int argc, char** argv) vector ids = topic->getSubscribers(); test(ids.size() == subscriberIdentities.size()); - for(vector::const_iterator i = ids.begin(); i != ids.end(); ++i) + for(const auto& p: ids) { - test(find(subscriberIdentities.begin(), subscriberIdentities.end(), *i) != subscriberIdentities.end()); + test(find(subscriberIdentities.begin(), subscriberIdentities.end(), p) != subscriberIdentities.end()); } - for(vector::const_iterator p = subscribers.begin(); p != subscribers.end(); ++p) + for(const auto& p: subscribers) { - (*p)->waitForEvents(); + p->waitForEvents(); } } diff --git a/cpp/test/IceStorm/stress/Publisher.cpp b/cpp/test/IceStorm/stress/Publisher.cpp index 221d4c74d73..9dac738bd6c 100644 --- a/cpp/test/IceStorm/stress/Publisher.cpp +++ b/cpp/test/IceStorm/stress/Publisher.cpp @@ -7,17 +7,18 @@ #include #include #include +#include using namespace std; using namespace Ice; using namespace IceStorm; using namespace Test; -class Publisher : public Test::TestHelper +class Publisher final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -56,8 +57,8 @@ Publisher::run(int argc, char** argv) bool oneway = opts.isSet("oneway"); bool maxQueueTest = opts.isSet("maxQueueTest"); - PropertiesPtr properties = communicator->getProperties(); - const char* managerProxyProperty = "IceStormAdmin.TopicManager.Default"; + auto properties = communicator->getProperties(); + string managerProxyProperty = "IceStormAdmin.TopicManager.Default"; string managerProxy = properties->getProperty(managerProxyProperty); if(managerProxy.empty()) { @@ -66,7 +67,7 @@ Publisher::run(int argc, char** argv) throw invalid_argument(os.str()); } - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast( + auto manager = checkedCast( communicator->stringToProxy(managerProxy)); if(!manager) { @@ -75,13 +76,13 @@ Publisher::run(int argc, char** argv) throw invalid_argument(os.str()); } - TopicPrx topic = manager->retrieve("fed1"); + auto topic = manager->retrieve("fed1"); - EventPrx twowayProxy = EventPrx::uncheckedCast(topic->getPublisher()->ice_twoway()); - EventPrx proxy; + auto twowayProxy = uncheckedCast(topic->getPublisher()->ice_twoway()); + shared_ptr proxy; if(oneway) { - proxy = EventPrx::uncheckedCast(twowayProxy->ice_oneway()); + proxy = twowayProxy->ice_oneway(); } else { @@ -93,7 +94,7 @@ Publisher::run(int argc, char** argv) if(maxQueueTest && i == 10) { // Sleep one seconds to give some time to IceStorm to connect to the subscriber - IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(1)); + this_thread::sleep_for(1s); } proxy->pub(i); } diff --git a/cpp/test/IceStorm/stress/Subscriber.cpp b/cpp/test/IceStorm/stress/Subscriber.cpp index 77d5dd9e029..58c4dd2315b 100644 --- a/cpp/test/IceStorm/stress/Subscriber.cpp +++ b/cpp/test/IceStorm/stress/Subscriber.cpp @@ -5,33 +5,30 @@ #include #include #include -#include -#include -#include #include -#include -#include #include +#include +#include using namespace std; using namespace Ice; using namespace IceStorm; using namespace Test; -struct Subscription; // Forward declaration. +struct Subscription; -class EventI : public Event, public IceUtil::Mutex +class EventI : public Event { public: - EventI(const CommunicatorPtr& communicator, int total) : - _communicator(communicator), _total(total), _count(0) + EventI(shared_ptr communicator, int total) : + _communicator(std::move(communicator)), _total(total), _count(0) { } - int count() const + int count() { - Lock sync(*this); + lock_guard lg(_mutex); return _count; } @@ -41,41 +38,36 @@ class EventI : public Event, public IceUtil::Mutex protected: - const CommunicatorPtr _communicator; + shared_ptr _communicator; const int _total; int _count; + mutex _mutex; }; -typedef IceUtil::Handle EventIPtr; -struct Subscription +struct Subscription final { - Subscription() : activate(true) - { - } - - Ice::ObjectAdapterPtr adapter; - Ice::ObjectPrx obj; - EventIPtr servant; + shared_ptr adapter; + shared_ptr obj; + shared_ptr servant; IceStorm::QoS qos; - Ice::ObjectPrx publisher; - bool activate; + shared_ptr publisher; + bool activate = true; }; -class OrderEventI : public EventI +class OrderEventI final : public EventI { public: - OrderEventI(const CommunicatorPtr& communicator, int total) : - EventI(communicator, total) + OrderEventI(shared_ptr communicator, int total) : + EventI(std::move(communicator), total) { } - virtual void - pub(int counter, const Ice::Current&) + void + pub(int counter, const Ice::Current&) override { - Lock sync(*this); - - if(counter != _count || counter == _total-1) + lock_guard lg(_mutex); + if(counter != _count || counter == _total - 1) { if(counter != _count) { @@ -87,20 +79,19 @@ class OrderEventI : public EventI } }; -class CountEventI : public EventI +class CountEventI final : public EventI { public: - CountEventI(const CommunicatorPtr& communicator, int total) : - EventI(communicator, total) + CountEventI(shared_ptr communicator, int total) : + EventI(std::move(communicator), total) { } - virtual void - pub(int, const Ice::Current&) + void + pub(int, const Ice::Current&) override { - Lock sync(*this); - + lock_guard lg(_mutex); if(++_count == _total) { _communicator->shutdown(); @@ -108,20 +99,19 @@ class CountEventI : public EventI } }; -class SlowEventI : public EventI +class SlowEventI final : public EventI { public: - SlowEventI(const CommunicatorPtr& communicator, int total) : - EventI(communicator, total) + SlowEventI(shared_ptr communicator, int total) : + EventI(std::move(communicator), total) { } - virtual void - pub(int, const Ice::Current&) + void + pub(int, const Ice::Current&) override { - Lock sync(*this); - + lock_guard lg(_mutex); // // Ignore events over and above the expected. // @@ -130,7 +120,7 @@ class SlowEventI : public EventI return; } // Sleep for 3 seconds - IceUtil::ThreadControl::sleep(IceUtil::Time::seconds(3)); + this_thread::sleep_for(3s); if(++_count == _total) { _communicator->shutdown(); @@ -138,35 +128,32 @@ class SlowEventI : public EventI } }; -class ErraticEventI : public EventI +class ErraticEventI final : public EventI { public: - ErraticEventI(const CommunicatorPtr& communicator, int total) : - EventI(communicator, total), _done(false) + ErraticEventI(shared_ptr communicator, int total) : + EventI(std::move(communicator), total) { - IceUtilInternal::MutexPtrLock sync(_remainingMutex); ++_remaining; } - virtual void - pub(int, const Ice::Current& current) + void + pub(int, const Ice::Current& current) override { - Lock sync(*this); + lock_guard lg(_mutex); // Randomly close the connection. - if(!_done && (IceUtilInternal::random(10) == 1 || ++_count == _total)) + if(!_done && (_rd() % 10 == 1 || ++_count == _total)) { _done = true; - current.con->close(ICE_SCOPED_ENUM(ConnectionClose, Forcefully)); + current.con->close(ConnectionClose::Forcefully); // Deactivate the OA. This ensures that the subscribers // that have subscribed with oneway QoS will be booted. current.adapter->deactivate(); _count = _total; { - IceUtilInternal::MutexPtrLock sync2(_remainingMutex); - --_remaining; - if(_remaining == 0) + if(--_remaining == 0) { _communicator->shutdown(); } @@ -174,30 +161,28 @@ class ErraticEventI : public EventI } } - static IceUtil::Mutex* _remainingMutex; - private: - static int _remaining; - bool _done; + static atomic_int _remaining; + bool _done = false; + random_device _rd; }; -IceUtil::Mutex* ErraticEventI::_remainingMutex = 0; -int ErraticEventI::_remaining = 0; +atomic_int ErraticEventI::_remaining = 0; -class MaxQueueEventI : public EventI +class MaxQueueEventI final : public EventI { public: - MaxQueueEventI(const CommunicatorPtr& communicator, int expected, int total, bool removeSubscriber) : - EventI(communicator, total), _removeSubscriber(removeSubscriber), _expected(expected) + MaxQueueEventI(shared_ptr communicator, int expected, int total, bool removeSubscriber) : + EventI(std::move(communicator), total), _removeSubscriber(removeSubscriber), _expected(expected) { } - virtual void - pub(int counter, const Ice::Current&) + void + pub(int counter, const Ice::Current&) override { - Lock sync(*this); + lock_guard lg(_mutex); if(counter != _count) { @@ -221,8 +206,8 @@ class MaxQueueEventI : public EventI } } - virtual void - check(const Subscription& subscription) + void + check(const Subscription& subscription) override { if(_removeSubscriber) { @@ -236,7 +221,7 @@ class MaxQueueEventI : public EventI while(--nRetry > 0) { subscription.publisher->ice_ping(); - IceUtil::ThreadControl::sleep(IceUtil::Time::milliSeconds(200)); + this_thread::sleep_for(200ms); } test(false); } @@ -252,19 +237,19 @@ class MaxQueueEventI : public EventI int _expected; }; -class ControllerEventI: public EventI +class ControllerEventI final : public EventI { public: - ControllerEventI(const CommunicatorPtr& communicator, int total, const Ice::ObjectAdapterPtr& adapter) : - EventI(communicator, total), _adapter(adapter) + ControllerEventI(shared_ptr communicator, int total, shared_ptr adapter) : + EventI(std::move(communicator), total), _adapter(std::move(adapter)) { } - virtual void - pub(int, const Ice::Current&) + void + pub(int, const Ice::Current&) override { - Lock sync(*this); + lock_guard lg(_mutex); if(++_count == _total) { _adapter->activate(); @@ -273,37 +258,14 @@ class ControllerEventI: public EventI private: - const Ice::ObjectAdapterPtr _adapter; -}; - -namespace -{ - -class Init -{ -public: - - Init() - { - ErraticEventI::_remainingMutex = new IceUtil::Mutex; - } - - ~Init() - { - delete ErraticEventI::_remainingMutex; - ErraticEventI::_remainingMutex = 0; - } + const shared_ptr _adapter; }; -Init init; - -} - -class Subscriber : public Test::TestHelper +class Subscriber final : public Test::TestHelper { public: - void run(int, char**); + void run(int, char**) override; }; void @@ -345,16 +307,16 @@ Subscriber::run(int argc, char** argv) IceStorm::QoS cmdLineQos; vector sqos = opts.argVec("qos"); - for(vector::const_iterator q = sqos.begin(); q != sqos.end(); ++q) + for(const auto& q: sqos) { - string::size_type off = q->find(","); + string::size_type off = q.find(","); if(off == string::npos) { ostringstream os; os << argv[0] << ": parse error: no , in QoS"; throw invalid_argument(os.str()); } - cmdLineQos[q->substr(0, off)] = q->substr(off+1); + cmdLineQos[q.substr(0, off)] = q.substr(off+1); } bool slow = opts.isSet("slow"); @@ -375,8 +337,8 @@ Subscriber::run(int argc, char** argv) throw invalid_argument(os.str()); } - PropertiesPtr properties = communicator->getProperties(); - const char* managerProxyProperty = "IceStormAdmin.TopicManager.Default"; + auto properties = communicator->getProperties(); + string managerProxyProperty = "IceStormAdmin.TopicManager.Default"; string managerProxy = properties->getProperty(managerProxyProperty); if(managerProxy.empty()) { @@ -385,7 +347,7 @@ Subscriber::run(int argc, char** argv) throw invalid_argument(os.str()); } - IceStorm::TopicManagerPrx manager = IceStorm::TopicManagerPrx::checkedCast( + auto manager = checkedCast( communicator->stringToProxy(managerProxy)); if(!manager) { @@ -404,7 +366,7 @@ Subscriber::run(int argc, char** argv) os << "SubscriberAdapter" << i; Subscription item; item.adapter = communicator->createObjectAdapterWithEndpoints(os.str(), "default"); - item.servant = new ErraticEventI(communicator.communicator(), events); + item.servant = make_shared(communicator.communicator(), events); item.qos["reliability"] = "twoway"; subs.push_back(item); } @@ -413,7 +375,7 @@ Subscriber::run(int argc, char** argv) { Subscription item; item.adapter = communicator->createObjectAdapterWithEndpoints("SubscriberAdapter", "default"); - item.servant = new SlowEventI(communicator.communicator(), events); + item.servant = make_shared(communicator.communicator(), events); item.qos = cmdLineQos; subs.push_back(item); } @@ -423,11 +385,11 @@ Subscriber::run(int argc, char** argv) item1.adapter = communicator->createObjectAdapterWithEndpoints("MaxQueueAdapter", "default"); if(maxQueueDropEvents) { - item1.servant = new MaxQueueEventI(communicator.communicator(), maxQueueDropEvents, events, false); + item1.servant = make_shared(communicator.communicator(), maxQueueDropEvents, events, false); } else { - item1.servant = new MaxQueueEventI(communicator.communicator(), maxQueueRemoveSub, events, true); + item1.servant = make_shared(communicator.communicator(), maxQueueRemoveSub, events, true); } item1.qos = cmdLineQos; item1.activate = false; @@ -435,7 +397,7 @@ Subscriber::run(int argc, char** argv) Subscription item2; item2.adapter = communicator->createObjectAdapterWithEndpoints("ControllerAdapter", "default"); - item2.servant = new ControllerEventI(communicator.communicator(), events, item1.adapter); + item2.servant = make_shared(communicator.communicator(), events, item1.adapter); item2.qos["reliability"] = "oneway"; subs.push_back(item2); } @@ -444,29 +406,29 @@ Subscriber::run(int argc, char** argv) Subscription item; item.adapter = communicator->createObjectAdapterWithEndpoints("SubscriberAdapter", "default"); item.qos = cmdLineQos; - map::const_iterator p = item.qos.find("reliability"); + auto p = item.qos.find("reliability"); if(p != item.qos.end() && p->second == "ordered") { - item.servant = new OrderEventI(communicator.communicator(), events); + item.servant = make_shared(communicator.communicator(), events); } else { - item.servant = new CountEventI(communicator.communicator(), events); + item.servant = make_shared(communicator.communicator(), events); } subs.push_back(item); } - TopicPrx topic = manager->retrieve("fed1"); + auto topic = manager->retrieve("fed1"); { - for(vector::iterator p = subs.begin(); p != subs.end(); ++p) + for(auto& p: subs) { - p->obj = p->adapter->addWithUUID(p->servant); + p.obj = p.adapter->addWithUUID(p.servant); IceStorm::QoS qos; string reliability = ""; - IceStorm::QoS::const_iterator q = p->qos.find("reliability"); - if(q != p->qos.end()) + IceStorm::QoS::const_iterator q = p.qos.find("reliability"); + if(q != p.qos.end()) { reliability = q->second; } @@ -480,22 +442,22 @@ Subscriber::run(int argc, char** argv) } else if(reliability == "batch") { - p->obj = p->obj->ice_batchOneway(); + p.obj = p.obj->ice_batchOneway(); } else //if(reliability == "oneway") { - p->obj = p->obj->ice_oneway(); + p.obj = p.obj->ice_oneway(); } - p->publisher = topic->subscribeAndGetPublisher(qos, p->obj); + p.publisher = topic->subscribeAndGetPublisher(qos, p.obj); } } { - for(vector::iterator p = subs.begin(); p != subs.end(); ++p) + for(const auto& p: subs) { - if(p->activate) + if(p.activate) { - p->adapter->activate(); + p.adapter->activate(); } } } @@ -503,14 +465,14 @@ Subscriber::run(int argc, char** argv) communicator->waitForShutdown(); { - for(vector::const_iterator p = subs.begin(); p != subs.end(); ++p) + for(const auto& p: subs) { - p->servant->check(*p); - topic->unsubscribe(p->obj); - if(p->servant->count() != events) + p.servant->check(p); + topic->unsubscribe(p.obj); + if(p.servant->count() != events) { ostringstream os; - os << "expected " << events << " events but got " << p->servant->count() << " events."; + os << "expected " << events << " events but got " << p.servant->count() << " events."; throw invalid_argument(os.str()); } } diff --git a/scripts/Component.py b/scripts/Component.py index 2bc1a1de839..3bd827e2841 100644 --- a/scripts/Component.py +++ b/scripts/Component.py @@ -117,14 +117,13 @@ def canRun(self, testId, mapping, current): if testId == "IceStorm/repgrid": return False - # No C++11 tests for IceStorm, IceGrid, etc - if isinstance(mapping, CppMapping) and current.config.cpp11: - if parent in ["IceStorm", "IceBridge"]: - return False - elif parent in ["IceGrid"] and testId not in ["IceGrid/simple"]: - return False - elif parent in ["Glacier2"] and testId not in ["Glacier2/application", "Glacier2/sessionHelper"]: - return False + # No C++98 tests for Glacier2, IceGrid, IceStorm, IceBridge + if isinstance(mapping, CppMapping) and not current.config.cpp11 and parent in [ + "Glacier2", + "IceBridge", + "IceGrid", + "IceStorm"]: + return False return True diff --git a/scripts/IceBridgeUtil.py b/scripts/IceBridgeUtil.py index f635036f968..2df68fede37 100644 --- a/scripts/IceBridgeUtil.py +++ b/scripts/IceBridgeUtil.py @@ -7,7 +7,7 @@ class IceBridge(ProcessFromBinDir, ProcessIsReleaseOnly, Server): def __init__(self, *args, **kargs): - Server.__init__(self, "icebridge", mapping=Mapping.getByName("cpp"), desc="IceBridge", *args, **kargs) + Server.__init__(self, "icebridge++11", mapping=Mapping.getByName("cpp"), desc="IceBridge", *args, **kargs) def getExe(self, current): return self.exe + "_32" if current.config.buildPlatform == "ppc" else self.exe diff --git a/scripts/IceGridUtil.py b/scripts/IceGridUtil.py index 36a5636622f..d8ee5d96cb0 100644 --- a/scripts/IceGridUtil.py +++ b/scripts/IceGridUtil.py @@ -46,7 +46,7 @@ def __init__(self, replica=None, *args, **kargs): class IceGridAdmin(ProcessFromBinDir, ProcessIsReleaseOnly, IceGridClient): def __init__(self, replica=None, username="admin1", password="test1", *args, **kargs): - IceGridClient.__init__(self, replica=replica, exe="icegridadmin", mapping=Mapping.getByName("cpp"), + IceGridClient.__init__(self, replica=replica, exe="icegridadmin++11", mapping=Mapping.getByName("cpp"), *args, **kargs) self.username = username self.password = password @@ -64,7 +64,7 @@ class IceGridNode(ProcessFromBinDir, Server): def __init__(self, name="localnode", *args, **kargs): - Server.__init__(self, "icegridnode", mapping=Mapping.getByName("cpp"), desc="IceGrid node " + name, + Server.__init__(self, "icegridnode++11", mapping=Mapping.getByName("cpp"), desc="IceGrid node " + name, ready="node", *args, **kargs) self.name = name @@ -96,6 +96,7 @@ def getProps(self, current): 'IceGrid.Node.Trace.Activator' : 0, 'IceGrid.Node.Trace.Adapter' : 0, 'IceGrid.Node.Trace.Server' : 0, + 'IceGrid.Node.Trace.Patch' : 0, 'IceGrid.Node.ThreadPool.SizeWarn' : 0, 'IceGrid.Node.PrintServersReady' : 'node', 'IceGrid.Node.Name' : self.name, @@ -121,7 +122,7 @@ def shutdown(self, current): class IceGridRegistry(ProcessFromBinDir, Server): def __init__(self, name, portnum=20, ready="AdminSessionManager", *args, **kargs): - Server.__init__(self, "icegridregistry", mapping=Mapping.getByName("cpp"), desc="IceGrid registry " + name, + Server.__init__(self, "icegridregistry++11", mapping=Mapping.getByName("cpp"), desc="IceGrid registry " + name, ready=ready, *args, **kargs) self.portnum = portnum self.readyCount = -1 diff --git a/scripts/IceStormUtil.py b/scripts/IceStormUtil.py index 4e9caf90486..7de6d174bcc 100644 --- a/scripts/IceStormUtil.py +++ b/scripts/IceStormUtil.py @@ -11,7 +11,7 @@ class IceStorm(ProcessFromBinDir, Server): def __init__(self, instanceName="IceStorm", replica=0, nreplicas=0, transient=False, portnum=0, createDb=True, cleanDb=True, *args, **kargs): - Server.__init__(self, exe="icebox", ready="IceStorm", mapping=Mapping.getByName("cpp"), *args, **kargs) + Server.__init__(self, exe="icebox++11", ready="IceStorm", mapping=Mapping.getByName("cpp"), *args, **kargs) self.portnum = portnum self.replica = replica self.nreplicas = nreplicas @@ -149,7 +149,7 @@ def getProps(self, current): class IceStormAdmin(ProcessFromBinDir, ProcessIsReleaseOnly, IceStormProcess, Client): def __init__(self, instanceName=None, instance=None, *args, **kargs): - Client.__init__(self, exe="icestormadmin", mapping=Mapping.getByName("cpp"), *args, **kargs) + Client.__init__(self, exe="icestormadmin++11", mapping=Mapping.getByName("cpp"), *args, **kargs) IceStormProcess.__init__(self, instanceName, instance) def getExe(self, current): diff --git a/slice/IceStorm/IceStorm.ice b/slice/IceStorm/IceStorm.ice index 8d1630fef6e..f587f470732 100644 --- a/slice/IceStorm/IceStorm.ice +++ b/slice/IceStorm/IceStorm.ice @@ -178,11 +178,11 @@ interface TopicManager /// @param name The name of the topic. /// @return A proxy to the topic instance. /// @throws NoSuchTopic Raised if the topic does not exist. - ["nonmutating", "cpp:const"] idempotent Topic* retrieve(string name) throws NoSuchTopic; + idempotent Topic* retrieve(string name) throws NoSuchTopic; /// Retrieve all topics managed by this topic manager. /// @return A dictionary of string, topic proxy pairs. - ["nonmutating", "cpp:const"] idempotent TopicDict retrieveAll(); + idempotent TopicDict retrieveAll(); } /// This interface is advertised by the IceStorm service through the Ice object with the identity `IceStorm/Finder'.