From 7980fcc14187bf06f507c0f89faf76bba6105a43 Mon Sep 17 00:00:00 2001 From: "yuzhi.lyz" Date: Fri, 19 Mar 2021 09:41:54 +0800 Subject: [PATCH] format with google style --- .../client/api/ConfigDataObserver.java | 21 +- .../registry/client/api/Configurator.java | 39 +- .../sofa/registry/client/api/EventBus.java | 67 +- .../registry/client/api/EventSubscriber.java | 27 +- .../sofa/registry/client/api/Publisher.java | 12 +- .../sofa/registry/client/api/Register.java | 86 +- .../registry/client/api/RegistryClient.java | 63 +- .../client/api/RegistryClientConfig.java | 297 +- .../sofa/registry/client/api/Subscriber.java | 51 +- .../client/api/SubscriberDataObserver.java | 21 +- .../api/exception/DuplicateException.java | 70 +- .../exception/RegistryClientException.java | 70 +- .../registry/client/api/model/ConfigData.java | 14 +- .../sofa/registry/client/api/model/Event.java | 5 +- .../client/api/model/RegistryType.java | 6 +- .../registry/client/api/model/UserData.java | 24 +- .../api/registration/BaseRegistration.java | 126 +- .../ConfiguratorRegistration.java | 78 +- .../registration/PublisherRegistration.java | 45 +- .../registration/SubscriberRegistration.java | 122 +- .../api/exception/DuplicateExceptionTest.java | 35 +- .../RegistryClientExceptionTest.java | 34 +- .../registration/BaseRegistrationTest.java | 31 +- .../ConfiguratorRegistrationTest.java | 31 +- .../PublisherRegistrationTest.java | 18 +- .../SubscriberRegistrationTest.java | 35 +- .../core/model/ReceivedConfigDataTest.java | 44 +- .../registry/core/model/ReceivedDataTest.java | 61 +- .../sofa/registry/core/model/ResultTest.java | 24 +- .../registry/core/model/ScopeEnumTest.java | 16 +- .../registry/client/auth/AuthManager.java | 16 +- .../registry/client/auth/NoopAuthManager.java | 27 +- .../client/constants/ValueConstants.java | 20 +- .../client/constants/VersionConstants.java | 3 +- .../event/ConfiguratorProcessEvent.java | 223 +- .../client/event/DefaultEventBus.java | 185 +- .../client/event/LookoutSubscriber.java | 168 +- .../client/event/SubscriberProcessEvent.java | 223 +- .../client/factory/NamedThreadFactory.java | 77 +- .../client/model/ConfiguratorData.java | 78 +- .../registry/client/model/SegmentData.java | 106 +- .../provider/AbstractInternalRegister.java | 670 ++- .../client/provider/DefaultConfigData.java | 39 +- .../client/provider/DefaultConfigurator.java | 339 +- .../provider/DefaultObserverHandler.java | 246 +- .../client/provider/DefaultPublisher.java | 249 +- .../provider/DefaultRegistryClient.java | 919 ++-- .../provider/DefaultRegistryClientConfig.java | 900 ++-- .../DefaultRegistryClientConfigBuilder.java | 504 +-- .../client/provider/DefaultServerManager.java | 209 +- .../client/provider/DefaultServerNode.java | 282 +- .../client/provider/DefaultSubscriber.java | 455 +- .../client/provider/DefaultUserData.java | 97 +- .../client/provider/RegisterCache.java | 224 +- .../sofa/registry/client/remoting/Client.java | 55 +- .../client/remoting/ClientConnection.java | 431 +- .../ClientConnectionCloseEventProcessor.java | 31 +- .../ClientConnectionOpenEventProcessor.java | 31 +- .../remoting/ReceivedConfigDataProcessor.java | 138 +- .../remoting/ReceivedDataProcessor.java | 161 +- .../client/remoting/ServerManager.java | 25 +- .../registry/client/remoting/ServerNode.java | 50 +- .../client/task/AbstractWorkerThread.java | 70 +- .../registry/client/task/ObserverHandler.java | 28 +- .../client/task/SyncConfigThread.java | 185 +- .../sofa/registry/client/task/TaskEvent.java | 229 +- .../sofa/registry/client/task/TaskQueue.java | 105 +- .../sofa/registry/client/task/Worker.java | 31 +- .../registry/client/task/WorkerThread.java | 298 +- .../registry/client/util/CommonUtils.java | 21 +- .../registry/client/util/HttpClientUtils.java | 161 +- .../client/util/ServerNodeParser.java | 186 +- .../registry/client/util/StringUtils.java | 179 +- .../sofa/registry/client/MockServer.java | 339 +- .../sofa/registry/client/base/BaseTest.java | 54 +- .../client/event/DefaultEventBusTest.java | 103 +- .../client/event/LookoutSubscriberTest.java | 81 +- .../sofa/registry/client/event/TestEvent.java | 42 +- .../client/event/TestEventSubscriber.java | 47 +- .../client/model/ConfiguratorDataTest.java | 23 +- .../provider/DefaultRegistryClientTest.java | 391 +- .../provider/DefaultServerManagerTest.java | 58 +- .../provider/DefaultSubscriberTest.java | 376 +- .../client/provider/RegisterOrderTest.java | 257 +- .../ReceivedConfigDataProcessorTest.java | 85 +- .../remoting/ReceivedDataProcessorTest.java | 101 +- .../client/task/SyncConfigThreadTest.java | 93 +- .../registry/client/task/TaskEventTest.java | 144 +- .../registry/client/util/CommonUtilsTest.java | 21 +- .../client/util/HttpClientUtilsTest.java | 127 +- .../client/util/ServerNodeParserTest.java | 143 +- .../registry/client/util/StringUtilsTest.java | 106 +- .../registry/client/log/LoggerFactory.java | 126 +- .../client/log/LoggerFactoryTest.java | 73 +- .../core/constants/AttributeKeyConstants.java | 28 +- .../core/constants/EventTypeConstants.java | 27 +- .../core/model/AppRevisionInterface.java | 68 +- .../registry/core/model/BaseRegister.java | 671 +-- .../core/model/ConfiguratorRegister.java | 7 +- .../sofa/registry/core/model/DataBox.java | 72 +- .../core/model/PublisherRegister.java | 55 +- .../core/model/ReceivedConfigData.java | 275 +- .../registry/core/model/ReceivedData.java | 469 +- .../registry/core/model/RegisterResponse.java | 232 +- .../sofa/registry/core/model/Result.java | 112 +- .../sofa/registry/core/model/ScopeEnum.java | 26 +- .../core/model/SubscriberRegister.java | 54 +- .../core/model/SyncConfigRequest.java | 97 +- .../core/model/SyncConfigResponse.java | 95 +- pom.xml | 75 +- .../common/model/ClientOffPublishers.java | 31 +- .../registry/common/model/CommonResponse.java | 165 +- .../sofa/registry/common/model/ConnectId.java | 217 +- .../sofa/registry/common/model/DataUtils.java | 65 +- .../registry/common/model/ElementType.java | 19 +- .../common/model/GenericResponse.java | 82 +- .../sofa/registry/common/model/IPPort.java | 86 +- .../sofa/registry/common/model/Node.java | 40 +- .../sofa/registry/common/model/ProcessId.java | 127 +- .../registry/common/model/PublishType.java | 16 +- .../common/model/PublisherDigestUtil.java | 83 +- .../registry/common/model/PublisherUtils.java | 57 +- .../common/model/RegisterVersion.java | 129 +- .../registry/common/model/ServerDataBox.java | 352 +- .../model/ServerDataBoxInputStream.java | 43 +- .../common/model/SubscriberUtils.java | 99 +- .../sofa/registry/common/model/Triple.java | 84 +- .../sofa/registry/common/model/Tuple.java | 77 +- .../model/appmeta/InterfaceMapping.java | 73 +- .../model/client/pb/AppDiscoveryMetaPb.java | 390 +- .../common/model/client/pb/AppList.java | 1075 +++-- .../model/client/pb/AppListOrBuilder.java | 40 +- .../model/client/pb/BaseRegisterPb.java | 3854 ++++++++--------- .../client/pb/BaseRegisterPbOrBuilder.java | 262 +- .../client/pb/BaseRegisterPbOuterClass.java | 132 +- .../common/model/client/pb/DataBoxPb.java | 892 ++-- .../model/client/pb/DataBoxPbOrBuilder.java | 22 +- .../model/client/pb/DataBoxPbOuterClass.java | 78 +- .../common/model/client/pb/DataBoxesPb.java | 1378 +++--- .../model/client/pb/DataBoxesPbOrBuilder.java | 41 +- .../client/pb/DataBoxesPbOuterClass.java | 88 +- .../common/model/client/pb/EventTypePb.java | 149 +- .../client/pb/EventTypePbOuterClass.java | 63 +- .../model/client/pb/GetRevisionsRequest.java | 1019 +++-- .../pb/GetRevisionsRequestOrBuilder.java | 34 +- .../model/client/pb/GetRevisionsResponse.java | 1543 ++++--- .../pb/GetRevisionsResponseOrBuilder.java | 74 +- .../model/client/pb/MetaHeartbeatRequest.java | 1019 +++-- .../pb/MetaHeartbeatRequestOrBuilder.java | 34 +- .../client/pb/MetaHeartbeatResponse.java | 1000 +++-- .../pb/MetaHeartbeatResponseOrBuilder.java | 28 +- .../common/model/client/pb/MetaRegister.java | 2284 +++++----- .../client/pb/MetaRegisterOrBuilder.java | 174 +- .../common/model/client/pb/MetaService.java | 1433 +++--- .../model/client/pb/MetaServiceOrBuilder.java | 67 +- .../model/client/pb/PublisherRegisterPb.java | 1838 ++++---- .../pb/PublisherRegisterPbOrBuilder.java | 61 +- .../pb/PublisherRegisterPbOuterClass.java | 100 +- .../model/client/pb/ReceivedConfigDataPb.java | 2064 +++++---- .../pb/ReceivedConfigDataPbOrBuilder.java | 94 +- .../pb/ReceivedConfigDataPbOuterClass.java | 96 +- .../model/client/pb/ReceivedDataPb.java | 2854 ++++++------ .../client/pb/ReceivedDataPbOrBuilder.java | 203 +- .../client/pb/ReceivedDataPbOuterClass.java | 129 +- .../model/client/pb/RegisterResponsePb.java | 1411 +++--- .../pb/RegisterResponsePbOrBuilder.java | 66 +- .../pb/RegisterResponsePbOuterClass.java | 84 +- .../common/model/client/pb/ResultPb.java | 988 +++-- .../model/client/pb/ResultPbOrBuilder.java | 28 +- .../model/client/pb/ResultPbOuterClass.java | 80 +- .../common/model/client/pb/ScopeEnumPb.java | 165 +- .../client/pb/ScopeEnumPbOuterClass.java | 63 +- .../client/pb/ServiceAppMappingRequest.java | 1023 +++-- .../pb/ServiceAppMappingRequestOrBuilder.java | 34 +- .../client/pb/ServiceAppMappingResponse.java | 1552 +++---- .../ServiceAppMappingResponseOrBuilder.java | 73 +- .../common/model/client/pb/StringList.java | 971 ++--- .../model/client/pb/StringListOrBuilder.java | 34 +- .../model/client/pb/SubscriberRegisterPb.java | 1292 +++--- .../pb/SubscriberRegisterPbOrBuilder.java | 41 +- .../pb/SubscriberRegisterPbOuterClass.java | 91 +- .../model/client/pb/SyncConfigRequestPb.java | 1119 +++-- .../pb/SyncConfigRequestPbOrBuilder.java | 34 +- .../pb/SyncConfigRequestPbOuterClass.java | 81 +- .../model/client/pb/SyncConfigResponsePb.java | 1466 +++---- .../pb/SyncConfigResponsePbOrBuilder.java | 58 +- .../pb/SyncConfigResponsePbOuterClass.java | 94 +- .../common/model/console/PersistenceData.java | 228 +- .../model/constants/ValueConstants.java | 81 +- .../model/dataserver/AbstractSlotRequest.java | 85 +- .../common/model/dataserver/BatchRequest.java | 31 +- .../model/dataserver/ClientOffPublisher.java | 56 +- .../common/model/dataserver/Datum.java | 431 +- .../common/model/dataserver/DatumDigest.java | 71 +- .../common/model/dataserver/DatumSummary.java | 121 +- .../common/model/dataserver/DatumVersion.java | 74 +- .../model/dataserver/GetDataRequest.java | 69 +- .../dataserver/GetDataVersionRequest.java | 60 +- .../metaserver/CheckRevisionsRequest.java | 8 +- .../ConfigureLoadbalanceRequest.java | 24 +- .../model/metaserver/DataCenterNodes.java | 187 +- .../common/model/metaserver/DataOperator.java | 8 +- .../metaserver/FetchProvideDataRequest.java | 50 +- .../metaserver/FetchRevisionsRequest.java | 8 +- .../GetLoadbalanceMetricsRequest.java | 6 +- .../model/metaserver/GetSlotTableRequest.java | 112 +- .../model/metaserver/GetSlotTableResult.java | 82 +- .../common/model/metaserver/Lease.java | 274 +- .../model/metaserver/LoadbalanceMetrics.java | 19 +- .../model/metaserver/NodeChangeResult.java | 227 +- .../common/model/metaserver/ProvideData.java | 200 +- .../metaserver/ProvideDataChangeEvent.java | 225 +- .../metaserver/SlotTableChangeEvent.java | 24 +- .../model/metaserver/cluster/Cluster.java | 27 +- .../metaserver/cluster/VersionedList.java | 33 +- .../heartbeat/BaseHeartBeatResponse.java | 132 +- .../heartbeat/DataHeartBeatResponse.java | 28 +- .../inter/heartbeat/HeartbeatRequest.java | 321 +- .../heartbeat/SessionHeartBeatResponse.java | 17 +- .../model/metaserver/nodes/DataNode.java | 273 +- .../model/metaserver/nodes/MetaNode.java | 222 +- .../model/metaserver/nodes/SessionNode.java | 268 +- .../rpc/NodeClusterViewRequest.java | 95 +- .../sessionserver/CancelAddressRequest.java | 63 +- .../sessionserver/DataChangeRequest.java | 44 +- .../model/sessionserver/DataPushRequest.java | 74 +- .../common/model/slot/BaseSlotStatus.java | 141 +- .../common/model/slot/DataNodeSlot.java | 265 +- .../model/slot/DataSlotDiffDigestRequest.java | 75 +- .../model/slot/DataSlotDiffDigestResult.java | 144 +- .../slot/DataSlotDiffPublisherRequest.java | 74 +- .../slot/DataSlotDiffPublisherResult.java | 173 +- .../common/model/slot/DataSlotDiffUtils.java | 208 +- .../common/model/slot/FollowerSlotStatus.java | 108 +- .../common/model/slot/LeaderSlotStatus.java | 69 +- .../sofa/registry/common/model/slot/Slot.java | 151 +- .../common/model/slot/SlotAccess.java | 95 +- .../model/slot/SlotAccessGenericResponse.java | 67 +- .../common/model/slot/SlotConfig.java | 139 +- .../registry/common/model/slot/SlotTable.java | 421 +- .../model/slot/func/Crc32cSlotFunction.java | 70 +- .../common/model/slot/func/HashFunction.java | 17 +- .../model/slot/func/MD5HashFunction.java | 44 +- .../model/slot/func/MD5SlotFunction.java | 41 +- .../common/model/slot/func/SlotFunction.java | 7 +- .../model/slot/func/SlotFunctionRegistry.java | 25 +- .../common/model/store/AppRevision.java | 307 +- .../registry/common/model/store/BaseInfo.java | 745 ++-- .../registry/common/model/store/DataInfo.java | 298 +- .../common/model/store/ProcessIdCache.java | 15 +- .../common/model/store/Publisher.java | 201 +- .../common/model/store/StoreData.java | 38 +- .../registry/common/model/store/SubDatum.java | 165 +- .../common/model/store/SubPublisher.java | 90 +- .../common/model/store/Subscriber.java | 246 +- .../sofa/registry/common/model/store/URL.java | 511 +-- .../common/model/store/UnPublisher.java | 65 +- .../registry/common/model/store/Watcher.java | 46 +- .../common/model/store/WordCache.java | 32 +- .../slot/DataSlotDiffSyncResultTest.java | 383 +- .../registry/common/model/store/SubTest.java | 62 +- .../converter/ScopeEnumConverter.java | 28 +- .../registry/datacenter/DataCenterAware.java | 5 +- .../registry/exception/DisposeException.java | 21 +- .../exception/InitializeException.java | 21 +- .../exception/SofaRegistryException.java | 23 +- .../exception/SofaRegistryIOException.java | 21 +- .../SofaRegistryMetaLeaderException.java | 63 +- .../exception/SofaRegistryRaftException.java | 29 +- .../SofaRegistryRuntimeException.java | 29 +- .../SofaRegistrySlotTableException.java | 33 +- .../registry/exception/StartException.java | 21 +- .../registry/exception/StopException.java | 21 +- .../sofa/registry/lifecycle/Disposable.java | 9 +- .../registry/lifecycle/Initializable.java | 9 +- .../sofa/registry/lifecycle/Lifecycle.java | 11 +- .../lifecycle/LifecycleController.java | 11 +- .../registry/lifecycle/LifecycleState.java | 183 +- .../lifecycle/LifecycleStateAware.java | 5 +- .../registry/lifecycle/LiteLifecycle.java | 6 +- .../lifecycle/SmartSpringLifecycle.java | 8 +- .../sofa/registry/lifecycle/Startable.java | 9 +- .../sofa/registry/lifecycle/Stoppable.java | 9 +- .../sofa/registry/lifecycle/Suspendable.java | 9 +- .../lifecycle/impl/AbstractLifecycle.java | 165 +- .../lifecycle/impl/AbstractLiteLifecycle.java | 52 +- .../impl/DefaultLifecycleController.java | 43 +- .../lifecycle/impl/DefaultLifecycleState.java | 322 +- .../lifecycle/impl/LifecycleHelper.java | 50 +- .../com/alipay/sofa/registry/log/Logger.java | 467 +- .../sofa/registry/log/LoggerFactory.java | 79 +- .../alipay/sofa/registry/log/SLF4JLogger.java | 460 +- .../sofa/registry/metrics/ReporterUtils.java | 77 +- .../sofa/registry/metrics/TaskMetrics.java | 50 +- .../com/alipay/sofa/registry/net/NetUtil.java | 326 +- .../sofa/registry/observer/Observable.java | 4 +- .../registry/observer/UnblockingObserver.java | 2 +- .../impl/AbstractLifecycleObservable.java | 52 +- .../observer/impl/AbstractObservable.java | 49 +- .../sofa/registry/task/BlockingQueues.java | 101 +- .../task/FastRejectedExecutionException.java | 17 +- .../task/KeyedPreemptThreadPoolExecutor.java | 162 +- .../alipay/sofa/registry/task/KeyedTask.java | 149 +- .../task/KeyedThreadPoolExecutor.java | 188 +- .../task/MetricsableThreadPoolExecutor.java | 102 +- .../task/RejectedLogErrorHandler.java | 19 +- .../alipay/sofa/registry/task/Retryable.java | 10 +- .../com/alipay/sofa/registry/task/Task.java | 31 +- .../task/batcher/AcceptorExecutor.java | 468 +- .../registry/task/batcher/TaskDispatcher.java | 41 +- .../task/batcher/TaskDispatchers.java | 207 +- .../registry/task/batcher/TaskExecutors.java | 226 +- .../registry/task/batcher/TaskHolder.java | 100 +- .../registry/task/batcher/TaskProcessor.java | 47 +- .../registry/task/batcher/TrafficShaper.java | 107 +- .../listener/DefaultTaskListenerManager.java | 33 +- .../registry/task/listener/TaskEvent.java | 304 +- .../registry/task/listener/TaskListener.java | 27 +- .../task/listener/TaskListenerManager.java | 24 +- .../registry/timer/AsyncHashedWheelTimer.java | 204 +- .../timer/RecycleAsyncHashedWheelTimer.java | 186 +- .../alipay/sofa/registry/trace/TraceID.java | 68 +- .../registry/util/BatchCallableRunnable.java | 295 +- .../com/alipay/sofa/registry/util/Bool.java | 33 +- .../sofa/registry/util/CollectionUtils.java | 21 +- .../sofa/registry/util/ConcurrentUtils.java | 137 +- .../sofa/registry/util/DatumVersionUtil.java | 90 +- .../registry/util/DefaultExecutorFactory.java | 241 +- .../alipay/sofa/registry/util/FileUtils.java | 433 +- .../alipay/sofa/registry/util/JsonUtils.java | 50 +- .../sofa/registry/util/LoopRunnable.java | 100 +- .../alipay/sofa/registry/util/MapUtils.java | 27 +- .../alipay/sofa/registry/util/MathUtils.java | 30 +- .../sofa/registry/util/MessageDigests.java | 142 +- .../registry/util/NamedThreadFactory.java | 72 +- .../sofa/registry/util/ObjectFactory.java | 5 +- .../alipay/sofa/registry/util/OsUtils.java | 28 +- .../sofa/registry/util/ParaCheckUtil.java | 118 +- .../sofa/registry/util/PropertySplitter.java | 99 +- .../sofa/registry/util/RevisionUtils.java | 17 +- .../sofa/registry/util/SingleFlight.java | 141 +- .../sofa/registry/util/StringFormatter.java | 11 +- .../sofa/registry/util/SystemUtils.java | 31 +- .../sofa/registry/util/TimestampUtil.java | 9 +- .../sofa/registry/util/VersionsMapUtils.java | 36 +- .../registry/util/WakeUpLoopRunnable.java | 18 +- .../alipay/sofa/registry/TestScheduler.java | 6 +- .../converter/ScopeEnumConverterTest.java | 14 +- .../task/listener/TaskListenerTest.java | 49 +- .../timer/AsyncHashedWheelTimerTest.java | 82 +- .../util/BatchCallableRunnableTest.java | 87 +- .../registry/util/CollectionUtilsTest.java | 41 +- .../registry/util/DatumVersionUtilTest.java | 31 +- .../sofa/registry/util/FileUtilsTest.java | 67 +- .../sofa/registry/util/MathUtilsTest.java | 18 +- .../registry/util/MessageDigestsTest.java | 138 +- .../sofa/registry/util/OsUtilsTest.java | 16 +- .../sofa/registry/util/ParaCheckUtilTest.java | 67 +- .../registry/util/PropertySplitterTest.java | 105 +- .../registry/util/VersionsMapUtilsTest.java | 24 +- .../registry/remoting/CallbackHandler.java | 43 +- .../sofa/registry/remoting/Channel.java | 85 +- .../registry/remoting/ChannelHandler.java | 160 +- .../alipay/sofa/registry/remoting/Client.java | 101 +- .../sofa/registry/remoting/Endpoint.java | 35 +- .../registry/remoting/RemotingException.java | 19 +- .../alipay/sofa/registry/remoting/Server.java | 113 +- .../registry/remoting/exchange/Exchange.java | 95 +- .../remoting/exchange/NodeExchanger.java | 18 +- .../RequestChannelClosedException.java | 12 +- .../remoting/exchange/RequestException.java | 136 +- .../remoting/exchange/message/Request.java | 68 +- .../remoting/exchange/message/Response.java | 26 +- .../remoting/RequestExceptionTest.java | 62 +- .../bolt/AsyncUserProcessorAdapter.java | 79 +- .../registry/remoting/bolt/BoltChannel.java | 227 +- .../remoting/bolt/BoltChannelUtil.java | 48 +- .../registry/remoting/bolt/BoltClient.java | 399 +- .../registry/remoting/bolt/BoltServer.java | 553 ++- .../remoting/bolt/ConnectionEventAdapter.java | 109 +- .../bolt/SyncUserProcessorAdapter.java | 69 +- .../remoting/bolt/exchange/BoltExchange.java | 115 +- .../CustomClassSerializerManager.java | 43 +- .../serializer/ProtobufCustomSerializer.java | 211 +- .../bolt/serializer/ProtobufSerializer.java | 253 +- .../remoting/bolt/BoltChannelUtilTest.java | 42 +- .../remoting/bolt/BoltServerTest.java | 105 +- .../registry/remoting/bolt/MockChannel.java | 68 +- .../bolt/MockChannelHandlerContext.java | 411 +- .../remoting/jersey/JerseyChannel.java | 135 +- .../remoting/jersey/JerseyClient.java | 235 +- .../remoting/jersey/JerseyJettyServer.java | 306 +- .../jersey/exchange/JerseyExchange.java | 137 +- .../server/HttpChannelOverHttpCustom.java | 44 +- .../jetty/server/HttpConnectionCustom.java | 25 +- .../server/HttpConnectionCustomFactory.java | 27 +- .../remoting/jersey/JerseyExchangeTest.java | 161 +- .../remoting/jersey/TestHttpResource.java | 10 +- .../registry/server/data/DataApplication.java | 19 +- .../server/data/bootstrap/CommonConfig.java | 99 +- .../DataServerBeanConfiguration.java | 551 +-- .../data/bootstrap/DataServerBootstrap.java | 386 +- .../data/bootstrap/DataServerConfig.java | 1402 +++--- .../data/bootstrap/DataServerInitializer.java | 71 +- .../data/bootstrap/EnableDataServer.java | 7 +- .../server/data/cache/DatumCache.java | 123 +- .../server/data/cache/DatumStorage.java | 69 +- .../server/data/cache/LocalDatumStorage.java | 405 +- .../server/data/cache/PublisherEnvelope.java | 107 +- .../server/data/cache/PublisherGroup.java | 486 ++- .../server/data/cache/PublisherGroups.java | 293 +- .../server/data/change/ChangeMetrics.java | 58 +- .../server/data/change/DataChangeEvent.java | 52 +- .../data/change/DataChangeEventCenter.java | 614 +-- .../data/change/DataTempChangeEvent.java | 32 +- .../server/data/change/IDataChangeEvent.java | 5 +- .../server/data/executor/ExecutorFactory.java | 76 +- .../data/lease/SessionLeaseManager.java | 210 +- .../data/remoting/DataMetaServerManager.java | 33 +- .../data/remoting/DataNodeExchanger.java | 56 +- .../data/remoting/SessionNodeExchanger.java | 57 +- .../SlotFollowerDiffDigestRequestHandler.java | 115 +- ...otFollowerDiffPublisherRequestHandler.java | 118 +- .../metaserver/MetaServerServiceImpl.java | 99 +- .../NotifyProvideDataChangeHandler.java | 50 +- .../provideData/ProvideDataProcessor.java | 10 +- .../ProvideDataProcessorManager.java | 36 +- .../SessionLeaseProvideDataProcessor.java | 48 +- .../SessionServerConnectionFactory.java | 280 +- .../handler/AbstractDataHandler.java | 153 +- .../handler/BatchPutDataHandler.java | 216 +- .../handler/DataServerConnectionHandler.java | 25 +- .../sessionserver/handler/GetDataHandler.java | 134 +- .../handler/GetDataVersionsHandler.java | 199 +- .../sessionserver/handler/HandlerMetrics.java | 49 +- .../data/resource/DataDigestResource.java | 241 +- .../data/resource/DatumApiResource.java | 562 +-- .../server/data/resource/DatumParam.java | 333 +- .../server/data/resource/HealthResource.java | 100 +- .../server/data/slot/SlotChangeListener.java | 4 +- .../server/data/slot/SlotDiffSyncer.java | 496 ++- .../server/data/slot/SlotManager.java | 20 +- .../server/data/slot/SlotManagerImpl.java | 1319 +++--- .../server/data/slot/SlotMetrics.java | 323 +- .../server/data/slot/SyncContinues.java | 2 +- .../server/data/timer/CacheCountTask.java | 134 +- .../server/data/timer/CacheDigestTask.java | 144 +- .../registry/server/data/MigrateTest.java | 54 +- .../registry/server/data/TestBaseUtils.java | 224 +- .../server/data/cache/DatumCacheTest.java | 65 +- .../data/cache/LocalDatumStorageTest.java | 377 +- .../data/cache/PublisherEnvelopeTest.java | 71 +- .../server/data/cache/PublisherGroupTest.java | 572 +-- .../data/cache/PublisherGroupsTest.java | 716 +-- .../data/lease/SessionLeaseManagerTest.java | 135 +- .../SessionServerConnectionFactoryTest.java | 580 ++- .../server/data/slot/SlotDiffSyncerTest.java | 895 ++-- .../server/data/slot/SlotManagerImplTest.java | 444 +- .../integration/RegistryApplication.java | 447 +- .../registry/server/meta/MetaApplication.java | 19 +- .../server/meta/MetaLeaderService.java | 76 +- .../sofa/registry/server/meta/MetaServer.java | 7 +- .../meta/bootstrap/EnableMetaServer.java | 7 +- .../meta/bootstrap/MetaServerBootstrap.java | 425 +- .../bootstrap/MetaServerConfiguration.java | 327 +- .../MetaServerInitializerConfiguration.java | 80 +- .../config/AbstractNodeConfigBean.java | 160 +- .../bootstrap/config/MetaServerConfig.java | 86 +- .../config/MetaServerConfigBean.java | 1571 +++---- .../meta/bootstrap/config/NodeConfig.java | 64 +- .../config/NodeConfigBeanProperty.java | 47 +- .../bootstrap/handler/DataServerHandler.java | 6 +- .../bootstrap/handler/MetaServerHandler.java | 6 +- .../handler/SessionServerHandler.java | 6 +- .../server/meta/cluster/NodeCluster.java | 6 +- .../server/meta/cluster/RemoteServer.java | 5 +- .../server/meta/cluster/RemoteServers.java | 7 +- .../meta/cluster/node/AbstractNodeEvent.java | 25 +- .../server/meta/cluster/node/NodeAdded.java | 9 +- .../server/meta/cluster/node/NodeEvent.java | 7 +- .../meta/cluster/node/NodeModified.java | 26 +- .../server/meta/cluster/node/NodeRemoved.java | 9 +- .../registry/server/meta/lease/Evictable.java | 9 +- .../server/meta/lease/LeaseManager.java | 49 +- .../meta/lease/data/DataManagerObserver.java | 6 +- .../meta/lease/data/DataServerManager.java | 44 +- .../lease/data/DefaultDataServerManager.java | 262 +- .../impl/AbstractEvictableLeaseManager.java | 127 +- .../impl/DefaultCrossDcMetaServerManager.java | 302 +- .../lease/impl/LeaderAwareLeaseManager.java | 91 +- .../meta/lease/impl/SimpleLeaseManager.java | 219 +- .../session/DefaultSessionServerManager.java | 210 +- .../lease/session/SessionManagerObserver.java | 6 +- .../lease/session/SessionServerManager.java | 10 +- .../meta/metaserver/CrossDcMetaServer.java | 9 +- .../metaserver/CrossDcMetaServerManager.java | 23 +- .../meta/metaserver/CurrentDcMetaServer.java | 14 +- .../meta/metaserver/MetaServerObserver.java | 6 +- .../metaserver/impl/AbstractMetaServer.java | 9 +- .../impl/DefaultCrossDcMetaServer.java | 522 +-- .../impl/DefaultCurrentDcMetaServer.java | 179 +- .../impl/DefaultMetaLeaderElector.java | 181 +- .../impl/DefaultMetaServerManager.java | 216 +- .../meta/metaserver/impl/LocalMetaServer.java | 160 +- .../registry/server/meta/monitor/Metrics.java | 583 +-- .../server/meta/monitor/SlotStats.java | 15 +- .../server/meta/monitor/SlotTableMonitor.java | 8 +- .../server/meta/monitor/SlotTableStats.java | 12 +- .../monitor/data/DataMessageListener.java | 7 +- .../meta/monitor/data/DataServerStats.java | 83 +- .../monitor/data/DataSlotMetricsRecorder.java | 21 +- .../monitor/heartbeat/HeartbeatListener.java | 5 +- .../meta/monitor/impl/DefaultSlotStats.java | 277 +- .../monitor/impl/DefaultSlotTableMonitor.java | 243 +- .../monitor/impl/DefaultSlotTableStats.java | 259 +- .../session/SessionMessageListener.java | 7 +- .../data/DefaultProvideDataNotifier.java | 66 +- .../provide/data/ProvideDataNotifier.java | 6 +- .../meta/provide/data/package-info.java | 28 +- .../meta/remoting/DataNodeExchanger.java | 42 +- .../meta/remoting/MetaServerExchanger.java | 22 +- .../meta/remoting/SessionNodeExchanger.java | 22 +- .../connection/DataConnectionHandler.java | 75 +- .../connection/MetaConnectionHandler.java | 125 +- .../connection/NodeConnectManager.java | 12 +- .../connection/SessionConnectionHandler.java | 71 +- .../meta/remoting/data/DataServerService.java | 7 +- .../data/DefaultDataServerService.java | 83 +- .../handler/BaseMetaServerHandler.java | 24 +- .../FetchProvideDataRequestHandler.java | 88 +- .../handler/GetSlotTableRequestHandler.java | 64 +- .../handler/HeartbeatRequestHandler.java | 594 +-- .../remoting/notifier/AbstractNotifier.java | 180 +- .../meta/remoting/notifier/Notifier.java | 7 +- .../session/DefaultSessionServerService.java | 74 +- .../session/SessionServerService.java | 7 +- .../meta/resource/BlacklistDataResource.java | 112 +- .../server/meta/resource/HealthResource.java | 106 +- .../meta/resource/MetaDigestResource.java | 160 +- .../meta/resource/ProvideDataResource.java | 138 +- .../meta/resource/SlotSyncResource.java | 61 +- .../meta/resource/SlotTableResource.java | 202 +- .../meta/resource/StopPushDataResource.java | 182 +- .../resource/filter/LeaderAwareFilter.java | 87 +- .../filter/LeaderAwareRestController.java | 9 +- .../server/meta/slot/RebalanceTask.java | 6 +- .../server/meta/slot/SlotAllocator.java | 3 +- .../server/meta/slot/SlotAssigner.java | 6 +- .../server/meta/slot/SlotBalancer.java | 5 +- .../server/meta/slot/SlotManager.java | 59 +- .../server/meta/slot/SlotTableAware.java | 18 +- .../slot/arrange/CrossDcSlotAllocator.java | 352 +- .../slot/arrange/ScheduledSlotArranger.java | 408 +- .../slot/assigner/DefaultSlotAssigner.java | 281 +- .../meta/slot/assigner/ScoreStrategy.java | 6 +- .../meta/slot/balance/BalancePolicy.java | 75 +- .../slot/balance/DefaultSlotBalancer.java | 1084 ++--- .../meta/slot/balance/LeaderOnlyBalancer.java | 166 +- .../meta/slot/balance/NaiveBalancePolicy.java | 69 +- .../meta/slot/manager/DefaultSlotManager.java | 96 +- .../meta/slot/manager/SimpleSlotManager.java | 148 +- .../server/meta/slot/tasks/BalanceTask.java | 134 +- .../meta/slot/util/MigrateSlotGroup.java | 241 +- .../meta/slot/util/builder/Builder.java | 5 +- .../meta/slot/util/builder/SlotBuilder.java | 197 +- .../slot/util/builder/SlotTableBuilder.java | 421 +- .../slot/util/comparator/Comparators.java | 212 +- .../meta/slot/util/comparator/SortType.java | 30 +- .../meta/slot/util/selector/Selector.java | 5 +- .../meta/slot/util/selector/Selectors.java | 165 +- .../com/alipay/sofa/registry/AllTests.java | 53 +- .../model/slot/BaseSlotFunctionTest.java | 15 +- .../model/slot/Crc32CSlotFunctionTest.java | 106 +- .../server/meta/AbstractH2DbTestBase.java | 252 +- .../server/meta/AbstractMetaServerTest.java | 865 ++-- .../registry/server/meta/AbstractTest.java | 377 +- .../sofa/registry/server/meta/AppTest.java | 29 +- .../meta/cluster/node/NodeModifiedTest.java | 49 +- .../node/TestAbstractNodeEventTest.java | 20 +- .../registry/server/meta/lease/LeaseTest.java | 107 +- .../data/DefaultDataServerManagerTest.java | 130 +- .../impl/CrossDcMetaServerManagerTest.java | 200 +- .../TestAbstractRaftEnabledLeaseManager.java | 476 +- .../DefaultSessionServerManagerTest.java | 170 +- .../impl/DefaultCrossDcMetaServerTest.java | 418 +- .../impl/DefaultCurrentDcMetaServerTest.java | 268 +- .../impl/DefaultMetaServerManagerTest.java | 84 +- .../metaserver/impl/LocalMetaServerTest.java | 290 +- .../monitor/DefaultSlotTableMonitorTest.java | 356 +- .../monitor/impl/DefaultSlotStatsTest.java | 83 +- .../impl/DefaultSlotTableStatsTest.java | 492 ++- .../data/DefaultProvideDataNotifierTest.java | 73 +- .../data/DefaultDataServerServiceTest.java | 308 +- .../handler/HeartbeatRequestHandlerTest.java | 196 +- .../DefaultSessionServerServiceTest.java | 149 +- .../meta/resource/SlotTableResourceTest.java | 139 +- .../filter/LeaderAwareFilterTest.java | 44 +- .../arrange/CrossDcSlotAllocatorTest.java | 248 +- .../arrange/ScheduledSlotArrangerTest.java | 143 +- .../slot/balance/DefaultSlotBalancerTest.java | 110 +- .../slot/balance/LeaderOnlyBalancerTest.java | 168 +- .../server/meta/slot/chaos/CheckerAction.java | 149 +- .../meta/slot/chaos/InjectionAction.java | 109 +- .../server/meta/slot/chaos/SlotChaosTest.java | 210 +- .../slot/manager/DefaultSlotManagerTest.java | 70 +- .../slot/manager/SimpleSlotManagerTest.java | 252 +- .../meta/slot/tasks/BalanceTaskTest.java | 139 +- .../tasks/SlotMigrationIntegrationTest.java | 634 +-- .../server/meta/slot/util/ListUtil.java | 58 +- .../meta/slot/util/MigrateSlotGroupTest.java | 96 +- .../meta/slot/util/NodeComparatorTest.java | 32 +- .../meta/slot/util/SlotBuilderTest.java | 130 +- .../meta/slot/util/SlotTableBuilderTest.java | 528 ++- .../slot/DiskSlotTableRecorderTest.java | 25 +- .../server/session/SessionApplication.java | 19 +- .../acceptor/ClientOffWriteDataRequest.java | 39 +- .../acceptor/PublisherWriteDataRequest.java | 38 +- .../session/acceptor/WriteDataAcceptor.java | 15 +- .../acceptor/WriteDataAcceptorImpl.java | 16 +- .../session/acceptor/WriteDataProcessor.java | 151 +- .../session/acceptor/WriteDataRequest.java | 32 +- .../session/bootstrap/CommonConfig.java | 110 +- .../bootstrap/SessionServerBootstrap.java | 655 ++- .../bootstrap/SessionServerConfig.java | 125 +- .../bootstrap/SessionServerConfigBean.java | 2047 ++++----- .../bootstrap/SessionServerConfiguration.java | 1343 +++--- .../bootstrap/SessionServerInitializer.java | 82 +- .../session/cache/CacheAccessException.java | 28 +- .../server/session/cache/CacheGenerator.java | 18 +- .../server/session/cache/CacheService.java | 31 +- .../session/cache/DatumCacheGenerator.java | 53 +- .../server/session/cache/DatumKey.java | 99 +- .../server/session/cache/EntityType.java | 20 +- .../registry/server/session/cache/Key.java | 102 +- .../session/cache/SessionCacheService.java | 180 +- .../registry/server/session/cache/Value.java | 35 +- .../connections/ConnectionsService.java | 104 +- .../converter/AppRegisterConstant.java | 15 +- .../server/session/converter/Converter.java | 9 +- .../session/converter/PublisherConverter.java | 87 +- .../converter/ReceivedDataConverter.java | 180 +- .../converter/SubscriberConverter.java | 122 +- .../converter/pb/AppRevisionConvertor.java | 71 +- .../converter/pb/DataBoxConvertor.java | 141 +- .../converter/pb/ListStringConvertor.java | 15 +- .../converter/pb/MetaServiceConvertor.java | 51 +- .../pb/PublisherRegisterConvertor.java | 130 +- .../converter/pb/ReceivedDataConvertor.java | 138 +- .../pb/RegisterResponseConvertor.java | 63 +- .../pb/SubscriberRegisterConvertor.java | 122 +- .../pb/SyncConfigRequestConvertor.java | 43 +- .../pb/SyncConfigResponseConvertor.java | 66 +- .../session/filter/DataIdMatchStrategy.java | 5 +- .../session/filter/IPMatchStrategy.java | 5 +- .../server/session/filter/ProcessFilter.java | 5 +- .../filter/blacklist/BlacklistConfig.java | 85 +- .../filter/blacklist/BlacklistConstants.java | 22 +- .../filter/blacklist/BlacklistManager.java | 48 +- .../blacklist/BlacklistManagerImpl.java | 278 +- .../BlacklistMatchProcessFilter.java | 179 +- .../blacklist/DefaultDataIdMatchStrategy.java | 18 +- .../blacklist/DefaultIPMatchStrategy.java | 78 +- .../session/filter/blacklist/MatchType.java | 91 +- .../session/limit/AccessLimitService.java | 8 +- .../session/limit/AccessLimitServiceImpl.java | 19 +- .../ProvideDataChangeFetchTaskListener.java | 95 +- .../ReceivedConfigDataPushTaskListener.java | 70 +- .../WatcherRegisterFetchTaskListener.java | 77 +- .../metadata/AppRevisionCacheRegistry.java | 106 +- .../AppRevisionHeartbeatRegistry.java | 47 +- .../session/metadata/MetadataMetrics.java | 64 +- .../ClientNodeSingleTaskProcessor.java | 32 +- .../ConsoleSyncSingleTaskProcessor.java | 46 +- .../DataNodeSingleTaskProcessor.java | 48 +- .../MetaNodeSingleTaskProcessor.java | 48 +- .../repository/AppRevisionRaftRepository.java | 160 +- .../node/service/AppRevisionNodeService.java | 7 +- .../service/AppRevisionNodeServiceImpl.java | 126 +- .../node/service/ClientNodeService.java | 5 +- .../node/service/ClientNodeServiceImpl.java | 44 +- .../session/node/service/DataNodeService.java | 75 +- .../node/service/DataNodeServiceImpl.java | 619 +-- .../node/service/MetaServerServiceImpl.java | 73 +- .../service/SessionMetaServerManager.java | 33 +- .../session/predicate/ZonePredicate.java | 43 +- .../provideData/ProvideDataProcessor.java | 12 +- .../ProvideDataProcessorManager.java | 50 +- .../BlackListProvideDataProcessor.java | 141 +- .../StopPushProvideDataProcessor.java | 70 +- .../server/session/push/ChangeProcessor.java | 274 +- .../server/session/push/FirePushService.java | 358 +- .../session/push/PushDataGenerator.java | 51 +- .../server/session/push/PushMetrics.java | 131 +- .../server/session/push/PushProcessor.java | 929 ++-- .../server/session/push/PushTrace.java | 238 +- .../server/session/registry/Registry.java | 77 +- .../session/registry/SessionRegistry.java | 653 ++- .../session/remoting/ClientNodeExchanger.java | 22 +- .../session/remoting/DataNodeExchanger.java | 105 +- .../handler/CancelAddressRequestHandler.java | 59 +- .../handler/ClientNodeConnectionHandler.java | 56 +- .../handler/ConfigureLoadbalanceHandler.java | 42 +- .../handler/DataChangeRequestHandler.java | 88 +- .../handler/DataPushRequestHandler.java | 41 +- .../DataSlotDiffDigestRequestHandler.java | 90 +- .../DataSlotDiffPublisherRequestHandler.java | 95 +- .../handler/GetRevisionPbHandler.java | 37 +- .../handler/LoadbalanceMetricsHandler.java | 33 +- .../handler/MetaNodeConnectionHandler.java | 11 +- .../MetaRevisionHeartbeatPbHandler.java | 55 +- .../handler/MetadataRegisterPbHandler.java | 36 +- .../NotifyProvideDataChangeHandler.java | 91 +- .../remoting/handler/PublisherHandler.java | 55 +- .../remoting/handler/PublisherPbHandler.java | 84 +- .../handler/ServiceAppMappingPbHandler.java | 37 +- .../remoting/handler/SubscriberHandler.java | 58 +- .../remoting/handler/SubscriberPbHandler.java | 106 +- .../remoting/handler/SyncConfigHandler.java | 42 +- .../remoting/handler/SyncConfigPbHandler.java | 85 +- .../remoting/handler/WatcherHandler.java | 61 +- .../session/resource/ClientsOpenResource.java | 49 +- .../session/resource/ConnectionsResource.java | 42 +- .../session/resource/HealthResource.java | 107 +- .../resource/SessionDigestResource.java | 434 +- .../session/resource/SessionOpenResource.java | 115 +- .../session/scheduler/ExecutorManager.java | 232 +- .../scheduler/task/AbstractSessionTask.java | 67 +- .../session/scheduler/task/Constant.java | 9 +- .../task/ProvideDataChangeFetchTask.java | 241 +- .../task/ReceivedConfigDataPushTask.java | 198 +- .../session/scheduler/task/SessionTask.java | 5 +- .../task/WatcherRegisterFetchTask.java | 193 +- .../scheduler/timertask/CacheCountTask.java | 168 +- .../timertask/SessionCacheDigestTask.java | 116 +- .../timertask/SyncClientsHeartbeatTask.java | 240 +- .../server/session/slot/SlotTableCache.java | 19 +- .../session/slot/SlotTableCacheImpl.java | 167 +- .../session/store/AbstractDataManager.java | 250 +- .../server/session/store/DataManager.java | 89 +- .../server/session/store/DataStore.java | 7 +- .../server/session/store/Interests.java | 57 +- .../session/store/SessionDataStore.java | 81 +- .../session/store/SessionInterests.java | 149 +- .../server/session/store/SessionWatchers.java | 76 +- .../session/store/SlotSessionDataStore.java | 235 +- .../server/session/store/StoreHelpers.java | 99 +- .../server/session/store/Watchers.java | 22 +- .../strategy/AppRevisionHandlerStrategy.java | 52 +- .../DefaultAppRevisionHandlerStrategy.java | 171 +- .../strategy/PublisherHandlerStrategy.java | 5 +- .../ReceivedConfigDataPushTaskStrategy.java | 2 +- .../strategy/SessionRegistryStrategy.java | 12 +- .../strategy/SubscriberHandlerStrategy.java | 5 +- .../strategy/SyncConfigHandlerStrategy.java | 2 +- .../strategy/WatcherHandlerStrategy.java | 7 +- .../impl/DefaultPublisherHandlerStrategy.java | 130 +- ...ultReceivedConfigDataPushTaskStrategy.java | 16 +- .../impl/DefaultSessionRegistryStrategy.java | 76 +- .../DefaultSubscriberHandlerStrategy.java | 132 +- .../DefaultSyncConfigHandlerStrategy.java | 13 +- .../impl/DefaultWatcherHandlerStrategy.java | 124 +- .../session/strategy/impl/RegisterLogs.java | 31 +- .../AccessLimitWrapperInterceptor.java | 37 +- .../wrapper/BlacklistWrapperInterceptor.java | 58 +- .../ClientCheckWrapperInterceptor.java | 40 +- .../server/session/wrapper/Wrapper.java | 7 +- .../session/wrapper/WrapperInterceptor.java | 30 +- .../wrapper/WrapperInterceptorManager.java | 77 +- .../session/wrapper/WrapperInvocation.java | 51 +- .../server/session/WrapperInvocationTest.java | 169 +- .../server/session/store/BaseTest.java | 4 +- .../server/session/store/DataCacheTest.java | 859 ++-- .../shared/comparator/AbstractComparator.java | 130 +- .../server/shared/comparator/Comparator.java | 22 +- .../shared/comparator/ComparatorVisitor.java | 11 +- .../shared/comparator/NodeComparator.java | 41 +- .../shared/config/DefaultSlotTableConfig.java | 27 +- .../server/shared/config/SlotTableConfig.java | 29 +- .../registry/server/shared/env/ServerEnv.java | 110 +- .../meta/AbstractMetaServerManager.java | 330 +- .../meta/AbstractMetaServerService.java | 334 +- .../server/shared/meta/MetaServerManager.java | 14 +- .../server/shared/meta/MetaServerService.java | 52 +- .../remoting/AbstractChannelHandler.java | 174 +- .../remoting/AbstractClientHandler.java | 13 +- .../remoting/AbstractServerHandler.java | 13 +- .../shared/remoting/ClientSideExchanger.java | 288 +- .../remoting/ListenClientChannelHandler.java | 33 +- .../remoting/ListenServerChannelHandler.java | 33 +- .../shared/remoting/RemotingHelper.java | 11 +- .../shared/remoting/ServerSideExchanger.java | 121 +- .../remoting/SlotTableChangeEventHandler.java | 59 +- .../shared/resource/MetricsResource.java | 34 +- .../shared/resource/SlotGenericResource.java | 44 +- .../shared/slot/DiskSlotTableRecorder.java | 26 +- .../server/shared/slot/SlotTableRecorder.java | 5 +- .../server/shared/slot/SlotTableUtils.java | 98 +- .../server/shared/util/AddressUtil.java | 68 +- .../server/shared/util/DatumUtils.java | 94 +- .../server/shared/util/NodeUtils.java | 25 +- .../server/shared/util/DatumUtilsTest.java | 25 +- .../sofa/registry/store/api/DBResponse.java | 273 +- .../registry/store/api/OperationStatus.java | 16 +- .../store/api/annotation/ReadOnLeader.java | 10 +- .../store/api/driver/RegistryRepository.java | 16 +- .../store/api/driver/RepositoryConfig.java | 64 +- .../store/api/driver/RepositoryManager.java | 126 +- .../api/elector/AbstractLeaderElector.java | 316 +- .../store/api/elector/LeaderAware.java | 15 +- .../store/api/elector/LeaderElector.java | 90 +- .../store/api/meta/ProvideDataRepository.java | 54 +- .../AppRevisionHeartbeatRepository.java | 16 +- .../api/repository/AppRevisionRepository.java | 45 +- .../repository/InterfaceAppsRepository.java | 54 +- .../store/api/spring/SpringContext.java | 9 +- .../jdbc/config/JdbcConfiguration.java | 346 +- .../jdbc/config/JdbcDriverConfig.java | 28 +- .../jdbc/config/JdbcDriverConfigBean.java | 382 +- .../jdbc/config/MetaElectorConfig.java | 7 +- .../jdbc/config/MetaElectorConfigBean.java | 69 +- .../registry/jdbc/config/MetadataConfig.java | 7 +- .../jdbc/config/MetadataConfigBean.java | 76 +- .../convertor/AppRevisionDomainConvertor.java | 89 +- .../domain/AppInterfaceIndexQueryModel.java | 115 +- .../jdbc/domain/AppRevisionDomain.java | 409 +- .../jdbc/domain/AppRevisionQueryModel.java | 115 +- .../jdbc/domain/DistributeLockDomain.java | 418 +- .../jdbc/domain/FollowCompeteLockDomain.java | 252 +- .../domain/InterfaceAppIndexQueryModel.java | 117 +- .../jdbc/domain/InterfaceAppsIndexDomain.java | 377 +- .../jdbc/domain/ProvideDataDomain.java | 291 +- .../jdbc/elector/MetaJdbcLeaderElector.java | 297 +- .../exception/AppInterfaceQueryException.java | 12 +- .../exception/InterfaceAppQueryException.java | 12 +- .../exception/RevisionNotExistException.java | 12 +- .../jdbc/mapper/AppRevisionMapper.java | 103 +- .../jdbc/mapper/DistributeLockMapper.java | 65 +- .../jdbc/mapper/InterfaceAppsIndexMapper.java | 89 +- .../jdbc/mapper/ProvideDataMapper.java | 36 +- .../jdbc/repository/JdbcRepository.java | 11 +- .../batch/AppRevisionBatchQueryCallable.java | 105 +- .../AppRevisionHeartbeatBatchCallable.java | 90 +- .../batch/InterfaceAppBatchQueryCallable.java | 124 +- .../AppRevisionHeartbeatJdbcRepository.java | 171 +- .../impl/AppRevisionJdbcRepository.java | 270 +- .../impl/InterfaceAppsJdbcRepository.java | 345 +- .../impl/ProvideDataJdbcRepository.java | 53 +- .../registry/jdbc/AbstractH2DbTestBase.java | 150 +- .../sofa/registry/jdbc/AbstractTest.java | 375 +- .../elector/MetaJdbcLeaderElectorTest.java | 41 +- .../impl/ProvideDataJdbcRepositoryTest.java | 31 +- .../registry/jraft/command/CommandCodec.java | 54 +- .../jraft/command/NotifyLeaderChange.java | 87 +- .../jraft/command/ProcessRequest.java | 196 +- .../jraft/command/ProcessResponse.java | 302 +- .../jraft/config/RaftConfiguration.java | 24 +- .../AppRevisionHeartbeatRaftRepository.java | 19 +- .../impl/InterfaceAppsRaftRepository.java | 52 +- .../jraft/repository/impl/RaftRepository.java | 11 +- .../jraft/revision/AppRevisionRegistry.java | 36 +- .../jraft/revision/AppRevisionService.java | 23 +- .../server/test/TestRegistryMain.java | 74 +- .../integration/RegistryApplicationTest.java | 4 +- .../server/integration/RegistryConsumer.java | 67 +- .../server/integration/RegistryProvider.java | 52 +- .../sofa/registry/test/AbstractTest.java | 375 +- .../registry/test/BaseIntegrationTest.java | 380 +- .../test/elector/MetaElectorTest.java | 283 +- .../test/elector/ProvideDataTest.java | 37 +- .../registry/test/metadata/MetadataTest.java | 291 +- .../sofa/registry/test/pubsub/PubSubTest.java | 338 +- .../test/pubsub/TempPublisherTest.java | 245 +- .../test/resource/HealthCheckTest.java | 51 +- .../resource/data/DataDigestResourceTest.java | 254 +- .../resource/data/DatumApiResourceTest.java | 500 ++- .../test/resource/meta/BlacklistTest.java | 289 +- .../resource/meta/MetaDigestResourceTest.java | 63 +- .../meta/ProvideDataResourceTest.java | 49 +- .../resource/meta/StopPushDataSwitchTest.java | 140 +- .../session/ClientsOpenResourceTest.java | 46 +- .../session/SessionDigestResourceTest.java | 313 +- .../session/SessionOpenResourceTest.java | 61 +- tools/codestyle/HEADER | 30 +- tools/codestyle/formatter.xml | 295 -- 884 files changed, 73205 insertions(+), 73668 deletions(-) delete mode 100644 tools/codestyle/formatter.xml diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/ConfigDataObserver.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/ConfigDataObserver.java index a3c4d1cca..f1b782a00 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/ConfigDataObserver.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/ConfigDataObserver.java @@ -20,20 +20,17 @@ /** * The interface Persistence data observer. - * + * * @author zhuoyu.sjw - * @version $Id : ConfigDataObserver.java, v 0.1 2018-04-17 17:02 zhuoyu.sjw Exp - * $$ + * @version $Id : ConfigDataObserver.java, v 0.1 2018-04-17 17:02 zhuoyu.sjw Exp $$ */ public interface ConfigDataObserver { - /** - * Handle data. - * - * @param dataId - * the data id - * @param configData - * the persistence data - */ - void handleData(String dataId, ConfigData configData); + /** + * Handle data. + * + * @param dataId the data id + * @param configData the persistence data + */ + void handleData(String dataId, ConfigData configData); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/Configurator.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/Configurator.java index 5b5c1b7fe..4766141a9 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/Configurator.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/Configurator.java @@ -20,31 +20,30 @@ /** * The interface Configurator. - * + * * @author zhuoyu.sjw * @version $Id : Configurator.java, v 0.1 2018-04-17 17:26 zhuoyu.sjw Exp $$ */ public interface Configurator extends Register { - /** - * Gets data observer. - * - * @return the data observer - */ - ConfigDataObserver getDataObserver(); + /** + * Gets data observer. + * + * @return the data observer + */ + ConfigDataObserver getDataObserver(); - /** - * Sets config data observer. - * - * @param configDataObserver - * the config data observer - */ - void setDataObserver(ConfigDataObserver configDataObserver); + /** + * Sets config data observer. + * + * @param configDataObserver the config data observer + */ + void setDataObserver(ConfigDataObserver configDataObserver); - /** - * Peek data config data. - * - * @return the config data - */ - ConfigData peekData(); + /** + * Peek data config data. + * + * @return the config data + */ + ConfigData peekData(); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/EventBus.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/EventBus.java index f9ded1234..db26ab24a 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/EventBus.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/EventBus.java @@ -20,46 +20,47 @@ /** * The interface Event bus. + * * @author zhuoyu.sjw * @version $Id : EventBus.java, v 0.1 2018-07-12 21:11 zhuoyu.sjw Exp $$ */ public interface EventBus { - /** - * Is enable boolean. - * - * @return the boolean - */ - boolean isEnable(); + /** + * Is enable boolean. + * + * @return the boolean + */ + boolean isEnable(); - /** - * Is enable boolean. - * - * @param eventClass the event class - * @return the boolean - */ - boolean isEnable(Class eventClass); + /** + * Is enable boolean. + * + * @param eventClass the event class + * @return the boolean + */ + boolean isEnable(Class eventClass); - /** - * Register. - * - * @param eventClass the event class - * @param eventSubscriber the event subscriber - */ - void register(Class eventClass, EventSubscriber eventSubscriber); + /** + * Register. + * + * @param eventClass the event class + * @param eventSubscriber the event subscriber + */ + void register(Class eventClass, EventSubscriber eventSubscriber); - /** - * Un register. - * - * @param eventClass the event class - * @param eventSubscriber the event subscriber - */ - void unRegister(Class eventClass, EventSubscriber eventSubscriber); + /** + * Un register. + * + * @param eventClass the event class + * @param eventSubscriber the event subscriber + */ + void unRegister(Class eventClass, EventSubscriber eventSubscriber); - /** - * Post event. - * - * @param event the event - */ - void post(final Event event); + /** + * Post event. + * + * @param event the event + */ + void post(final Event event); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/EventSubscriber.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/EventSubscriber.java index 8debf30fb..b6557c51e 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/EventSubscriber.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/EventSubscriber.java @@ -20,24 +20,23 @@ /** * The interface Event subscriber. - * + * * @author zhuoyu.sjw * @version $Id : EventSubscriber.java, v 0.1 2018-07-12 21:12 zhuoyu.sjw Exp $$ */ public interface EventSubscriber { - /** - * Is sync boolean. - * - * @return the boolean - */ - boolean isSync(); + /** + * Is sync boolean. + * + * @return the boolean + */ + boolean isSync(); - /** - * On event. - * - * @param event - * the event - */ - void onEvent(Event event); + /** + * On event. + * + * @param event the event + */ + void onEvent(Event event); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/Publisher.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/Publisher.java index 45330b543..c21b843e3 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/Publisher.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/Publisher.java @@ -24,10 +24,10 @@ */ public interface Publisher extends Register { - /** - * Publish. - * - * @param data the data - */ - void republish(String... data); + /** + * Publish. + * + * @param data the data + */ + void republish(String... data); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/Register.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/Register.java index 6917d964d..98abc196c 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/Register.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/Register.java @@ -18,61 +18,57 @@ /** * The interface Register. - * + * * @author zhuoyu.sjw * @version $Id : Register.java, v 0.1 2017-11-22 16:00 zhuoyu.sjw Exp $$ */ public interface Register { - /** - * Reset. - */ - void reset(); + /** Reset. */ + void reset(); - /** - * Is registered boolean. - * - * @return the boolean - */ - boolean isRegistered(); + /** + * Is registered boolean. + * + * @return the boolean + */ + boolean isRegistered(); - /** - * Unregister. - */ - void unregister(); + /** Unregister. */ + void unregister(); - /** - * Gets data id. - * - * @return String data id - */ - String getDataId(); + /** + * Gets data id. + * + * @return String data id + */ + String getDataId(); - /** - * Gets group. - * - * @return the group - */ - String getGroup(); + /** + * Gets group. + * + * @return the group + */ + String getGroup(); - /** - * Gets regist id. - * - * @return the regist id - */ - String getRegistId(); + /** + * Gets regist id. + * + * @return the regist id + */ + String getRegistId(); - /** - * Is enabled boolean. - * - * @return boolean boolean - */ - boolean isEnabled(); + /** + * Is enabled boolean. + * + * @return boolean boolean + */ + boolean isEnabled(); - /** - * Gets timestamp. - * - * @return the timestamp - */ - long getTimestamp(); + /** + * Gets timestamp. + * + * @return the timestamp + */ + long getTimestamp(); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/RegistryClient.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/RegistryClient.java index 29d3ac8cc..8ac8d008c 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/RegistryClient.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/RegistryClient.java @@ -23,43 +23,44 @@ /** * The interface Registry client. + * * @author zhuoyu.sjw * @version $Id : RegistryClient.java, v 0.1 2017-11-20 18:16 zhuoyu.sjw Exp $$ */ public interface RegistryClient { - /** - * Register publisher. - * - * @param registration the registration - * @param data the data - * @return the publisher - */ - Publisher register(PublisherRegistration registration, String... data); + /** + * Register publisher. + * + * @param registration the registration + * @param data the data + * @return the publisher + */ + Publisher register(PublisherRegistration registration, String... data); - /** - * Register multi subscriber multi. - * - * @param registration the registration - * @return the subscriber multi - */ - Subscriber register(SubscriberRegistration registration); + /** + * Register multi subscriber multi. + * + * @param registration the registration + * @return the subscriber multi + */ + Subscriber register(SubscriberRegistration registration); - /** - * Register configurator. - * - * @param registration the registration - * @return the configurator - */ - Configurator register(ConfiguratorRegistration registration); + /** + * Register configurator. + * + * @param registration the registration + * @return the configurator + */ + Configurator register(ConfiguratorRegistration registration); - /** - * Unregister all publishers or subscribers belong to dataId. - * - * @param dataId the data id - * @param group registration group, use default group if null - * @param registryType the registry type, publisher or subscriber - * @return unregister total registers - */ - int unregister(String dataId, String group, RegistryType registryType); + /** + * Unregister all publishers or subscribers belong to dataId. + * + * @param dataId the data id + * @param group registration group, use default group if null + * @param registryType the registry type, publisher or subscriber + * @return unregister total registers + */ + int unregister(String dataId, String group, RegistryType registryType); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/RegistryClientConfig.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/RegistryClientConfig.java index fa29462d7..efa4393d4 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/RegistryClientConfig.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/RegistryClientConfig.java @@ -18,157 +18,156 @@ /** * The interface Registry client config. - * + * * @author zhuoyu.sjw - * @version $Id : RegistryClientConfig.java, v 0.1 2017-11-23 19:52 zhuoyu.sjw - * Exp $$ + * @version $Id : RegistryClientConfig.java, v 0.1 2017-11-23 19:52 zhuoyu.sjw Exp $$ */ public interface RegistryClientConfig { - /** - * Gets env. - * - * @return the env - */ - String getEnv(); - - /** - * Gets instance id. - * - * @return the instance id - */ - String getInstanceId(); - - /** - * Gets cell. - * - * @return the cell - */ - String getZone(); - - /** - * Gets registry endpoint. - * - * @return the registry endpoint - */ - String getRegistryEndpoint(); - - /** - * Gets registry endpoint port. - * - * @return the registry endpoint port - */ - int getRegistryEndpointPort(); - - /** - * Gets data center. - * - * @return the data center - */ - String getDataCenter(); - - /** - * Gets app name. - * - * @return the app name - */ - String getAppName(); - - /** - * Gets connect timeout. - * - * @return the connect timeout - */ - int getConnectTimeout(); - - /** - * Gets socket timeout. - * - * @return the socket timeout - */ - int getSocketTimeout(); - - /** - * Gets invoke timeout. - * - * @return the invoke timeout - */ - int getInvokeTimeout(); - - /** - * Gets recheck interval. - * - * @return the recheck interval - */ - int getRecheckInterval(); - - /** - * Gets observer thread core size. - * - * @return the observer thread core size - */ - int getObserverThreadCoreSize(); - - /** - * Gets observer thread max size. - * - * @return the observer thread max size - */ - int getObserverThreadMaxSize(); - - /** - * Gets observer thread queue length. - * - * @return the observer thread queue length - */ - int getObserverThreadQueueLength(); - - /** - * Gets observer callback timeout. - * - * @return the observer callback timeout - */ - int getObserverCallbackTimeout(); - - /** - * Gets sync config retry interval. - * - * @return the sync config retry interval - */ - int getSyncConfigRetryInterval(); - - /** - * Gets access key. - * - * @return the access key - */ - String getAccessKey(); - - /** - * Gets secret key. - * - * @return the secret key - */ - String getSecretKey(); - - /** - * Gets algorithm. - * - * @return the algorithm - */ - String getAlgorithm(); - - /** - * Gets auth cache interval. - * - * @return the auth cache interval - */ - long getAuthCacheInterval(); - - /** - * Is event bus enable boolean. - * - * @return the boolean - */ - boolean isEventBusEnable(); + /** + * Gets env. + * + * @return the env + */ + String getEnv(); + + /** + * Gets instance id. + * + * @return the instance id + */ + String getInstanceId(); + + /** + * Gets cell. + * + * @return the cell + */ + String getZone(); + + /** + * Gets registry endpoint. + * + * @return the registry endpoint + */ + String getRegistryEndpoint(); + + /** + * Gets registry endpoint port. + * + * @return the registry endpoint port + */ + int getRegistryEndpointPort(); + + /** + * Gets data center. + * + * @return the data center + */ + String getDataCenter(); + + /** + * Gets app name. + * + * @return the app name + */ + String getAppName(); + + /** + * Gets connect timeout. + * + * @return the connect timeout + */ + int getConnectTimeout(); + + /** + * Gets socket timeout. + * + * @return the socket timeout + */ + int getSocketTimeout(); + + /** + * Gets invoke timeout. + * + * @return the invoke timeout + */ + int getInvokeTimeout(); + + /** + * Gets recheck interval. + * + * @return the recheck interval + */ + int getRecheckInterval(); + + /** + * Gets observer thread core size. + * + * @return the observer thread core size + */ + int getObserverThreadCoreSize(); + + /** + * Gets observer thread max size. + * + * @return the observer thread max size + */ + int getObserverThreadMaxSize(); + + /** + * Gets observer thread queue length. + * + * @return the observer thread queue length + */ + int getObserverThreadQueueLength(); + + /** + * Gets observer callback timeout. + * + * @return the observer callback timeout + */ + int getObserverCallbackTimeout(); + + /** + * Gets sync config retry interval. + * + * @return the sync config retry interval + */ + int getSyncConfigRetryInterval(); + + /** + * Gets access key. + * + * @return the access key + */ + String getAccessKey(); + + /** + * Gets secret key. + * + * @return the secret key + */ + String getSecretKey(); + + /** + * Gets algorithm. + * + * @return the algorithm + */ + String getAlgorithm(); + + /** + * Gets auth cache interval. + * + * @return the auth cache interval + */ + long getAuthCacheInterval(); + + /** + * Is event bus enable boolean. + * + * @return the boolean + */ + boolean isEventBusEnable(); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/Subscriber.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/Subscriber.java index fd844ea8f..61632f3e5 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/Subscriber.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/Subscriber.java @@ -21,38 +21,37 @@ /** * The interface Subscriber multi. - * + * * @author zhuoyu.sjw * @version $Id : Subscriber.java, v 0.1 2017-11-23 14:35 zhuoyu.sjw Exp $$ */ public interface Subscriber extends Register { - /** - * Gets data observer. - * - * @return the data observer - */ - SubscriberDataObserver getDataObserver(); + /** + * Gets data observer. + * + * @return the data observer + */ + SubscriberDataObserver getDataObserver(); - /** - * Sets data observer. - * - * @param observer - * the observer - */ - void setDataObserver(SubscriberDataObserver observer); + /** + * Sets data observer. + * + * @param observer the observer + */ + void setDataObserver(SubscriberDataObserver observer); - /** - * Peek data user data multi. - * - * @return the user data multi - */ - UserData peekData(); + /** + * Peek data user data multi. + * + * @return the user data multi + */ + UserData peekData(); - /** - * Gets scope enum. - * - * @return the scope enum - */ - ScopeEnum getScopeEnum(); + /** + * Gets scope enum. + * + * @return the scope enum + */ + ScopeEnum getScopeEnum(); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/SubscriberDataObserver.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/SubscriberDataObserver.java index 55713a153..d68f15275 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/SubscriberDataObserver.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/SubscriberDataObserver.java @@ -20,20 +20,17 @@ /** * The interface Subscriber data observer multi. - * + * * @author zhuoyu.sjw - * @version $Id : SubscriberDataObserver.java, v 0.1 2017-11-23 15:16 zhuoyu.sjw - * Exp $$ + * @version $Id : SubscriberDataObserver.java, v 0.1 2017-11-23 15:16 zhuoyu.sjw Exp $$ */ public interface SubscriberDataObserver { - /** - * Handle data. - * - * @param dataId - * the data id - * @param data - * the data - */ - void handleData(String dataId, UserData data); + /** + * Handle data. + * + * @param dataId the data id + * @param data the data + */ + void handleData(String dataId, UserData data); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/exception/DuplicateException.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/exception/DuplicateException.java index c676670b7..f927f723b 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/exception/DuplicateException.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/exception/DuplicateException.java @@ -18,51 +18,43 @@ /** * The type Duplicate exception. - * + * * @author zhuoyu.sjw - * @version $Id : DuplicateException.java, v 0.1 2017-11-30 19:46 zhuoyu.sjw Exp - * $$ + * @version $Id : DuplicateException.java, v 0.1 2017-11-30 19:46 zhuoyu.sjw Exp $$ */ public class DuplicateException extends IllegalArgumentException { - /** UID */ - private static final long serialVersionUID = 167969795120169890L; + /** UID */ + private static final long serialVersionUID = 167969795120169890L; - /** - * Instantiates a new Duplicate exception. - */ - public DuplicateException() { - } + /** Instantiates a new Duplicate exception. */ + public DuplicateException() {} - /** - * Instantiates a new Duplicate exception. - * - * @param s - * the s - */ - public DuplicateException(String s) { - super(s); - } + /** + * Instantiates a new Duplicate exception. + * + * @param s the s + */ + public DuplicateException(String s) { + super(s); + } - /** - * Instantiates a new Duplicate exception. - * - * @param message - * the message - * @param cause - * the cause - */ - public DuplicateException(String message, Throwable cause) { - super(message, cause); - } + /** + * Instantiates a new Duplicate exception. + * + * @param message the message + * @param cause the cause + */ + public DuplicateException(String message, Throwable cause) { + super(message, cause); + } - /** - * Instantiates a new Duplicate exception. - * - * @param cause - * the cause - */ - public DuplicateException(Throwable cause) { - super(cause); - } + /** + * Instantiates a new Duplicate exception. + * + * @param cause the cause + */ + public DuplicateException(Throwable cause) { + super(cause); + } } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/exception/RegistryClientException.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/exception/RegistryClientException.java index a9fb3f49a..304a6e5cb 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/exception/RegistryClientException.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/exception/RegistryClientException.java @@ -18,51 +18,43 @@ /** * The type Registry client exception. - * + * * @author zhuoyu.sjw - * @version $Id : RegistryClientException.java, v 0.1 2017-11-30 19:43 - * zhuoyu.sjw Exp $$ + * @version $Id : RegistryClientException.java, v 0.1 2017-11-30 19:43 zhuoyu.sjw Exp $$ */ public class RegistryClientException extends RuntimeException { - /** UID */ - private static final long serialVersionUID = -1068018180829676315L; + /** UID */ + private static final long serialVersionUID = -1068018180829676315L; - /** - * Instantiates a new Registry client exception. - */ - public RegistryClientException() { - } + /** Instantiates a new Registry client exception. */ + public RegistryClientException() {} - /** - * Instantiates a new Registry client exception. - * - * @param message - * the message - */ - public RegistryClientException(String message) { - super(message); - } + /** + * Instantiates a new Registry client exception. + * + * @param message the message + */ + public RegistryClientException(String message) { + super(message); + } - /** - * Instantiates a new Registry client exception. - * - * @param message - * the message - * @param cause - * the cause - */ - public RegistryClientException(String message, Throwable cause) { - super(message, cause); - } + /** + * Instantiates a new Registry client exception. + * + * @param message the message + * @param cause the cause + */ + public RegistryClientException(String message, Throwable cause) { + super(message, cause); + } - /** - * Instantiates a new Registry client exception. - * - * @param cause - * the cause - */ - public RegistryClientException(Throwable cause) { - super(cause); - } + /** + * Instantiates a new Registry client exception. + * + * @param cause the cause + */ + public RegistryClientException(Throwable cause) { + super(cause); + } } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/ConfigData.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/ConfigData.java index 3854e3759..a2a6d0f83 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/ConfigData.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/ConfigData.java @@ -18,16 +18,16 @@ /** * The interface Persistence data. - * + * * @author zhuoyu.sjw * @version $Id : ConfigData.java, v 0.1 2018-04-17 17:15 zhuoyu.sjw Exp $$ */ public interface ConfigData { - /** - * Gets data. - * - * @return the data - */ - String getData(); + /** + * Gets data. + * + * @return the data + */ + String getData(); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/Event.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/Event.java index 2c4382abf..bcdcd03d6 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/Event.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/Event.java @@ -18,9 +18,8 @@ /** * The interface Event. - * + * * @author zhuoyu.sjw * @version $Id : Event.java, v 0.1 2018-07-12 21:10 zhuoyu.sjw Exp $$ */ -public interface Event { -} +public interface Event {} diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/RegistryType.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/RegistryType.java index 057ba3be8..3cfa5cea8 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/RegistryType.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/RegistryType.java @@ -17,11 +17,11 @@ package com.alipay.sofa.registry.client.api.model; /** - * * @author zhuoyu.sjw * @version $Id: RegistryType.java, v 0.1 2018-03-13 15:22 zhuoyu.sjw Exp $$ */ public enum RegistryType { - - PUBLISHER, SUBSCRIBER, CONFIGURATOR + PUBLISHER, + SUBSCRIBER, + CONFIGURATOR } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/UserData.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/UserData.java index 46cc2eabd..bec41f8d7 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/UserData.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/model/UserData.java @@ -27,17 +27,17 @@ */ public interface UserData { - /** - * Getter method for property zoneData. - * - * @return property value of zoneData - */ - Map> getZoneData(); + /** + * Getter method for property zoneData. + * + * @return property value of zoneData + */ + Map> getZoneData(); - /** - * Gets local zone. - * - * @return the local zone - */ - String getLocalZone(); + /** + * Gets local zone. + * + * @return the local zone + */ + String getLocalZone(); } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/BaseRegistration.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/BaseRegistration.java index c7e10bf7f..9ce8ed215 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/BaseRegistration.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/BaseRegistration.java @@ -18,77 +18,85 @@ /** * Base registration. + * * @author yeqing.yq * @version $Id : BaseRegistration.java, v 0.1 2018-09-04 11:36 yeqing.yq Exp $$ */ public class BaseRegistration { - protected String dataId; + protected String dataId; - protected String group; + protected String group; - protected String appName; + protected String appName; - /** - * Getter method for property dataId. - * - * @return property value of dataId - */ - public String getDataId() { - return dataId; - } + /** + * Getter method for property dataId. + * + * @return property value of dataId + */ + public String getDataId() { + return dataId; + } - /** - * Setter method for property dataId. - * - * @param dataId value to be assigned to property dataId - */ - public void setDataId(String dataId) { - this.dataId = dataId; - } + /** + * Setter method for property dataId. + * + * @param dataId value to be assigned to property dataId + */ + public void setDataId(String dataId) { + this.dataId = dataId; + } - /** - * Getter method for property group. - * - * @return property value of group - */ - public String getGroup() { - return group; - } + /** + * Getter method for property group. + * + * @return property value of group + */ + public String getGroup() { + return group; + } - /** - * Setter method for property group. - * - * @param group value to be assigned to property group - */ - public void setGroup(String group) { - this.group = group; - } + /** + * Setter method for property group. + * + * @param group value to be assigned to property group + */ + public void setGroup(String group) { + this.group = group; + } - /** - * Getter method for property appName. - * - * @return property value of appName - */ - public String getAppName() { - return appName; - } + /** + * Getter method for property appName. + * + * @return property value of appName + */ + public String getAppName() { + return appName; + } - /** - * Setter method for property appName. - * - * @param appName value to be assigned to property appName - */ - public void setAppName(String appName) { - this.appName = appName; - } + /** + * Setter method for property appName. + * + * @param appName value to be assigned to property appName + */ + public void setAppName(String appName) { + this.appName = appName; + } - /** - * @see Object#toString() - */ - @Override - public String toString() { - return "BaseRegistration{" + "dataId='" + dataId + '\'' + ", group='" + group + '\'' - + ", appName='" + appName + '\'' + '}'; - } + /** @see Object#toString() */ + @Override + public String toString() { + return "BaseRegistration{" + + "dataId='" + + dataId + + '\'' + + ", group='" + + group + + '\'' + + ", appName='" + + appName + + '\'' + + '}'; + } } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/ConfiguratorRegistration.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/ConfiguratorRegistration.java index 7e44be10b..48c723cce 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/ConfiguratorRegistration.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/ConfiguratorRegistration.java @@ -20,48 +20,56 @@ /** * The type Configurator registration. + * * @author zhuoyu.sjw * @version $Id : ConfiguratorRegistration.java, v 0.1 2018-04-20 11:36 zhuoyu.sjw Exp $$ */ public class ConfiguratorRegistration extends BaseRegistration { - private ConfigDataObserver configDataObserver; + private ConfigDataObserver configDataObserver; - /** - * Instantiates a new Configurator registration. - * - * @param dataId the data id - * @param configDataObserver the config data observer - */ - public ConfiguratorRegistration(String dataId, ConfigDataObserver configDataObserver) { - this.dataId = dataId; - this.configDataObserver = configDataObserver; - } + /** + * Instantiates a new Configurator registration. + * + * @param dataId the data id + * @param configDataObserver the config data observer + */ + public ConfiguratorRegistration(String dataId, ConfigDataObserver configDataObserver) { + this.dataId = dataId; + this.configDataObserver = configDataObserver; + } - /** - * Getter method for property configDataObserver. - * - * @return property value of configDataObserver - */ - public ConfigDataObserver getConfigDataObserver() { - return configDataObserver; - } + /** + * Getter method for property configDataObserver. + * + * @return property value of configDataObserver + */ + public ConfigDataObserver getConfigDataObserver() { + return configDataObserver; + } - /** - * Setter method for property configDataObserver. - * - * @param configDataObserver value to be assigned to property configDataObserver - */ - public void setConfigDataObserver(ConfigDataObserver configDataObserver) { - this.configDataObserver = configDataObserver; - } + /** + * Setter method for property configDataObserver. + * + * @param configDataObserver value to be assigned to property configDataObserver + */ + public void setConfigDataObserver(ConfigDataObserver configDataObserver) { + this.configDataObserver = configDataObserver; + } - /** - * @see Object#toString() - */ - @Override - public String toString() { - return "ConfiguratorRegistration{" + "dataId='" + dataId + '\'' + ", group='" + group - + '\'' + ", appName='" + appName + '\'' + '}'; - } + /** @see Object#toString() */ + @Override + public String toString() { + return "ConfiguratorRegistration{" + + "dataId='" + + dataId + + '\'' + + ", group='" + + group + + '\'' + + ", appName='" + + appName + + '\'' + + '}'; + } } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/PublisherRegistration.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/PublisherRegistration.java index 8194b77c5..9dcc07710 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/PublisherRegistration.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/PublisherRegistration.java @@ -24,23 +24,32 @@ */ public class PublisherRegistration extends BaseRegistration { - /** - * Instantiates a new Publisher registration. - * - * @param dataId the data id - */ - public PublisherRegistration(String dataId) { - this.dataId = dataId; - } + /** + * Instantiates a new Publisher registration. + * + * @param dataId the data id + */ + public PublisherRegistration(String dataId) { + this.dataId = dataId; + } - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "PublisherRegistration{" + "dataId='" + dataId + '\'' + ", group='" + group + '\'' - + ", appName='" + appName + '\'' + '}'; - } + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "PublisherRegistration{" + + "dataId='" + + dataId + + '\'' + + ", group='" + + group + + '\'' + + ", appName='" + + appName + + '\'' + + '}'; + } } diff --git a/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/SubscriberRegistration.java b/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/SubscriberRegistration.java index 83037d3c9..6534795a4 100644 --- a/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/SubscriberRegistration.java +++ b/client/api/src/main/java/com/alipay/sofa/registry/client/api/registration/SubscriberRegistration.java @@ -27,66 +27,78 @@ */ public class SubscriberRegistration extends BaseRegistration { - private ScopeEnum scopeEnum; + private ScopeEnum scopeEnum; - private SubscriberDataObserver subscriberDataObserver; + private SubscriberDataObserver subscriberDataObserver; - /** - * Instantiates a new Subscriber registration. - * - * @param dataId the data id - * @param subscriberDataObserver the subscriber data observer - */ - public SubscriberRegistration(String dataId, SubscriberDataObserver subscriberDataObserver) { - this.dataId = dataId; - this.subscriberDataObserver = subscriberDataObserver; - } + /** + * Instantiates a new Subscriber registration. + * + * @param dataId the data id + * @param subscriberDataObserver the subscriber data observer + */ + public SubscriberRegistration(String dataId, SubscriberDataObserver subscriberDataObserver) { + this.dataId = dataId; + this.subscriberDataObserver = subscriberDataObserver; + } - /** - * Getter method for property scopeEnum. - * - * @return property value of scopeEnum - */ - public ScopeEnum getScopeEnum() { - return scopeEnum; - } + /** + * Getter method for property scopeEnum. + * + * @return property value of scopeEnum + */ + public ScopeEnum getScopeEnum() { + return scopeEnum; + } - /** - * Setter method for property scopeEnum. - * - * @param scopeEnum value to be assigned to property scopeEnum - */ - public void setScopeEnum(ScopeEnum scopeEnum) { - this.scopeEnum = scopeEnum; - } + /** + * Setter method for property scopeEnum. + * + * @param scopeEnum value to be assigned to property scopeEnum + */ + public void setScopeEnum(ScopeEnum scopeEnum) { + this.scopeEnum = scopeEnum; + } - /** - * Getter method for property subscriberDataObserver. - * - * @return property value of subscriberDataObserver - */ - public SubscriberDataObserver getSubscriberDataObserver() { - return subscriberDataObserver; - } + /** + * Getter method for property subscriberDataObserver. + * + * @return property value of subscriberDataObserver + */ + public SubscriberDataObserver getSubscriberDataObserver() { + return subscriberDataObserver; + } - /** - * Setter method for property subscriberDataObserver. - * - * @param subscriberDataObserver value to be assigned to property subscriberDataObserver - */ - public void setSubscriberDataObserver(SubscriberDataObserver subscriberDataObserver) { - this.subscriberDataObserver = subscriberDataObserver; - } + /** + * Setter method for property subscriberDataObserver. + * + * @param subscriberDataObserver value to be assigned to property subscriberDataObserver + */ + public void setSubscriberDataObserver(SubscriberDataObserver subscriberDataObserver) { + this.subscriberDataObserver = subscriberDataObserver; + } - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "SubscriberRegistration{" + "dataId='" + dataId + '\'' + ", group='" + group + '\'' - + ", appName='" + appName + '\'' + ", scopeEnum=" + scopeEnum - + ", subscriberDataObserver=" + subscriberDataObserver + '}'; - } + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "SubscriberRegistration{" + + "dataId='" + + dataId + + '\'' + + ", group='" + + group + + '\'' + + ", appName='" + + appName + + '\'' + + ", scopeEnum=" + + scopeEnum + + ", subscriberDataObserver=" + + subscriberDataObserver + + '}'; + } } diff --git a/client/api/src/test/java/com/alipay/sofa/registry/client/api/exception/DuplicateExceptionTest.java b/client/api/src/test/java/com/alipay/sofa/registry/client/api/exception/DuplicateExceptionTest.java index 6fc2e74a9..7274c646e 100644 --- a/client/api/src/test/java/com/alipay/sofa/registry/client/api/exception/DuplicateExceptionTest.java +++ b/client/api/src/test/java/com/alipay/sofa/registry/client/api/exception/DuplicateExceptionTest.java @@ -19,27 +19,24 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class DuplicateExceptionTest { - @Test - public void testConstruct() { - DuplicateException exception = new DuplicateException(); - Assert.assertNull(exception.getMessage()); - - exception = new DuplicateException("1"); - Assert.assertEquals("1", exception.getMessage()); + @Test + public void testConstruct() { + DuplicateException exception = new DuplicateException(); + Assert.assertNull(exception.getMessage()); - RuntimeException runtimeException = new RuntimeException("xxx"); - exception = new DuplicateException(runtimeException); - Assert.assertEquals("java.lang.RuntimeException: xxx", exception.getMessage()); - Assert.assertEquals(runtimeException, exception.getCause()); + exception = new DuplicateException("1"); + Assert.assertEquals("1", exception.getMessage()); - exception = new DuplicateException("1", runtimeException); - Assert.assertEquals("1", exception.getMessage()); - Assert.assertEquals(runtimeException, exception.getCause()); - } + RuntimeException runtimeException = new RuntimeException("xxx"); + exception = new DuplicateException(runtimeException); + Assert.assertEquals("java.lang.RuntimeException: xxx", exception.getMessage()); + Assert.assertEquals(runtimeException, exception.getCause()); -} \ No newline at end of file + exception = new DuplicateException("1", runtimeException); + Assert.assertEquals("1", exception.getMessage()); + Assert.assertEquals(runtimeException, exception.getCause()); + } +} diff --git a/client/api/src/test/java/com/alipay/sofa/registry/client/api/exception/RegistryClientExceptionTest.java b/client/api/src/test/java/com/alipay/sofa/registry/client/api/exception/RegistryClientExceptionTest.java index 7d45f61f9..6e7ac6d7c 100644 --- a/client/api/src/test/java/com/alipay/sofa/registry/client/api/exception/RegistryClientExceptionTest.java +++ b/client/api/src/test/java/com/alipay/sofa/registry/client/api/exception/RegistryClientExceptionTest.java @@ -19,26 +19,24 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class RegistryClientExceptionTest { - @Test - public void testConstruct() { - RegistryClientException exception = new RegistryClientException(); - Assert.assertNull(exception.getMessage()); + @Test + public void testConstruct() { + RegistryClientException exception = new RegistryClientException(); + Assert.assertNull(exception.getMessage()); - exception = new RegistryClientException("1"); - Assert.assertEquals("1", exception.getMessage()); + exception = new RegistryClientException("1"); + Assert.assertEquals("1", exception.getMessage()); - RuntimeException runtimeException = new RuntimeException("xxx"); - exception = new RegistryClientException(runtimeException); - Assert.assertEquals("java.lang.RuntimeException: xxx", exception.getMessage()); - Assert.assertEquals(runtimeException, exception.getCause()); + RuntimeException runtimeException = new RuntimeException("xxx"); + exception = new RegistryClientException(runtimeException); + Assert.assertEquals("java.lang.RuntimeException: xxx", exception.getMessage()); + Assert.assertEquals(runtimeException, exception.getCause()); - exception = new RegistryClientException("1", runtimeException); - Assert.assertEquals("1", exception.getMessage()); - Assert.assertEquals(runtimeException, exception.getCause()); - } -} \ No newline at end of file + exception = new RegistryClientException("1", runtimeException); + Assert.assertEquals("1", exception.getMessage()); + Assert.assertEquals(runtimeException, exception.getCause()); + } +} diff --git a/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/BaseRegistrationTest.java b/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/BaseRegistrationTest.java index dcca6ba6e..84f252030 100644 --- a/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/BaseRegistrationTest.java +++ b/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/BaseRegistrationTest.java @@ -19,22 +19,19 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class BaseRegistrationTest { - @Test - public void testAll() { - BaseRegistration registration = new BaseRegistration(); - registration.setAppName("app"); - registration.setDataId("dataId"); - registration.setGroup("group"); - Assert.assertEquals("app", registration.getAppName()); - Assert.assertEquals("dataId", registration.getDataId()); - Assert.assertEquals("group", registration.getGroup()); - Assert.assertEquals("BaseRegistration{dataId='dataId', group='group', appName='app'}", - registration.toString()); - } - -} \ No newline at end of file + @Test + public void testAll() { + BaseRegistration registration = new BaseRegistration(); + registration.setAppName("app"); + registration.setDataId("dataId"); + registration.setGroup("group"); + Assert.assertEquals("app", registration.getAppName()); + Assert.assertEquals("dataId", registration.getDataId()); + Assert.assertEquals("group", registration.getGroup()); + Assert.assertEquals( + "BaseRegistration{dataId='dataId', group='group', appName='app'}", registration.toString()); + } +} diff --git a/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/ConfiguratorRegistrationTest.java b/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/ConfiguratorRegistrationTest.java index 74f7889bc..218aa0378 100644 --- a/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/ConfiguratorRegistrationTest.java +++ b/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/ConfiguratorRegistrationTest.java @@ -21,23 +21,20 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class ConfiguratorRegistrationTest { - @Test - public void testAll() { - ConfiguratorRegistration registration = new ConfiguratorRegistration("xxx", null); - Assert.assertEquals("xxx", registration.getDataId()); - Assert.assertNull(registration.getConfigDataObserver()); - registration.setConfigDataObserver(new ConfigDataObserver() { - @Override - public void handleData(String dataId, ConfigData configData) { - - } + @Test + public void testAll() { + ConfiguratorRegistration registration = new ConfiguratorRegistration("xxx", null); + Assert.assertEquals("xxx", registration.getDataId()); + Assert.assertNull(registration.getConfigDataObserver()); + registration.setConfigDataObserver( + new ConfigDataObserver() { + @Override + public void handleData(String dataId, ConfigData configData) {} }); - Assert.assertNotNull(registration.getConfigDataObserver()); - Assert.assertTrue(registration.toString().contains("xxx")); - } -} \ No newline at end of file + Assert.assertNotNull(registration.getConfigDataObserver()); + Assert.assertTrue(registration.toString().contains("xxx")); + } +} diff --git a/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/PublisherRegistrationTest.java b/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/PublisherRegistrationTest.java index bf37f97db..55df59dfd 100644 --- a/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/PublisherRegistrationTest.java +++ b/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/PublisherRegistrationTest.java @@ -19,15 +19,13 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class PublisherRegistrationTest { - @Test - public void testAll() { - PublisherRegistration registration = new PublisherRegistration("xxx"); - Assert.assertEquals("xxx", registration.getDataId()); - Assert.assertTrue(registration.toString().contains("xxx")); - } -} \ No newline at end of file + @Test + public void testAll() { + PublisherRegistration registration = new PublisherRegistration("xxx"); + Assert.assertEquals("xxx", registration.getDataId()); + Assert.assertTrue(registration.toString().contains("xxx")); + } +} diff --git a/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/SubscriberRegistrationTest.java b/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/SubscriberRegistrationTest.java index 2cfb98e35..6d1b15e3e 100644 --- a/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/SubscriberRegistrationTest.java +++ b/client/api/src/test/java/com/alipay/sofa/registry/client/api/registration/SubscriberRegistrationTest.java @@ -22,25 +22,22 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class SubscriberRegistrationTest { - @Test - public void testAll() { - SubscriberRegistration registration = new SubscriberRegistration("xxx", null); - Assert.assertEquals("xxx", registration.getDataId()); - Assert.assertNull(registration.getSubscriberDataObserver()); - registration.setSubscriberDataObserver(new SubscriberDataObserver() { - @Override - public void handleData(String dataId, UserData data) { - - } + @Test + public void testAll() { + SubscriberRegistration registration = new SubscriberRegistration("xxx", null); + Assert.assertEquals("xxx", registration.getDataId()); + Assert.assertNull(registration.getSubscriberDataObserver()); + registration.setSubscriberDataObserver( + new SubscriberDataObserver() { + @Override + public void handleData(String dataId, UserData data) {} }); - Assert.assertNotNull(registration.getSubscriberDataObserver()); - registration.setScopeEnum(ScopeEnum.dataCenter); - Assert.assertEquals(ScopeEnum.dataCenter, registration.getScopeEnum()); - Assert.assertTrue(registration.toString().contains("xxx")); - } -} \ No newline at end of file + Assert.assertNotNull(registration.getSubscriberDataObserver()); + registration.setScopeEnum(ScopeEnum.dataCenter); + Assert.assertEquals(ScopeEnum.dataCenter, registration.getScopeEnum()); + Assert.assertTrue(registration.toString().contains("xxx")); + } +} diff --git a/client/api/src/test/java/com/alipay/sofa/registry/core/model/ReceivedConfigDataTest.java b/client/api/src/test/java/com/alipay/sofa/registry/core/model/ReceivedConfigDataTest.java index 72bf3a01f..12332a4cb 100644 --- a/client/api/src/test/java/com/alipay/sofa/registry/core/model/ReceivedConfigDataTest.java +++ b/client/api/src/test/java/com/alipay/sofa/registry/core/model/ReceivedConfigDataTest.java @@ -16,32 +16,28 @@ */ package com.alipay.sofa.registry.core.model; +import java.util.Arrays; import org.junit.Assert; import org.junit.Test; -import java.util.Arrays; - -/** - * @author GengZhang - */ +/** @author GengZhang */ public class ReceivedConfigDataTest { - @Test - public void testAll() { - ReceivedConfigData data = new ReceivedConfigData(); - data.setDataId("dataIdd"); - data.setGroup("groupp"); - data.setInstanceId("instanceIdd"); - data.setConfiguratorRegistIds(Arrays.asList("id1", "id2")); - data.setDataBox(new DataBox()); - data.setVersion(1234L); - Assert.assertEquals("dataIdd", data.getDataId()); - Assert.assertEquals("groupp", data.getGroup()); - Assert.assertEquals("instanceIdd", data.getInstanceId()); - Assert.assertEquals(2, data.getConfiguratorRegistIds().size()); - Assert.assertNotNull(data.getDataBox()); - Assert.assertEquals(1234L, (long) data.getVersion()); - Assert.assertTrue(data.toString().contains("instanceIdd")); - } - -} \ No newline at end of file + @Test + public void testAll() { + ReceivedConfigData data = new ReceivedConfigData(); + data.setDataId("dataIdd"); + data.setGroup("groupp"); + data.setInstanceId("instanceIdd"); + data.setConfiguratorRegistIds(Arrays.asList("id1", "id2")); + data.setDataBox(new DataBox()); + data.setVersion(1234L); + Assert.assertEquals("dataIdd", data.getDataId()); + Assert.assertEquals("groupp", data.getGroup()); + Assert.assertEquals("instanceIdd", data.getInstanceId()); + Assert.assertEquals(2, data.getConfiguratorRegistIds().size()); + Assert.assertNotNull(data.getDataBox()); + Assert.assertEquals(1234L, (long) data.getVersion()); + Assert.assertTrue(data.toString().contains("instanceIdd")); + } +} diff --git a/client/api/src/test/java/com/alipay/sofa/registry/core/model/ReceivedDataTest.java b/client/api/src/test/java/com/alipay/sofa/registry/core/model/ReceivedDataTest.java index 1fe5e45e1..8766ce282 100644 --- a/client/api/src/test/java/com/alipay/sofa/registry/core/model/ReceivedDataTest.java +++ b/client/api/src/test/java/com/alipay/sofa/registry/core/model/ReceivedDataTest.java @@ -16,43 +16,40 @@ */ package com.alipay.sofa.registry.core.model; -import org.junit.Assert; -import org.junit.Test; - import java.util.Arrays; import java.util.HashMap; import java.util.List; +import org.junit.Assert; +import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class ReceivedDataTest { - @Test - public void testAll() { + @Test + public void testAll() { - ReceivedData data = new ReceivedData(); - data.setDataId("dataIdd"); - data.setGroup("groupp"); - data.setInstanceId("instanceIdd"); - data.setSubscriberRegistIds(Arrays.asList("id1", "id2")); - data.setLocalZone("local"); - data.setScope("zone"); - data.setData(new HashMap>()); - data.setSegment("seg1"); - data.setVersion(1234L); - Assert.assertEquals("dataIdd", data.getDataId()); - Assert.assertEquals("groupp", data.getGroup()); - Assert.assertEquals("instanceIdd", data.getInstanceId()); - Assert.assertEquals(2, data.getSubscriberRegistIds().size()); - Assert.assertEquals("zone", data.getScope()); - Assert.assertEquals("seg1", data.getSegment()); - Assert.assertEquals("local", data.getLocalZone()); - Assert.assertEquals(1234L, (long) data.getVersion()); - Assert.assertEquals(0, data.getData().size()); - Assert.assertTrue(data.toString().contains("instanceIdd")); + ReceivedData data = new ReceivedData(); + data.setDataId("dataIdd"); + data.setGroup("groupp"); + data.setInstanceId("instanceIdd"); + data.setSubscriberRegistIds(Arrays.asList("id1", "id2")); + data.setLocalZone("local"); + data.setScope("zone"); + data.setData(new HashMap>()); + data.setSegment("seg1"); + data.setVersion(1234L); + Assert.assertEquals("dataIdd", data.getDataId()); + Assert.assertEquals("groupp", data.getGroup()); + Assert.assertEquals("instanceIdd", data.getInstanceId()); + Assert.assertEquals(2, data.getSubscriberRegistIds().size()); + Assert.assertEquals("zone", data.getScope()); + Assert.assertEquals("seg1", data.getSegment()); + Assert.assertEquals("local", data.getLocalZone()); + Assert.assertEquals(1234L, (long) data.getVersion()); + Assert.assertEquals(0, data.getData().size()); + Assert.assertTrue(data.toString().contains("instanceIdd")); - ReceivedData data1 = new ReceivedData(null, null, null, null, null, null, null); - Assert.assertNull(data1.getVersion()); - } -} \ No newline at end of file + ReceivedData data1 = new ReceivedData(null, null, null, null, null, null, null); + Assert.assertNull(data1.getVersion()); + } +} diff --git a/client/api/src/test/java/com/alipay/sofa/registry/core/model/ResultTest.java b/client/api/src/test/java/com/alipay/sofa/registry/core/model/ResultTest.java index af5fc00f0..7f140051f 100644 --- a/client/api/src/test/java/com/alipay/sofa/registry/core/model/ResultTest.java +++ b/client/api/src/test/java/com/alipay/sofa/registry/core/model/ResultTest.java @@ -19,18 +19,16 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class ResultTest { - @Test - public void testAll() { - Result result = new Result(); - result.setSuccess(false); - result.setMessage("xxx"); - Assert.assertFalse(result.isSuccess()); - Assert.assertEquals("xxx", result.getMessage()); - Assert.assertTrue(result.toString().contains("xxx")); - } -} \ No newline at end of file + @Test + public void testAll() { + Result result = new Result(); + result.setSuccess(false); + result.setMessage("xxx"); + Assert.assertFalse(result.isSuccess()); + Assert.assertEquals("xxx", result.getMessage()); + Assert.assertTrue(result.toString().contains("xxx")); + } +} diff --git a/client/api/src/test/java/com/alipay/sofa/registry/core/model/ScopeEnumTest.java b/client/api/src/test/java/com/alipay/sofa/registry/core/model/ScopeEnumTest.java index a0d600872..dc44a0be9 100644 --- a/client/api/src/test/java/com/alipay/sofa/registry/core/model/ScopeEnumTest.java +++ b/client/api/src/test/java/com/alipay/sofa/registry/core/model/ScopeEnumTest.java @@ -19,14 +19,12 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class ScopeEnumTest { - @Test - public void contains() { - Assert.assertTrue(ScopeEnum.contains("zone")); - Assert.assertFalse(ScopeEnum.contains("xxxx")); - } -} \ No newline at end of file + @Test + public void contains() { + Assert.assertTrue(ScopeEnum.contains("zone")); + Assert.assertFalse(ScopeEnum.contains("xxxx")); + } +} diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/auth/AuthManager.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/auth/AuthManager.java index ed346bd3f..92e19ec2f 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/auth/AuthManager.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/auth/AuthManager.java @@ -17,21 +17,21 @@ package com.alipay.sofa.registry.client.auth; import com.alipay.sofa.registry.core.model.BaseRegister; - import java.util.Map; /** * The interface Auth manager. + * * @author zhuoyu.sjw * @version $Id : AuthManager.java, v 0.1 2018-04-18 12:12 zhuoyu.sjw Exp $$ */ public interface AuthManager { - /** - * Gets auth content. - * - * @param register the register - * @return the auth content - */ - Map getAuthContent(BaseRegister register); + /** + * Gets auth content. + * + * @param register the register + * @return the auth content + */ + Map getAuthContent(BaseRegister register); } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/auth/NoopAuthManager.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/auth/NoopAuthManager.java index 3f03e5de0..e296a463d 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/auth/NoopAuthManager.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/auth/NoopAuthManager.java @@ -17,30 +17,27 @@ package com.alipay.sofa.registry.client.auth; import com.alipay.sofa.registry.core.model.BaseRegister; - import java.util.HashMap; import java.util.Map; /** - * * @author zhuoyu.sjw * @version $Id: NoopAuthManager.java, v 0.1 2018-04-18 12:13 zhuoyu.sjw Exp $$ */ public final class NoopAuthManager implements AuthManager { - public static final AuthManager INSTANCE = new NoopAuthManager(); + public static final AuthManager INSTANCE = new NoopAuthManager(); - private NoopAuthManager() { - } + private NoopAuthManager() {} - /** - * Gets auth content. - * - * @param register the register - * @return the auth content - */ - @Override - public Map getAuthContent(BaseRegister register) { - return new HashMap(); - } + /** + * Gets auth content. + * + * @param register the register + * @return the auth content + */ + @Override + public Map getAuthContent(BaseRegister register) { + return new HashMap(); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/constants/ValueConstants.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/constants/ValueConstants.java index 76929f6d0..fffa34fa0 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/constants/ValueConstants.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/constants/ValueConstants.java @@ -18,24 +18,18 @@ /** * The type Value constants. - * + * * @author zhuoyu.sjw * @version $Id : ValueConstants.java, v 0.1 2017-11-30 20:03 zhuoyu.sjw Exp $$ */ public class ValueConstants { - /** - * The constant DEFAULT_GROUP. - */ - public static final String DEFAULT_GROUP = "DEFAULT_GROUP"; + /** The constant DEFAULT_GROUP. */ + public static final String DEFAULT_GROUP = "DEFAULT_GROUP"; - /** - * The constant DEFAULT_ZONE. - */ - public static final String DEFAULT_ZONE = "DEFAULT_ZONE"; + /** The constant DEFAULT_ZONE. */ + public static final String DEFAULT_ZONE = "DEFAULT_ZONE"; - /** - * The constant DEFAULT_DATA_CENTER. - */ - public static final String DEFAULT_DATA_CENTER = "DefaultDataCenter"; + /** The constant DEFAULT_DATA_CENTER. */ + public static final String DEFAULT_DATA_CENTER = "DefaultDataCenter"; } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/constants/VersionConstants.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/constants/VersionConstants.java index ca355c1ff..4b3c56760 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/constants/VersionConstants.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/constants/VersionConstants.java @@ -17,11 +17,10 @@ package com.alipay.sofa.registry.client.constants; /** - * * @author zhuoyu.sjw * @version $Id: VersionConstants.java, v 0.1 2017-11-23 22:36 zhuoyu.sjw Exp $$ */ public class VersionConstants { - public static final long UNINITIALIZED_VERSION = 0; + public static final long UNINITIALIZED_VERSION = 0; } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/event/ConfiguratorProcessEvent.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/event/ConfiguratorProcessEvent.java index c5ba46c17..9a1715565 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/event/ConfiguratorProcessEvent.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/event/ConfiguratorProcessEvent.java @@ -21,118 +21,123 @@ import com.alipay.sofa.registry.client.api.model.Event; /** - * * @author zhuoyu.sjw * @version $Id: ConfiguratorProcessEvent.java, v 0.1 2018-07-13 18:44 zhuoyu.sjw Exp $$ */ public class ConfiguratorProcessEvent implements Event { - private Configurator configurator; - - private RegistryClientConfig config; - - private long start; - - private long end; - - private Throwable throwable; - - /** - * Getter method for property configurator. - * - * @return property value of configurator - */ - public Configurator getConfigurator() { - return configurator; - } - - /** - * Setter method for property configurator. - * - * @param configurator value to be assigned to property configurator - */ - public void setConfigurator(Configurator configurator) { - this.configurator = configurator; - } - - /** - * Getter method for property config. - * - * @return property value of config - */ - public RegistryClientConfig getConfig() { - return config; - } - - /** - * Setter method for property config. - * - * @param config value to be assigned to property config - */ - public void setConfig(RegistryClientConfig config) { - this.config = config; - } - - /** - * Getter method for property start. - * - * @return property value of start - */ - public long getStart() { - return start; - } - - /** - * Setter method for property start. - * - * @param start value to be assigned to property start - */ - public void setStart(long start) { - this.start = start; - } - - /** - * Getter method for property end. - * - * @return property value of end - */ - public long getEnd() { - return end; - } - - /** - * Setter method for property end. - * - * @param end value to be assigned to property end - */ - public void setEnd(long end) { - this.end = end; - } - - /** - * Getter method for property throwable. - * - * @return property value of throwable - */ - public Throwable getThrowable() { - return throwable; - } - - /** - * Setter method for property throwable. - * - * @param throwable value to be assigned to property throwable - */ - public void setThrowable(Throwable throwable) { - this.throwable = throwable; - } - - /** - * @see Object#toString() - */ - @Override - public String toString() { - return "ConfiguratorProcessEvent{" + "configurator=" + configurator + ", start=" + start - + ", end=" + end + ", throwable=" + throwable + '}'; - } + private Configurator configurator; + + private RegistryClientConfig config; + + private long start; + + private long end; + + private Throwable throwable; + + /** + * Getter method for property configurator. + * + * @return property value of configurator + */ + public Configurator getConfigurator() { + return configurator; + } + + /** + * Setter method for property configurator. + * + * @param configurator value to be assigned to property configurator + */ + public void setConfigurator(Configurator configurator) { + this.configurator = configurator; + } + + /** + * Getter method for property config. + * + * @return property value of config + */ + public RegistryClientConfig getConfig() { + return config; + } + + /** + * Setter method for property config. + * + * @param config value to be assigned to property config + */ + public void setConfig(RegistryClientConfig config) { + this.config = config; + } + + /** + * Getter method for property start. + * + * @return property value of start + */ + public long getStart() { + return start; + } + + /** + * Setter method for property start. + * + * @param start value to be assigned to property start + */ + public void setStart(long start) { + this.start = start; + } + + /** + * Getter method for property end. + * + * @return property value of end + */ + public long getEnd() { + return end; + } + + /** + * Setter method for property end. + * + * @param end value to be assigned to property end + */ + public void setEnd(long end) { + this.end = end; + } + + /** + * Getter method for property throwable. + * + * @return property value of throwable + */ + public Throwable getThrowable() { + return throwable; + } + + /** + * Setter method for property throwable. + * + * @param throwable value to be assigned to property throwable + */ + public void setThrowable(Throwable throwable) { + this.throwable = throwable; + } + + /** @see Object#toString() */ + @Override + public String toString() { + return "ConfiguratorProcessEvent{" + + "configurator=" + + configurator + + ", start=" + + start + + ", end=" + + end + + ", throwable=" + + throwable + + '}'; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/event/DefaultEventBus.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/event/DefaultEventBus.java index 410469c1f..cd7da1752 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/event/DefaultEventBus.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/event/DefaultEventBus.java @@ -23,8 +23,6 @@ import com.alipay.sofa.registry.client.factory.NamedThreadFactory; import com.alipay.sofa.registry.client.log.LoggerFactory; import com.alipay.sofa.registry.client.util.CommonUtils; -import org.slf4j.Logger; - import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArraySet; @@ -32,121 +30,124 @@ import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; /** * The type Default event bus. + * * @author zhanggeng.zg * @author zhuoyu.sjw * @version $Id : DefaultEventBus.java, v 0.1 2018-07-13 10:56 zhuoyu.sjw Exp $$ */ public class DefaultEventBus implements EventBus { - /** LOGGER */ - private static final Logger LOGGER = LoggerFactory - .getLogger(DefaultEventBus.class); + /** LOGGER */ + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultEventBus.class); - private RegistryClientConfig config; + private RegistryClientConfig config; - private ConcurrentMap, CopyOnWriteArraySet> eventSubscriberMap = new ConcurrentHashMap, CopyOnWriteArraySet>(); + private ConcurrentMap, CopyOnWriteArraySet> + eventSubscriberMap = + new ConcurrentHashMap, CopyOnWriteArraySet>(); - private Executor executor; + private Executor executor; - /** - * Instantiates a new Default event bus. - * - * @param config the config - */ - public DefaultEventBus(RegistryClientConfig config) { - this.config = config; - this.executor = new ThreadPoolExecutor(config.getObserverThreadCoreSize(), - config.getObserverThreadMaxSize(), 0, TimeUnit.SECONDS, + /** + * Instantiates a new Default event bus. + * + * @param config the config + */ + public DefaultEventBus(RegistryClientConfig config) { + this.config = config; + this.executor = + new ThreadPoolExecutor( + config.getObserverThreadCoreSize(), + config.getObserverThreadMaxSize(), + 0, + TimeUnit.SECONDS, new LinkedBlockingDeque(config.getObserverThreadQueueLength()), new NamedThreadFactory("DefaultEventBusThread")); - } + } - /** - * @see EventBus#register(Class, EventSubscriber) - */ - @Override - public void register(Class eventClass, EventSubscriber eventSubscriber) { - CopyOnWriteArraySet set = eventSubscriberMap.get(eventClass); - if (set == null) { - set = new CopyOnWriteArraySet(); - CopyOnWriteArraySet old = eventSubscriberMap.putIfAbsent(eventClass, - set); - if (old != null) { - set = old; - } - } - set.add(eventSubscriber); - LOGGER.debug("Register subscriber: {} of event: {}.", eventSubscriber, eventClass); + /** @see EventBus#register(Class, EventSubscriber) */ + @Override + public void register(Class eventClass, EventSubscriber eventSubscriber) { + CopyOnWriteArraySet set = eventSubscriberMap.get(eventClass); + if (set == null) { + set = new CopyOnWriteArraySet(); + CopyOnWriteArraySet old = eventSubscriberMap.putIfAbsent(eventClass, set); + if (old != null) { + set = old; + } } + set.add(eventSubscriber); + LOGGER.debug("Register subscriber: {} of event: {}.", eventSubscriber, eventClass); + } - /** - * @see EventBus#unRegister(Class, EventSubscriber) - */ - @Override - public void unRegister(Class eventClass, EventSubscriber eventSubscriber) { - CopyOnWriteArraySet set = eventSubscriberMap.get(eventClass); - if (set != null) { - set.remove(eventSubscriber); - LOGGER.debug("UnRegister subscriber: {} of event: {}.", eventSubscriber, eventClass); - } + /** @see EventBus#unRegister(Class, EventSubscriber) */ + @Override + public void unRegister(Class eventClass, EventSubscriber eventSubscriber) { + CopyOnWriteArraySet set = eventSubscriberMap.get(eventClass); + if (set != null) { + set.remove(eventSubscriber); + LOGGER.debug("UnRegister subscriber: {} of event: {}.", eventSubscriber, eventClass); } + } - /** - * Post. - * - * @param event the event - */ - @Override - public void post(final Event event) { - if (!isEnable()) { - return; - } - CopyOnWriteArraySet subscribers = eventSubscriberMap.get(event.getClass()); - if (null != subscribers && !subscribers.isEmpty()) { - for (final EventSubscriber subscriber : subscribers) { - if (subscriber.isSync()) { - handleEvent(subscriber, event); - } else { // 异步 - executor.execute(new Runnable() { - @Override - public void run() { - handleEvent(subscriber, event); - } - }); + /** + * Post. + * + * @param event the event + */ + @Override + public void post(final Event event) { + if (!isEnable()) { + return; + } + CopyOnWriteArraySet subscribers = eventSubscriberMap.get(event.getClass()); + if (null != subscribers && !subscribers.isEmpty()) { + for (final EventSubscriber subscriber : subscribers) { + if (subscriber.isSync()) { + handleEvent(subscriber, event); + } else { // 异步 + executor.execute( + new Runnable() { + @Override + public void run() { + handleEvent(subscriber, event); } - } + }); } + } } + } - /** - * Is enable boolean. - * - * @return the boolean - */ - @Override - public boolean isEnable() { - return null != config && config.isEventBusEnable(); - } + /** + * Is enable boolean. + * + * @return the boolean + */ + @Override + public boolean isEnable() { + return null != config && config.isEventBusEnable(); + } - /** - * Is enable boolean. - * - * @param eventClass the event class - * @return the boolean - */ - @Override - public boolean isEnable(Class eventClass) { - return isEnable() && CommonUtils.isNotEmpty(eventSubscriberMap.get(eventClass)); - } + /** + * Is enable boolean. + * + * @param eventClass the event class + * @return the boolean + */ + @Override + public boolean isEnable(Class eventClass) { + return isEnable() && CommonUtils.isNotEmpty(eventSubscriberMap.get(eventClass)); + } - private void handleEvent(final EventSubscriber subscriber, final Event event) { - try { - subscriber.onEvent(event); - } catch (Throwable e) { - LOGGER.warn("Handle {} error", event.getClass(), e); - } + private void handleEvent(final EventSubscriber subscriber, final Event event) { + try { + subscriber.onEvent(event); + } catch (Throwable e) { + LOGGER.warn("Handle {} error", event.getClass(), e); } + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/event/LookoutSubscriber.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/event/LookoutSubscriber.java index 6bb6fcc62..cc7fb79f8 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/event/LookoutSubscriber.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/event/LookoutSubscriber.java @@ -25,106 +25,104 @@ import com.alipay.sofa.registry.client.api.Subscriber; import com.alipay.sofa.registry.client.api.model.Event; import com.alipay.sofa.registry.client.util.StringUtils; - import java.util.concurrent.TimeUnit; /** - * * @author zhuoyu.sjw * @version $Id: LookoutSubscriber.java, v 0.1 2018-07-13 20:31 zhuoyu.sjw Exp $$ */ public class LookoutSubscriber implements EventSubscriber { - /** */ - private static final String METRIC_DATA_ID_NAME = "data_id"; + /** */ + private static final String METRIC_DATA_ID_NAME = "data_id"; - /** */ - private static final String METRIC_INSTANCE_ID_NAME = "instance_id"; + /** */ + private static final String METRIC_INSTANCE_ID_NAME = "instance_id"; - /** */ - private static final String METRIC_COUNT_NAME = "count"; + /** */ + private static final String METRIC_COUNT_NAME = "count"; - /** */ - private static final String METRIC_TIME_NAME = "time"; + /** */ + private static final String METRIC_TIME_NAME = "time"; - /** */ - private static final String METRIC_SUCCESS_NAME = "success"; + /** */ + private static final String METRIC_SUCCESS_NAME = "success"; - /** */ - private static final String REGISTRY_PROCESS_SUBSCRIBER = "registry.process.subscriber"; + /** */ + private static final String REGISTRY_PROCESS_SUBSCRIBER = "registry.process.subscriber"; - /** */ - private static final String REGISTRY_PROCESS_CONFIGURATOR = "registry.process.configurator"; + /** */ + private static final String REGISTRY_PROCESS_CONFIGURATOR = "registry.process.configurator"; - /** - * @see EventSubscriber#isSync() - */ - @Override - public boolean isSync() { - return false; - } + /** @see EventSubscriber#isSync() */ + @Override + public boolean isSync() { + return false; + } - /** - * @see EventSubscriber#onEvent(Event) - */ - @Override - public void onEvent(Event event) { - if (null == event) { - return; - } - Class eventClass = event.getClass(); - - if (eventClass == SubscriberProcessEvent.class) { - SubscriberProcessEvent subscriberProcessEvent = (SubscriberProcessEvent) event; - Subscriber subscriber = subscriberProcessEvent.getSubscriber(); - if (null == subscriber) { - return; - } - - RegistryClientConfig config = subscriberProcessEvent.getConfig(); - if (null == config) { - return; - } - - Id id = Lookout - .registry() - .createId(REGISTRY_PROCESS_SUBSCRIBER) - .withTag(METRIC_DATA_ID_NAME, StringUtils.defaultString(subscriber.getDataId())) - .withTag(METRIC_INSTANCE_ID_NAME, StringUtils.defaultString(config.getInstanceId())); - MixinMetric mixin = Lookout.registry().mixinMetric(id); - - mixin.counter(METRIC_COUNT_NAME).inc(); - mixin.timer(METRIC_TIME_NAME).record( - subscriberProcessEvent.getEnd() - subscriberProcessEvent.getStart(), - TimeUnit.MILLISECONDS); - - if (null == subscriberProcessEvent.getThrowable()) { - mixin.counter(METRIC_SUCCESS_NAME).inc(); - } - } else if (eventClass == ConfiguratorProcessEvent.class) { - ConfiguratorProcessEvent configuratorProcessEvent = (ConfiguratorProcessEvent) event; - Configurator configurator = configuratorProcessEvent.getConfigurator(); - if (null == configurator) { - return; - } - - RegistryClientConfig config = configuratorProcessEvent.getConfig(); - - Id id = Lookout - .registry() - .createId(REGISTRY_PROCESS_CONFIGURATOR) - .withTag(METRIC_DATA_ID_NAME, StringUtils.defaultString(configurator.getDataId())) - .withTag(METRIC_INSTANCE_ID_NAME, StringUtils.defaultString(config.getInstanceId())); - MixinMetric mixin = Lookout.registry().mixinMetric(id); - - mixin.counter(METRIC_COUNT_NAME).inc(); - mixin.timer(METRIC_TIME_NAME).record( - configuratorProcessEvent.getEnd() - configuratorProcessEvent.getStart(), - TimeUnit.MILLISECONDS); - - if (null == configuratorProcessEvent.getThrowable()) { - mixin.counter(METRIC_SUCCESS_NAME).inc(); - } - } + /** @see EventSubscriber#onEvent(Event) */ + @Override + public void onEvent(Event event) { + if (null == event) { + return; + } + Class eventClass = event.getClass(); + + if (eventClass == SubscriberProcessEvent.class) { + SubscriberProcessEvent subscriberProcessEvent = (SubscriberProcessEvent) event; + Subscriber subscriber = subscriberProcessEvent.getSubscriber(); + if (null == subscriber) { + return; + } + + RegistryClientConfig config = subscriberProcessEvent.getConfig(); + if (null == config) { + return; + } + + Id id = + Lookout.registry() + .createId(REGISTRY_PROCESS_SUBSCRIBER) + .withTag(METRIC_DATA_ID_NAME, StringUtils.defaultString(subscriber.getDataId())) + .withTag(METRIC_INSTANCE_ID_NAME, StringUtils.defaultString(config.getInstanceId())); + MixinMetric mixin = Lookout.registry().mixinMetric(id); + + mixin.counter(METRIC_COUNT_NAME).inc(); + mixin + .timer(METRIC_TIME_NAME) + .record( + subscriberProcessEvent.getEnd() - subscriberProcessEvent.getStart(), + TimeUnit.MILLISECONDS); + + if (null == subscriberProcessEvent.getThrowable()) { + mixin.counter(METRIC_SUCCESS_NAME).inc(); + } + } else if (eventClass == ConfiguratorProcessEvent.class) { + ConfiguratorProcessEvent configuratorProcessEvent = (ConfiguratorProcessEvent) event; + Configurator configurator = configuratorProcessEvent.getConfigurator(); + if (null == configurator) { + return; + } + + RegistryClientConfig config = configuratorProcessEvent.getConfig(); + + Id id = + Lookout.registry() + .createId(REGISTRY_PROCESS_CONFIGURATOR) + .withTag(METRIC_DATA_ID_NAME, StringUtils.defaultString(configurator.getDataId())) + .withTag(METRIC_INSTANCE_ID_NAME, StringUtils.defaultString(config.getInstanceId())); + MixinMetric mixin = Lookout.registry().mixinMetric(id); + + mixin.counter(METRIC_COUNT_NAME).inc(); + mixin + .timer(METRIC_TIME_NAME) + .record( + configuratorProcessEvent.getEnd() - configuratorProcessEvent.getStart(), + TimeUnit.MILLISECONDS); + + if (null == configuratorProcessEvent.getThrowable()) { + mixin.counter(METRIC_SUCCESS_NAME).inc(); + } } + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/event/SubscriberProcessEvent.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/event/SubscriberProcessEvent.java index d8c6b2a2b..aa723e8c4 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/event/SubscriberProcessEvent.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/event/SubscriberProcessEvent.java @@ -22,117 +22,124 @@ /** * The type Subscriber process event. + * * @author zhuoyu.sjw * @version $Id : SubscriberProcessEvent.java, v 0.1 2018-07-13 18:40 zhuoyu.sjw Exp $$ */ public class SubscriberProcessEvent implements Event { - private Subscriber subscriber; - - private RegistryClientConfig config; - - private long start; - - private long end; - - private Throwable throwable; - - /** - * Getter method for property subscriber. - * - * @return property value of subscriber - */ - public Subscriber getSubscriber() { - return subscriber; - } - - /** - * Setter method for property subscriber. - * - * @param subscriber value to be assigned to property subscriber - */ - public void setSubscriber(Subscriber subscriber) { - this.subscriber = subscriber; - } - - /** - * Getter method for property config. - * - * @return property value of config - */ - public RegistryClientConfig getConfig() { - return config; - } - - /** - * Setter method for property config. - * - * @param config value to be assigned to property config - */ - public void setConfig(RegistryClientConfig config) { - this.config = config; - } - - /** - * Getter method for property start. - * - * @return property value of start - */ - public long getStart() { - return start; - } - - /** - * Setter method for property start. - * - * @param start value to be assigned to property start - */ - public void setStart(long start) { - this.start = start; - } - - /** - * Getter method for property end. - * - * @return property value of end - */ - public long getEnd() { - return end; - } - - /** - * Setter method for property end. - * - * @param end value to be assigned to property end - */ - public void setEnd(long end) { - this.end = end; - } - - /** - * Getter method for property throwable. - * - * @return property value of throwable - */ - public Throwable getThrowable() { - return throwable; - } - - /** - * Setter method for property throwable. - * - * @param throwable value to be assigned to property throwable - */ - public void setThrowable(Throwable throwable) { - this.throwable = throwable; - } - - /** - * @see Object#toString() - */ - @Override - public String toString() { - return "SubscriberProcessEvent{" + "subscriber=" + subscriber + ", start=" + start - + ", end=" + end + ", throwable=" + throwable + '}'; - } + private Subscriber subscriber; + + private RegistryClientConfig config; + + private long start; + + private long end; + + private Throwable throwable; + + /** + * Getter method for property subscriber. + * + * @return property value of subscriber + */ + public Subscriber getSubscriber() { + return subscriber; + } + + /** + * Setter method for property subscriber. + * + * @param subscriber value to be assigned to property subscriber + */ + public void setSubscriber(Subscriber subscriber) { + this.subscriber = subscriber; + } + + /** + * Getter method for property config. + * + * @return property value of config + */ + public RegistryClientConfig getConfig() { + return config; + } + + /** + * Setter method for property config. + * + * @param config value to be assigned to property config + */ + public void setConfig(RegistryClientConfig config) { + this.config = config; + } + + /** + * Getter method for property start. + * + * @return property value of start + */ + public long getStart() { + return start; + } + + /** + * Setter method for property start. + * + * @param start value to be assigned to property start + */ + public void setStart(long start) { + this.start = start; + } + + /** + * Getter method for property end. + * + * @return property value of end + */ + public long getEnd() { + return end; + } + + /** + * Setter method for property end. + * + * @param end value to be assigned to property end + */ + public void setEnd(long end) { + this.end = end; + } + + /** + * Getter method for property throwable. + * + * @return property value of throwable + */ + public Throwable getThrowable() { + return throwable; + } + + /** + * Setter method for property throwable. + * + * @param throwable value to be assigned to property throwable + */ + public void setThrowable(Throwable throwable) { + this.throwable = throwable; + } + + /** @see Object#toString() */ + @Override + public String toString() { + return "SubscriberProcessEvent{" + + "subscriber=" + + subscriber + + ", start=" + + start + + ", end=" + + end + + ", throwable=" + + throwable + + '}'; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/factory/NamedThreadFactory.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/factory/NamedThreadFactory.java index f58a9a312..e221d38b6 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/factory/NamedThreadFactory.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/factory/NamedThreadFactory.java @@ -21,51 +21,52 @@ /** * The type Named thread factory. + * * @author zhuoyu.sjw * @version $Id : NamedThreadFactory.java, v 0.1 2018-03-02 21:23 zhuoyu.sjw Exp $$ */ public class NamedThreadFactory implements ThreadFactory { - private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); - private final AtomicInteger threadNumber = new AtomicInteger(1); - private final ThreadGroup group; - private final String namePrefix; - private final boolean isDaemon; + private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); + private final AtomicInteger threadNumber = new AtomicInteger(1); + private final ThreadGroup group; + private final String namePrefix; + private final boolean isDaemon; - /** - * Instantiates a new Named thread factory. - * - * @param name the name - */ - public NamedThreadFactory(String name) { - this(name, false); - } + /** + * Instantiates a new Named thread factory. + * + * @param name the name + */ + public NamedThreadFactory(String name) { + this(name, false); + } - /** - * Instantiates a new Named thread factory. - * - * @param prefix the prefix - * @param daemon the daemon - */ - public NamedThreadFactory(String prefix, boolean daemon) { - SecurityManager s = System.getSecurityManager(); - group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); - namePrefix = prefix + "-" + POOL_NUMBER.getAndIncrement() + "-thread-"; - isDaemon = daemon; - } + /** + * Instantiates a new Named thread factory. + * + * @param prefix the prefix + * @param daemon the daemon + */ + public NamedThreadFactory(String prefix, boolean daemon) { + SecurityManager s = System.getSecurityManager(); + group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); + namePrefix = prefix + "-" + POOL_NUMBER.getAndIncrement() + "-thread-"; + isDaemon = daemon; + } - /** - * Create a thread. - * - * @see ThreadFactory#newThread(Runnable) - */ - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); - t.setDaemon(isDaemon); - if (t.getPriority() != Thread.NORM_PRIORITY) { - t.setPriority(Thread.NORM_PRIORITY); - } - return t; + /** + * Create a thread. + * + * @see ThreadFactory#newThread(Runnable) + */ + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); + t.setDaemon(isDaemon); + if (t.getPriority() != Thread.NORM_PRIORITY) { + t.setPriority(Thread.NORM_PRIORITY); } + return t; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/model/ConfiguratorData.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/model/ConfiguratorData.java index aaa9d2f1a..0888a68c6 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/model/ConfiguratorData.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/model/ConfiguratorData.java @@ -17,59 +17,55 @@ package com.alipay.sofa.registry.client.model; import com.alipay.sofa.registry.core.model.DataBox; - import java.io.Serializable; /** * The type Configurator data. - * + * * @author zhuoyu.sjw - * @version $Id : ConfiguratorData.java, v 0.1 2018-04-18 15:17 zhuoyu.sjw Exp - * $$ + * @version $Id : ConfiguratorData.java, v 0.1 2018-04-18 15:17 zhuoyu.sjw Exp $$ */ public class ConfiguratorData implements Serializable { - private static final long serialVersionUID = 3667107975967019132L; + private static final long serialVersionUID = 3667107975967019132L; - private DataBox dataBox; + private DataBox dataBox; - private Long version; + private Long version; - /** - * Getter method for property dataBox. - * - * @return property value of dataBox - */ - public DataBox getDataBox() { - return dataBox; - } + /** + * Getter method for property dataBox. + * + * @return property value of dataBox + */ + public DataBox getDataBox() { + return dataBox; + } - /** - * Setter method for property dataBox. - * - * @param dataBox - * value to be assigned to property dataBox - */ - public void setDataBox(DataBox dataBox) { - this.dataBox = dataBox; - } + /** + * Setter method for property dataBox. + * + * @param dataBox value to be assigned to property dataBox + */ + public void setDataBox(DataBox dataBox) { + this.dataBox = dataBox; + } - /** - * Getter method for property version. - * - * @return property value of version - */ - public Long getVersion() { - return version; - } + /** + * Getter method for property version. + * + * @return property value of version + */ + public Long getVersion() { + return version; + } - /** - * Setter method for property version. - * - * @param version - * value to be assigned to property version - */ - public void setVersion(Long version) { - this.version = version; - } + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(Long version) { + this.version = version; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/model/SegmentData.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/model/SegmentData.java index 7215a42ed..4fb5cb1af 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/model/SegmentData.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/model/SegmentData.java @@ -17,77 +17,75 @@ package com.alipay.sofa.registry.client.model; import com.alipay.sofa.registry.core.model.DataBox; - import java.io.Serializable; import java.util.List; import java.util.Map; /** - * * @author zhuoyu.sjw * @version $Id: SegmentData.java, v 0.1 2018-03-12 22:13 zhuoyu.sjw Exp $$ */ public class SegmentData implements Serializable { - private static final long serialVersionUID = 3066687802211879826L; + private static final long serialVersionUID = 3066687802211879826L; - private String segment; + private String segment; - private Map> data; + private Map> data; - private Long version; + private Long version; - /** - * Getter method for property segment. - * - * @return property value of segment - */ - public String getSegment() { - return segment; - } + /** + * Getter method for property segment. + * + * @return property value of segment + */ + public String getSegment() { + return segment; + } - /** - * Setter method for property segment. - * - * @param segment value to be assigned to property segment - */ - public void setSegment(String segment) { - this.segment = segment; - } + /** + * Setter method for property segment. + * + * @param segment value to be assigned to property segment + */ + public void setSegment(String segment) { + this.segment = segment; + } - /** - * Getter method for property data. - * - * @return property value of data - */ - public Map> getData() { - return data; - } + /** + * Getter method for property data. + * + * @return property value of data + */ + public Map> getData() { + return data; + } - /** - * Setter method for property data. - * - * @param data value to be assigned to property data - */ - public void setData(Map> data) { - this.data = data; - } + /** + * Setter method for property data. + * + * @param data value to be assigned to property data + */ + public void setData(Map> data) { + this.data = data; + } - /** - * Getter method for property version. - * - * @return property value of version - */ - public Long getVersion() { - return version; - } + /** + * Getter method for property version. + * + * @return property value of version + */ + public Long getVersion() { + return version; + } - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(Long version) { - this.version = version; - } + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(Long version) { + this.version = version; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/AbstractInternalRegister.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/AbstractInternalRegister.java index d0032ab7d..68e87d67a 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/AbstractInternalRegister.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/AbstractInternalRegister.java @@ -20,7 +20,6 @@ import com.alipay.sofa.registry.client.auth.AuthManager; import com.alipay.sofa.registry.client.constants.VersionConstants; import com.alipay.sofa.registry.core.model.BaseRegister; - import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -37,392 +36,371 @@ */ public abstract class AbstractInternalRegister implements Register { - /** - * - */ - private final AtomicLong initialVersion = new AtomicLong(VersionConstants.UNINITIALIZED_VERSION); - /** - * - */ - private AuthManager authManager; - /** - * - */ - private volatile boolean registered = false; - /** - * - */ - private volatile boolean enabled = true; - /** - * - */ - private volatile boolean refused = false; - /** - * - */ - private AtomicLong pubVersion = new AtomicLong(VersionConstants.UNINITIALIZED_VERSION); - /** - * - */ - private AtomicLong ackVersion = new AtomicLong(VersionConstants.UNINITIALIZED_VERSION); - /** - * - */ - private volatile long timestamp = System.currentTimeMillis(); - /** - * - */ - private volatile int registerCount = 0; - /** - * - */ - private volatile String requestId = UUID.randomUUID().toString(); - - private ReadWriteLock lock = new ReentrantReadWriteLock(); - - /** - * The Read lock. - */ - protected Lock readLock = lock.readLock(); - - /** - * The Write lock. - */ - protected Lock writeLock = lock.writeLock(); - - /** - * Assembly object. - * - * @return the object - */ - public abstract Object assembly(); - - /** - * Is registered boolean. - * - * @return boolean boolean - */ - @Override - public boolean isRegistered() { - readLock.lock(); - try { - return registered; - } finally { - readLock.unlock(); - } + /** */ + private final AtomicLong initialVersion = new AtomicLong(VersionConstants.UNINITIALIZED_VERSION); + /** */ + private AuthManager authManager; + /** */ + private volatile boolean registered = false; + /** */ + private volatile boolean enabled = true; + /** */ + private volatile boolean refused = false; + /** */ + private AtomicLong pubVersion = new AtomicLong(VersionConstants.UNINITIALIZED_VERSION); + /** */ + private AtomicLong ackVersion = new AtomicLong(VersionConstants.UNINITIALIZED_VERSION); + /** */ + private volatile long timestamp = System.currentTimeMillis(); + /** */ + private volatile int registerCount = 0; + /** */ + private volatile String requestId = UUID.randomUUID().toString(); + + private ReadWriteLock lock = new ReentrantReadWriteLock(); + + /** The Read lock. */ + protected Lock readLock = lock.readLock(); + + /** The Write lock. */ + protected Lock writeLock = lock.writeLock(); + + /** + * Assembly object. + * + * @return the object + */ + public abstract Object assembly(); + + /** + * Is registered boolean. + * + * @return boolean boolean + */ + @Override + public boolean isRegistered() { + readLock.lock(); + try { + return registered; + } finally { + readLock.unlock(); } - - /** - * Wait to sync. - */ - void waitToSync() { - writeLock.lock(); - try { - this.registered = false; - this.requestId = UUID.randomUUID().toString(); - } finally { - writeLock.unlock(); - } + } + + /** Wait to sync. */ + void waitToSync() { + writeLock.lock(); + try { + this.registered = false; + this.requestId = UUID.randomUUID().toString(); + } finally { + writeLock.unlock(); } - - /** - * Sync ok. - * - * @param requestId the request id - * @param version the version - * @param refused the refused - * @return the boolean - */ - public boolean syncOK(String requestId, long version, boolean refused) { - writeLock.lock(); - try { - if (this.requestId.equals(requestId)) { - this.registered = true; - this.refused = refused; - this.setAckVersion(version); - return true; - } - return false; - } finally { - writeLock.unlock(); - } + } + + /** + * Sync ok. + * + * @param requestId the request id + * @param version the version + * @param refused the refused + * @return the boolean + */ + public boolean syncOK(String requestId, long version, boolean refused) { + writeLock.lock(); + try { + if (this.requestId.equals(requestId)) { + this.registered = true; + this.refused = refused; + this.setAckVersion(version); + return true; + } + return false; + } finally { + writeLock.unlock(); } - - /** - * @see Register#isEnabled() - */ - @Override - public boolean isEnabled() { - readLock.lock(); - try { - return enabled; - } finally { - readLock.unlock(); - } + } + + /** @see Register#isEnabled() */ + @Override + public boolean isEnabled() { + readLock.lock(); + try { + return enabled; + } finally { + readLock.unlock(); } - - /** - * Sets enabled. - * - * @param requestId the request id - */ - public void refused(String requestId) { - writeLock.lock(); - try { - if (this.requestId.equals(requestId)) { - this.enabled = false; - this.refused = true; - } - } finally { - writeLock.unlock(); - } + } + + /** + * Sets enabled. + * + * @param requestId the request id + */ + public void refused(String requestId) { + writeLock.lock(); + try { + if (this.requestId.equals(requestId)) { + this.enabled = false; + this.refused = true; + } + } finally { + writeLock.unlock(); } - - /** - * Is done boolean. - * - * @return boolean boolean - */ - public boolean isDone() { - readLock.lock(); - try { - return (this.isRegistered() && this.pubVersion.get() == this.ackVersion.get()) - || this.isRefused(); - } finally { - readLock.unlock(); - } + } + + /** + * Is done boolean. + * + * @return boolean boolean + */ + public boolean isDone() { + readLock.lock(); + try { + return (this.isRegistered() && this.pubVersion.get() == this.ackVersion.get()) + || this.isRefused(); + } finally { + readLock.unlock(); } - - /** - * Assembly sync task sync task. - * - * @return the sync task - */ - public SyncTask assemblySyncTask() { - readLock.lock(); - try { - SyncTask syncTask = new SyncTask(); - syncTask.setRequestId(requestId); - syncTask.setRequest(assembly()); - syncTask.setDone(isDone()); - return syncTask; - } finally { - readLock.unlock(); - } + } + + /** + * Assembly sync task sync task. + * + * @return the sync task + */ + public SyncTask assemblySyncTask() { + readLock.lock(); + try { + SyncTask syncTask = new SyncTask(); + syncTask.setRequestId(requestId); + syncTask.setRequest(assembly()); + syncTask.setDone(isDone()); + return syncTask; + } finally { + readLock.unlock(); } - - /** - * Gets pub version. - * - * @return AtomicLong pub version - */ - public AtomicLong getPubVersion() { - return this.pubVersion; + } + + /** + * Gets pub version. + * + * @return AtomicLong pub version + */ + public AtomicLong getPubVersion() { + return this.pubVersion; + } + + /** + * Sets ack version. + * + * @param version the ack version + */ + public void setAckVersion(Long version) { + if (null == version) { + return; } - /** - * Sets ack version. - * - * @param version the ack version - */ - public void setAckVersion(Long version) { - if (null == version) { - return; - } - - long current = ackVersion.get(); - if (version <= current) { - return; - } - - boolean result = this.ackVersion.compareAndSet(current, version); - if (result) { - return; - } - - setAckVersion(version); + long current = ackVersion.get(); + if (version <= current) { + return; } - /** - * @see Register#reset() - */ - @Override - public void reset() { - writeLock.lock(); - try { - this.registered = false; - this.registerCount = 0; - this.timestamp = System.currentTimeMillis(); - this.ackVersion = new AtomicLong(initialVersion.longValue()); - this.requestId = UUID.randomUUID().toString(); - } finally { - writeLock.unlock(); - } + boolean result = this.ackVersion.compareAndSet(current, version); + if (result) { + return; } - /** - * @see Register#unregister() - */ - @Override - public void unregister() { - writeLock.lock(); - try { - this.enabled = false; - this.pubVersion.incrementAndGet(); - this.requestId = UUID.randomUUID().toString(); - this.registerCount = 0; - } finally { - writeLock.unlock(); - } + setAckVersion(version); + } + + /** @see Register#reset() */ + @Override + public void reset() { + writeLock.lock(); + try { + this.registered = false; + this.registerCount = 0; + this.timestamp = System.currentTimeMillis(); + this.ackVersion = new AtomicLong(initialVersion.longValue()); + this.requestId = UUID.randomUUID().toString(); + } finally { + writeLock.unlock(); } - - /** - * Getter method for property refused. - * - * @return property value of refused - */ - boolean isRefused() { - readLock.lock(); - try { - return refused; - } finally { - readLock.unlock(); - } + } + + /** @see Register#unregister() */ + @Override + public void unregister() { + writeLock.lock(); + try { + this.enabled = false; + this.pubVersion.incrementAndGet(); + this.requestId = UUID.randomUUID().toString(); + this.registerCount = 0; + } finally { + writeLock.unlock(); + } + } + + /** + * Getter method for property refused. + * + * @return property value of refused + */ + boolean isRefused() { + readLock.lock(); + try { + return refused; + } finally { + readLock.unlock(); + } + } + + /** + * Getter method for property timestamp. + * + * @return property value of timestamp + */ + @Override + public long getTimestamp() { + readLock.lock(); + try { + return timestamp; + } finally { + readLock.unlock(); + } + } + + /** + * Setter method for property timestamp. + * + * @param timestamp value to be assigned to property timestamp + */ + void setTimestamp(long timestamp) { + writeLock.lock(); + try { + this.timestamp = timestamp; + } finally { + writeLock.unlock(); } + } + + /** + * Sets auth signature. + * + * @param register the register + */ + void setAuthSignature(BaseRegister register) { + // auth signature + if (null != authManager) { + Map authAttributes = authManager.getAuthContent(register); + + // merge auth attributes with exists register attributes + Map registerAttributes = register.getAttributes(); + if (null == registerAttributes) { + registerAttributes = new HashMap(); + } + registerAttributes.putAll(authAttributes); + register.setAttributes(registerAttributes); + } + } + + /** + * Setter method for property authManager. + * + * @param authManager value to be assigned to property authManager + */ + public void setAuthManager(AuthManager authManager) { + this.authManager = authManager; + } + + /** @see Object#toString() */ + @Override + public String toString() { + return "AbstractInternalRegister{" + + "initialVersion=" + + initialVersion + + ", registered=" + + registered + + ", enabled=" + + enabled + + ", refused=" + + refused + + ", pubVersion=" + + pubVersion + + ", ackVersion=" + + ackVersion + + ", timestamp=" + + timestamp + + ", registerCount=" + + registerCount + + ", requestId='" + + requestId + + '}'; + } + + /** The type Sync task. */ + public static class SyncTask { + + private String requestId; + + private Object request; + + private boolean done; /** - * Getter method for property timestamp. + * Getter method for property requestId. * - * @return property value of timestamp + * @return property value of requestId */ - @Override - public long getTimestamp() { - readLock.lock(); - try { - return timestamp; - } finally { - readLock.unlock(); - } + public String getRequestId() { + return requestId; } /** - * Setter method for property timestamp. + * Setter method for property requestId. * - * @param timestamp value to be assigned to property timestamp + * @param requestId value to be assigned to property requestId */ - void setTimestamp(long timestamp) { - writeLock.lock(); - try { - this.timestamp = timestamp; - } finally { - writeLock.unlock(); - } + void setRequestId(String requestId) { + this.requestId = requestId; } /** - * Sets auth signature. + * Getter method for property request. * - * @param register the register + * @return property value of request */ - void setAuthSignature(BaseRegister register) { - // auth signature - if (null != authManager) { - Map authAttributes = authManager.getAuthContent(register); - - // merge auth attributes with exists register attributes - Map registerAttributes = register.getAttributes(); - if (null == registerAttributes) { - registerAttributes = new HashMap(); - } - registerAttributes.putAll(authAttributes); - register.setAttributes(registerAttributes); - } + public Object getRequest() { + return request; } /** - * Setter method for property authManager. + * Setter method for property request. * - * @param authManager value to be assigned to property authManager + * @param request value to be assigned to property request */ - public void setAuthManager(AuthManager authManager) { - this.authManager = authManager; + void setRequest(Object request) { + this.request = request; } /** - * @see Object#toString() + * Getter method for property done. + * + * @return property value of done */ - @Override - public String toString() { - return "AbstractInternalRegister{" + "initialVersion=" + initialVersion + ", registered=" - + registered + ", enabled=" + enabled + ", refused=" + refused + ", pubVersion=" - + pubVersion + ", ackVersion=" + ackVersion + ", timestamp=" + timestamp - + ", registerCount=" + registerCount + ", requestId='" + requestId + '}'; + public boolean isDone() { + return done; } /** - * The type Sync task. + * Setter method for property done. + * + * @param done value to be assigned to property done */ - public static class SyncTask { - - private String requestId; - - private Object request; - - private boolean done; - - /** - * Getter method for property requestId. - * - * @return property value of requestId - */ - public String getRequestId() { - return requestId; - } - - /** - * Setter method for property requestId. - * - * @param requestId value to be assigned to property requestId - */ - void setRequestId(String requestId) { - this.requestId = requestId; - } - - /** - * Getter method for property request. - * - * @return property value of request - */ - public Object getRequest() { - return request; - } - - /** - * Setter method for property request. - * - * @param request value to be assigned to property request - */ - void setRequest(Object request) { - this.request = request; - } - - /** - * Getter method for property done. - * - * @return property value of done - */ - public boolean isDone() { - return done; - } - - /** - * Setter method for property done. - * - * @param done value to be assigned to property done - */ - public void setDone(boolean done) { - this.done = done; - } - + public void setDone(boolean done) { + this.done = done; } + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultConfigData.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultConfigData.java index 61be0795d..bcd33c648 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultConfigData.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultConfigData.java @@ -20,32 +20,31 @@ /** * The type Default config data. + * * @author zhuoyu.sjw * @version $Id : DefaultConfigData.java, v 0.1 2018-04-18 15:29 zhuoyu.sjw Exp $$ */ public class DefaultConfigData implements ConfigData { - private String data; + private String data; - /** - * Instantiates a new Default config data. - * - * @param data the data - */ - public DefaultConfigData(String data) { - this.data = data; - } + /** + * Instantiates a new Default config data. + * + * @param data the data + */ + public DefaultConfigData(String data) { + this.data = data; + } - /** - * @see ConfigData#getData() - */ - @Override - public String getData() { - return data; - } + /** @see ConfigData#getData() */ + @Override + public String getData() { + return data; + } - @Override - public String toString() { - return "DefaultConfigData{" + "data='" + data + '\'' + '}'; - } + @Override + public String toString() { + return "DefaultConfigData{" + "data='" + data + '\'' + '}'; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultConfigurator.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultConfigurator.java index 45965c426..40b7567ec 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultConfigurator.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultConfigurator.java @@ -29,7 +29,6 @@ import com.alipay.sofa.registry.core.constants.EventTypeConstants; import com.alipay.sofa.registry.core.model.ConfiguratorRegister; import com.alipay.sofa.registry.core.model.DataBox; - import java.util.UUID; import java.util.concurrent.atomic.AtomicBoolean; @@ -40,188 +39,186 @@ * @version $Id : DefaultConfigurator.java, v 0.1 2018-04-18 14:41 zhuoyu.sjw Exp $$ */ public class DefaultConfigurator extends AbstractInternalRegister implements Configurator { - private final String REGIST_ID; - - private ConfiguratorRegistration registration; + private final String REGIST_ID; - private ConfigDataObserver configDataObserver; + private ConfiguratorRegistration registration; - private RegistryClientConfig config; + private ConfigDataObserver configDataObserver; - private ConfiguratorData configuratorData; + private RegistryClientConfig config; - private Worker worker; + private ConfiguratorData configuratorData; - private AtomicBoolean init = new AtomicBoolean(false); + private Worker worker; - /** - * Instantiates a new Default configurator. - * - * @param config the config - * @param worker the worker - */ - public DefaultConfigurator(ConfiguratorRegistration registration, RegistryClientConfig config, - Worker worker) { - if (null != registration) { - this.configDataObserver = registration.getConfigDataObserver(); - } - this.registration = registration; - this.config = config; - this.worker = worker; - this.REGIST_ID = UUID.randomUUID().toString(); - } + private AtomicBoolean init = new AtomicBoolean(false); - /** - * Gets data observer. - * - * @return the data observer - */ - @Override - public ConfigDataObserver getDataObserver() { - return configDataObserver; + /** + * Instantiates a new Default configurator. + * + * @param config the config + * @param worker the worker + */ + public DefaultConfigurator( + ConfiguratorRegistration registration, RegistryClientConfig config, Worker worker) { + if (null != registration) { + this.configDataObserver = registration.getConfigDataObserver(); } - - /** - * Setter method for property configDataObserver. - * - * @param configDataObserver value to be assigned to property configDataObserver - */ - @Override - public void setDataObserver(ConfigDataObserver configDataObserver) { - this.configDataObserver = configDataObserver; + this.registration = registration; + this.config = config; + this.worker = worker; + this.REGIST_ID = UUID.randomUUID().toString(); + } + + /** + * Gets data observer. + * + * @return the data observer + */ + @Override + public ConfigDataObserver getDataObserver() { + return configDataObserver; + } + + /** + * Setter method for property configDataObserver. + * + * @param configDataObserver value to be assigned to property configDataObserver + */ + @Override + public void setDataObserver(ConfigDataObserver configDataObserver) { + this.configDataObserver = configDataObserver; + } + + /** + * Peek data config data. + * + * @return the config data + */ + @Override + public ConfigData peekData() { + if (!init.get()) { + throw new IllegalStateException("Config data is not ready yet."); } - - /** - * Peek data config data. - * - * @return the config data - */ - @Override - public ConfigData peekData() { - if (!init.get()) { - throw new IllegalStateException("Config data is not ready yet."); - } - if (null != configuratorData) { - DataBox dataBox = configuratorData.getDataBox(); - if (null != dataBox) { - return new DefaultConfigData(dataBox.getData()); - } - } - return new DefaultConfigData(null); + if (null != configuratorData) { + DataBox dataBox = configuratorData.getDataBox(); + if (null != dataBox) { + return new DefaultConfigData(dataBox.getData()); + } } - - /** - * Assembly object. - * - * @return the object - */ - @Override - public Object assembly() { - readLock.lock(); - ConfiguratorRegister register = new ConfiguratorRegister(); - try { - register.setInstanceId(config.getInstanceId()); - if (StringUtils.isNotEmpty(config.getZone())) { - register.setZone(config.getZone()); - } else { - register.setZone(ValueConstants.DEFAULT_ZONE); - } - if (StringUtils.isNotEmpty(registration.getAppName())) { - register.setAppName(registration.getAppName()); - } else { - register.setAppName(config.getAppName()); - } - register.setDataId(registration.getDataId()); - register.setGroup(registration.getGroup()); - register.setRegistId(REGIST_ID); - register.setVersion(this.getPubVersion().get()); - register.setTimestamp(this.getTimestamp()); - - // auth signature - setAuthSignature(register); - - if (isEnabled()) { - register.setEventType(EventTypeConstants.REGISTER); - } else { - register.setEventType(EventTypeConstants.UNREGISTER); - } - } finally { - readLock.unlock(); - } - return register; + return new DefaultConfigData(null); + } + + /** + * Assembly object. + * + * @return the object + */ + @Override + public Object assembly() { + readLock.lock(); + ConfiguratorRegister register = new ConfiguratorRegister(); + try { + register.setInstanceId(config.getInstanceId()); + if (StringUtils.isNotEmpty(config.getZone())) { + register.setZone(config.getZone()); + } else { + register.setZone(ValueConstants.DEFAULT_ZONE); + } + if (StringUtils.isNotEmpty(registration.getAppName())) { + register.setAppName(registration.getAppName()); + } else { + register.setAppName(config.getAppName()); + } + register.setDataId(registration.getDataId()); + register.setGroup(registration.getGroup()); + register.setRegistId(REGIST_ID); + register.setVersion(this.getPubVersion().get()); + register.setTimestamp(this.getTimestamp()); + + // auth signature + setAuthSignature(register); + + if (isEnabled()) { + register.setEventType(EventTypeConstants.REGISTER); + } else { + register.setEventType(EventTypeConstants.UNREGISTER); + } + } finally { + readLock.unlock(); } - - /** - * Put configurator data. - * - * @param receivedConfigData the received config data - */ - public void putConfiguratorData(ConfiguratorData receivedConfigData) { - writeLock.lock(); - try { - if (null == receivedConfigData) { - return; - } - - // default version set to zero - if (null == receivedConfigData.getVersion()) { - receivedConfigData.setVersion(0L); - } - - if (null == configuratorData - || receivedConfigData.getVersion() > configuratorData.getVersion()) { - configuratorData = receivedConfigData; - init.compareAndSet(false, true); - } - - } finally { - writeLock.unlock(); - } + return register; + } + + /** + * Put configurator data. + * + * @param receivedConfigData the received config data + */ + public void putConfiguratorData(ConfiguratorData receivedConfigData) { + writeLock.lock(); + try { + if (null == receivedConfigData) { + return; + } + + // default version set to zero + if (null == receivedConfigData.getVersion()) { + receivedConfigData.setVersion(0L); + } + + if (null == configuratorData + || receivedConfigData.getVersion() > configuratorData.getVersion()) { + configuratorData = receivedConfigData; + init.compareAndSet(false, true); + } + + } finally { + writeLock.unlock(); } - - /** - * Gets data id. - * - * @return the data id - */ - @Override - public String getDataId() { - return registration.getDataId(); + } + + /** + * Gets data id. + * + * @return the data id + */ + @Override + public String getDataId() { + return registration.getDataId(); + } + + /** + * Gets group. + * + * @return the group + */ + @Override + public String getGroup() { + return registration.getGroup(); + } + + /** + * Gets regist id. + * + * @return the regist id + */ + @Override + public String getRegistId() { + return REGIST_ID; + } + + /** Unregister. */ + @Override + public void unregister() { + if (isEnabled()) { + super.unregister(); + this.worker.schedule(new TaskEvent(this)); } + } - /** - * Gets group. - * - * @return the group - */ - @Override - public String getGroup() { - return registration.getGroup(); - } - - /** - * Gets regist id. - * - * @return the regist id - */ - @Override - public String getRegistId() { - return REGIST_ID; - } - - /** - * Unregister. - */ - @Override - public void unregister() { - if (isEnabled()) { - super.unregister(); - this.worker.schedule(new TaskEvent(this)); - } - } - - @Override - public String toString() { - return "DefaultConfigurator{" + "registration=" + registration + '}'; - } + @Override + public String toString() { + return "DefaultConfigurator{" + "registration=" + registration + '}'; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultObserverHandler.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultObserverHandler.java index 2cde5978f..abed51b2b 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultObserverHandler.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultObserverHandler.java @@ -27,166 +27,160 @@ import com.alipay.sofa.registry.client.factory.NamedThreadFactory; import com.alipay.sofa.registry.client.log.LoggerFactory; import com.alipay.sofa.registry.client.task.ObserverHandler; -import org.slf4j.Logger; - import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; /** * The type Default observer handler. + * * @author zhuoyu.sjw * @version $Id : DefaultObserverHandler.java, v 0.1 2018-03-15 12:02 zhuoyu.sjw Exp $$ */ public class DefaultObserverHandler implements ObserverHandler { - /** LOGGER */ - private static final Logger LOGGER = LoggerFactory - .getLogger(DefaultObserverHandler.class); + /** LOGGER */ + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultObserverHandler.class); - private static final int KEEP_ALIVE_TIME = 60; + private static final int KEEP_ALIVE_TIME = 60; - private ExecutorService executor; + private ExecutorService executor; - private EventBus eventBus; + private EventBus eventBus; - private RegistryClientConfig config; + private RegistryClientConfig config; - /** - * Constructor. - * - * @param config the config - */ - public DefaultObserverHandler(RegistryClientConfig config, EventBus eventBus) { - this.config = config; - this.executor = new ThreadPoolExecutor(config.getObserverThreadCoreSize(), - config.getObserverThreadMaxSize(), KEEP_ALIVE_TIME, TimeUnit.SECONDS, + /** + * Constructor. + * + * @param config the config + */ + public DefaultObserverHandler(RegistryClientConfig config, EventBus eventBus) { + this.config = config; + this.executor = + new ThreadPoolExecutor( + config.getObserverThreadCoreSize(), + config.getObserverThreadMaxSize(), + KEEP_ALIVE_TIME, + TimeUnit.SECONDS, new LinkedBlockingDeque(config.getObserverThreadQueueLength()), new NamedThreadFactory("ObserverNotifyThread")); - this.eventBus = eventBus; - } + this.eventBus = eventBus; + } - /** - * @see ObserverHandler#notify(Subscriber) - */ - @Override - public void notify(Subscriber subscriber) { - executor.submit(new SubscriberNotifyTask(subscriber)); - } + /** @see ObserverHandler#notify(Subscriber) */ + @Override + public void notify(Subscriber subscriber) { + executor.submit(new SubscriberNotifyTask(subscriber)); + } - /** - * @see ObserverHandler#notify(Configurator) - */ - @Override - public void notify(Configurator configurator) { - executor.submit(new ConfiguratorNotifyTask(configurator)); - } + /** @see ObserverHandler#notify(Configurator) */ + @Override + public void notify(Configurator configurator) { + executor.submit(new ConfiguratorNotifyTask(configurator)); + } + + /** The type Observer notify task. */ + public class SubscriberNotifyTask implements Runnable { + + private Subscriber subscriber; /** - * The type Observer notify task. + * Constructor. + * + * @param subscriber the subscriber */ - public class SubscriberNotifyTask implements Runnable { - - private Subscriber subscriber; + public SubscriberNotifyTask(Subscriber subscriber) { + this.subscriber = subscriber; + } - /** - * Constructor. - * - * @param subscriber the subscriber - */ - public SubscriberNotifyTask(Subscriber subscriber) { - this.subscriber = subscriber; + /** @see Runnable#run() */ + @Override + public void run() { + // ignore empty task + if (null == subscriber) { + return; + } + + SubscriberProcessEvent event = new SubscriberProcessEvent(); + long start = System.currentTimeMillis(); + event.setStart(start); + event.setConfig(config); + event.setSubscriber(subscriber); + try { + SubscriberDataObserver dataObserver = subscriber.getDataObserver(); + if (null != dataObserver) { + dataObserver.handleData(subscriber.getDataId(), subscriber.peekData()); } - - /** - * @see Runnable#run() - */ - @Override - public void run() { - // ignore empty task - if (null == subscriber) { - return; - } - - SubscriberProcessEvent event = new SubscriberProcessEvent(); - long start = System.currentTimeMillis(); - event.setStart(start); - event.setConfig(config); - event.setSubscriber(subscriber); - try { - SubscriberDataObserver dataObserver = subscriber.getDataObserver(); - if (null != dataObserver) { - dataObserver.handleData(subscriber.getDataId(), subscriber.peekData()); - } - LOGGER.info( - "[notify] notify subscriber success, dataId: {}, registId:{}, cost: {}ms", - subscriber.getDataId(), subscriber.getRegistId(), - (System.currentTimeMillis() - start)); - } catch (Exception e) { - LOGGER.error("[notify] SubscriberNotifyTask execute error, dataId: {}", - subscriber.getDataId(), e); - event.setThrowable(e); - } finally { - event.setEnd(System.currentTimeMillis()); - if (null != eventBus) { - eventBus.post(event); - } - } + LOGGER.info( + "[notify] notify subscriber success, dataId: {}, registId:{}, cost: {}ms", + subscriber.getDataId(), + subscriber.getRegistId(), + (System.currentTimeMillis() - start)); + } catch (Exception e) { + LOGGER.error( + "[notify] SubscriberNotifyTask execute error, dataId: {}", subscriber.getDataId(), e); + event.setThrowable(e); + } finally { + event.setEnd(System.currentTimeMillis()); + if (null != eventBus) { + eventBus.post(event); } - + } } + } + + /** The type Configurator notify task. */ + public class ConfiguratorNotifyTask implements Runnable { + + private Configurator configurator; /** - * The type Configurator notify task. + * Instantiates a new Configurator notify task. + * + * @param configurator the configurator */ - public class ConfiguratorNotifyTask implements Runnable { - - private Configurator configurator; + public ConfiguratorNotifyTask(Configurator configurator) { + this.configurator = configurator; + } - /** - * Instantiates a new Configurator notify task. - * - * @param configurator the configurator - */ - public ConfiguratorNotifyTask(Configurator configurator) { - this.configurator = configurator; + /** @see Runnable#run() */ + @Override + public void run() { + if (null == configurator) { + return; + } + + ConfiguratorProcessEvent event = new ConfiguratorProcessEvent(); + long start = System.currentTimeMillis(); + event.setStart(start); + event.setConfig(config); + event.setConfigurator(configurator); + try { + ConfigDataObserver dataObserver = configurator.getDataObserver(); + if (null != dataObserver) { + dataObserver.handleData(configurator.getDataId(), configurator.peekData()); } - /** - * @see Runnable#run() - */ - @Override - public void run() { - if (null == configurator) { - return; - } - - ConfiguratorProcessEvent event = new ConfiguratorProcessEvent(); - long start = System.currentTimeMillis(); - event.setStart(start); - event.setConfig(config); - event.setConfigurator(configurator); - try { - ConfigDataObserver dataObserver = configurator.getDataObserver(); - if (null != dataObserver) { - dataObserver.handleData(configurator.getDataId(), configurator.peekData()); - } - - LOGGER.info( - "[notify] notify configurator success, dataId: {}, registId:{}, cost: {}ms", - configurator.getDataId(), configurator.getRegistId(), - (System.currentTimeMillis() - start)); - } catch (Exception e) { - LOGGER.error("[notify] ConfiguratorNotifyTask execute error, dataId: {}", - configurator.getDataId(), e); - event.setThrowable(e); - } finally { - event.setEnd(System.currentTimeMillis()); - if (null != eventBus) { - eventBus.post(event); - } - } + LOGGER.info( + "[notify] notify configurator success, dataId: {}, registId:{}, cost: {}ms", + configurator.getDataId(), + configurator.getRegistId(), + (System.currentTimeMillis() - start)); + } catch (Exception e) { + LOGGER.error( + "[notify] ConfiguratorNotifyTask execute error, dataId: {}", + configurator.getDataId(), + e); + event.setThrowable(e); + } finally { + event.setEnd(System.currentTimeMillis()); + if (null != eventBus) { + eventBus.post(event); } + } } + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultPublisher.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultPublisher.java index f305a7d11..27c732141 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultPublisher.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultPublisher.java @@ -26,7 +26,6 @@ import com.alipay.sofa.registry.core.constants.EventTypeConstants; import com.alipay.sofa.registry.core.model.DataBox; import com.alipay.sofa.registry.core.model.PublisherRegister; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -41,140 +40,130 @@ */ public class DefaultPublisher extends AbstractInternalRegister implements Publisher { - private final String REGIST_ID; - private PublisherRegistration registration; - private Worker worker; - private Collection dataList; - private RegistryClientConfig config; - - /** - * Instantiates a new Default publisher. - * - * @param registration the publisher registration - * @param worker the worker - */ - DefaultPublisher(PublisherRegistration registration, Worker worker, RegistryClientConfig config) { - this.registration = registration; - this.worker = worker; - this.config = config; - this.REGIST_ID = UUID.randomUUID().toString(); + private final String REGIST_ID; + private PublisherRegistration registration; + private Worker worker; + private Collection dataList; + private RegistryClientConfig config; + + /** + * Instantiates a new Default publisher. + * + * @param registration the publisher registration + * @param worker the worker + */ + DefaultPublisher(PublisherRegistration registration, Worker worker, RegistryClientConfig config) { + this.registration = registration; + this.worker = worker; + this.config = config; + this.REGIST_ID = UUID.randomUUID().toString(); + } + + /** @see Publisher#republish(String...) */ + @Override + public void republish(String... data) { + if (isRefused()) { + throw new IllegalStateException( + "Publisher is refused by server. Try to check your configuration."); } - /** - * @see Publisher#republish(String...) - */ - @Override - public void republish(String... data) { - if (isRefused()) { - throw new IllegalStateException( - "Publisher is refused by server. Try to check your configuration."); - } - - if (!isEnabled()) { - throw new IllegalStateException("Unregistered publisher can not be reused."); - } - - writeLock.lock(); - try { - if (null != data) { - this.dataList = Arrays.asList(data); - } - - this.getPubVersion().incrementAndGet(); - this.setTimestamp(System.currentTimeMillis()); - this.waitToSync(); - } finally { - writeLock.unlock(); - } - this.worker.schedule(new TaskEvent(this)); + if (!isEnabled()) { + throw new IllegalStateException("Unregistered publisher can not be reused."); } - /** - * Unregister. - */ - @Override - public void unregister() { - if (isEnabled()) { - super.unregister(); - this.worker.schedule(new TaskEvent(this)); - } + writeLock.lock(); + try { + if (null != data) { + this.dataList = Arrays.asList(data); + } + + this.getPubVersion().incrementAndGet(); + this.setTimestamp(System.currentTimeMillis()); + this.waitToSync(); + } finally { + writeLock.unlock(); } - - /** - * Assembly publisher register. - * - * @return the publisher register - */ - @Override - public PublisherRegister assembly() { - readLock.lock(); - PublisherRegister register; - try { - register = new PublisherRegister(); - register.setInstanceId(config.getInstanceId()); - if (StringUtils.isNotEmpty(config.getZone())) { - register.setZone(config.getZone()); - } else { - register.setZone(ValueConstants.DEFAULT_ZONE); - } - if (StringUtils.isNotEmpty(registration.getAppName())) { - register.setAppName(registration.getAppName()); - } else { - register.setAppName(config.getAppName()); - } - register.setDataId(registration.getDataId()); - register.setGroup(registration.getGroup()); - register.setRegistId(REGIST_ID); - register.setVersion(this.getPubVersion().get()); - register.setTimestamp(this.getTimestamp()); - - // auth signature - setAuthSignature(register); - - if (isEnabled()) { - register.setEventType(EventTypeConstants.REGISTER); - if (null != dataList) { - List dataBoxes = new ArrayList(); - for (String data : dataList) { - dataBoxes.add(new DataBox(data)); - } - register.setDataList(dataBoxes); - } - } else { - register.setEventType(EventTypeConstants.UNREGISTER); - } - } finally { - readLock.unlock(); - } - return register; + this.worker.schedule(new TaskEvent(this)); + } + + /** Unregister. */ + @Override + public void unregister() { + if (isEnabled()) { + super.unregister(); + this.worker.schedule(new TaskEvent(this)); } - - /** - * @see Publisher#getDataId() - */ - @Override - public String getDataId() { - return registration.getDataId(); - } - - @Override - public String getGroup() { - return registration.getGroup(); - } - - /** - * @see Publisher#getRegistId() - */ - @Override - public String getRegistId() { - return REGIST_ID; - } - - /** - * @see Object#toString() - */ - @Override - public String toString() { - return "DefaultPublisher{" + "registration=" + registration + '}' + super.toString(); + } + + /** + * Assembly publisher register. + * + * @return the publisher register + */ + @Override + public PublisherRegister assembly() { + readLock.lock(); + PublisherRegister register; + try { + register = new PublisherRegister(); + register.setInstanceId(config.getInstanceId()); + if (StringUtils.isNotEmpty(config.getZone())) { + register.setZone(config.getZone()); + } else { + register.setZone(ValueConstants.DEFAULT_ZONE); + } + if (StringUtils.isNotEmpty(registration.getAppName())) { + register.setAppName(registration.getAppName()); + } else { + register.setAppName(config.getAppName()); + } + register.setDataId(registration.getDataId()); + register.setGroup(registration.getGroup()); + register.setRegistId(REGIST_ID); + register.setVersion(this.getPubVersion().get()); + register.setTimestamp(this.getTimestamp()); + + // auth signature + setAuthSignature(register); + + if (isEnabled()) { + register.setEventType(EventTypeConstants.REGISTER); + if (null != dataList) { + List dataBoxes = new ArrayList(); + for (String data : dataList) { + dataBoxes.add(new DataBox(data)); + } + register.setDataList(dataBoxes); + } + } else { + register.setEventType(EventTypeConstants.UNREGISTER); + } + } finally { + readLock.unlock(); } + return register; + } + + /** @see Publisher#getDataId() */ + @Override + public String getDataId() { + return registration.getDataId(); + } + + @Override + public String getGroup() { + return registration.getGroup(); + } + + /** @see Publisher#getRegistId() */ + @Override + public String getRegistId() { + return REGIST_ID; + } + + /** @see Object#toString() */ + @Override + public String toString() { + return "DefaultPublisher{" + "registration=" + registration + '}' + super.toString(); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClient.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClient.java index b58568d80..a36d8ad7d 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClient.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClient.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.client.provider; +import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; + import com.alipay.remoting.ConnectionEventProcessor; import com.alipay.remoting.ConnectionEventType; import com.alipay.remoting.rpc.protocol.UserProcessor; @@ -52,8 +54,6 @@ import com.alipay.sofa.registry.client.util.StringUtils; import com.alipay.sofa.registry.core.model.ReceivedConfigData; import com.alipay.sofa.registry.core.model.ReceivedData; -import org.slf4j.Logger; - import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -62,548 +62,557 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicBoolean; - -import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; +import org.slf4j.Logger; /** * The type Default registry client. + * * @author zhuoyu.sjw * @version $Id : DefaultRegistryClient.java, v 0.1 2017-11-23 20:07 zhuoyu.sjw Exp $$ */ public class DefaultRegistryClient implements RegistryClient { - /** LOGGER */ - private static final Logger LOGGER = LoggerFactory - .getLogger(DefaultRegistryClient.class); + /** LOGGER */ + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRegistryClient.class); + + private RegistryClientConfig registryClientConfig; - private RegistryClientConfig registryClientConfig; + private RegisterCache registerCache; - private RegisterCache registerCache; + private ServerManager serverManager; - private ServerManager serverManager; + private WorkerThread workerThread; - private WorkerThread workerThread; + private ClientConnection client; - private ClientConnection client; + private Map, UserProcessor> userProcessorMap; - private Map, UserProcessor> userProcessorMap; + private Map connectionEventProcessorMap; - private Map connectionEventProcessorMap; + private ConcurrentMap registrationPublisherMap; - private ConcurrentMap registrationPublisherMap; + private ConcurrentMap registrationSubscriberMap; - private ConcurrentMap registrationSubscriberMap; + private ConcurrentMap registrationConfiguratorMap; - private ConcurrentMap registrationConfiguratorMap; + private ObserverHandler observerHandler; - private ObserverHandler observerHandler; + private AuthManager authManager; - private AuthManager authManager; + private EventBus eventBus; - private EventBus eventBus; + private LookoutSubscriber lookoutSubscriber; - private LookoutSubscriber lookoutSubscriber; + private AtomicBoolean init = new AtomicBoolean(false); - private AtomicBoolean init = new AtomicBoolean(false); + /** + * Instantiates a new Default registry client. + * + * @param registryClientConfig the registry client config + */ + public DefaultRegistryClient(RegistryClientConfig registryClientConfig) { + // clone config to avoid configuration changes at runtime + this.registryClientConfig = cloneConfig(registryClientConfig); + this.registerCache = new RegisterCache(); + this.registrationPublisherMap = new ConcurrentHashMap(); + this.registrationSubscriberMap = new ConcurrentHashMap(); + this.registrationConfiguratorMap = + new ConcurrentHashMap(); + } - /** - * Instantiates a new Default registry client. - * - * @param registryClientConfig the registry client config - */ - public DefaultRegistryClient(RegistryClientConfig registryClientConfig) { - // clone config to avoid configuration changes at runtime - this.registryClientConfig = cloneConfig(registryClientConfig); - this.registerCache = new RegisterCache(); - this.registrationPublisherMap = new ConcurrentHashMap(); - this.registrationSubscriberMap = new ConcurrentHashMap(); - this.registrationConfiguratorMap = new ConcurrentHashMap(); + private DefaultRegistryClientConfig cloneConfig(RegistryClientConfig registryClientConfig) { + DefaultRegistryClientConfig cloneConfig = null; + DefaultRegistryClientConfigBuilder builder = DefaultRegistryClientConfigBuilder.start(); + if (null != registryClientConfig) { + cloneConfig = + builder + .setEnv(registryClientConfig.getEnv()) + .setAppName(registryClientConfig.getAppName()) + .setInstanceId(registryClientConfig.getInstanceId()) + .setDataCenter(registryClientConfig.getDataCenter()) + .setZone(registryClientConfig.getZone()) + .setRegistryEndpoint(registryClientConfig.getRegistryEndpoint()) + .setRegistryEndpointPort(registryClientConfig.getRegistryEndpointPort()) + .setConnectTimeout(registryClientConfig.getConnectTimeout()) + .setSocketTimeout(registryClientConfig.getSocketTimeout()) + .setInvokeTimeout(registryClientConfig.getInvokeTimeout()) + .setRecheckInterval(registryClientConfig.getRecheckInterval()) + .setObserverThreadCoreSize(registryClientConfig.getObserverThreadCoreSize()) + .setObserverThreadMaxSize(registryClientConfig.getObserverThreadMaxSize()) + .setObserverThreadQueueLength(registryClientConfig.getObserverThreadQueueLength()) + .setObserverCallbackTimeout(registryClientConfig.getObserverCallbackTimeout()) + .setSyncConfigRetryInterval(registryClientConfig.getSyncConfigRetryInterval()) + .setAccessKey(registryClientConfig.getAccessKey()) + .setSecretKey(registryClientConfig.getSecretKey()) + .build(); } + return cloneConfig; + } - private DefaultRegistryClientConfig cloneConfig(RegistryClientConfig registryClientConfig) { - DefaultRegistryClientConfig cloneConfig = null; - DefaultRegistryClientConfigBuilder builder = DefaultRegistryClientConfigBuilder.start(); - if (null != registryClientConfig) { - cloneConfig = builder.setEnv(registryClientConfig.getEnv()) - .setAppName(registryClientConfig.getAppName()) - .setInstanceId(registryClientConfig.getInstanceId()) - .setDataCenter(registryClientConfig.getDataCenter()) - .setZone(registryClientConfig.getZone()) - .setRegistryEndpoint(registryClientConfig.getRegistryEndpoint()) - .setRegistryEndpointPort(registryClientConfig.getRegistryEndpointPort()) - .setConnectTimeout(registryClientConfig.getConnectTimeout()) - .setSocketTimeout(registryClientConfig.getSocketTimeout()) - .setInvokeTimeout(registryClientConfig.getInvokeTimeout()) - .setRecheckInterval(registryClientConfig.getRecheckInterval()) - .setObserverThreadCoreSize(registryClientConfig.getObserverThreadCoreSize()) - .setObserverThreadMaxSize(registryClientConfig.getObserverThreadMaxSize()) - .setObserverThreadQueueLength(registryClientConfig.getObserverThreadQueueLength()) - .setObserverCallbackTimeout(registryClientConfig.getObserverCallbackTimeout()) - .setSyncConfigRetryInterval(registryClientConfig.getSyncConfigRetryInterval()) - .setAccessKey(registryClientConfig.getAccessKey()) - .setSecretKey(registryClientConfig.getSecretKey()).build(); - } - return cloneConfig; + /** Init. */ + public void init() { + if (!init.compareAndSet(false, true)) { + return; } - /** - * Init. - */ - public void init() { - if (!init.compareAndSet(false, true)) { - return; - } + // init lookout subscriber + if (null == lookoutSubscriber) { + this.lookoutSubscriber = new LookoutSubscriber(); + } - // init lookout subscriber - if (null == lookoutSubscriber) { - this.lookoutSubscriber = new LookoutSubscriber(); - } + // init event bus + if (null == eventBus) { + this.eventBus = new DefaultEventBus(registryClientConfig); + this.eventBus.register(SubscriberProcessEvent.class, lookoutSubscriber); + this.eventBus.register(ConfiguratorProcessEvent.class, lookoutSubscriber); + } - // init event bus - if (null == eventBus) { - this.eventBus = new DefaultEventBus(registryClientConfig); - this.eventBus.register(SubscriberProcessEvent.class, lookoutSubscriber); - this.eventBus.register(ConfiguratorProcessEvent.class, lookoutSubscriber); - } + // init server manager + if (null == serverManager) { + this.serverManager = new DefaultServerManager(registryClientConfig); + } - // init server manager - if (null == serverManager) { - this.serverManager = new DefaultServerManager(registryClientConfig); - } + // init observer handler + if (null == observerHandler) { + observerHandler = new DefaultObserverHandler(registryClientConfig, eventBus); + } - // init observer handler - if (null == observerHandler) { - observerHandler = new DefaultObserverHandler(registryClientConfig, eventBus); - } + // init auth manager + if (null == authManager) { + authManager = NoopAuthManager.INSTANCE; + } - // init auth manager - if (null == authManager) { - authManager = NoopAuthManager.INSTANCE; - } + // init user processor + List userProcessorList = new ArrayList(); + if (null == userProcessorMap) { + userProcessorList.add(new ReceivedDataProcessor(registerCache, observerHandler)); + userProcessorList.add(new ReceivedConfigDataProcessor(registerCache, observerHandler)); + } else { + UserProcessor userProcessor = userProcessorMap.get(ReceivedData.class); + if (null == userProcessor) { + userProcessorList.add(new ReceivedDataProcessor(registerCache, observerHandler)); + } + userProcessor = userProcessorMap.get(ReceivedConfigData.class); + if (null == userProcessor) { + userProcessorList.add(new ReceivedConfigDataProcessor(registerCache, observerHandler)); + } + userProcessorList.addAll(userProcessorMap.values()); + } - // init user processor - List userProcessorList = new ArrayList(); - if (null == userProcessorMap) { - userProcessorList.add(new ReceivedDataProcessor(registerCache, observerHandler)); - userProcessorList.add(new ReceivedConfigDataProcessor(registerCache, observerHandler)); - } else { - UserProcessor userProcessor = userProcessorMap.get(ReceivedData.class); - if (null == userProcessor) { - userProcessorList.add(new ReceivedDataProcessor(registerCache, observerHandler)); - } - userProcessor = userProcessorMap.get(ReceivedConfigData.class); - if (null == userProcessor) { - userProcessorList.add(new ReceivedConfigDataProcessor(registerCache, - observerHandler)); - } - userProcessorList.addAll(userProcessorMap.values()); - } + // init connection event processor + if (null == connectionEventProcessorMap) { + connectionEventProcessorMap = + new HashMap( + ConnectionEventType.values().length); + } + if (null == connectionEventProcessorMap.get(ConnectionEventType.CLOSE)) { + ClientConnectionCloseEventProcessor connectionCloseEventProcessor = + new ClientConnectionCloseEventProcessor(); + connectionEventProcessorMap.put(ConnectionEventType.CLOSE, connectionCloseEventProcessor); + } + if (null == connectionEventProcessorMap.get(ConnectionEventType.CONNECT)) { + ClientConnectionOpenEventProcessor connectionOpenEventProcessor = + new ClientConnectionOpenEventProcessor(); + connectionEventProcessorMap.put(ConnectionEventType.CONNECT, connectionOpenEventProcessor); + } - // init connection event processor - if (null == connectionEventProcessorMap) { - connectionEventProcessorMap = new HashMap( - ConnectionEventType.values().length); - } - if (null == connectionEventProcessorMap.get(ConnectionEventType.CLOSE)) { - ClientConnectionCloseEventProcessor connectionCloseEventProcessor = new ClientConnectionCloseEventProcessor(); - connectionEventProcessorMap.put(ConnectionEventType.CLOSE, - connectionCloseEventProcessor); - } - if (null == connectionEventProcessorMap.get(ConnectionEventType.CONNECT)) { - ClientConnectionOpenEventProcessor connectionOpenEventProcessor = new ClientConnectionOpenEventProcessor(); - connectionEventProcessorMap.put(ConnectionEventType.CONNECT, - connectionOpenEventProcessor); - } + // init client connection and register worker + client = + new ClientConnection( + serverManager, + userProcessorList, + connectionEventProcessorMap, + registerCache, + registryClientConfig); - // init client connection and register worker - client = new ClientConnection(serverManager, userProcessorList, - connectionEventProcessorMap, registerCache, registryClientConfig); + workerThread = new WorkerThread(client, registryClientConfig, registerCache); + client.setWorker(workerThread); - workerThread = new WorkerThread(client, registryClientConfig, registerCache); - client.setWorker(workerThread); + client.init(); - client.init(); + // init registry check thread + new RegistryCheckThread().start(); - // init registry check thread - new RegistryCheckThread().start(); + // init sync config thread + new SyncConfigThread(client, registerCache, registryClientConfig, observerHandler).start(); + } - // init sync config thread - new SyncConfigThread(client, registerCache, registryClientConfig, observerHandler).start(); + /** @see RegistryClient#register(PublisherRegistration, String...) */ + @Override + public Publisher register(PublisherRegistration registration, String... data) { + if (!init.get()) { + throw new IllegalStateException("Client needs to be initialized before using."); } - /** - * @see RegistryClient#register(PublisherRegistration, String...) - */ - @Override - public Publisher register(PublisherRegistration registration, String... data) { - if (!init.get()) { - throw new IllegalStateException("Client needs to be initialized before using."); - } - - if (null == registration) { - throw new IllegalArgumentException("Registration can not be null."); - } - - if (StringUtils.isBlank(registration.getDataId())) { - throw new IllegalArgumentException("DataId can not be null"); - } - - if (StringUtils.isBlank(registration.getGroup())) { - registration.setGroup(DEFAULT_GROUP); - } - - Publisher publisher = registrationPublisherMap.get(registration); - - if (null != publisher) { - throwDuplicateException(registration, publisher); - } + if (null == registration) { + throw new IllegalArgumentException("Registration can not be null."); + } - publisher = new DefaultPublisher(registration, workerThread, registryClientConfig); - ((DefaultPublisher) publisher).setAuthManager(authManager); + if (StringUtils.isBlank(registration.getDataId())) { + throw new IllegalArgumentException("DataId can not be null"); + } - Publisher oldPublisher = registrationPublisherMap.putIfAbsent(registration, publisher); - if (null != oldPublisher) { - throwDuplicateException(registration, oldPublisher); - } + if (StringUtils.isBlank(registration.getGroup())) { + registration.setGroup(DEFAULT_GROUP); + } - registerCache.addRegister(publisher); + Publisher publisher = registrationPublisherMap.get(registration); - publisher.republish(data); + if (null != publisher) { + throwDuplicateException(registration, publisher); + } - LOGGER.info("[api] Regist publisher success, dataId: {}, group: {}, registerId: {}", - publisher.getDataId(), publisher.getGroup(), publisher.getRegistId()); + publisher = new DefaultPublisher(registration, workerThread, registryClientConfig); + ((DefaultPublisher) publisher).setAuthManager(authManager); - return publisher; + Publisher oldPublisher = registrationPublisherMap.putIfAbsent(registration, publisher); + if (null != oldPublisher) { + throwDuplicateException(registration, oldPublisher); } - private void throwDuplicateException(PublisherRegistration registration, Publisher publisher) { - LOGGER.info("[api] Publisher already exists, dataId: {}, group: {}, registerId: {}", - publisher.getDataId(), publisher.getGroup(), publisher.getRegistId()); - - throw new DuplicateException("Duplicate Publisher registration. (dataId: " - + registration.getDataId() + ", group: " - + registration.getGroup() + ")"); + registerCache.addRegister(publisher); + + publisher.republish(data); + + LOGGER.info( + "[api] Regist publisher success, dataId: {}, group: {}, registerId: {}", + publisher.getDataId(), + publisher.getGroup(), + publisher.getRegistId()); + + return publisher; + } + + private void throwDuplicateException(PublisherRegistration registration, Publisher publisher) { + LOGGER.info( + "[api] Publisher already exists, dataId: {}, group: {}, registerId: {}", + publisher.getDataId(), + publisher.getGroup(), + publisher.getRegistId()); + + throw new DuplicateException( + "Duplicate Publisher registration. (dataId: " + + registration.getDataId() + + ", group: " + + registration.getGroup() + + ")"); + } + + /** @see RegistryClient#register(SubscriberRegistration) */ + @Override + public Subscriber register(SubscriberRegistration registration) { + if (!init.get()) { + throw new IllegalStateException("Client needs to be initialized before using."); } - /** - * @see RegistryClient#register(SubscriberRegistration) - */ - @Override - public Subscriber register(SubscriberRegistration registration) { - if (!init.get()) { - throw new IllegalStateException("Client needs to be initialized before using."); - } + if (null == registration) { + throw new IllegalArgumentException("Registration can not be null."); + } - if (null == registration) { - throw new IllegalArgumentException("Registration can not be null."); - } + if (StringUtils.isBlank(registration.getDataId())) { + throw new IllegalArgumentException("DataId can not be null."); + } - if (StringUtils.isBlank(registration.getDataId())) { - throw new IllegalArgumentException("DataId can not be null."); - } + if (null == registration.getSubscriberDataObserver()) { + throw new IllegalArgumentException("Subscriber data observer can not be null."); + } - if (null == registration.getSubscriberDataObserver()) { - throw new IllegalArgumentException("Subscriber data observer can not be null."); - } + if (StringUtils.isBlank(registration.getGroup())) { + registration.setGroup(DEFAULT_GROUP); + } - if (StringUtils.isBlank(registration.getGroup())) { - registration.setGroup(DEFAULT_GROUP); - } + Subscriber subscriber = registrationSubscriberMap.get(registration); - Subscriber subscriber = registrationSubscriberMap.get(registration); + if (null != subscriber) { + throwDuplicateException(registration, subscriber); + } - if (null != subscriber) { - throwDuplicateException(registration, subscriber); - } + subscriber = new DefaultSubscriber(registration, workerThread, registryClientConfig); + ((DefaultSubscriber) subscriber).setAuthManager(authManager); - subscriber = new DefaultSubscriber(registration, workerThread, registryClientConfig); - ((DefaultSubscriber) subscriber).setAuthManager(authManager); + Subscriber oldSubscriber = registrationSubscriberMap.putIfAbsent(registration, subscriber); + if (null != oldSubscriber) { + throwDuplicateException(registration, oldSubscriber); + } - Subscriber oldSubscriber = registrationSubscriberMap.putIfAbsent(registration, subscriber); - if (null != oldSubscriber) { - throwDuplicateException(registration, oldSubscriber); - } + registerCache.addRegister(subscriber); + addRegisterTask(subscriber); - registerCache.addRegister(subscriber); - addRegisterTask(subscriber); + LOGGER.info( + "[api] Regist subscriber success, dataId: {}, group: {}, scope: {}, registerId: {}", + subscriber.getDataId(), + subscriber.getGroup(), + subscriber.getScopeEnum(), + subscriber.getRegistId()); - LOGGER.info( - "[api] Regist subscriber success, dataId: {}, group: {}, scope: {}, registerId: {}", - subscriber.getDataId(), subscriber.getGroup(), subscriber.getScopeEnum(), - subscriber.getRegistId()); + return subscriber; + } - return subscriber; + /** @see RegistryClient#register(ConfiguratorRegistration) */ + @Override + public Configurator register(ConfiguratorRegistration registration) { + if (!init.get()) { + throw new IllegalStateException("Client needs to be initialized before using."); } - /** - * @see RegistryClient#register(ConfiguratorRegistration) - */ - @Override - public Configurator register(ConfiguratorRegistration registration) { - if (!init.get()) { - throw new IllegalStateException("Client needs to be initialized before using."); - } + if (null == registration) { + throw new IllegalArgumentException("Registration can not be null."); + } - if (null == registration) { - throw new IllegalArgumentException("Registration can not be null."); - } + if (StringUtils.isBlank(registration.getDataId())) { + throw new IllegalArgumentException("DataId can not be null."); + } - if (StringUtils.isBlank(registration.getDataId())) { - throw new IllegalArgumentException("DataId can not be null."); - } + if (null == registration.getConfigDataObserver()) { + throw new IllegalArgumentException("Config data observer can not be null"); + } - if (null == registration.getConfigDataObserver()) { - throw new IllegalArgumentException("Config data observer can not be null"); - } + if (StringUtils.isBlank(registration.getGroup())) { + registration.setGroup(DEFAULT_GROUP); + } - if (StringUtils.isBlank(registration.getGroup())) { - registration.setGroup(DEFAULT_GROUP); - } + Configurator configurator = registrationConfiguratorMap.get(registration); - Configurator configurator = registrationConfiguratorMap.get(registration); + if (null != configurator) { + throwDuplicateException(configurator); + } - if (null != configurator) { - throwDuplicateException(configurator); - } + configurator = new DefaultConfigurator(registration, registryClientConfig, workerThread); + ((DefaultConfigurator) configurator).setAuthManager(authManager); - configurator = new DefaultConfigurator(registration, registryClientConfig, workerThread); - ((DefaultConfigurator) configurator).setAuthManager(authManager); + Configurator oldConfigurator = + registrationConfiguratorMap.putIfAbsent(registration, configurator); + if (null != oldConfigurator) { + throwDuplicateException(configurator); + } - Configurator oldConfigurator = registrationConfiguratorMap.putIfAbsent(registration, - configurator); - if (null != oldConfigurator) { - throwDuplicateException(configurator); - } + registerCache.addRegister(configurator); + addRegisterTask(configurator); + + LOGGER.info( + "[api] Regist configurator success, dataId: {}, registerId: {}", + configurator.getDataId(), + configurator.getRegistId()); + + return configurator; + } + + private void throwDuplicateException(Configurator configurator) { + LOGGER.info( + "[api] Configurator already exists, dataId: {}, registerId: {}", + configurator.getDataObserver(), + configurator.getRegistId()); + throw new DuplicateException( + "Duplicate configurator registration. (dataId: " + configurator.getDataId() + " )"); + } + + /** @see RegistryClient#unregister(String, String, RegistryType) */ + @Override + public int unregister(String dataId, String group, RegistryType registryType) { + if (StringUtils.isBlank(dataId)) { + throw new IllegalArgumentException("dataId can not be empty"); + } - registerCache.addRegister(configurator); - addRegisterTask(configurator); + if (null == registryType) { + throw new IllegalArgumentException("registry type can not be null"); + } - LOGGER.info("[api] Regist configurator success, dataId: {}, registerId: {}", - configurator.getDataId(), configurator.getRegistId()); + if (null == group) { + group = DEFAULT_GROUP; + } - return configurator; + List registers = new ArrayList(); + + if (RegistryType.PUBLISHER == registryType) { + Collection publishers = registerCache.getAllPublishers(); + for (Publisher publisher : publishers) { + if (dataId.equals(publisher.getDataId()) && group.equals(publisher.getGroup())) { + registers.add(publisher); + } + } + } else if (RegistryType.SUBSCRIBER == registryType) { + Collection subscribers = registerCache.getAllSubscribers(); + for (Subscriber subscriber : subscribers) { + if (dataId.equals(subscriber.getDataId()) && group.equals(subscriber.getGroup())) { + registers.add(subscriber); + } + } + } else if (RegistryType.CONFIGURATOR == registryType) { + Collection configurators = registerCache.getAllConfigurator(); + for (Configurator configurator : configurators) { + if (dataId.equals(configurator.getDataId())) { + registers.add(configurator); + } + } } - private void throwDuplicateException(Configurator configurator) { - LOGGER.info("[api] Configurator already exists, dataId: {}, registerId: {}", - configurator.getDataObserver(), configurator.getRegistId()); - throw new DuplicateException("Duplicate configurator registration. (dataId: " - + configurator.getDataId() + " )"); + for (Register register : registers) { + register.unregister(); + } + return registers.size(); + } + + private void throwDuplicateException(SubscriberRegistration registration, Subscriber subscriber) { + LOGGER.info( + "[api] Subscriber already exists, dataId: {}, group: {}, scope: {}, registerId: {}", + subscriber.getDataId(), + subscriber.getGroup(), + subscriber.getScopeEnum(), + subscriber.getRegistId()); + throw new DuplicateException( + "Duplicate subscriber registration. (dataId: " + + registration.getDataId() + + ", group: " + + registration.getGroup() + + ")"); + } + + /** + * Add register task. + * + * @param register the register + * @throws RegistryClientException the registry client exception + */ + private void addRegisterTask(Register register) throws RegistryClientException { + try { + TaskEvent event = new TaskEvent(register); + workerThread.schedule(event); + } catch (Exception e) { + LOGGER.error("Register task schedule error, {}", register, e); + throw new RegistryClientException("Register task schedule error", e); + } + } + + /** + * Getter method for property registerCache. + * + * @return property value of registerCache + */ + public RegisterCache getRegisterCache() { + return registerCache; + } + + /** + * Setter method for property userProcessorMap. + * + * @param userProcessorMap value to be assigned to property userProcessorMap + */ + public void setUserProcessorMap(Map, UserProcessor> userProcessorMap) { + this.userProcessorMap = userProcessorMap; + } + + /** + * Setter method for property connectionEventProcessorMap. + * + * @param connectionEventProcessorMap value to be assigned to property connectionEventProcessorMap + */ + public void setConnectionEventProcessorMap( + Map connectionEventProcessorMap) { + this.connectionEventProcessorMap = connectionEventProcessorMap; + } + + /** + * Setter method for property observerHandler. + * + * @param observerHandler value to be assigned to property observerHandler + */ + public void setObserverHandler(ObserverHandler observerHandler) { + this.observerHandler = observerHandler; + } + + /** + * Setter method for property serverManager. + * + * @param serverManager value to be assigned to property serverManager + */ + public void setServerManager(ServerManager serverManager) { + this.serverManager = serverManager; + } + + /** + * Setter method for property authManager. + * + * @param authManager value to be assigned to property authManager + */ + public void setAuthManager(AuthManager authManager) { + this.authManager = authManager; + } + + /** + * Setter method for property lookoutSubscriber. + * + * @param lookoutSubscriber value to be assigned to property lookoutSubscriber + */ + public void setLookoutSubscriber(LookoutSubscriber lookoutSubscriber) { + this.lookoutSubscriber = lookoutSubscriber; + } + + /** + * Setter method for property eventBus. + * + * @param eventBus value to be assigned to property eventBus + */ + public void setEventBus(EventBus eventBus) { + this.eventBus = eventBus; + } + + /** The type Registry check thread. */ + class RegistryCheckThread extends Thread { + + /** Instantiates a new Registry check thread. */ + public RegistryCheckThread() { + super("RegistryClientCheckThread"); + setDaemon(true); } - /** - * @see RegistryClient#unregister(String, String, RegistryType) - */ + /** @see Thread#run() */ @Override - public int unregister(String dataId, String group, RegistryType registryType) { - if (StringUtils.isBlank(dataId)) { - throw new IllegalArgumentException("dataId can not be empty"); - } + public void run() { - if (null == registryType) { - throw new IllegalArgumentException("registry type can not be null"); - } - - if (null == group) { - group = DEFAULT_GROUP; - } + //noinspection InfiniteLoopStatement + while (true) { + try { + Thread.sleep(registryClientConfig.getRecheckInterval()); - List registers = new ArrayList(); + Collection allPublishers = registerCache.getAllPublishers(); - if (RegistryType.PUBLISHER == registryType) { - Collection publishers = registerCache.getAllPublishers(); - for (Publisher publisher : publishers) { - if (dataId.equals(publisher.getDataId()) && group.equals(publisher.getGroup())) { - registers.add(publisher); - } - } - } else if (RegistryType.SUBSCRIBER == registryType) { - Collection subscribers = registerCache.getAllSubscribers(); - for (Subscriber subscriber : subscribers) { - if (dataId.equals(subscriber.getDataId()) && group.equals(subscriber.getGroup())) { - registers.add(subscriber); - } - } - } else if (RegistryType.CONFIGURATOR == registryType) { - Collection configurators = registerCache.getAllConfigurator(); - for (Configurator configurator : configurators) { - if (dataId.equals(configurator.getDataId())) { - registers.add(configurator); - } + for (Publisher publisher : allPublishers) { + try { + if (null != publisher && !((AbstractInternalRegister) publisher).isDone()) { + addRegisterTask(publisher); + } + } catch (Exception e) { + LOGGER.error("Sync publisher error, {}", publisher, e); } - } + } - for (Register register : registers) { - register.unregister(); - } - return registers.size(); - } - - private void throwDuplicateException(SubscriberRegistration registration, Subscriber subscriber) { - LOGGER.info( - "[api] Subscriber already exists, dataId: {}, group: {}, scope: {}, registerId: {}", - subscriber.getDataId(), subscriber.getGroup(), subscriber.getScopeEnum(), - subscriber.getRegistId()); - throw new DuplicateException("Duplicate subscriber registration. (dataId: " - + registration.getDataId() + ", group: " - + registration.getGroup() + ")"); - } - - /** - * Add register task. - * - * @param register the register - * @throws RegistryClientException the registry client exception - */ - private void addRegisterTask(Register register) throws RegistryClientException { - try { - TaskEvent event = new TaskEvent(register); - workerThread.schedule(event); - } catch (Exception e) { - LOGGER.error("Register task schedule error, {}", register, e); - throw new RegistryClientException("Register task schedule error", e); - } - } + Collection allSubscribers = registerCache.getAllSubscribers(); - /** - * Getter method for property registerCache. - * - * @return property value of registerCache - */ - public RegisterCache getRegisterCache() { - return registerCache; - } - - /** - * Setter method for property userProcessorMap. - * - * @param userProcessorMap value to be assigned to property userProcessorMap - */ - public void setUserProcessorMap(Map, UserProcessor> userProcessorMap) { - this.userProcessorMap = userProcessorMap; - } - - /** - * Setter method for property connectionEventProcessorMap. - * - * @param connectionEventProcessorMap value to be assigned to property connectionEventProcessorMap - */ - public void setConnectionEventProcessorMap(Map connectionEventProcessorMap) { - this.connectionEventProcessorMap = connectionEventProcessorMap; - } - - /** - * Setter method for property observerHandler. - * - * @param observerHandler value to be assigned to property observerHandler - */ - public void setObserverHandler(ObserverHandler observerHandler) { - this.observerHandler = observerHandler; - } - - /** - * Setter method for property serverManager. - * - * @param serverManager value to be assigned to property serverManager - */ - public void setServerManager(ServerManager serverManager) { - this.serverManager = serverManager; - } - - /** - * Setter method for property authManager. - * - * @param authManager value to be assigned to property authManager - */ - public void setAuthManager(AuthManager authManager) { - this.authManager = authManager; - } - - /** - * Setter method for property lookoutSubscriber. - * - * @param lookoutSubscriber value to be assigned to property lookoutSubscriber - */ - public void setLookoutSubscriber(LookoutSubscriber lookoutSubscriber) { - this.lookoutSubscriber = lookoutSubscriber; - } - - /** - * Setter method for property eventBus. - * - * @param eventBus value to be assigned to property eventBus - */ - public void setEventBus(EventBus eventBus) { - this.eventBus = eventBus; - } - - /** - * The type Registry check thread. - */ - class RegistryCheckThread extends Thread { - - /** - * Instantiates a new Registry check thread. - */ - public RegistryCheckThread() { - super("RegistryClientCheckThread"); - setDaemon(true); - } + for (Subscriber subscriber : allSubscribers) { + try { + if (null != subscriber && !((AbstractInternalRegister) subscriber).isDone()) { + addRegisterTask(subscriber); + } + } catch (Exception e) { + LOGGER.error("Sync subscriber error, {}", subscriber, e); + } + } + + Collection allConfigurators = registerCache.getAllConfigurator(); - /** - * @see Thread#run() - */ - @Override - public void run() { - - //noinspection InfiniteLoopStatement - while (true) { - try { - Thread.sleep(registryClientConfig.getRecheckInterval()); - - Collection allPublishers = registerCache.getAllPublishers(); - - for (Publisher publisher : allPublishers) { - try { - if (null != publisher - && !((AbstractInternalRegister) publisher).isDone()) { - addRegisterTask(publisher); - } - } catch (Exception e) { - LOGGER.error("Sync publisher error, {}", publisher, e); - } - } - - Collection allSubscribers = registerCache.getAllSubscribers(); - - for (Subscriber subscriber : allSubscribers) { - try { - if (null != subscriber - && !((AbstractInternalRegister) subscriber).isDone()) { - addRegisterTask(subscriber); - } - } catch (Exception e) { - LOGGER.error("Sync subscriber error, {}", subscriber, e); - } - } - - Collection allConfigurators = registerCache.getAllConfigurator(); - - for (Configurator configurator : allConfigurators) { - try { - if (null != configurator - && !((AbstractInternalRegister) configurator).isDone()) { - addRegisterTask(configurator); - } - } catch (Exception e) { - LOGGER.error("Sync configurator error, {}", configurator, e); - } - } - } catch (Throwable e) { - LOGGER.error("Execute error", e); - } + for (Configurator configurator : allConfigurators) { + try { + if (null != configurator && !((AbstractInternalRegister) configurator).isDone()) { + addRegisterTask(configurator); + } + } catch (Exception e) { + LOGGER.error("Sync configurator error, {}", configurator, e); } + } + } catch (Throwable e) { + LOGGER.error("Execute error", e); } - + } } + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientConfig.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientConfig.java index ee8c4caca..8a74426fd 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientConfig.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientConfig.java @@ -26,437 +26,491 @@ */ public class DefaultRegistryClientConfig implements RegistryClientConfig { - /** */ - private String env; - - /** */ - private String instanceId; - - /** */ - private String zone; - - /** */ - private String registryEndpoint; - - /** */ - private int registryEndpointPort; - - /** */ - private String dataCenter; - - /** */ - private String appName; - - /** */ - private int connectTimeout; - - /** */ - private int socketTimeout; - - /** */ - private int invokeTimeout; - - /** */ - private int recheckInterval; - - /** */ - private int observerThreadCoreSize; - - /** */ - private int observerThreadMaxSize; - - /** */ - private int observerThreadQueueLength; - - /** */ - private int observerCallbackTimeout; - - /** */ - private int syncConfigRetryInterval; - - /** */ - private String accessKey; - - /** */ - private String secretKey; - - /** */ - private String algorithm; - - /** */ - private long authCacheInterval; - - /** */ - private boolean eventBusEnable; - - /** - * Instantiates a new Default registry client config. - * - * @param env the env - * @param instanceId the instance id - * @param zone the zone - * @param registryEndpoint the registry endpoint - * @param registryEndpointPort the registry endpoint port - * @param dataCenter the data center - * @param appName the app name - * @param connectTimeout the connect timeout - * @param socketTimeout the socket timeout - * @param invokeTimeout the invoke timeout - * @param recheckInterval the recheck interval - * @param observerThreadCoreSize the observer thread core size - * @param observerThreadMaxSize the observer thread max size - * @param observerThreadQueueLength the observer thread queue length - * @param observerCallbackTimeout the observer callback timeout - * @param syncConfigRetryInterval the sync config retry interval - * @param accessKey the access key - * @param secretKey the secret key - * @param algorithm the algorithm - * @param authCacheInterval the auth cache interval - */ - public DefaultRegistryClientConfig(String env, String instanceId, String zone, - String registryEndpoint, int registryEndpointPort, - String dataCenter, String appName, int connectTimeout, - int socketTimeout, int invokeTimeout, int recheckInterval, - int observerThreadCoreSize, int observerThreadMaxSize, - int observerThreadQueueLength, int observerCallbackTimeout, - int syncConfigRetryInterval, String accessKey, - String secretKey, String algorithm, long authCacheInterval, - boolean eventBusEnable) { - this.env = env; - this.instanceId = instanceId; - this.zone = zone; - this.registryEndpoint = registryEndpoint; - this.registryEndpointPort = registryEndpointPort; - this.dataCenter = dataCenter; - this.appName = appName; - this.connectTimeout = connectTimeout; - this.socketTimeout = socketTimeout; - this.invokeTimeout = invokeTimeout; - this.recheckInterval = recheckInterval; - this.observerThreadCoreSize = observerThreadCoreSize; - this.observerThreadMaxSize = observerThreadMaxSize; - this.observerThreadQueueLength = observerThreadQueueLength; - this.observerCallbackTimeout = observerCallbackTimeout; - this.syncConfigRetryInterval = syncConfigRetryInterval; - this.accessKey = accessKey; - this.secretKey = secretKey; - this.algorithm = algorithm; - this.authCacheInterval = authCacheInterval; - this.eventBusEnable = eventBusEnable; + /** */ + private String env; + + /** */ + private String instanceId; + + /** */ + private String zone; + + /** */ + private String registryEndpoint; + + /** */ + private int registryEndpointPort; + + /** */ + private String dataCenter; + + /** */ + private String appName; + + /** */ + private int connectTimeout; + + /** */ + private int socketTimeout; + + /** */ + private int invokeTimeout; + + /** */ + private int recheckInterval; + + /** */ + private int observerThreadCoreSize; + + /** */ + private int observerThreadMaxSize; + + /** */ + private int observerThreadQueueLength; + + /** */ + private int observerCallbackTimeout; + + /** */ + private int syncConfigRetryInterval; + + /** */ + private String accessKey; + + /** */ + private String secretKey; + + /** */ + private String algorithm; + + /** */ + private long authCacheInterval; + + /** */ + private boolean eventBusEnable; + + /** + * Instantiates a new Default registry client config. + * + * @param env the env + * @param instanceId the instance id + * @param zone the zone + * @param registryEndpoint the registry endpoint + * @param registryEndpointPort the registry endpoint port + * @param dataCenter the data center + * @param appName the app name + * @param connectTimeout the connect timeout + * @param socketTimeout the socket timeout + * @param invokeTimeout the invoke timeout + * @param recheckInterval the recheck interval + * @param observerThreadCoreSize the observer thread core size + * @param observerThreadMaxSize the observer thread max size + * @param observerThreadQueueLength the observer thread queue length + * @param observerCallbackTimeout the observer callback timeout + * @param syncConfigRetryInterval the sync config retry interval + * @param accessKey the access key + * @param secretKey the secret key + * @param algorithm the algorithm + * @param authCacheInterval the auth cache interval + */ + public DefaultRegistryClientConfig( + String env, + String instanceId, + String zone, + String registryEndpoint, + int registryEndpointPort, + String dataCenter, + String appName, + int connectTimeout, + int socketTimeout, + int invokeTimeout, + int recheckInterval, + int observerThreadCoreSize, + int observerThreadMaxSize, + int observerThreadQueueLength, + int observerCallbackTimeout, + int syncConfigRetryInterval, + String accessKey, + String secretKey, + String algorithm, + long authCacheInterval, + boolean eventBusEnable) { + this.env = env; + this.instanceId = instanceId; + this.zone = zone; + this.registryEndpoint = registryEndpoint; + this.registryEndpointPort = registryEndpointPort; + this.dataCenter = dataCenter; + this.appName = appName; + this.connectTimeout = connectTimeout; + this.socketTimeout = socketTimeout; + this.invokeTimeout = invokeTimeout; + this.recheckInterval = recheckInterval; + this.observerThreadCoreSize = observerThreadCoreSize; + this.observerThreadMaxSize = observerThreadMaxSize; + this.observerThreadQueueLength = observerThreadQueueLength; + this.observerCallbackTimeout = observerCallbackTimeout; + this.syncConfigRetryInterval = syncConfigRetryInterval; + this.accessKey = accessKey; + this.secretKey = secretKey; + this.algorithm = algorithm; + this.authCacheInterval = authCacheInterval; + this.eventBusEnable = eventBusEnable; + } + + /** + * Getter method for property env. + * + * @return property value of env + */ + @Override + public String getEnv() { + return env; + } + + /** + * Getter method for property instanceId. + * + * @return property value of instanceId + */ + @Override + public String getInstanceId() { + return instanceId; + } + + /** + * Getter method for property zone. + * + * @return property value of zone + */ + @Override + public String getZone() { + return zone; + } + + /** + * Getter method for property registryEndpoint. + * + * @return property value of registryEndpoint + */ + @Override + public String getRegistryEndpoint() { + return registryEndpoint; + } + + /** + * Getter method for property registryEndpointPort. + * + * @return property value of registryEndpointPort + */ + @Override + public int getRegistryEndpointPort() { + return registryEndpointPort; + } + + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + @Override + public String getDataCenter() { + return dataCenter; + } + + /** + * Getter method for property appName. + * + * @return property value of appName + */ + @Override + public String getAppName() { + return appName; + } + + /** + * Getter method for property connectTimeout. + * + * @return property value of connectTimeout + */ + @Override + public int getConnectTimeout() { + return connectTimeout; + } + + /** + * Getter method for property socketTimeout. + * + * @return property value of socketTimeout + */ + @Override + public int getSocketTimeout() { + return socketTimeout; + } + + /** + * Getter method for property invokeTimeout. + * + * @return property value of invokeTimeout + */ + @Override + public int getInvokeTimeout() { + return invokeTimeout; + } + + /** + * Getter method for property recheckInterval. + * + * @return property value of recheckInterval + */ + @Override + public int getRecheckInterval() { + return recheckInterval; + } + + /** + * Getter method for property observerThreadCoreSize. + * + * @return property value of observerThreadCoreSize + */ + @Override + public int getObserverThreadCoreSize() { + return observerThreadCoreSize; + } + + /** + * Getter method for property observerThreadMaxSize. + * + * @return property value of observerThreadMaxSize + */ + @Override + public int getObserverThreadMaxSize() { + return observerThreadMaxSize; + } + + /** + * Getter method for property observerThreadQueueLength. + * + * @return property value of observerThreadQueueLength + */ + @Override + public int getObserverThreadQueueLength() { + return observerThreadQueueLength; + } + + /** + * Getter method for property observerCallbackTimeout. + * + * @return property value of observerCallbackTimeout + */ + @Override + public int getObserverCallbackTimeout() { + return observerCallbackTimeout; + } + + /** + * Getter method for property syncConfigRetryInterval. + * + * @return property value of syncConfigRetryInterval + */ + @Override + public int getSyncConfigRetryInterval() { + return syncConfigRetryInterval; + } + + /** + * Getter method for property accessKey. + * + * @return property value of accessKey + */ + @Override + public String getAccessKey() { + return accessKey; + } + + /** + * Getter method for property secretKey. + * + * @return property value of secretKey + */ + @Override + public String getSecretKey() { + return secretKey; + } + + /** + * Getter method for property algorithm. + * + * @return property value of algorithm + */ + @Override + public String getAlgorithm() { + return algorithm; + } + + /** + * Setter method for property algorithm. + * + * @param algorithm value to be assigned to property algorithm + */ + public void setAlgorithm(String algorithm) { + this.algorithm = algorithm; + } + + /** + * Getter method for property authCacheInterval. + * + * @return property value of authCacheInterval + */ + @Override + public long getAuthCacheInterval() { + return authCacheInterval; + } + + /** + * Setter method for property authCacheInterval. + * + * @param authCacheInterval value to be assigned to property authCacheInterval + */ + public void setAuthCacheInterval(long authCacheInterval) { + this.authCacheInterval = authCacheInterval; + } + + /** + * Getter method for property eventBusEnable. + * + * @return property value of eventBusEnable + */ + @Override + public boolean isEventBusEnable() { + return eventBusEnable; + } + + /** + * Setter method for property eventBusEnable. + * + * @param eventBusEnable value to be assigned to property eventBusEnable + */ + public void setEventBusEnable(boolean eventBusEnable) { + this.eventBusEnable = eventBusEnable; + } + + /** + * Equals boolean. + * + * @param o the o + * @return the boolean + */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - /** - * Getter method for property env. - * - * @return property value of env - */ - @Override - public String getEnv() { - return env; - } - - /** - * Getter method for property instanceId. - * - * @return property value of instanceId - */ - @Override - public String getInstanceId() { - return instanceId; - } - - /** - * Getter method for property zone. - * - * @return property value of zone - */ - @Override - public String getZone() { - return zone; - } - - /** - * Getter method for property registryEndpoint. - * - * @return property value of registryEndpoint - */ - @Override - public String getRegistryEndpoint() { - return registryEndpoint; + if (!(o instanceof DefaultRegistryClientConfig)) { + return false; } - /** - * Getter method for property registryEndpointPort. - * - * @return property value of registryEndpointPort - */ - @Override - public int getRegistryEndpointPort() { - return registryEndpointPort; - } + DefaultRegistryClientConfig that = (DefaultRegistryClientConfig) o; - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - @Override - public String getDataCenter() { - return dataCenter; + if (registryEndpointPort != that.registryEndpointPort) { + return false; } - - /** - * Getter method for property appName. - * - * @return property value of appName - */ - @Override - public String getAppName() { - return appName; + if (env != null ? !env.equals(that.env) : that.env != null) { + return false; } - - /** - * Getter method for property connectTimeout. - * - * @return property value of connectTimeout - */ - @Override - public int getConnectTimeout() { - return connectTimeout; + if (instanceId != null ? !instanceId.equals(that.instanceId) : that.instanceId != null) { + return false; } - - /** - * Getter method for property socketTimeout. - * - * @return property value of socketTimeout - */ - @Override - public int getSocketTimeout() { - return socketTimeout; + if (zone != null ? !zone.equals(that.zone) : that.zone != null) { + return false; } - - /** - * Getter method for property invokeTimeout. - * - * @return property value of invokeTimeout - */ - @Override - public int getInvokeTimeout() { - return invokeTimeout; + if (registryEndpoint != null + ? !registryEndpoint.equals(that.registryEndpoint) + : that.registryEndpoint != null) { + return false; } - - /** - * Getter method for property recheckInterval. - * - * @return property value of recheckInterval - */ - @Override - public int getRecheckInterval() { - return recheckInterval; - } - - /** - * Getter method for property observerThreadCoreSize. - * - * @return property value of observerThreadCoreSize - */ - @Override - public int getObserverThreadCoreSize() { - return observerThreadCoreSize; - } - - /** - * Getter method for property observerThreadMaxSize. - * - * @return property value of observerThreadMaxSize - */ - @Override - public int getObserverThreadMaxSize() { - return observerThreadMaxSize; - } - - /** - * Getter method for property observerThreadQueueLength. - * - * @return property value of observerThreadQueueLength - */ - @Override - public int getObserverThreadQueueLength() { - return observerThreadQueueLength; - } - - /** - * Getter method for property observerCallbackTimeout. - * - * @return property value of observerCallbackTimeout - */ - @Override - public int getObserverCallbackTimeout() { - return observerCallbackTimeout; - } - - /** - * Getter method for property syncConfigRetryInterval. - * - * @return property value of syncConfigRetryInterval - */ - @Override - public int getSyncConfigRetryInterval() { - return syncConfigRetryInterval; - } - - /** - * Getter method for property accessKey. - * - * @return property value of accessKey - */ - @Override - public String getAccessKey() { - return accessKey; - } - - /** - * Getter method for property secretKey. - * - * @return property value of secretKey - */ - @Override - public String getSecretKey() { - return secretKey; - } - - /** - * Getter method for property algorithm. - * - * @return property value of algorithm - */ - @Override - public String getAlgorithm() { - return algorithm; - } - - /** - * Setter method for property algorithm. - * - * @param algorithm value to be assigned to property algorithm - */ - public void setAlgorithm(String algorithm) { - this.algorithm = algorithm; - } - - /** - * Getter method for property authCacheInterval. - * - * @return property value of authCacheInterval - */ - @Override - public long getAuthCacheInterval() { - return authCacheInterval; - } - - /** - * Setter method for property authCacheInterval. - * - * @param authCacheInterval value to be assigned to property authCacheInterval - */ - public void setAuthCacheInterval(long authCacheInterval) { - this.authCacheInterval = authCacheInterval; - } - - /** - * Getter method for property eventBusEnable. - * - * @return property value of eventBusEnable - */ - @Override - public boolean isEventBusEnable() { - return eventBusEnable; - } - - /** - * Setter method for property eventBusEnable. - * - * @param eventBusEnable value to be assigned to property eventBusEnable - */ - public void setEventBusEnable(boolean eventBusEnable) { - this.eventBusEnable = eventBusEnable; - } - - /** - * Equals boolean. - * - * @param o the o - * @return the boolean - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof DefaultRegistryClientConfig)) { - return false; - } - - DefaultRegistryClientConfig that = (DefaultRegistryClientConfig) o; - - if (registryEndpointPort != that.registryEndpointPort) { - return false; - } - if (env != null ? !env.equals(that.env) : that.env != null) { - return false; - } - if (instanceId != null ? !instanceId.equals(that.instanceId) : that.instanceId != null) { - return false; - } - if (zone != null ? !zone.equals(that.zone) : that.zone != null) { - return false; - } - if (registryEndpoint != null ? !registryEndpoint.equals(that.registryEndpoint) - : that.registryEndpoint != null) { - return false; - } - if (dataCenter != null ? !dataCenter.equals(that.dataCenter) : that.dataCenter != null) { - return false; - } - return appName != null ? appName.equals(that.appName) : that.appName == null; - } - - /** - * Hash code int. - * - * @return the int - */ - @Override - public int hashCode() { - int result = env != null ? env.hashCode() : 0; - result = 31 * result + (instanceId != null ? instanceId.hashCode() : 0); - result = 31 * result + (zone != null ? zone.hashCode() : 0); - result = 31 * result + (registryEndpoint != null ? registryEndpoint.hashCode() : 0); - result = 31 * result + registryEndpointPort; - result = 31 * result + (dataCenter != null ? dataCenter.hashCode() : 0); - result = 31 * result + (appName != null ? appName.hashCode() : 0); - return result; - } - - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "DefaultRegistryClientConfig{" + "env='" + env + '\'' + ", instanceId='" - + instanceId + '\'' + ", zone='" + zone + '\'' + ", registryEndpoint='" - + registryEndpoint + '\'' + ", registryEndpointPort=" + registryEndpointPort - + ", dataCenter='" + dataCenter + '\'' + ", appName='" + appName + '\'' - + ", connectTimeout=" + connectTimeout + ", socketTimeout=" + socketTimeout - + ", invokeTimeout=" + invokeTimeout + ", recheckInterval=" + recheckInterval - + ", observerThreadCoreSize=" + observerThreadCoreSize + ", observerThreadMaxSize=" - + observerThreadMaxSize + ", observerThreadQueueLength=" + observerThreadQueueLength - + ", observerCallbackTimeout=" + observerCallbackTimeout - + ", syncConfigRetryInterval=" + syncConfigRetryInterval + ", accessKey='" - + accessKey + '\'' + ", secretKey='" + secretKey + '\'' + ", algorithm='" - + algorithm + '\'' + ", authCacheInterval=" + authCacheInterval - + ", eventBusEnable=" + eventBusEnable + '}'; + if (dataCenter != null ? !dataCenter.equals(that.dataCenter) : that.dataCenter != null) { + return false; } + return appName != null ? appName.equals(that.appName) : that.appName == null; + } + + /** + * Hash code int. + * + * @return the int + */ + @Override + public int hashCode() { + int result = env != null ? env.hashCode() : 0; + result = 31 * result + (instanceId != null ? instanceId.hashCode() : 0); + result = 31 * result + (zone != null ? zone.hashCode() : 0); + result = 31 * result + (registryEndpoint != null ? registryEndpoint.hashCode() : 0); + result = 31 * result + registryEndpointPort; + result = 31 * result + (dataCenter != null ? dataCenter.hashCode() : 0); + result = 31 * result + (appName != null ? appName.hashCode() : 0); + return result; + } + + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "DefaultRegistryClientConfig{" + + "env='" + + env + + '\'' + + ", instanceId='" + + instanceId + + '\'' + + ", zone='" + + zone + + '\'' + + ", registryEndpoint='" + + registryEndpoint + + '\'' + + ", registryEndpointPort=" + + registryEndpointPort + + ", dataCenter='" + + dataCenter + + '\'' + + ", appName='" + + appName + + '\'' + + ", connectTimeout=" + + connectTimeout + + ", socketTimeout=" + + socketTimeout + + ", invokeTimeout=" + + invokeTimeout + + ", recheckInterval=" + + recheckInterval + + ", observerThreadCoreSize=" + + observerThreadCoreSize + + ", observerThreadMaxSize=" + + observerThreadMaxSize + + ", observerThreadQueueLength=" + + observerThreadQueueLength + + ", observerCallbackTimeout=" + + observerCallbackTimeout + + ", syncConfigRetryInterval=" + + syncConfigRetryInterval + + ", accessKey='" + + accessKey + + '\'' + + ", secretKey='" + + secretKey + + '\'' + + ", algorithm='" + + algorithm + + '\'' + + ", authCacheInterval=" + + authCacheInterval + + ", eventBusEnable=" + + eventBusEnable + + '}'; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientConfigBuilder.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientConfigBuilder.java index 542cda238..88278f759 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientConfigBuilder.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientConfigBuilder.java @@ -26,268 +26,288 @@ * @version $Id : DefaultRegistryClientConfig.java, v 0.1 2017-11-23 20:12 zhuoyu.sjw Exp $$ */ public class DefaultRegistryClientConfigBuilder { - private String env; - private String instanceId; - private String zone = DEFAULT_ZONE; - private String registryEndpoint; - private int registryEndpointPort = 9603; - private String dataCenter = DEFAULT_DATA_CENTER; - private String appName; - private int connectTimeout = 3000; - private int socketTimeout = 3000; - private int invokeTimeout = 1000; - private int recheckInterval = 500; - private int observerThreadCoreSize = 5; - private int observerThreadMaxSize = 10; - private int observerThreadQueueLength = 1000; - private int observerCallbackTimeout = 5000; - private int syncConfigRetryInterval = 30000; - private String accessKey; - private String secretKey; - private String algorithm = "HmacSHA256"; - private long authCacheInterval = 5 * 60 * 1000; - private boolean eventBusEnable = true; + private String env; + private String instanceId; + private String zone = DEFAULT_ZONE; + private String registryEndpoint; + private int registryEndpointPort = 9603; + private String dataCenter = DEFAULT_DATA_CENTER; + private String appName; + private int connectTimeout = 3000; + private int socketTimeout = 3000; + private int invokeTimeout = 1000; + private int recheckInterval = 500; + private int observerThreadCoreSize = 5; + private int observerThreadMaxSize = 10; + private int observerThreadQueueLength = 1000; + private int observerCallbackTimeout = 5000; + private int syncConfigRetryInterval = 30000; + private String accessKey; + private String secretKey; + private String algorithm = "HmacSHA256"; + private long authCacheInterval = 5 * 60 * 1000; + private boolean eventBusEnable = true; - /** - * Start default registry client config builder. - * - * @return the default registry client config builder - */ - public static DefaultRegistryClientConfigBuilder start() { - return new DefaultRegistryClientConfigBuilder(); - } + /** + * Start default registry client config builder. + * + * @return the default registry client config builder + */ + public static DefaultRegistryClientConfigBuilder start() { + return new DefaultRegistryClientConfigBuilder(); + } - /** - * Sets env. - * - * @param env the env - * @return the env - */ - public DefaultRegistryClientConfigBuilder setEnv(String env) { - this.env = env; - return this; - } + /** + * Sets env. + * + * @param env the env + * @return the env + */ + public DefaultRegistryClientConfigBuilder setEnv(String env) { + this.env = env; + return this; + } - /** - * Sets instance id. - * - * @param instanceId the instance id - * @return the instance id - */ - public DefaultRegistryClientConfigBuilder setInstanceId(String instanceId) { - this.instanceId = instanceId; - return this; - } + /** + * Sets instance id. + * + * @param instanceId the instance id + * @return the instance id + */ + public DefaultRegistryClientConfigBuilder setInstanceId(String instanceId) { + this.instanceId = instanceId; + return this; + } - /** - * Sets zone. - * - * @param zone the zone - * @return the zone - */ - public DefaultRegistryClientConfigBuilder setZone(String zone) { - this.zone = zone; - return this; - } + /** + * Sets zone. + * + * @param zone the zone + * @return the zone + */ + public DefaultRegistryClientConfigBuilder setZone(String zone) { + this.zone = zone; + return this; + } - /** - * Sets registry endpoint. - * - * @param registryEndpoint the registry endpoint - * @return the registry endpoint - */ - public DefaultRegistryClientConfigBuilder setRegistryEndpoint(String registryEndpoint) { - this.registryEndpoint = registryEndpoint; - return this; - } + /** + * Sets registry endpoint. + * + * @param registryEndpoint the registry endpoint + * @return the registry endpoint + */ + public DefaultRegistryClientConfigBuilder setRegistryEndpoint(String registryEndpoint) { + this.registryEndpoint = registryEndpoint; + return this; + } - /** - * Sets registry endpoint port. - * - * @param registryEndpointPort the registry endpoint port - * @return the registry endpoint port - */ - public DefaultRegistryClientConfigBuilder setRegistryEndpointPort(int registryEndpointPort) { - this.registryEndpointPort = registryEndpointPort; - return this; - } + /** + * Sets registry endpoint port. + * + * @param registryEndpointPort the registry endpoint port + * @return the registry endpoint port + */ + public DefaultRegistryClientConfigBuilder setRegistryEndpointPort(int registryEndpointPort) { + this.registryEndpointPort = registryEndpointPort; + return this; + } - /** - * Sets data center. - * - * @param dataCenter the data center - * @return the data center - */ - public DefaultRegistryClientConfigBuilder setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - return this; - } + /** + * Sets data center. + * + * @param dataCenter the data center + * @return the data center + */ + public DefaultRegistryClientConfigBuilder setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + return this; + } - /** - * Sets app name. - * - * @param appName the app name - * @return the app name - */ - public DefaultRegistryClientConfigBuilder setAppName(String appName) { - this.appName = appName; - return this; - } + /** + * Sets app name. + * + * @param appName the app name + * @return the app name + */ + public DefaultRegistryClientConfigBuilder setAppName(String appName) { + this.appName = appName; + return this; + } - /** - * Setter method for property observerThreadCoreSize. - * - * @param observerThreadCoreSize value to be assigned to property observerThreadCoreSize - */ - public DefaultRegistryClientConfigBuilder setObserverThreadCoreSize(int observerThreadCoreSize) { - this.observerThreadCoreSize = observerThreadCoreSize; - return this; - } + /** + * Setter method for property observerThreadCoreSize. + * + * @param observerThreadCoreSize value to be assigned to property observerThreadCoreSize + */ + public DefaultRegistryClientConfigBuilder setObserverThreadCoreSize(int observerThreadCoreSize) { + this.observerThreadCoreSize = observerThreadCoreSize; + return this; + } - /** - * Setter method for property observerThreadMaxSize. - * - * @param observerThreadMaxSize value to be assigned to property observerThreadMaxSize - */ - public DefaultRegistryClientConfigBuilder setObserverThreadMaxSize(int observerThreadMaxSize) { - this.observerThreadMaxSize = observerThreadMaxSize; - return this; - } + /** + * Setter method for property observerThreadMaxSize. + * + * @param observerThreadMaxSize value to be assigned to property observerThreadMaxSize + */ + public DefaultRegistryClientConfigBuilder setObserverThreadMaxSize(int observerThreadMaxSize) { + this.observerThreadMaxSize = observerThreadMaxSize; + return this; + } - /** - * Setter method for property observerThreadQueueLength. - * - * @param observerThreadQueueLength value to be assigned to property observerThreadQueueLength - */ - public DefaultRegistryClientConfigBuilder setObserverThreadQueueLength(int observerThreadQueueLength) { - this.observerThreadQueueLength = observerThreadQueueLength; - return this; - } + /** + * Setter method for property observerThreadQueueLength. + * + * @param observerThreadQueueLength value to be assigned to property observerThreadQueueLength + */ + public DefaultRegistryClientConfigBuilder setObserverThreadQueueLength( + int observerThreadQueueLength) { + this.observerThreadQueueLength = observerThreadQueueLength; + return this; + } - /** - * Setter method for property observerCallbackTimeout. - * - * @param observerCallbackTimeout value to be assigned to property observerCallbackTimeout - */ - public DefaultRegistryClientConfigBuilder setObserverCallbackTimeout(int observerCallbackTimeout) { - this.observerCallbackTimeout = observerCallbackTimeout; - return this; - } + /** + * Setter method for property observerCallbackTimeout. + * + * @param observerCallbackTimeout value to be assigned to property observerCallbackTimeout + */ + public DefaultRegistryClientConfigBuilder setObserverCallbackTimeout( + int observerCallbackTimeout) { + this.observerCallbackTimeout = observerCallbackTimeout; + return this; + } - /** - * Sets connect timeout. - * - * @param connectTimeout the connect timeout - * @return the connect timeout - */ - public DefaultRegistryClientConfigBuilder setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - return this; - } + /** + * Sets connect timeout. + * + * @param connectTimeout the connect timeout + * @return the connect timeout + */ + public DefaultRegistryClientConfigBuilder setConnectTimeout(int connectTimeout) { + this.connectTimeout = connectTimeout; + return this; + } - /** - * Sets socket timeout. - * - * @param socketTimeout the socket timeout - * @return the socket timeout - */ - public DefaultRegistryClientConfigBuilder setSocketTimeout(int socketTimeout) { - this.socketTimeout = socketTimeout; - return this; - } + /** + * Sets socket timeout. + * + * @param socketTimeout the socket timeout + * @return the socket timeout + */ + public DefaultRegistryClientConfigBuilder setSocketTimeout(int socketTimeout) { + this.socketTimeout = socketTimeout; + return this; + } - /** - * Sets invoke timeout. - * - * @param invokeTimeout the invoke timeout - * @return the invoke timeout - */ - public DefaultRegistryClientConfigBuilder setInvokeTimeout(int invokeTimeout) { - this.invokeTimeout = invokeTimeout; - return this; - } + /** + * Sets invoke timeout. + * + * @param invokeTimeout the invoke timeout + * @return the invoke timeout + */ + public DefaultRegistryClientConfigBuilder setInvokeTimeout(int invokeTimeout) { + this.invokeTimeout = invokeTimeout; + return this; + } - /** - * Sets recheck interval. - * - * @param recheckInterval the recheck interval - * @return the recheck interval - */ - public DefaultRegistryClientConfigBuilder setRecheckInterval(int recheckInterval) { - this.recheckInterval = recheckInterval; - return this; - } + /** + * Sets recheck interval. + * + * @param recheckInterval the recheck interval + * @return the recheck interval + */ + public DefaultRegistryClientConfigBuilder setRecheckInterval(int recheckInterval) { + this.recheckInterval = recheckInterval; + return this; + } - /** - * Setter method for property syncConfigRetryInterval. - * - * @param syncConfigRetryInterval value to be assigned to property syncConfigRetryInterval - */ - public DefaultRegistryClientConfigBuilder setSyncConfigRetryInterval(int syncConfigRetryInterval) { - this.syncConfigRetryInterval = syncConfigRetryInterval; - return this; - } + /** + * Setter method for property syncConfigRetryInterval. + * + * @param syncConfigRetryInterval value to be assigned to property syncConfigRetryInterval + */ + public DefaultRegistryClientConfigBuilder setSyncConfigRetryInterval( + int syncConfigRetryInterval) { + this.syncConfigRetryInterval = syncConfigRetryInterval; + return this; + } - /** - * Setter method for property accessKey. - * - * @param accessKey value to be assigned to property accessKey - */ - public DefaultRegistryClientConfigBuilder setAccessKey(String accessKey) { - this.accessKey = accessKey; - return this; - } + /** + * Setter method for property accessKey. + * + * @param accessKey value to be assigned to property accessKey + */ + public DefaultRegistryClientConfigBuilder setAccessKey(String accessKey) { + this.accessKey = accessKey; + return this; + } - /** - * Setter method for property secretKey. - * - * @param secretKey value to be assigned to property secretKey - */ - public DefaultRegistryClientConfigBuilder setSecretKey(String secretKey) { - this.secretKey = secretKey; - return this; - } + /** + * Setter method for property secretKey. + * + * @param secretKey value to be assigned to property secretKey + */ + public DefaultRegistryClientConfigBuilder setSecretKey(String secretKey) { + this.secretKey = secretKey; + return this; + } - /** - * Setter method for property algorithm. - * - * @param algorithm value to be assigned to property algorithm - */ - public DefaultRegistryClientConfigBuilder setAlgorithm(String algorithm) { - this.algorithm = algorithm; - return this; - } + /** + * Setter method for property algorithm. + * + * @param algorithm value to be assigned to property algorithm + */ + public DefaultRegistryClientConfigBuilder setAlgorithm(String algorithm) { + this.algorithm = algorithm; + return this; + } - /** - * Setter method for property authCacheInterval. - * - * @param authCacheInterval value to be assigned to property authCacheInterval - */ - public DefaultRegistryClientConfigBuilder setAuthCacheInterval(long authCacheInterval) { - this.authCacheInterval = authCacheInterval; - return this; - } + /** + * Setter method for property authCacheInterval. + * + * @param authCacheInterval value to be assigned to property authCacheInterval + */ + public DefaultRegistryClientConfigBuilder setAuthCacheInterval(long authCacheInterval) { + this.authCacheInterval = authCacheInterval; + return this; + } - /** - * Setter method for property eventBusEnable. - * - * @param eventBusEnable value to be assigned to property eventBusEnable - */ - public DefaultRegistryClientConfigBuilder setEventBusEnable(boolean eventBusEnable) { - this.eventBusEnable = eventBusEnable; - return this; - } + /** + * Setter method for property eventBusEnable. + * + * @param eventBusEnable value to be assigned to property eventBusEnable + */ + public DefaultRegistryClientConfigBuilder setEventBusEnable(boolean eventBusEnable) { + this.eventBusEnable = eventBusEnable; + return this; + } - /** - * Create default registry client config default registry client config. - * - * @return the default registry client config - */ - public DefaultRegistryClientConfig build() { - return new DefaultRegistryClientConfig(env, instanceId, zone, registryEndpoint, - registryEndpointPort, dataCenter, appName, connectTimeout, socketTimeout, - invokeTimeout, recheckInterval, observerThreadCoreSize, observerThreadMaxSize, - observerThreadQueueLength, observerCallbackTimeout, syncConfigRetryInterval, accessKey, - secretKey, algorithm, authCacheInterval, eventBusEnable); - } -} \ No newline at end of file + /** + * Create default registry client config default registry client config. + * + * @return the default registry client config + */ + public DefaultRegistryClientConfig build() { + return new DefaultRegistryClientConfig( + env, + instanceId, + zone, + registryEndpoint, + registryEndpointPort, + dataCenter, + appName, + connectTimeout, + socketTimeout, + invokeTimeout, + recheckInterval, + observerThreadCoreSize, + observerThreadMaxSize, + observerThreadQueueLength, + observerCallbackTimeout, + syncConfigRetryInterval, + accessKey, + secretKey, + algorithm, + authCacheInterval, + eventBusEnable); + } +} diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultServerManager.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultServerManager.java index 281cd1d7d..050e46c3a 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultServerManager.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultServerManager.java @@ -22,8 +22,6 @@ import com.alipay.sofa.registry.client.remoting.ServerNode; import com.alipay.sofa.registry.client.util.HttpClientUtils; import com.alipay.sofa.registry.client.util.ServerNodeParser; -import org.slf4j.Logger; - import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -32,135 +30,128 @@ import java.util.Random; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; +import org.slf4j.Logger; /** * The type Default server manager. + * * @author zhuoyu.sjw * @version $Id : DefaultServerManager.java, v 0.1 2017-12-25 11:48 zhuoyu.sjw Exp $$ */ public class DefaultServerManager implements ServerManager { - /** - * The constant MIN_RETRY_INTERVAL. - */ - public static final int MIN_RETRY_INTERVAL = 10000; - /** LOGGER */ - private static final Logger LOGGER = LoggerFactory - .getLogger(DefaultServerManager.class); - private RegistryClientConfig config; - private Set serverNodes; - private SyncServerListThread syncServerListTask; + /** The constant MIN_RETRY_INTERVAL. */ + public static final int MIN_RETRY_INTERVAL = 10000; + /** LOGGER */ + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultServerManager.class); - private AtomicBoolean inited = new AtomicBoolean(false); + private RegistryClientConfig config; + private Set serverNodes; + private SyncServerListThread syncServerListTask; - /** - * Instantiates a new Default server manager. - * - * @param config the config - */ - public DefaultServerManager(RegistryClientConfig config) { - this.config = config; - this.serverNodes = new HashSet(); - this.syncServerListTask = new SyncServerListThread(config); - } + private AtomicBoolean inited = new AtomicBoolean(false); - /** - * @see ServerManager#getServerList() - */ - @Override - public List getServerList() { - // init once - if (inited.compareAndSet(false, true)) { - this.syncServerListTask.start(); - } - // sync query when server list is empty - if (serverNodes.isEmpty()) { - syncServerList(); - } - return new ArrayList(serverNodes); + /** + * Instantiates a new Default server manager. + * + * @param config the config + */ + public DefaultServerManager(RegistryClientConfig config) { + this.config = config; + this.serverNodes = new HashSet(); + this.syncServerListTask = new SyncServerListThread(config); + } + + /** @see ServerManager#getServerList() */ + @Override + public List getServerList() { + // init once + if (inited.compareAndSet(false, true)) { + this.syncServerListTask.start(); } + // sync query when server list is empty + if (serverNodes.isEmpty()) { + syncServerList(); + } + return new ArrayList(serverNodes); + } - /** - * @see ServerManager#random() - */ - @Override - public ServerNode random() { - List urls = getServerList(); - if (null == urls || urls.size() == 0) { - return null; - } - Random random = new Random(); - return urls.get(random.nextInt(urls.size())); + /** @see ServerManager#random() */ + @Override + public ServerNode random() { + List urls = getServerList(); + if (null == urls || urls.size() == 0) { + return null; } + Random random = new Random(); + return urls.get(random.nextInt(urls.size())); + } - private void syncServerList() { - String url = String.format("http://%s:%d/api/servers/query", config.getRegistryEndpoint(), - config.getRegistryEndpointPort()); - Map params = new HashMap(); - params.put("env", config.getEnv()); - params.put("zone", config.getZone()); - params.put("dataCenter", config.getDataCenter()); - params.put("appName", config.getAppName()); - params.put("instanceId", config.getInstanceId()); - try { - String result = HttpClientUtils.get(url, params, config); - if (null != result) { - String[] servers = result.split(";"); - Set tempNodes = new HashSet(); - for (String server : servers) { - try { - ServerNode serverNode = ServerNodeParser.parse(server); - tempNodes.add(serverNode); - } catch (Exception e) { - LOGGER.error("[serverManager] parse server node error, {}", server, e); - } - } - if (!tempNodes.equals(serverNodes)) { - serverNodes = tempNodes; - LOGGER.info("[serverManager] update nodes success, {}", tempNodes); - } - } - } catch (Exception e) { - LOGGER.error("[serverManager] get server list error", e); + private void syncServerList() { + String url = + String.format( + "http://%s:%d/api/servers/query", + config.getRegistryEndpoint(), config.getRegistryEndpointPort()); + Map params = new HashMap(); + params.put("env", config.getEnv()); + params.put("zone", config.getZone()); + params.put("dataCenter", config.getDataCenter()); + params.put("appName", config.getAppName()); + params.put("instanceId", config.getInstanceId()); + try { + String result = HttpClientUtils.get(url, params, config); + if (null != result) { + String[] servers = result.split(";"); + Set tempNodes = new HashSet(); + for (String server : servers) { + try { + ServerNode serverNode = ServerNodeParser.parse(server); + tempNodes.add(serverNode); + } catch (Exception e) { + LOGGER.error("[serverManager] parse server node error, {}", server, e); + } + } + if (!tempNodes.equals(serverNodes)) { + serverNodes = tempNodes; + LOGGER.info("[serverManager] update nodes success, {}", tempNodes); } + } + } catch (Exception e) { + LOGGER.error("[serverManager] get server list error", e); } + } - /** - * The type Sync server list task. - */ - class SyncServerListThread extends Thread { + /** The type Sync server list task. */ + class SyncServerListThread extends Thread { - private RegistryClientConfig config; + private RegistryClientConfig config; - /** - * Instantiates a new Sync server list task. - * - * @param config the config - */ - public SyncServerListThread(RegistryClientConfig config) { - this.setName("SyncServerListThread"); - this.setDaemon(true); - this.config = config; - } + /** + * Instantiates a new Sync server list task. + * + * @param config the config + */ + public SyncServerListThread(RegistryClientConfig config) { + this.setName("SyncServerListThread"); + this.setDaemon(true); + this.config = config; + } - /** - * @see Thread#run() - */ - @SuppressWarnings("InfiniteLoopStatement") - @Override - public void run() { - int retryInterval; - while (true) { - try { - retryInterval = Math.max(MIN_RETRY_INTERVAL, - config.getSyncConfigRetryInterval()); - Thread.sleep(retryInterval); + /** @see Thread#run() */ + @SuppressWarnings("InfiniteLoopStatement") + @Override + public void run() { + int retryInterval; + while (true) { + try { + retryInterval = Math.max(MIN_RETRY_INTERVAL, config.getSyncConfigRetryInterval()); + Thread.sleep(retryInterval); - syncServerList(); - } catch (Throwable e) { - LOGGER.error("[serverManager] sync server list task error", e); - } - } + syncServerList(); + } catch (Throwable e) { + LOGGER.error("[serverManager] sync server list task error", e); } + } } + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultServerNode.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultServerNode.java index 3e5a067c5..886631ff0 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultServerNode.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultServerNode.java @@ -17,159 +17,163 @@ package com.alipay.sofa.registry.client.provider; import com.alipay.sofa.registry.client.remoting.ServerNode; - import java.util.Properties; /** * The type Default server node. + * * @author zhuoyu.sjw * @version $Id : DefaultServerNode.java, v 0.1 2018-03-01 17:13 zhuoyu.sjw Exp $$ */ public class DefaultServerNode implements ServerNode { - private String url; - - private String host; - - private int port; - - private Properties properties; - - /** - * Instantiates a new Default server node. - * - * @param url the url - * @param host the host - * @param port the port - * @param properties the properties - */ - public DefaultServerNode(String url, String host, int port, Properties properties) { - this.url = url; - this.host = host; - this.port = port; - this.properties = properties; - } - - /** - * Gets host. - * - * @return the host - */ - @Override - public String getHost() { - return host; - } - - /** - * Gets port. - * - * @return the port - */ - @Override - public int getPort() { - return port; - } - - /** - * Gets url. - * - * @return the url - */ - @Override - public String getUrl() { - return url; - } - - /** - * Gets properties. - * - * @return the properties - */ - @Override - public Properties getProperties() { - return properties; + private String url; + + private String host; + + private int port; + + private Properties properties; + + /** + * Instantiates a new Default server node. + * + * @param url the url + * @param host the host + * @param port the port + * @param properties the properties + */ + public DefaultServerNode(String url, String host, int port, Properties properties) { + this.url = url; + this.host = host; + this.port = port; + this.properties = properties; + } + + /** + * Gets host. + * + * @return the host + */ + @Override + public String getHost() { + return host; + } + + /** + * Gets port. + * + * @return the port + */ + @Override + public int getPort() { + return port; + } + + /** + * Gets url. + * + * @return the url + */ + @Override + public String getUrl() { + return url; + } + + /** + * Gets properties. + * + * @return the properties + */ + @Override + public Properties getProperties() { + return properties; + } + + /** + * Setter method for property url. + * + * @param url value to be assigned to property url + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * Setter method for property host. + * + * @param host value to be assigned to property host + */ + public void setHost(String host) { + this.host = host; + } + + /** + * Setter method for property port. + * + * @param port value to be assigned to property port + */ + public void setPort(int port) { + this.port = port; + } + + /** + * Setter method for property properties. + * + * @param properties value to be assigned to property properties + */ + public void setProperties(Properties properties) { + this.properties = properties; + } + + /** @see Object#equals(Object) */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - /** - * Setter method for property url. - * - * @param url value to be assigned to property url - */ - public void setUrl(String url) { - this.url = url; + if (!(o instanceof DefaultServerNode)) { + return false; } - /** - * Setter method for property host. - * - * @param host value to be assigned to property host - */ - public void setHost(String host) { - this.host = host; - } + DefaultServerNode that = (DefaultServerNode) o; - /** - * Setter method for property port. - * - * @param port value to be assigned to property port - */ - public void setPort(int port) { - this.port = port; + if (port != that.port) { + return false; } - - /** - * Setter method for property properties. - * - * @param properties value to be assigned to property properties - */ - public void setProperties(Properties properties) { - this.properties = properties; + if (url != null ? !url.equals(that.url) : that.url != null) { + return false; } - - /** - * @see Object#equals(Object) - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof DefaultServerNode)) { - return false; - } - - DefaultServerNode that = (DefaultServerNode) o; - - if (port != that.port) { - return false; - } - if (url != null ? !url.equals(that.url) : that.url != null) { - return false; - } - if (host != null ? !host.equals(that.host) : that.host != null) { - return false; - } - return properties != null ? properties.equals(that.properties) : that.properties == null; - } - - /** - * @see Object#hashCode() - */ - @Override - public int hashCode() { - int result = url != null ? url.hashCode() : 0; - result = 31 * result + (host != null ? host.hashCode() : 0); - result = 31 * result + port; - result = 31 * result + (properties != null ? properties.hashCode() : 0); - return result; - } - - /** - * @see Object#toString() - */ - @Override - public String toString() { - return "DefaultServerNode{" + "url='" + url + '\'' + ", host='" + host + '\'' + ", port=" - + port + ", properties=" + properties + '}'; + if (host != null ? !host.equals(that.host) : that.host != null) { + return false; } + return properties != null ? properties.equals(that.properties) : that.properties == null; + } + + /** @see Object#hashCode() */ + @Override + public int hashCode() { + int result = url != null ? url.hashCode() : 0; + result = 31 * result + (host != null ? host.hashCode() : 0); + result = 31 * result + port; + result = 31 * result + (properties != null ? properties.hashCode() : 0); + return result; + } + + /** @see Object#toString() */ + @Override + public String toString() { + return "DefaultServerNode{" + + "url='" + + url + + '\'' + + ", host='" + + host + + '\'' + + ", port=" + + port + + ", properties=" + + properties + + '}'; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultSubscriber.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultSubscriber.java index 3cb07b572..2e451f2f8 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultSubscriber.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultSubscriber.java @@ -31,7 +31,6 @@ import com.alipay.sofa.registry.core.model.DataBox; import com.alipay.sofa.registry.core.model.ScopeEnum; import com.alipay.sofa.registry.core.model.SubscriberRegister; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -50,270 +49,262 @@ */ public class DefaultSubscriber extends AbstractInternalRegister implements Subscriber { - private final String REGIST_ID; - private SubscriberDataObserver dataObserver; - private ConcurrentHashMap data = new ConcurrentHashMap(); - private AtomicBoolean init = new AtomicBoolean(false); - private RegistryClientConfig config; - private SubscriberRegistration registration; - private Worker worker; - private volatile String localZone; - private List availableSegments = new ArrayList(); + private final String REGIST_ID; + private SubscriberDataObserver dataObserver; + private ConcurrentHashMap data = + new ConcurrentHashMap(); + private AtomicBoolean init = new AtomicBoolean(false); + private RegistryClientConfig config; + private SubscriberRegistration registration; + private Worker worker; + private volatile String localZone; + private List availableSegments = new ArrayList(); - /** - * Instantiates a new Default subscriber multi. - * - * @param registration the registration - */ - DefaultSubscriber(SubscriberRegistration registration, Worker worker, - RegistryClientConfig config) { - if (null != registration) { - this.dataObserver = registration.getSubscriberDataObserver(); - } - this.registration = registration; - this.worker = worker; - this.config = config; - this.REGIST_ID = UUID.randomUUID().toString(); - this.localZone = config.getZone(); - this.getPubVersion().incrementAndGet(); + /** + * Instantiates a new Default subscriber multi. + * + * @param registration the registration + */ + DefaultSubscriber( + SubscriberRegistration registration, Worker worker, RegistryClientConfig config) { + if (null != registration) { + this.dataObserver = registration.getSubscriberDataObserver(); } + this.registration = registration; + this.worker = worker; + this.config = config; + this.REGIST_ID = UUID.randomUUID().toString(); + this.localZone = config.getZone(); + this.getPubVersion().incrementAndGet(); + } - /** - * @see Subscriber#getDataObserver() - */ - @Override - public SubscriberDataObserver getDataObserver() { - return dataObserver; - } + /** @see Subscriber#getDataObserver() */ + @Override + public SubscriberDataObserver getDataObserver() { + return dataObserver; + } - /** - * @see Subscriber#setDataObserver(SubscriberDataObserver) - */ - @Override - public void setDataObserver(SubscriberDataObserver dataObserver) { - this.dataObserver = dataObserver; - } + /** @see Subscriber#setDataObserver(SubscriberDataObserver) */ + @Override + public void setDataObserver(SubscriberDataObserver dataObserver) { + this.dataObserver = dataObserver; + } - /** - * @see Subscriber#peekData() - */ - @Override - public UserData peekData() { - readLock.lock(); - try { - if (!init.get()) { - //todo sync read from server - return new DefaultUserData(); - } - Set> values = data.entrySet(); - DefaultUserData userData = new DefaultUserData(); - if (null == localZone) { - userData.setLocalZone(config.getZone()); - } else { - userData.setLocalZone(localZone); - } - Map> zoneMap = new HashMap>(); - for (Entry segmentDataEntry : values) { - String segment = segmentDataEntry.getKey(); + /** @see Subscriber#peekData() */ + @Override + public UserData peekData() { + readLock.lock(); + try { + if (!init.get()) { + // todo sync read from server + return new DefaultUserData(); + } + Set> values = data.entrySet(); + DefaultUserData userData = new DefaultUserData(); + if (null == localZone) { + userData.setLocalZone(config.getZone()); + } else { + userData.setLocalZone(localZone); + } + Map> zoneMap = new HashMap>(); + for (Entry segmentDataEntry : values) { + String segment = segmentDataEntry.getKey(); - // only accept available segments, when available segments is empty accept all - if (CommonUtils.isNotEmpty(availableSegments) - && !availableSegments.contains(segment)) { - continue; - } + // only accept available segments, when available segments is empty accept all + if (CommonUtils.isNotEmpty(availableSegments) && !availableSegments.contains(segment)) { + continue; + } - SegmentData segmentData = segmentDataEntry.getValue(); + SegmentData segmentData = segmentDataEntry.getValue(); - if (null == segmentData) { - continue; - } + if (null == segmentData) { + continue; + } - Map> data = segmentData.getData(); - for (Entry> entry : data.entrySet()) { - String zone = entry.getKey(); - List resultList = zoneMap.get(zone); - if (null == resultList) { - resultList = new ArrayList(); - zoneMap.put(zone, resultList); - } - List dataList = entry.getValue(); - for (DataBox dataBox : dataList) { - resultList.add(dataBox.getData()); - } - } - } - userData.setZoneData(zoneMap); - return userData; - } finally { - readLock.unlock(); + Map> data = segmentData.getData(); + for (Entry> entry : data.entrySet()) { + String zone = entry.getKey(); + List resultList = zoneMap.get(zone); + if (null == resultList) { + resultList = new ArrayList(); + zoneMap.put(zone, resultList); + } + List dataList = entry.getValue(); + for (DataBox dataBox : dataList) { + resultList.add(dataBox.getData()); + } } + } + userData.setZoneData(zoneMap); + return userData; + } finally { + readLock.unlock(); } + } - /** - * Gets scope enum. - * - * @return the scope enum - */ - @Override - public ScopeEnum getScopeEnum() { - return registration.getScopeEnum(); - } + /** + * Gets scope enum. + * + * @return the scope enum + */ + @Override + public ScopeEnum getScopeEnum() { + return registration.getScopeEnum(); + } - /** - * Unregister. - */ - @Override - public void unregister() { - if (isEnabled()) { - super.unregister(); - worker.schedule(new TaskEvent(this)); - } + /** Unregister. */ + @Override + public void unregister() { + if (isEnabled()) { + super.unregister(); + worker.schedule(new TaskEvent(this)); } + } - /** - * Assembly subscriber register. - * - * @return the subscriber register - */ - @Override - public SubscriberRegister assembly() { - readLock.lock(); - SubscriberRegister register; - try { - if (null == registration.getScopeEnum()) { - registration.setScopeEnum(ScopeEnum.zone); - } + /** + * Assembly subscriber register. + * + * @return the subscriber register + */ + @Override + public SubscriberRegister assembly() { + readLock.lock(); + SubscriberRegister register; + try { + if (null == registration.getScopeEnum()) { + registration.setScopeEnum(ScopeEnum.zone); + } - register = new SubscriberRegister(); - register.setInstanceId(config.getInstanceId()); - if (StringUtils.isNotEmpty(config.getZone())) { - register.setZone(config.getZone()); - } else { - register.setZone(ValueConstants.DEFAULT_ZONE); - } - if (StringUtils.isNotEmpty(registration.getAppName())) { - register.setAppName(registration.getAppName()); - } else { - register.setAppName(config.getAppName()); - } - register.setDataId(registration.getDataId()); - register.setGroup(registration.getGroup()); - register.setRegistId(REGIST_ID); - register.setVersion(this.getPubVersion().get()); - register.setTimestamp(this.getTimestamp()); - register.setScope(registration.getScopeEnum().name()); + register = new SubscriberRegister(); + register.setInstanceId(config.getInstanceId()); + if (StringUtils.isNotEmpty(config.getZone())) { + register.setZone(config.getZone()); + } else { + register.setZone(ValueConstants.DEFAULT_ZONE); + } + if (StringUtils.isNotEmpty(registration.getAppName())) { + register.setAppName(registration.getAppName()); + } else { + register.setAppName(config.getAppName()); + } + register.setDataId(registration.getDataId()); + register.setGroup(registration.getGroup()); + register.setRegistId(REGIST_ID); + register.setVersion(this.getPubVersion().get()); + register.setTimestamp(this.getTimestamp()); + register.setScope(registration.getScopeEnum().name()); - // auth signature - setAuthSignature(register); + // auth signature + setAuthSignature(register); - if (isEnabled()) { - register.setEventType(EventTypeConstants.REGISTER); - } else { - register.setEventType(EventTypeConstants.UNREGISTER); - } - } finally { - readLock.unlock(); - } - return register; + if (isEnabled()) { + register.setEventType(EventTypeConstants.REGISTER); + } else { + register.setEventType(EventTypeConstants.UNREGISTER); + } + } finally { + readLock.unlock(); } + return register; + } - public void putReceivedData(SegmentData segmentData, String localZone) { - writeLock.lock(); - try { - putSegmentData(segmentData); - this.localZone = localZone; - } finally { - writeLock.unlock(); - } + public void putReceivedData(SegmentData segmentData, String localZone) { + writeLock.lock(); + try { + putSegmentData(segmentData); + this.localZone = localZone; + } finally { + writeLock.unlock(); } + } - private void putSegmentData(SegmentData segmentData) { - if (null != segmentData) { + private void putSegmentData(SegmentData segmentData) { + if (null != segmentData) { - SegmentData existsData = data.putIfAbsent(segmentData.getSegment(), segmentData); - if (null == existsData) { - init.compareAndSet(false, true); - return; - } + SegmentData existsData = data.putIfAbsent(segmentData.getSegment(), segmentData); + if (null == existsData) { + init.compareAndSet(false, true); + return; + } - if (existsData.getVersion() < segmentData.getVersion()) { - boolean result = data.replace(segmentData.getSegment(), existsData, segmentData); - if (!result) { - putSegmentData(segmentData); - } - init.compareAndSet(false, true); - } + if (existsData.getVersion() < segmentData.getVersion()) { + boolean result = data.replace(segmentData.getSegment(), existsData, segmentData); + if (!result) { + putSegmentData(segmentData); } + init.compareAndSet(false, true); + } } + } - /** - * Gets data id. - * - * @return the data id - */ - @Override - public String getDataId() { - return registration.getDataId(); - } + /** + * Gets data id. + * + * @return the data id + */ + @Override + public String getDataId() { + return registration.getDataId(); + } - /** - * Gets group. - * - * @return the group - */ - @Override - public String getGroup() { - return registration.getGroup(); - } + /** + * Gets group. + * + * @return the group + */ + @Override + public String getGroup() { + return registration.getGroup(); + } - /** - * Gets regist id. - * - * @return the regist id - */ - @Override - public String getRegistId() { - return REGIST_ID; - } + /** + * Gets regist id. + * + * @return the regist id + */ + @Override + public String getRegistId() { + return REGIST_ID; + } - /** - * Getter method for property availableSegments. - * - * @return property value of availableSegments - */ - public List getAvailableSegments() { - readLock.lock(); - try { - return new ArrayList(availableSegments); - } finally { - readLock.unlock(); - } + /** + * Getter method for property availableSegments. + * + * @return property value of availableSegments + */ + public List getAvailableSegments() { + readLock.lock(); + try { + return new ArrayList(availableSegments); + } finally { + readLock.unlock(); } + } - /** - * Setter method for property availableSegments. - * - * @param availableSegments value to be assigned to property availableSegments - */ - public void setAvailableSegments(List availableSegments) { - writeLock.lock(); - try { - if (null == availableSegments) { - this.availableSegments = new ArrayList(); - } else { - this.availableSegments = new ArrayList(availableSegments); - } - } finally { - writeLock.unlock(); - } + /** + * Setter method for property availableSegments. + * + * @param availableSegments value to be assigned to property availableSegments + */ + public void setAvailableSegments(List availableSegments) { + writeLock.lock(); + try { + if (null == availableSegments) { + this.availableSegments = new ArrayList(); + } else { + this.availableSegments = new ArrayList(availableSegments); + } + } finally { + writeLock.unlock(); } + } - public boolean isInited() { - return init.get(); - } + public boolean isInited() { + return init.get(); + } - @Override - public String toString() { - return "DefaultSubscriber{" + "registration=" + registration + '}' + super.toString(); - } + @Override + public String toString() { + return "DefaultSubscriber{" + "registration=" + registration + '}' + super.toString(); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultUserData.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultUserData.java index a47d52b28..2c88bf201 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultUserData.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/DefaultUserData.java @@ -17,70 +17,67 @@ package com.alipay.sofa.registry.client.provider; import com.alipay.sofa.registry.client.api.model.UserData; - import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** - * * @author zhuoyu.sjw * @version $Id: DefaultUserData.java, v 0.1 2017-11-30 21:01 zhuoyu.sjw Exp $$ */ public class DefaultUserData implements UserData { - /** zone, List */ - private Map> zoneData = new ConcurrentHashMap>(); + /** zone, List */ + private Map> zoneData = new ConcurrentHashMap>(); - /** The current client`s zone */ - private String localZone; + /** The current client`s zone */ + private String localZone; - /** - * Getter method for property zoneData. - * - * @return property value of zoneData - */ - @Override - public Map> getZoneData() { - return zoneData; - } + /** + * Getter method for property zoneData. + * + * @return property value of zoneData + */ + @Override + public Map> getZoneData() { + return zoneData; + } - /** - * Setter method for property zoneData. - * - * @param zoneData value to be assigned to property zoneData - */ - public void setZoneData(Map> zoneData) { - this.zoneData = zoneData; - } + /** + * Setter method for property zoneData. + * + * @param zoneData value to be assigned to property zoneData + */ + public void setZoneData(Map> zoneData) { + this.zoneData = zoneData; + } - /** - * Getter method for property localZone. - * - * @return property value of localZone - */ - @Override - public String getLocalZone() { - return localZone; - } + /** + * Getter method for property localZone. + * + * @return property value of localZone + */ + @Override + public String getLocalZone() { + return localZone; + } - /** - * Setter method for property localZone. - * - * @param localZone value to be assigned to property localZone - */ - public void setLocalZone(String localZone) { - this.localZone = localZone; - } + /** + * Setter method for property localZone. + * + * @param localZone value to be assigned to property localZone + */ + public void setLocalZone(String localZone) { + this.localZone = localZone; + } - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "DefaultUserData{" + "zoneData=" + zoneData + ", localZone='" + localZone + '\'' - + '}'; - } + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "DefaultUserData{" + "zoneData=" + zoneData + ", localZone='" + localZone + '\'' + '}'; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/RegisterCache.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/RegisterCache.java index ee35272a8..58f88eeb5 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/RegisterCache.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/provider/RegisterCache.java @@ -20,7 +20,6 @@ import com.alipay.sofa.registry.client.api.Publisher; import com.alipay.sofa.registry.client.api.Subscriber; import com.alipay.sofa.registry.client.util.StringUtils; - import java.util.ArrayList; import java.util.Collection; import java.util.Map; @@ -28,130 +27,125 @@ /** * The type Register cache. + * * @author zhuoyu.sjw * @version $Id : RegisterCache.java, v 0.1 2017-11-30 18:18 zhuoyu.sjw Exp $$ */ public class RegisterCache { - /** - * publisher register cache Map - */ - private Map publisherMap = new ConcurrentHashMap(); - /** - * subscriber register cache Map - */ - private Map subscriberMap = new ConcurrentHashMap(); - /** - * configurator register cache Map - */ - private Map configuratorMap = new ConcurrentHashMap(); - - /** - * Add register. - * - * @param publisher the publisher - */ - public void addRegister(Publisher publisher) { - if (null == publisher || StringUtils.isEmpty(publisher.getDataId())) { - return; - } - - publisherMap.put(publisher.getRegistId(), publisher); - } - - /** - * Add register. - * - * @param subscriber the subscriber - */ - public void addRegister(Subscriber subscriber) { - if (null == subscriber || StringUtils.isEmpty(subscriber.getDataId())) { - return; - } - - subscriberMap.put(subscriber.getRegistId(), subscriber); - } - - /** - * Add register. - * - * @param configurator the configurator - */ - public void addRegister(Configurator configurator) { - if (null == configurator || StringUtils.isEmpty(configurator.getDataId())) { - return; - } - - configuratorMap.put(configurator.getRegistId(), configurator); - } - - /** - * Remove. - * - * @param registId the regist id - */ - public void remove(String registId) { - if (publisherMap.remove(registId) == null) { - if (subscriberMap.remove(registId) == null) { - configuratorMap.remove(registId); - } - } - } - - /** - * Gets publisher by regist id. - * - * @param registId the regist id - * @return the publisher by regist id - */ - public Publisher getPublisherByRegistId(String registId) { - return publisherMap.get(registId); - } - - /** - * Gets subscriber by regist id. - * - * @param registId the regist id - * @return the subscriber by regist id - */ - public Subscriber getSubscriberByRegistId(String registId) { - return subscriberMap.get(registId); - } - - /** - * Gets configurator by data id. - * - * @param registId the regist id - * @return the configurator by data id - */ - public Configurator getConfiguratorByRegistId(String registId) { - return configuratorMap.get(registId); + /** publisher register cache Map */ + private Map publisherMap = new ConcurrentHashMap(); + /** subscriber register cache Map */ + private Map subscriberMap = new ConcurrentHashMap(); + /** configurator register cache Map */ + private Map configuratorMap = new ConcurrentHashMap(); + + /** + * Add register. + * + * @param publisher the publisher + */ + public void addRegister(Publisher publisher) { + if (null == publisher || StringUtils.isEmpty(publisher.getDataId())) { + return; } - /** - * Gets all publishers. - * - * @return the all publishers - */ - public Collection getAllPublishers() { - return new ArrayList(publisherMap.values()); + publisherMap.put(publisher.getRegistId(), publisher); + } + + /** + * Add register. + * + * @param subscriber the subscriber + */ + public void addRegister(Subscriber subscriber) { + if (null == subscriber || StringUtils.isEmpty(subscriber.getDataId())) { + return; } - /** - * Gets all subscribers. - * - * @return the all subscribers - */ - public Collection getAllSubscribers() { - return new ArrayList(subscriberMap.values()); + subscriberMap.put(subscriber.getRegistId(), subscriber); + } + + /** + * Add register. + * + * @param configurator the configurator + */ + public void addRegister(Configurator configurator) { + if (null == configurator || StringUtils.isEmpty(configurator.getDataId())) { + return; } - /** - * Gets all configurator. - * - * @return the all configurator - */ - public Collection getAllConfigurator() { - return new ArrayList(configuratorMap.values()); + configuratorMap.put(configurator.getRegistId(), configurator); + } + + /** + * Remove. + * + * @param registId the regist id + */ + public void remove(String registId) { + if (publisherMap.remove(registId) == null) { + if (subscriberMap.remove(registId) == null) { + configuratorMap.remove(registId); + } } + } + + /** + * Gets publisher by regist id. + * + * @param registId the regist id + * @return the publisher by regist id + */ + public Publisher getPublisherByRegistId(String registId) { + return publisherMap.get(registId); + } + + /** + * Gets subscriber by regist id. + * + * @param registId the regist id + * @return the subscriber by regist id + */ + public Subscriber getSubscriberByRegistId(String registId) { + return subscriberMap.get(registId); + } + + /** + * Gets configurator by data id. + * + * @param registId the regist id + * @return the configurator by data id + */ + public Configurator getConfiguratorByRegistId(String registId) { + return configuratorMap.get(registId); + } + + /** + * Gets all publishers. + * + * @return the all publishers + */ + public Collection getAllPublishers() { + return new ArrayList(publisherMap.values()); + } + + /** + * Gets all subscribers. + * + * @return the all subscribers + */ + public Collection getAllSubscribers() { + return new ArrayList(subscriberMap.values()); + } + + /** + * Gets all configurator. + * + * @return the all configurator + */ + public Collection getAllConfigurator() { + return new ArrayList(configuratorMap.values()); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/Client.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/Client.java index a71643ca0..b8e006729 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/Client.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/Client.java @@ -20,43 +20,36 @@ /** * The interface Client. - * + * * @author zhuoyu.sjw * @version $Id : Client.java, v 0.1 2018-03-06 20:43 zhuoyu.sjw Exp $$ */ public interface Client { - /** - * Init. - */ - void init(); + /** Init. */ + void init(); - /** - * Is connected boolean. - * - * @return the boolean - */ - boolean isConnected(); + /** + * Is connected boolean. + * + * @return the boolean + */ + boolean isConnected(); - /** - * Ensure connected. - * - * @throws InterruptedException - * the interrupted exception - */ - void ensureConnected() throws InterruptedException; + /** + * Ensure connected. + * + * @throws InterruptedException the interrupted exception + */ + void ensureConnected() throws InterruptedException; - /** - * Invoke sync object. - * - * @param request - * the request - * @return the object - * @throws RemotingException - * the remoting exception - * @throws InterruptedException - * the interrupted exception - */ - Object invokeSync(Object request) throws RemotingException, - InterruptedException; + /** + * Invoke sync object. + * + * @param request the request + * @return the object + * @throws RemotingException the remoting exception + * @throws InterruptedException the interrupted exception + */ + Object invokeSync(Object request) throws RemotingException, InterruptedException; } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnection.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnection.java index 320b565ff..7d4e5ea6e 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnection.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnection.java @@ -30,8 +30,6 @@ import com.alipay.sofa.registry.client.provider.RegisterCache; import com.alipay.sofa.registry.client.task.TaskEvent; import com.alipay.sofa.registry.client.task.Worker; -import org.slf4j.Logger; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -39,262 +37,263 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Random; +import org.slf4j.Logger; /** * The type Client connection. + * * @author zhuoyu.sjw * @version $Id : ClientConnection.java, v 0.1 2018-03-01 16:44 zhuoyu.sjw Exp $$ */ public class ClientConnection implements Client { - /** LOGGER */ - private static final Logger LOGGER = LoggerFactory - .getLogger(ClientConnection.class); - /** - * The Reconnecting delay. - */ - private final static int RECONNECTING_DELAY = 5000; - private RpcClient client; - private ServerManager serverManager; - private List userProcessorList; - private Map connectionEventProcessorMap; - private RegistryClientConfig config; - private Connection clientConnection; - private RegisterCache registerCache; - private Worker worker; - - /** - * Instantiates a new Client connection. - * - * @param serverManager the server manager - * @param userProcessorList the user processor list - * @param connectionEventProcessorMap the connection event processor map - * @param config the config - */ - public ClientConnection(ServerManager serverManager, - List userProcessorList, - Map connectionEventProcessorMap, - RegisterCache registerCache, RegistryClientConfig config) { - this.client = new RpcClient(); - this.serverManager = serverManager; - this.userProcessorList = userProcessorList; - this.connectionEventProcessorMap = connectionEventProcessorMap; - this.registerCache = registerCache; - this.config = config; - } + /** LOGGER */ + private static final Logger LOGGER = LoggerFactory.getLogger(ClientConnection.class); + /** The Reconnecting delay. */ + private static final int RECONNECTING_DELAY = 5000; - /** - * Init. - */ - @Override - public void init() { - for (UserProcessor userProcessor : userProcessorList) { - client.registerUserProcessor(userProcessor); - } + private RpcClient client; + private ServerManager serverManager; + private List userProcessorList; + private Map connectionEventProcessorMap; + private RegistryClientConfig config; + private Connection clientConnection; + private RegisterCache registerCache; + private Worker worker; - if (null != connectionEventProcessorMap) { - for (Entry entry : connectionEventProcessorMap - .entrySet()) { - client.addConnectionEventProcessor(entry.getKey(), entry.getValue()); - } - } + /** + * Instantiates a new Client connection. + * + * @param serverManager the server manager + * @param userProcessorList the user processor list + * @param connectionEventProcessorMap the connection event processor map + * @param config the config + */ + public ClientConnection( + ServerManager serverManager, + List userProcessorList, + Map connectionEventProcessorMap, + RegisterCache registerCache, + RegistryClientConfig config) { + this.client = new RpcClient(); + this.serverManager = serverManager; + this.userProcessorList = userProcessorList; + this.connectionEventProcessorMap = connectionEventProcessorMap; + this.registerCache = registerCache; + this.config = config; + } - client.init(); + /** Init. */ + @Override + public void init() { + for (UserProcessor userProcessor : userProcessorList) { + client.registerUserProcessor(userProcessor); } - /** - * Ensure connected. - * - * @throws InterruptedException the interrupted exception - */ - @Override - public void ensureConnected() throws InterruptedException { - if (isConnected()) { - return; - } - while (!connect()) { - Thread.sleep(ClientConnection.RECONNECTING_DELAY); - } + if (null != connectionEventProcessorMap) { + for (Entry entry : + connectionEventProcessorMap.entrySet()) { + client.addConnectionEventProcessor(entry.getKey(), entry.getValue()); + } } - /** - * Connect boolean. - * - * @return the boolean - */ - private boolean connect() { - Random random = new Random(); - Connection connection = null; - List serverNodes = new ArrayList(serverManager.getServerList()); - // shuffle server list to make server connections as discrete as possible - Collections.shuffle(serverNodes); - for (ServerNode serverNode : serverNodes) { - try { - connection = connect(serverNode); - if (null != connection && connection.isFine()) { - resetRegister(); - LOGGER.info("[Connect] Successfully connected to server: {}", serverNode); - break; - } else { - recycle(connection); - } + client.init(); + } - Thread.sleep(random.nextInt(RECONNECTING_DELAY)); - } catch (Exception e) { - LOGGER.error("[Connect] Failed trying connect to {}", serverNode, e); - } - } + /** + * Ensure connected. + * + * @throws InterruptedException the interrupted exception + */ + @Override + public void ensureConnected() throws InterruptedException { + if (isConnected()) { + return; + } + while (!connect()) { + Thread.sleep(ClientConnection.RECONNECTING_DELAY); + } + } + /** + * Connect boolean. + * + * @return the boolean + */ + private boolean connect() { + Random random = new Random(); + Connection connection = null; + List serverNodes = new ArrayList(serverManager.getServerList()); + // shuffle server list to make server connections as discrete as possible + Collections.shuffle(serverNodes); + for (ServerNode serverNode : serverNodes) { + try { + connection = connect(serverNode); if (null != connection && connection.isFine()) { - clientConnection = connection; - return true; + resetRegister(); + LOGGER.info("[Connect] Successfully connected to server: {}", serverNode); + break; + } else { + recycle(connection); } - return false; + + Thread.sleep(random.nextInt(RECONNECTING_DELAY)); + } catch (Exception e) { + LOGGER.error("[Connect] Failed trying connect to {}", serverNode, e); + } } - /** - * Invoke sync object. - * - * @param request the request - * @return the object - * @throws RemotingException the remoting exception - * @throws InterruptedException the interrupted exception - */ - @Override - public Object invokeSync(Object request) throws RemotingException, InterruptedException { - if (!isConnected()) { - throw new IllegalStateException("Not connected"); - } + if (null != connection && connection.isFine()) { + clientConnection = connection; + return true; + } + return false; + } - return client.invokeSync(clientConnection, request, config.getInvokeTimeout()); + /** + * Invoke sync object. + * + * @param request the request + * @return the object + * @throws RemotingException the remoting exception + * @throws InterruptedException the interrupted exception + */ + @Override + public Object invokeSync(Object request) throws RemotingException, InterruptedException { + if (!isConnected()) { + throw new IllegalStateException("Not connected"); } - private void recycle(Connection connection) { - if (null == connection) { - return; - } + return client.invokeSync(clientConnection, request, config.getInvokeTimeout()); + } + + private void recycle(Connection connection) { + if (null == connection) { + return; + } - client.closeConnection(connection.getUrl()); + client.closeConnection(connection.getUrl()); + } + + private Connection connect(ServerNode serverNode) { + Connection connection = null; + try { + connection = client.getConnection(serverNode.getUrl(), config.getConnectTimeout()); + } catch (Exception e) { + LOGGER.error("[connection] Create connection error, {}", serverNode, e); } + return connection; + } + + private void resetRegister() { + try { + List eventList = new ArrayList(); - private Connection connect(ServerNode serverNode) { - Connection connection = null; + Collection publishers = registerCache.getAllPublishers(); + for (Publisher publisher : publishers) { try { - connection = client.getConnection(serverNode.getUrl(), config.getConnectTimeout()); + publisher.reset(); + eventList.add(new TaskEvent(publisher)); } catch (Exception e) { - LOGGER.error("[connection] Create connection error, {}", serverNode, e); + LOGGER.error("[connection] Publisher reset error, {}", publisher, e); } - return connection; - } + } - private void resetRegister() { + Collection subscribers = registerCache.getAllSubscribers(); + for (Subscriber subscriber : subscribers) { try { - List eventList = new ArrayList(); - - Collection publishers = registerCache.getAllPublishers(); - for (Publisher publisher : publishers) { - try { - publisher.reset(); - eventList.add(new TaskEvent(publisher)); - } catch (Exception e) { - LOGGER.error("[connection] Publisher reset error, {}", publisher, e); - } - } - - Collection subscribers = registerCache.getAllSubscribers(); - for (Subscriber subscriber : subscribers) { - try { - subscriber.reset(); - eventList.add(new TaskEvent(subscriber)); - } catch (Exception e) { - LOGGER.error("[connection] Subscriber reset error, {}", subscriber, e); - } - } - - Collection configurators = registerCache.getAllConfigurator(); - for (Configurator configurator : configurators) { - try { - configurator.reset(); - eventList.add(new TaskEvent(configurator)); - } catch (Exception e) { - LOGGER.error("[connection] Configurator reset error, {}", configurator, e); - } - } - - worker.schedule(eventList); - LOGGER.info("[reset] {} publishers and {} subscribers has been reset", - publishers.size(), subscribers.size()); + subscriber.reset(); + eventList.add(new TaskEvent(subscriber)); } catch (Exception e) { - LOGGER.error("[reset] Reset register after reconnect error", e); + LOGGER.error("[connection] Subscriber reset error, {}", subscriber, e); } - } + } - /** - * Gets remote address. - * - * @return the remote address - */ - public String getRemoteAddress() { - if (null != clientConnection) { - return clientConnection.getRemoteIP(); + Collection configurators = registerCache.getAllConfigurator(); + for (Configurator configurator : configurators) { + try { + configurator.reset(); + eventList.add(new TaskEvent(configurator)); + } catch (Exception e) { + LOGGER.error("[connection] Configurator reset error, {}", configurator, e); } - return null; - } + } - /** - * Is connected boolean. - * - * @return boolean boolean - */ - @Override - public boolean isConnected() { - return clientConnection != null && clientConnection.isFine(); + worker.schedule(eventList); + LOGGER.info( + "[reset] {} publishers and {} subscribers has been reset", + publishers.size(), + subscribers.size()); + } catch (Exception e) { + LOGGER.error("[reset] Reset register after reconnect error", e); } + } - /** - * Destroy. - */ - public void destroy() { - if (null != clientConnection) { - clientConnection.close(); - } - if (null != client) { - client.shutdown(); - } + /** + * Gets remote address. + * + * @return the remote address + */ + public String getRemoteAddress() { + if (null != clientConnection) { + return clientConnection.getRemoteIP(); } + return null; + } - /** - * Setter method for property serverManager. - * - * @param serverManager value to be assigned to property serverManager - */ - public void setServerManager(ServerManager serverManager) { - this.serverManager = serverManager; - } + /** + * Is connected boolean. + * + * @return boolean boolean + */ + @Override + public boolean isConnected() { + return clientConnection != null && clientConnection.isFine(); + } - /** - * Setter method for property userProcessorList. - * - * @param userProcessorList value to be assigned to property userProcessorList - */ - public void setUserProcessorList(List userProcessorList) { - this.userProcessorList = userProcessorList; + /** Destroy. */ + public void destroy() { + if (null != clientConnection) { + clientConnection.close(); } - - /** - * Setter method for property connectionEventProcessorMap. - * - * @param connectionEventProcessorMap value to be assigned to property connectionEventProcessorMap - */ - public void setConnectionEventProcessorMap(Map connectionEventProcessorMap) { - this.connectionEventProcessorMap = connectionEventProcessorMap; + if (null != client) { + client.shutdown(); } + } - /** - * Setter method for property worker. - * - * @param worker value to be assigned to property worker - */ - public void setWorker(Worker worker) { - this.worker = worker; - } + /** + * Setter method for property serverManager. + * + * @param serverManager value to be assigned to property serverManager + */ + public void setServerManager(ServerManager serverManager) { + this.serverManager = serverManager; + } + + /** + * Setter method for property userProcessorList. + * + * @param userProcessorList value to be assigned to property userProcessorList + */ + public void setUserProcessorList(List userProcessorList) { + this.userProcessorList = userProcessorList; + } + + /** + * Setter method for property connectionEventProcessorMap. + * + * @param connectionEventProcessorMap value to be assigned to property connectionEventProcessorMap + */ + public void setConnectionEventProcessorMap( + Map connectionEventProcessorMap) { + this.connectionEventProcessorMap = connectionEventProcessorMap; + } + + /** + * Setter method for property worker. + * + * @param worker value to be assigned to property worker + */ + public void setWorker(Worker worker) { + this.worker = worker; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnectionCloseEventProcessor.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnectionCloseEventProcessor.java index b8b112368..c29a97d33 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnectionCloseEventProcessor.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnectionCloseEventProcessor.java @@ -23,24 +23,27 @@ /** * The type Client connection close event processor. + * * @author zhuoyu.sjw * @version $Id : ClientConnectionCloseEventProcessor.java, v 0.1 2018-02-26 20:28 zhuoyu.sjw Exp $$ */ public class ClientConnectionCloseEventProcessor implements ConnectionEventProcessor { - private static final Logger LOGGER = LoggerFactory - .getLogger(ClientConnectionCloseEventProcessor.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(ClientConnectionCloseEventProcessor.class); - /** - * On event. - * - * @param remoteAddr the remote addr - * @param conn the conn - */ - @Override - public void onEvent(String remoteAddr, Connection conn) { - if (null != conn) { - LOGGER.info("[connection] Client disconnected, remote address: {}, localAddress: {}", - remoteAddr, conn.getLocalAddress()); - } + /** + * On event. + * + * @param remoteAddr the remote addr + * @param conn the conn + */ + @Override + public void onEvent(String remoteAddr, Connection conn) { + if (null != conn) { + LOGGER.info( + "[connection] Client disconnected, remote address: {}, localAddress: {}", + remoteAddr, + conn.getLocalAddress()); } + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnectionOpenEventProcessor.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnectionOpenEventProcessor.java index 7ee2ee987..dee73a914 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnectionOpenEventProcessor.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ClientConnectionOpenEventProcessor.java @@ -23,24 +23,27 @@ /** * The type Client connection close event processor. + * * @author zhuoyu.sjw * @version $Id : ClientConnectionCloseEventProcessor.java, v 0.1 2018-02-26 20:28 zhuoyu.sjw Exp $$ */ public class ClientConnectionOpenEventProcessor implements ConnectionEventProcessor { - private static final Logger LOGGER = LoggerFactory - .getLogger(ClientConnectionOpenEventProcessor.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(ClientConnectionOpenEventProcessor.class); - /** - * On event. - * - * @param remoteAddr the remote addr - * @param conn the conn - */ - @Override - public void onEvent(String remoteAddr, Connection conn) { - if (null != conn) { - LOGGER.info("[connection] Client connected, remote address: {}, localAddress: {}", - remoteAddr, conn.getLocalAddress()); - } + /** + * On event. + * + * @param remoteAddr the remote addr + * @param conn the conn + */ + @Override + public void onEvent(String remoteAddr, Connection conn) { + if (null != conn) { + LOGGER.info( + "[connection] Client connected, remote address: {}, localAddress: {}", + remoteAddr, + conn.getLocalAddress()); } + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ReceivedConfigDataProcessor.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ReceivedConfigDataProcessor.java index 108598ca4..52573b316 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ReceivedConfigDataProcessor.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ReceivedConfigDataProcessor.java @@ -26,90 +26,92 @@ import com.alipay.sofa.registry.client.task.ObserverHandler; import com.alipay.sofa.registry.core.model.ReceivedConfigData; import com.alipay.sofa.registry.core.model.Result; -import org.slf4j.Logger; - import java.util.List; +import org.slf4j.Logger; /** * The type Received config data processor. + * * @author zhuoyu.sjw * @version $Id : ReceivedConfigDataProcessor.java, v 0.1 2018-04-18 15:40 zhuoyu.sjw Exp $$ */ public class ReceivedConfigDataProcessor extends SyncUserProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(ReceivedConfigDataProcessor.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ReceivedConfigDataProcessor.class); - private RegisterCache registerCache; + private RegisterCache registerCache; - private ObserverHandler observerHandler; + private ObserverHandler observerHandler; - /** - * Instantiates a new Received config data processor. - * - * @param registerCache the register cache - * @param observerHandler the observer handler - */ - public ReceivedConfigDataProcessor(RegisterCache registerCache, ObserverHandler observerHandler) { - this.registerCache = registerCache; - this.observerHandler = observerHandler; - } + /** + * Instantiates a new Received config data processor. + * + * @param registerCache the register cache + * @param observerHandler the observer handler + */ + public ReceivedConfigDataProcessor(RegisterCache registerCache, ObserverHandler observerHandler) { + this.registerCache = registerCache; + this.observerHandler = observerHandler; + } - /** - * @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(BizContext, Object) - */ - @Override - public Object handleRequest(BizContext bizCtx, ReceivedConfigData request) { - Result result = new Result(); - result.setSuccess(true); - if (null == request) { - return result; - } + /** @see com.alipay.remoting.rpc.protocol.UserProcessor#handleRequest(BizContext, Object) */ + @Override + public Object handleRequest(BizContext bizCtx, ReceivedConfigData request) { + Result result = new Result(); + result.setSuccess(true); + if (null == request) { + return result; + } - List registIds = request.getConfiguratorRegistIds(); - try { + List registIds = request.getConfiguratorRegistIds(); + try { - ConfiguratorData configuratorData = new ConfiguratorData(); - configuratorData.setDataBox(request.getDataBox()); - configuratorData.setVersion(request.getVersion()); - for (String registId : registIds) { - Configurator configurator = registerCache.getConfiguratorByRegistId(registId); - if (null == configurator) { - continue; - } + ConfiguratorData configuratorData = new ConfiguratorData(); + configuratorData.setDataBox(request.getDataBox()); + configuratorData.setVersion(request.getVersion()); + for (String registId : registIds) { + Configurator configurator = registerCache.getConfiguratorByRegistId(registId); + if (null == configurator) { + continue; + } - if (configurator instanceof DefaultConfigurator) { - ((DefaultConfigurator) configurator).putConfiguratorData(configuratorData); - try { - observerHandler.notify(configurator); - } catch (Exception e) { - LOGGER - .error( - "[received] add configurator notify task error, dataId: {}, registId: {}", - configurator.getDataId(), configurator.getRegistId(), e); - } - } else { - LOGGER.warn("[received] ignore unknown configurator type: {}", configurator - .getClass().getName()); - } - } - LOGGER - .info( - "[received] receive configurator data save success, dataId: {} version: {} data:{} registIds:{}", - request.getDataId(), request.getVersion(), request.getDataBox(), registIds); - } catch (Exception e) { - result.setSuccess(false); - result.setMessage(""); - LOGGER.info( - "[received] receive configurator data save failed, dataId: {} version: {} data:{}", - request.getDataId(), request.getVersion(), request.getDataBox(), e); + if (configurator instanceof DefaultConfigurator) { + ((DefaultConfigurator) configurator).putConfiguratorData(configuratorData); + try { + observerHandler.notify(configurator); + } catch (Exception e) { + LOGGER.error( + "[received] add configurator notify task error, dataId: {}, registId: {}", + configurator.getDataId(), + configurator.getRegistId(), + e); + } + } else { + LOGGER.warn( + "[received] ignore unknown configurator type: {}", configurator.getClass().getName()); } - return result; + } + LOGGER.info( + "[received] receive configurator data save success, dataId: {} version: {} data:{} registIds:{}", + request.getDataId(), + request.getVersion(), + request.getDataBox(), + registIds); + } catch (Exception e) { + result.setSuccess(false); + result.setMessage(""); + LOGGER.info( + "[received] receive configurator data save failed, dataId: {} version: {} data:{}", + request.getDataId(), + request.getVersion(), + request.getDataBox(), + e); } + return result; + } - /** - * @see com.alipay.remoting.rpc.protocol.UserProcessor#interest() - */ - @Override - public String interest() { - return ReceivedConfigData.class.getName(); - } + /** @see com.alipay.remoting.rpc.protocol.UserProcessor#interest() */ + @Override + public String interest() { + return ReceivedConfigData.class.getName(); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ReceivedDataProcessor.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ReceivedDataProcessor.java index bf128b396..a4af2042d 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ReceivedDataProcessor.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ReceivedDataProcessor.java @@ -26,99 +26,106 @@ import com.alipay.sofa.registry.client.task.ObserverHandler; import com.alipay.sofa.registry.core.model.ReceivedData; import com.alipay.sofa.registry.core.model.Result; -import org.slf4j.Logger; - import java.util.List; +import org.slf4j.Logger; /** * The type Received data multi processor. + * * @author zhuoyu.sjw * @version $Id : ReceivedDataProcessor.java, v 0.1 2018-02-27 14:54 zhuoyu.sjw Exp $$ */ public class ReceivedDataProcessor extends SyncUserProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(ReceivedDataProcessor.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ReceivedDataProcessor.class); - private RegisterCache registerCache; + private RegisterCache registerCache; - private ObserverHandler observerHandler; + private ObserverHandler observerHandler; - /** - * Instantiates a new Received data multi processor. - * - * @param registerCache the register cache - */ - public ReceivedDataProcessor(RegisterCache registerCache, ObserverHandler observerHandler) { - this.registerCache = registerCache; - this.observerHandler = observerHandler; - } + /** + * Instantiates a new Received data multi processor. + * + * @param registerCache the register cache + */ + public ReceivedDataProcessor(RegisterCache registerCache, ObserverHandler observerHandler) { + this.registerCache = registerCache; + this.observerHandler = observerHandler; + } - /** - * Handle request object. - * - * @param bizCtx the biz ctx - * @param request the request - * @return the object - */ - @Override - public Object handleRequest(BizContext bizCtx, ReceivedData request) { - Result result = new Result(); - result.setSuccess(true); - if (null == request || null == request.getData()) { - return result; - } - try { - List registIds = request.getSubscriberRegistIds(); - - SegmentData segmentData = new SegmentData(); - segmentData.setData(request.getData()); - segmentData.setVersion(request.getVersion()); - segmentData.setSegment(request.getSegment()); + /** + * Handle request object. + * + * @param bizCtx the biz ctx + * @param request the request + * @return the object + */ + @Override + public Object handleRequest(BizContext bizCtx, ReceivedData request) { + Result result = new Result(); + result.setSuccess(true); + if (null == request || null == request.getData()) { + return result; + } + try { + List registIds = request.getSubscriberRegistIds(); - for (String registId : registIds) { - Subscriber subscriber = registerCache.getSubscriberByRegistId(registId); - if (null == subscriber) { - continue; - } + SegmentData segmentData = new SegmentData(); + segmentData.setData(request.getData()); + segmentData.setVersion(request.getVersion()); + segmentData.setSegment(request.getSegment()); - if (subscriber instanceof DefaultSubscriber) { - DefaultSubscriber defaultSubscriber = (DefaultSubscriber) subscriber; - defaultSubscriber.putReceivedData(segmentData, request.getLocalZone()); - try { - observerHandler.notify(subscriber); - } catch (Exception e) { - LOGGER.error("[received] add notify task error, dataId: {}, registId: {}", - subscriber.getDataId(), subscriber.getRegistId(), e); - } - } else { - LOGGER.warn("[received] ignore unknown subscriber type: {}", subscriber - .getClass().getName()); - } - } + for (String registId : registIds) { + Subscriber subscriber = registerCache.getSubscriberByRegistId(registId); + if (null == subscriber) { + continue; + } - LOGGER - .info( - "[received] receive subscriber data save success, dataId: {} group: {} version: {} data:{} registIds:{}", - request.getDataId(), request.getGroup(), request.getVersion(), - request.getData(), registIds); - } catch (Exception e) { - result.setSuccess(false); - result.setMessage(""); - LOGGER - .info( - "[received] receive subscriber data save failed, dataId: {} group: {} version: {} data:{}", - request.getDataId(), request.getGroup(), request.getVersion(), - request.getData(), e); + if (subscriber instanceof DefaultSubscriber) { + DefaultSubscriber defaultSubscriber = (DefaultSubscriber) subscriber; + defaultSubscriber.putReceivedData(segmentData, request.getLocalZone()); + try { + observerHandler.notify(subscriber); + } catch (Exception e) { + LOGGER.error( + "[received] add notify task error, dataId: {}, registId: {}", + subscriber.getDataId(), + subscriber.getRegistId(), + e); + } + } else { + LOGGER.warn( + "[received] ignore unknown subscriber type: {}", subscriber.getClass().getName()); } - return result; - } + } - /** - * Interest string. - * - * @return the string - */ - @Override - public String interest() { - return ReceivedData.class.getName(); + LOGGER.info( + "[received] receive subscriber data save success, dataId: {} group: {} version: {} data:{} registIds:{}", + request.getDataId(), + request.getGroup(), + request.getVersion(), + request.getData(), + registIds); + } catch (Exception e) { + result.setSuccess(false); + result.setMessage(""); + LOGGER.info( + "[received] receive subscriber data save failed, dataId: {} group: {} version: {} data:{}", + request.getDataId(), + request.getGroup(), + request.getVersion(), + request.getData(), + e); } + return result; + } + + /** + * Interest string. + * + * @return the string + */ + @Override + public String interest() { + return ReceivedData.class.getName(); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ServerManager.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ServerManager.java index cc92a1ef8..66737d762 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ServerManager.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ServerManager.java @@ -20,22 +20,23 @@ /** * The interface Server manager. + * * @author zhuoyu.sjw * @version $Id : ServerManager.java, v 0.1 2017-12-25 11:42 zhuoyu.sjw Exp $$ */ public interface ServerManager { - /** - * Gets server list. - * - * @return the server list - */ - List getServerList(); + /** + * Gets server list. + * + * @return the server list + */ + List getServerList(); - /** - * Random url. - * - * @return the url - */ - ServerNode random(); + /** + * Random url. + * + * @return the url + */ + ServerNode random(); } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ServerNode.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ServerNode.java index 6d31d0c78..360baa2b0 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ServerNode.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/remoting/ServerNode.java @@ -20,37 +20,37 @@ /** * The interface Server node. - * + * * @author zhuoyu.sjw * @version $Id : ServerNode.java, v 0.1 2018-03-01 17:07 zhuoyu.sjw Exp $$ */ public interface ServerNode { - /** - * Gets host. - * - * @return the host - */ - String getHost(); + /** + * Gets host. + * + * @return the host + */ + String getHost(); - /** - * Gets port. - * - * @return the port - */ - int getPort(); + /** + * Gets port. + * + * @return the port + */ + int getPort(); - /** - * Gets properties. - * - * @return the properties - */ - Properties getProperties(); + /** + * Gets properties. + * + * @return the properties + */ + Properties getProperties(); - /** - * Gets url. - * - * @return the url - */ - String getUrl(); + /** + * Gets url. + * + * @return the url + */ + String getUrl(); } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/AbstractWorkerThread.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/AbstractWorkerThread.java index c4d6d2673..c2763ea5a 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/AbstractWorkerThread.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/AbstractWorkerThread.java @@ -20,53 +20,49 @@ /** * The type Abstract worker thread. + * * @author zhuoyu.sjw * @version $Id : AbstractWorkerThread.java, v 0.1 2018-03-01 11:54 zhuoyu.sjw Exp $$ */ public abstract class AbstractWorkerThread extends Thread implements Worker { - /** */ - private final Object bell = new Object(); + /** */ + private final Object bell = new Object(); - /** - * The Client. - */ - protected Client client; + /** The Client. */ + protected Client client; - /** - * Instantiates a new Abstract worker thread. - * - * @param client the client - */ - public AbstractWorkerThread(Client client) { - this.client = client; - } + /** + * Instantiates a new Abstract worker thread. + * + * @param client the client + */ + public AbstractWorkerThread(Client client) { + this.client = client; + } - /** - * Notify execute signal for task thread. - */ - void signal() { - synchronized (bell) { - bell.notifyAll(); - } + /** Notify execute signal for task thread. */ + void signal() { + synchronized (bell) { + bell.notifyAll(); } + } - /** - * Await for next task. - * @param timeout wait timeout - * @throws InterruptedException thread interrupted - */ - void await(long timeout) throws InterruptedException { - synchronized (bell) { - bell.wait(timeout); - } + /** + * Await for next task. + * + * @param timeout wait timeout + * @throws InterruptedException thread interrupted + */ + void await(long timeout) throws InterruptedException { + synchronized (bell) { + bell.wait(timeout); } + } - /** - * @see Runnable#run() - */ - @Override - public void run() { - handle(); - } + /** @see Runnable#run() */ + @Override + public void run() { + handle(); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/ObserverHandler.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/ObserverHandler.java index be3ab699d..fea995f6b 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/ObserverHandler.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/ObserverHandler.java @@ -21,25 +21,23 @@ /** * The interface Observer handler. - * + * * @author zhuoyu.sjw * @version $Id : ObserverHandler.java, v 0.1 2018-03-15 12:15 zhuoyu.sjw Exp $$ */ public interface ObserverHandler { - /** - * Notify. - * - * @param subscriber - * the subscriber - */ - void notify(Subscriber subscriber); + /** + * Notify. + * + * @param subscriber the subscriber + */ + void notify(Subscriber subscriber); - /** - * Notify. - * - * @param configurator - * the configurator - */ - void notify(Configurator configurator); + /** + * Notify. + * + * @param configurator the configurator + */ + void notify(Configurator configurator); } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/SyncConfigThread.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/SyncConfigThread.java index 121866d61..266de5c7c 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/SyncConfigThread.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/SyncConfigThread.java @@ -24,117 +24,118 @@ import com.alipay.sofa.registry.client.remoting.Client; import com.alipay.sofa.registry.core.model.SyncConfigRequest; import com.alipay.sofa.registry.core.model.SyncConfigResponse; -import org.slf4j.Logger; - import java.util.ArrayList; import java.util.Collection; import java.util.List; +import org.slf4j.Logger; /** - * * @author zhuoyu.sjw * @version $Id: SyncConfigThread.java, v 0.1 2018-03-14 23:36 zhuoyu.sjw Exp $$ */ public class SyncConfigThread extends Thread { - private static final Logger LOGGER = LoggerFactory.getLogger(SyncConfigThread.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SyncConfigThread.class); + + private Client client; + + private RegisterCache registerCache; + + private RegistryClientConfig config; + + private ObserverHandler observerHandler; + + public SyncConfigThread( + Client client, + RegisterCache registerCache, + RegistryClientConfig config, + ObserverHandler observerHandler) { + super("SyncConfigThread"); + this.setDaemon(true); + this.client = client; + this.registerCache = registerCache; + this.config = config; + this.observerHandler = observerHandler; + } + + @Override + public void run() { + int retryInterval = config.getSyncConfigRetryInterval(); + //noinspection InfiniteLoopStatement + while (true) { + try { + Thread.sleep(retryInterval); + + if (!client.isConnected()) { + continue; + } - private Client client; + SyncConfigRequest request = new SyncConfigRequest(); + request.setDataCenter(config.getDataCenter()); + request.setZone(config.getZone()); + Object result = client.invokeSync(request); - private RegisterCache registerCache; + if (!(result instanceof SyncConfigResponse)) { + LOGGER.warn("[syncConfig] unknown response type, {}", result); + continue; + } - private RegistryClientConfig config; + SyncConfigResponse response = (SyncConfigResponse) result; + if (!response.isSuccess()) { + LOGGER.warn("[syncConfig] request failed, {}", response); + continue; + } - private ObserverHandler observerHandler; + int interval = response.getRetryInterval(); + retryInterval = Math.max(retryInterval, interval); - public SyncConfigThread(Client client, RegisterCache registerCache, - RegistryClientConfig config, ObserverHandler observerHandler) { - super("SyncConfigThread"); - this.setDaemon(true); - this.client = client; - this.registerCache = registerCache; - this.config = config; - this.observerHandler = observerHandler; - } + List availableSegments = response.getAvailableSegments(); - @Override - public void run() { - int retryInterval = config.getSyncConfigRetryInterval(); - //noinspection InfiniteLoopStatement - while (true) { - try { - Thread.sleep(retryInterval); - - if (!client.isConnected()) { - continue; - } - - SyncConfigRequest request = new SyncConfigRequest(); - request.setDataCenter(config.getDataCenter()); - request.setZone(config.getZone()); - Object result = client.invokeSync(request); - - if (!(result instanceof SyncConfigResponse)) { - LOGGER.warn("[syncConfig] unknown response type, {}", result); - continue; - } - - SyncConfigResponse response = (SyncConfigResponse) result; - if (!response.isSuccess()) { - LOGGER.warn("[syncConfig] request failed, {}", response); - continue; - } - - int interval = response.getRetryInterval(); - retryInterval = Math.max(retryInterval, interval); - - List availableSegments = response.getAvailableSegments(); - - Collection allSubscribers = registerCache.getAllSubscribers(); - for (Subscriber subscriber : allSubscribers) { - try { - if (!(subscriber instanceof DefaultSubscriber)) { - continue; - } - - DefaultSubscriber defaultSubscriber = (DefaultSubscriber) subscriber; - - if (!defaultSubscriber.isInited()) { - LOGGER.info("[syncConfig] DefaultSubscriber not init, {}", - defaultSubscriber.getRegistId()); - continue; - } - List nowAvailableSegments = defaultSubscriber - .getAvailableSegments(); - - if (isEqualCollections(availableSegments, nowAvailableSegments)) { - continue; - } - - defaultSubscriber.setAvailableSegments(availableSegments); - - observerHandler.notify(defaultSubscriber); - } catch (Exception e) { - LOGGER - .error( - "[syncConfig] try notify subscriber error, registId: {}, availableSegments: {}", - subscriber.getRegistId(), availableSegments, e); - } - } - } catch (Throwable e) { - LOGGER.error("[syncConfig] sync config error, retryInterval: {}", retryInterval, e); + Collection allSubscribers = registerCache.getAllSubscribers(); + for (Subscriber subscriber : allSubscribers) { + try { + if (!(subscriber instanceof DefaultSubscriber)) { + continue; } - } - } - private boolean isEqualCollections(Collection a, Collection b) { - if (null == a) { - a = new ArrayList(); - } + DefaultSubscriber defaultSubscriber = (DefaultSubscriber) subscriber; + + if (!defaultSubscriber.isInited()) { + LOGGER.info( + "[syncConfig] DefaultSubscriber not init, {}", defaultSubscriber.getRegistId()); + continue; + } + List nowAvailableSegments = defaultSubscriber.getAvailableSegments(); + + if (isEqualCollections(availableSegments, nowAvailableSegments)) { + continue; + } - if (null == b) { - b = new ArrayList(); + defaultSubscriber.setAvailableSegments(availableSegments); + + observerHandler.notify(defaultSubscriber); + } catch (Exception e) { + LOGGER.error( + "[syncConfig] try notify subscriber error, registId: {}, availableSegments: {}", + subscriber.getRegistId(), + availableSegments, + e); + } } + } catch (Throwable e) { + LOGGER.error("[syncConfig] sync config error, retryInterval: {}", retryInterval, e); + } + } + } - return a.size() == b.size() && a.equals(b); + private boolean isEqualCollections(Collection a, Collection b) { + if (null == a) { + a = new ArrayList(); } + + if (null == b) { + b = new ArrayList(); + } + + return a.size() == b.size() && a.equals(b); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/TaskEvent.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/TaskEvent.java index ce62554e4..ed5db9d6c 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/TaskEvent.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/TaskEvent.java @@ -20,134 +20,131 @@ /** * The type Task event. + * * @author zhuoyu.sjw * @version $Id : TaskEvent.java, v 0.1 2018-02-28 20:33 zhuoyu.sjw Exp $$ */ public class TaskEvent implements Comparable { - private static final int MAX_DELAY_TIME = 1000; - - private Register source; - - private int sendCount; - - private long triggerTime; - - /** - * Constructor. - * - * @param source the source - */ - public TaskEvent(Register source) { - this.source = source; - this.triggerTime = System.currentTimeMillis(); - this.sendCount = 0; + private static final int MAX_DELAY_TIME = 1000; + + private Register source; + + private int sendCount; + + private long triggerTime; + + /** + * Constructor. + * + * @param source the source + */ + public TaskEvent(Register source) { + this.source = source; + this.triggerTime = System.currentTimeMillis(); + this.sendCount = 0; + } + + /** + * Getter method for property source. + * + * @return property value of source + */ + public Register getSource() { + return source; + } + + /** + * Setter method for property triggerTime. + * + * @param triggerTime value to be assigned to property triggerTime + */ + public void setTriggerTime(long triggerTime) { + this.triggerTime = triggerTime; + } + + /** + * Delay time long. + * + * @return long long + */ + public long delayTime() { + int time = sendCount * 200; + if (time > MAX_DELAY_TIME) { + time = MAX_DELAY_TIME; } - - /** - * Getter method for property source. - * - * @return property value of source - */ - public Register getSource() { - return source; + return time - (System.currentTimeMillis() - this.triggerTime); + } + + /** + * Compare to int. + * + * @param event the event + * @return the int + */ + @Override + public int compareTo(TaskEvent event) { + if (this.sendCount > event.sendCount) { + return 1; + } else if (this.sendCount < event.sendCount) { + return -1; } - - /** - * Setter method for property triggerTime. - * - * @param triggerTime value to be assigned to property triggerTime - */ - public void setTriggerTime(long triggerTime) { - this.triggerTime = triggerTime; + Register register1 = source; + Register register2 = event.getSource(); + + if (register1 == null) { + return register2 != null ? -1 : 0; + } else { + if (register2 == null) { + return 1; + } } - /** - * Delay time long. - * - * @return long long - */ - public long delayTime() { - int time = sendCount * 200; - if (time > MAX_DELAY_TIME) { - time = MAX_DELAY_TIME; - } - return time - (System.currentTimeMillis() - this.triggerTime); + long t1 = register1.getTimestamp(); + long t2 = register2.getTimestamp(); + if (t1 > t2) { + return 1; + } else if (t1 < t2) { + return -1; } - - /** - * Compare to int. - * - * @param event the event - * @return the int - */ - @Override - public int compareTo(TaskEvent event) { - if (this.sendCount > event.sendCount) { - return 1; - } else if (this.sendCount < event.sendCount) { - return -1; - } - Register register1 = source; - Register register2 = event.getSource(); - - if (register1 == null) { - return register2 != null ? -1 : 0; - } else { - if (register2 == null) { - return 1; - } - } - - long t1 = register1.getTimestamp(); - long t2 = register2.getTimestamp(); - if (t1 > t2) { - return 1; - } else if (t1 < t2) { - return -1; - } - return 0; + return 0; + } + + /** @see Object#equals(Object) */ + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - /** - * @see Object#equals(Object) - */ - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof TaskEvent)) { - return false; - } - - TaskEvent taskEvent = (TaskEvent) o; - - if (sendCount != taskEvent.sendCount) { - return false; - } - if (triggerTime != taskEvent.triggerTime) { - return false; - } - return source != null ? source.equals(taskEvent.source) : taskEvent.source == null; + if (!(o instanceof TaskEvent)) { + return false; } - /** - * @see Object#hashCode() - */ - @Override - public int hashCode() { - int result = source != null ? source.hashCode() : 0; - result = 31 * result + sendCount; - result = 31 * result + (int) (triggerTime ^ (triggerTime >>> 32)); - return result; - } + TaskEvent taskEvent = (TaskEvent) o; - /** - * Inc send count int. - * - * @return the int - */ - public int incSendCount() { - return this.sendCount++; + if (sendCount != taskEvent.sendCount) { + return false; + } + if (triggerTime != taskEvent.triggerTime) { + return false; } + return source != null ? source.equals(taskEvent.source) : taskEvent.source == null; + } + + /** @see Object#hashCode() */ + @Override + public int hashCode() { + int result = source != null ? source.hashCode() : 0; + result = 31 * result + sendCount; + result = 31 * result + (int) (triggerTime ^ (triggerTime >>> 32)); + return result; + } + + /** + * Inc send count int. + * + * @return the int + */ + public int incSendCount() { + return this.sendCount++; + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/TaskQueue.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/TaskQueue.java index 8bc33eb60..81d755a19 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/TaskQueue.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/TaskQueue.java @@ -18,7 +18,6 @@ import com.alipay.sofa.registry.client.api.Register; import com.alipay.sofa.registry.client.provider.AbstractInternalRegister; - import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; @@ -28,68 +27,68 @@ /** * The type Task queue. + * * @author zhuoyu.sjw * @version $Id : TaskQueue.java, v 0.1 2018-02-28 20:44 zhuoyu.sjw Exp $$ */ public class TaskQueue implements Iterable { - private final ConcurrentMap taskMap = new ConcurrentHashMap(); - - /** - * Iterator iterator. - * - * @return the iterator - */ - @Override - public Iterator iterator() { - List taskList = new ArrayList(taskMap.values()); - Collections.sort(taskList); - return taskList.iterator(); - } + private final ConcurrentMap taskMap = + new ConcurrentHashMap(); - /** - * Delete the completed task, return task queue size. - */ - public void cleanCompletedTasks() { - List taskList = new ArrayList(taskMap.keySet()); - for (String key : taskList) { - TaskEvent event = taskMap.get(key); - AbstractInternalRegister r = (AbstractInternalRegister) event.getSource(); - if (r.isDone()) { - taskMap.remove(key, event); - } - } - taskMap.size(); - } + /** + * Iterator iterator. + * + * @return the iterator + */ + @Override + public Iterator iterator() { + List taskList = new ArrayList(taskMap.values()); + Collections.sort(taskList); + return taskList.iterator(); + } - /** - * Add task event to task queue. - * @param event task event - */ - public void put(TaskEvent event) { - Register register = event.getSource(); - String key = register.getRegistId(); - taskMap.put(key, event); + /** Delete the completed task, return task queue size. */ + public void cleanCompletedTasks() { + List taskList = new ArrayList(taskMap.keySet()); + for (String key : taskList) { + TaskEvent event = taskMap.get(key); + AbstractInternalRegister r = (AbstractInternalRegister) event.getSource(); + if (r.isDone()) { + taskMap.remove(key, event); + } } + taskMap.size(); + } - /** - * Put all. - * - * @param taskEvents the task events - */ - public void putAll(List taskEvents) { - for (TaskEvent event : taskEvents) { - put(event); - } - } + /** + * Add task event to task queue. + * + * @param event task event + */ + public void put(TaskEvent event) { + Register register = event.getSource(); + String key = register.getRegistId(); + taskMap.put(key, event); + } - /** - * Is empty boolean. - * - * @return the boolean - */ - public boolean isEmpty() { - return taskMap.isEmpty(); + /** + * Put all. + * + * @param taskEvents the task events + */ + public void putAll(List taskEvents) { + for (TaskEvent event : taskEvents) { + put(event); } + } + /** + * Is empty boolean. + * + * @return the boolean + */ + public boolean isEmpty() { + return taskMap.isEmpty(); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/Worker.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/Worker.java index f3a89916e..1f988105b 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/Worker.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/Worker.java @@ -20,27 +20,26 @@ /** * The interface Worker. + * * @author zhuoyu.sjw * @version $Id : Worker.java, v 0.1 2018-02-28 22:45 zhuoyu.sjw Exp $$ */ public interface Worker { - /** - * Schedule. - * - * @param event the event - */ - void schedule(TaskEvent event); + /** + * Schedule. + * + * @param event the event + */ + void schedule(TaskEvent event); - /** - * Schedule. - * - * @param events the events - */ - void schedule(List events); + /** + * Schedule. + * + * @param events the events + */ + void schedule(List events); - /** - * Handle. - */ - void handle(); + /** Handle. */ + void handle(); } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/WorkerThread.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/WorkerThread.java index 285c656d3..d5d6af8a7 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/task/WorkerThread.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/task/WorkerThread.java @@ -24,173 +24,171 @@ import com.alipay.sofa.registry.client.provider.RegisterCache; import com.alipay.sofa.registry.client.remoting.Client; import com.alipay.sofa.registry.core.model.RegisterResponse; -import org.slf4j.Logger; - import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; +import org.slf4j.Logger; /** * The type Worker thread. + * * @author zhuoyu.sjw * @version $Id : WorkerThread.java, v 0.1 2018-03-01 11:51 zhuoyu.sjw Exp $$ */ public class WorkerThread extends AbstractWorkerThread { - private static final Logger LOGGER = LoggerFactory.getLogger(WorkerThread.class); - - /** - * Task queue - */ - protected final TaskQueue requestQueue = new TaskQueue(); - - private RegistryClientConfig config; - - private RegisterCache registerCache; - - private AtomicBoolean inited = new AtomicBoolean(false); - - /** - * Instantiates a new Worker thread. - * - * @param client the client connection - * @param config the config - */ - public WorkerThread(Client client, RegistryClientConfig config, RegisterCache registerCache) { - super(client); - this.config = config; - this.registerCache = registerCache; - this.setName("RegistryWorkerThread"); - this.setDaemon(true); + private static final Logger LOGGER = LoggerFactory.getLogger(WorkerThread.class); + + /** Task queue */ + protected final TaskQueue requestQueue = new TaskQueue(); + + private RegistryClientConfig config; + + private RegisterCache registerCache; + + private AtomicBoolean inited = new AtomicBoolean(false); + + /** + * Instantiates a new Worker thread. + * + * @param client the client connection + * @param config the config + */ + public WorkerThread(Client client, RegistryClientConfig config, RegisterCache registerCache) { + super(client); + this.config = config; + this.registerCache = registerCache; + this.setName("RegistryWorkerThread"); + this.setDaemon(true); + } + + /** + * Schedule. + * + * @param event the event + */ + @Override + public void schedule(TaskEvent event) { + if (inited.compareAndSet(false, true)) { + this.start(); } - - /** - * Schedule. - * - * @param event the event - */ - @Override - public void schedule(TaskEvent event) { - if (inited.compareAndSet(false, true)) { - this.start(); - } - requestQueue.put(event); - signal(); + requestQueue.put(event); + signal(); + } + + /** + * Schedule. + * + * @param events the events + */ + @Override + public void schedule(List events) { + if (inited.compareAndSet(false, true)) { + this.start(); } - - /** - * Schedule. - * - * @param events the events - */ - @Override - public void schedule(List events) { - if (inited.compareAndSet(false, true)) { - this.start(); + requestQueue.putAll(events); + } + + /** Handle. */ + @Override + public void handle() { + //noinspection InfiniteLoopStatement + while (true) { + try { + // check connection status, try to reconnect to the server when connection lose + client.ensureConnected(); + + if (requestQueue.isEmpty()) { + await(config.getRecheckInterval()); + continue; } - requestQueue.putAll(events); - } - /** - * Handle. - */ - @Override - public void handle() { - //noinspection InfiniteLoopStatement - while (true) { - try { - // check connection status, try to reconnect to the server when connection lose - client.ensureConnected(); - - if (requestQueue.isEmpty()) { - await(config.getRecheckInterval()); - continue; - } - - Iterator lt = requestQueue.iterator(); - - while (lt.hasNext()) { - client.ensureConnected(); - TaskEvent ev = lt.next(); - lt.remove(); - int sendCount = ev.incSendCount(); - - // Resent needs delay when task event is not the first time to send. - if (sendCount != 0 && ev.delayTime() > 0) { - continue; - } - - handleTask(ev); - } - - // Cleaning completed task, it will take more time when the registration number is large. - requestQueue.cleanCompletedTasks(); - } catch (Throwable e) { - LOGGER.error("[send] handle data error!", e); - } - } - } + Iterator lt = requestQueue.iterator(); - private void handleTask(TaskEvent event) { - if (null == event) { - return; - } + while (lt.hasNext()) { + client.ensureConnected(); + TaskEvent ev = lt.next(); + lt.remove(); + int sendCount = ev.incSendCount(); + + // Resent needs delay when task event is not the first time to send. + if (sendCount != 0 && ev.delayTime() > 0) { + continue; + } - try { - event.setTriggerTime(System.currentTimeMillis()); - Register register = event.getSource(); - - if (!(register instanceof AbstractInternalRegister)) { - LOGGER.warn("[register] register type unknown, {}", register); - return; - } - - AbstractInternalRegister abstractInternalRegister = (AbstractInternalRegister) register; - - SyncTask syncTask = abstractInternalRegister.assemblySyncTask(); - String requestId = syncTask.getRequestId(); - - if (syncTask.isDone()) { - LOGGER.info("[register] register already sync succeeded, {}", register); - return; - } - - Object request = syncTask.getRequest(); - - Object result = client.invokeSync(request); - - if (!(result instanceof RegisterResponse)) { - LOGGER.warn("[register] result type is wrong, {}", result); - return; - } - - RegisterResponse response = (RegisterResponse) result; - if (!response.isSuccess()) { - LOGGER.info("[register] register to server failed, {}, {}", request, response); - return; - } - - boolean syncOK = abstractInternalRegister.syncOK(requestId, response.getVersion(), - response.isRefused()); - if (!syncOK) { - LOGGER.info("[register] requestId has expired, ignore this response, {}, {}, {}", - requestId, request, response); - return; - } - - if (!register.isEnabled()) { - registerCache.remove(register.getRegistId()); - } - - if (response.isRefused()) { - LOGGER.info("[register] register refused by server, {}, {}, {}", requestId, - request, response); - } else { - LOGGER.info("[register] register to server success, {}, {}, {}", requestId, - request, response); - } - } catch (Exception e) { - LOGGER.error("[send] handle request failed, {}", event, e); + handleTask(ev); } + + // Cleaning completed task, it will take more time when the registration number is large. + requestQueue.cleanCompletedTasks(); + } catch (Throwable e) { + LOGGER.error("[send] handle data error!", e); + } + } + } + + private void handleTask(TaskEvent event) { + if (null == event) { + return; } + try { + event.setTriggerTime(System.currentTimeMillis()); + Register register = event.getSource(); + + if (!(register instanceof AbstractInternalRegister)) { + LOGGER.warn("[register] register type unknown, {}", register); + return; + } + + AbstractInternalRegister abstractInternalRegister = (AbstractInternalRegister) register; + + SyncTask syncTask = abstractInternalRegister.assemblySyncTask(); + String requestId = syncTask.getRequestId(); + + if (syncTask.isDone()) { + LOGGER.info("[register] register already sync succeeded, {}", register); + return; + } + + Object request = syncTask.getRequest(); + + Object result = client.invokeSync(request); + + if (!(result instanceof RegisterResponse)) { + LOGGER.warn("[register] result type is wrong, {}", result); + return; + } + + RegisterResponse response = (RegisterResponse) result; + if (!response.isSuccess()) { + LOGGER.info("[register] register to server failed, {}, {}", request, response); + return; + } + + boolean syncOK = + abstractInternalRegister.syncOK(requestId, response.getVersion(), response.isRefused()); + if (!syncOK) { + LOGGER.info( + "[register] requestId has expired, ignore this response, {}, {}, {}", + requestId, + request, + response); + return; + } + + if (!register.isEnabled()) { + registerCache.remove(register.getRegistId()); + } + + if (response.isRefused()) { + LOGGER.info( + "[register] register refused by server, {}, {}, {}", requestId, request, response); + } else { + LOGGER.info( + "[register] register to server success, {}, {}, {}", requestId, request, response); + } + } catch (Exception e) { + LOGGER.error("[send] handle request failed, {}", event, e); + } + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/util/CommonUtils.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/util/CommonUtils.java index e4c851a1b..ab5a14388 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/util/CommonUtils.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/util/CommonUtils.java @@ -20,20 +20,19 @@ /** * The type Common utils. - * + * * @author zhuoyu.sjw * @version $Id : CommonUtils.java, v 0.1 2018-07-15 22:48 zhuoyu.sjw Exp $$ */ public class CommonUtils { - /** - * Is not empty boolean. - * - * @param collection - * the collection - * @return the boolean - */ - public static boolean isNotEmpty(Collection collection) { - return collection != null && !collection.isEmpty(); - } + /** + * Is not empty boolean. + * + * @param collection the collection + * @return the boolean + */ + public static boolean isNotEmpty(Collection collection) { + return collection != null && !collection.isEmpty(); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/util/HttpClientUtils.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/util/HttpClientUtils.java index 2415ea560..8643c91a6 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/util/HttpClientUtils.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/util/HttpClientUtils.java @@ -17,7 +17,6 @@ package com.alipay.sofa.registry.client.util; import com.alipay.sofa.registry.client.api.RegistryClientConfig; - import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; @@ -28,97 +27,97 @@ /** * The type Http client utils. + * * @author zhuoyu.sjw * @version $Id : HttpClientUtils.java, v 0.1 2018-03-22 17:38 zhuoyu.sjw Exp $$ */ public class HttpClientUtils { - private static final char AND = '&'; + private static final char AND = '&'; - /** - * Get string. - * - * @param url the url - * @param params the params - * @param config the config - * @return the string - * @throws Exception the exception - */ - public static String get(String url, Map params, RegistryClientConfig config) - throws Exception { - HttpURLConnection httpURLConnection = create(getFullPath(url, params), config); - httpURLConnection.setRequestMethod("GET"); + /** + * Get string. + * + * @param url the url + * @param params the params + * @param config the config + * @return the string + * @throws Exception the exception + */ + public static String get(String url, Map params, RegistryClientConfig config) + throws Exception { + HttpURLConnection httpURLConnection = create(getFullPath(url, params), config); + httpURLConnection.setRequestMethod("GET"); - BufferedReader reader = null; - try { - StringBuilder stringBuffer = new StringBuilder(); + BufferedReader reader = null; + try { + StringBuilder stringBuffer = new StringBuilder(); - int responseCode = httpURLConnection.getResponseCode(); - if (responseCode == HttpURLConnection.HTTP_OK) { - String charset = httpURLConnection.getContentEncoding(); - if (charset != null) { - reader = new BufferedReader(new InputStreamReader( - httpURLConnection.getInputStream(), charset)); - } else { - reader = new BufferedReader(new InputStreamReader( - httpURLConnection.getInputStream())); - } - - String strCurrentLine; - while ((strCurrentLine = reader.readLine()) != null) { - stringBuffer.append(strCurrentLine).append("\n"); - } - if (stringBuffer.length() > 0 - && stringBuffer.charAt(stringBuffer.length() - 1) == '\n') { - stringBuffer.deleteCharAt(stringBuffer.length() - 1); - } + int responseCode = httpURLConnection.getResponseCode(); + if (responseCode == HttpURLConnection.HTTP_OK) { + String charset = httpURLConnection.getContentEncoding(); + if (charset != null) { + reader = + new BufferedReader( + new InputStreamReader(httpURLConnection.getInputStream(), charset)); + } else { + reader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream())); + } - return stringBuffer.toString(); - } - } finally { - httpURLConnection.disconnect(); - if (null != reader) { - reader.close(); - } + String strCurrentLine; + while ((strCurrentLine = reader.readLine()) != null) { + stringBuffer.append(strCurrentLine).append("\n"); + } + if (stringBuffer.length() > 0 && stringBuffer.charAt(stringBuffer.length() - 1) == '\n') { + stringBuffer.deleteCharAt(stringBuffer.length() - 1); } - return null; - } - /** - * Create http url connection. - * - * @param httpUrl the http url - * @param config the config - * @return the http url connection - * @throws Exception the exception - */ - private static HttpURLConnection create(String httpUrl, RegistryClientConfig config) - throws Exception { - URL url = new URL(httpUrl); - URLConnection urlConnection = url.openConnection(); - HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; - httpConnection.setDoOutput(true); - httpConnection.setDoInput(true); - httpConnection.setUseCaches(false); - httpConnection.setRequestProperty("Content-type", "text/plain"); - httpConnection.setConnectTimeout(config.getConnectTimeout()); - httpConnection.setReadTimeout(config.getSocketTimeout()); - return httpConnection; + return stringBuffer.toString(); + } + } finally { + httpURLConnection.disconnect(); + if (null != reader) { + reader.close(); + } } + return null; + } - private static String getFullPath(String url, Map params) { - StringBuilder sb = new StringBuilder(url); - if (params != null) { - sb.append("?"); - for (Entry param : params.entrySet()) { - sb.append(param.getKey()); - sb.append("="); - sb.append(param.getValue()); - sb.append("&"); - } - if (sb.charAt(sb.length() - 1) == AND) { - sb.deleteCharAt(sb.length() - 1); - } - } - return sb.toString(); + /** + * Create http url connection. + * + * @param httpUrl the http url + * @param config the config + * @return the http url connection + * @throws Exception the exception + */ + private static HttpURLConnection create(String httpUrl, RegistryClientConfig config) + throws Exception { + URL url = new URL(httpUrl); + URLConnection urlConnection = url.openConnection(); + HttpURLConnection httpConnection = (HttpURLConnection) urlConnection; + httpConnection.setDoOutput(true); + httpConnection.setDoInput(true); + httpConnection.setUseCaches(false); + httpConnection.setRequestProperty("Content-type", "text/plain"); + httpConnection.setConnectTimeout(config.getConnectTimeout()); + httpConnection.setReadTimeout(config.getSocketTimeout()); + return httpConnection; + } + + private static String getFullPath(String url, Map params) { + StringBuilder sb = new StringBuilder(url); + if (params != null) { + sb.append("?"); + for (Entry param : params.entrySet()) { + sb.append(param.getKey()); + sb.append("="); + sb.append(param.getValue()); + sb.append("&"); + } + if (sb.charAt(sb.length() - 1) == AND) { + sb.deleteCharAt(sb.length() - 1); + } } + return sb.toString(); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/util/ServerNodeParser.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/util/ServerNodeParser.java index da8b41f77..a776805b0 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/util/ServerNodeParser.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/util/ServerNodeParser.java @@ -18,123 +18,117 @@ import com.alipay.sofa.registry.client.provider.DefaultServerNode; import com.alipay.sofa.registry.client.remoting.ServerNode; - import java.util.Properties; /** - * * @author zhuoyu.sjw * @version $Id: ServerNodeParser.java, v 0.1 2018-03-22 20:28 zhuoyu.sjw Exp $$ */ public class ServerNodeParser { - /** symbol : */ - private static final char COLON = ':'; + /** symbol : */ + private static final char COLON = ':'; - /** symbol = */ - private static final char EQUAL = '='; + /** symbol = */ + private static final char EQUAL = '='; - /** symbol & */ - private static final char AND = '&'; + /** symbol & */ + private static final char AND = '&'; - /** symbol ? */ - private static final char QUES = '?'; + /** symbol ? */ + private static final char QUES = '?'; + + /** @see com.alipay.remoting.RemotingAddressParser#parse(String) */ + @SuppressWarnings("ConstantConditions") + public static ServerNode parse(String url) { + if (StringUtils.isBlank(url)) { + throw new IllegalArgumentException( + "Illegal format address string [" + url + "], should not be blank! "); + } + String ip = null; + String port = null; + Properties properties = null; - /** - * @see com.alipay.remoting.RemotingAddressParser#parse(String) - */ - @SuppressWarnings("ConstantConditions") - public static ServerNode parse(String url) { - if (StringUtils.isBlank(url)) { - throw new IllegalArgumentException("Illegal format address string [" + url - + "], should not be blank! "); + int size = url.length(); + int pos = 0; + for (int i = 0; i < size; ++i) { + if (COLON == url.charAt(i)) { + ip = url.substring(pos, i); + pos = i; + // should not end with COLON + if (i == size - 1) { + throw new IllegalArgumentException( + "Illegal format address string [" + url + "], should not end with COLON[:]! "); } - String ip = null; - String port = null; - Properties properties = null; + break; + } + // must have one COLON + if (i == size - 1) { + throw new IllegalArgumentException( + "Illegal format address string [" + url + "], must have one COLON[:]! "); + } + } - int size = url.length(); - int pos = 0; - for (int i = 0; i < size; ++i) { - if (COLON == url.charAt(i)) { - ip = url.substring(pos, i); - pos = i; - // should not end with COLON - if (i == size - 1) { - throw new IllegalArgumentException("Illegal format address string [" + url - + "], should not end with COLON[:]! "); - } - break; - } - // must have one COLON - if (i == size - 1) { - throw new IllegalArgumentException("Illegal format address string [" + url - + "], must have one COLON[:]! "); - } + for (int i = pos; i < size; ++i) { + if (QUES == url.charAt(i)) { + port = url.substring(pos + 1, i); + pos = i; + if (i == size - 1) { + // should not end with QUES + throw new IllegalArgumentException( + "Illegal format address string [" + url + "], should not end with QUES[?]! "); } + break; + } + // end without a QUES + if (i == size - 1) { + port = url.substring(pos + 1, i + 1); + pos = size; + } + } + if (pos < (size - 1)) { + properties = new Properties(); + while (pos < (size - 1)) { + String key = null; + String value = null; for (int i = pos; i < size; ++i) { - if (QUES == url.charAt(i)) { - port = url.substring(pos + 1, i); - pos = i; - if (i == size - 1) { - // should not end with QUES - throw new IllegalArgumentException("Illegal format address string [" + url - + "], should not end with QUES[?]! "); - } - break; - } - // end without a QUES + if (EQUAL == url.charAt(i)) { + key = url.substring(pos + 1, i); + pos = i; if (i == size - 1) { - port = url.substring(pos + 1, i + 1); - pos = size; + // should not end with EQUAL + throw new IllegalArgumentException( + "Illegal format address string [" + url + "], should not end with EQUAL[=]! "); } + break; + } + if (i == size - 1) { + // must have one EQUAL + throw new IllegalArgumentException( + "Illegal format address string [" + url + "], must have one EQUAL[=]! "); + } } - - if (pos < (size - 1)) { - properties = new Properties(); - while (pos < (size - 1)) { - String key = null; - String value = null; - for (int i = pos; i < size; ++i) { - if (EQUAL == url.charAt(i)) { - key = url.substring(pos + 1, i); - pos = i; - if (i == size - 1) { - // should not end with EQUAL - throw new IllegalArgumentException( - "Illegal format address string [" + url - + "], should not end with EQUAL[=]! "); - } - break; - } - if (i == size - 1) { - // must have one EQUAL - throw new IllegalArgumentException("Illegal format address string [" + url - + "], must have one EQUAL[=]! "); - } - } - for (int i = pos; i < size; ++i) { - if (AND == url.charAt(i)) { - value = url.substring(pos + 1, i); - pos = i; - if (i == size - 1) { - // should not end with AND - throw new IllegalArgumentException("Illegal format address string [" - + url - + "], should not end with AND[&]! "); - } - break; - } - // end without more AND - if (i == size - 1) { - value = url.substring(pos + 1, i + 1); - pos = size; - } - } - properties.put(key, value); + for (int i = pos; i < size; ++i) { + if (AND == url.charAt(i)) { + value = url.substring(pos + 1, i); + pos = i; + if (i == size - 1) { + // should not end with AND + throw new IllegalArgumentException( + "Illegal format address string [" + url + "], should not end with AND[&]! "); } + break; + } + // end without more AND + if (i == size - 1) { + value = url.substring(pos + 1, i + 1); + pos = size; + } } - return new DefaultServerNode(url, ip, Integer.parseInt(port), properties); + properties.put(key, value); + } } + return new DefaultServerNode(url, ip, Integer.parseInt(port), properties); + } } diff --git a/client/impl/src/main/java/com/alipay/sofa/registry/client/util/StringUtils.java b/client/impl/src/main/java/com/alipay/sofa/registry/client/util/StringUtils.java index 6b70f8e4a..4a5024c9c 100644 --- a/client/impl/src/main/java/com/alipay/sofa/registry/client/util/StringUtils.java +++ b/client/impl/src/main/java/com/alipay/sofa/registry/client/util/StringUtils.java @@ -18,112 +18,99 @@ /** * The type String utils. - * + * * @author zhuoyu.sjw * @version $Id : StringUtils.java, v 0.1 2018-03-05 17:36 zhuoyu.sjw Exp $$ */ public class StringUtils { - /** - * The constant EMPTY. - */ - public static final String EMPTY = ""; + /** The constant EMPTY. */ + public static final String EMPTY = ""; - /** - * Is empty boolean. - * - * @param cs - * the cs - * @return the boolean - */ - public static boolean isEmpty(CharSequence cs) { - return cs == null || cs.length() == 0; - } + /** + * Is empty boolean. + * + * @param cs the cs + * @return the boolean + */ + public static boolean isEmpty(CharSequence cs) { + return cs == null || cs.length() == 0; + } - /** - * Is not empty boolean. - * - * @param cs - * the cs - * @return the boolean - */ - public static boolean isNotEmpty(CharSequence cs) { - return !isEmpty(cs); - } + /** + * Is not empty boolean. + * + * @param cs the cs + * @return the boolean + */ + public static boolean isNotEmpty(CharSequence cs) { + return !isEmpty(cs); + } - /** - * Is blank boolean. - * - * @param cs - * the cs - * @return the boolean - */ - public static boolean isBlank(CharSequence cs) { - int strLen; - if (cs == null || (strLen = cs.length()) == 0) { - return true; - } - for (int i = 0; i < strLen; i++) { - if (!Character.isWhitespace(cs.charAt(i))) { - return false; - } - } - return true; - } + /** + * Is blank boolean. + * + * @param cs the cs + * @return the boolean + */ + public static boolean isBlank(CharSequence cs) { + int strLen; + if (cs == null || (strLen = cs.length()) == 0) { + return true; + } + for (int i = 0; i < strLen; i++) { + if (!Character.isWhitespace(cs.charAt(i))) { + return false; + } + } + return true; + } - /** - * Is not blank boolean. - * - * @param cs - * the cs - * @return the boolean - */ - public static boolean isNotBlank(CharSequence cs) { - return !isBlank(cs); - } + /** + * Is not blank boolean. + * + * @param cs the cs + * @return the boolean + */ + public static boolean isNotBlank(CharSequence cs) { + return !isBlank(cs); + } - /** - *

- * Returns either the passed in String, or if the String is {@code null}, an - * empty String (""). - *

- * - *
-	 * StringUtils.defaultString(null)  = ""
-	 * StringUtils.defaultString("")    = ""
-	 * StringUtils.defaultString("bat") = "bat"
-	 * 
- * - * @param str - * the String to check, may be null - * @return the passed in String, or the empty String if it was {@code null} - * @see String#valueOf(Object) String#valueOf(Object) - */ - public static String defaultString(final Object str) { - return toString(str, EMPTY); - } + /** + * Returns either the passed in String, or if the String is {@code null}, an empty String (""). + * + *
+   * StringUtils.defaultString(null)  = ""
+   * StringUtils.defaultString("")    = ""
+   * StringUtils.defaultString("bat") = "bat"
+   * 
+ * + * @param str the String to check, may be null + * @return the passed in String, or the empty String if it was {@code null} + * @see String#valueOf(Object) String#valueOf(Object) + */ + public static String defaultString(final Object str) { + return toString(str, EMPTY); + } - /** - * To string string. - * - * @param o - * the o - * @param defaultVal - * the default val - * @return the string - */ - public static String toString(Object o, String defaultVal) { - return o == null ? defaultVal : o.toString(); - } + /** + * To string string. + * + * @param o the o + * @param defaultVal the default val + * @return the string + */ + public static String toString(Object o, String defaultVal) { + return o == null ? defaultVal : o.toString(); + } - /** - * To string string. - * - * @param o - * the o - * @return the string - */ - public static String toString(Object o) { - return toString(o, null); - } + /** + * To string string. + * + * @param o the o + * @return the string + */ + public static String toString(Object o) { + return toString(o, null); + } } diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/MockServer.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/MockServer.java index a8f5b3867..d2a76dd19 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/MockServer.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/MockServer.java @@ -27,198 +27,189 @@ import com.alipay.sofa.registry.core.model.RegisterResponse; import com.alipay.sofa.registry.core.model.Result; import com.alipay.sofa.registry.core.model.SubscriberRegister; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import java.util.HashMap; import java.util.List; import java.util.Map; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * The type Mock server. + * * @author zhuoyu.sjw * @version $Id : MockServer.java, v 0.1 2017-12-25 22:39 zhuoyu.sjw Exp $$ */ public class MockServer { - /** LOGGER */ - private static final Logger LOGGER = LoggerFactory - .getLogger(MockServer.class); - - private RpcServer rpcServer; - - private String ip = "127.0.0.1"; - - private int port = 9600; - - private Map publisherMap = new HashMap(); - private Map subscriberMap = new HashMap(); - private Map configuratorMap = new HashMap(); - - /** - * Start. - */ - public void start() { - rpcServer = new RpcServer(port); - rpcServer.registerUserProcessor(new MockSubscriberRegisterProcessor()); - rpcServer.registerUserProcessor(new MockPublisherRegisterProcessor()); - rpcServer.registerUserProcessor(new MockConfiguratorRegisterProcesor()); - rpcServer.start(); + /** LOGGER */ + private static final Logger LOGGER = LoggerFactory.getLogger(MockServer.class); + + private RpcServer rpcServer; + + private String ip = "127.0.0.1"; + + private int port = 9600; + + private Map publisherMap = new HashMap(); + private Map subscriberMap = new HashMap(); + private Map configuratorMap = + new HashMap(); + + /** Start. */ + public void start() { + rpcServer = new RpcServer(port); + rpcServer.registerUserProcessor(new MockSubscriberRegisterProcessor()); + rpcServer.registerUserProcessor(new MockPublisherRegisterProcessor()); + rpcServer.registerUserProcessor(new MockConfiguratorRegisterProcesor()); + rpcServer.start(); + } + + /** Stop. */ + public void stop() { + rpcServer.stop(); + } + + /** + * Getter method for property ip. + * + * @return property value of ip + */ + public String getIp() { + return ip; + } + + /** + * Setter method for property ip. + * + * @param ip value to be assigned to property ip + */ + public void setIp(String ip) { + this.ip = ip; + } + + /** + * Getter method for property port. + * + * @return property value of port + */ + public int getPort() { + return port; + } + + /** + * Setter method for property port. + * + * @param port value to be assigned to property port + */ + public void setPort(int port) { + this.port = port; + } + + /** + * Query publisher by registId + * + * @param registId + * @return + */ + public PublisherRegister queryPubliser(String registId) { + return publisherMap.get(registId); + } + + /** + * Query subscriber by registId + * + * @param registId + * @return + */ + public SubscriberRegister querySubscriber(String registId) { + return subscriberMap.get(registId); + } + + /** The type Mock subscriber register processor. */ + class MockSubscriberRegisterProcessor extends SyncUserProcessor { + + @Override + public Object handleRequest(BizContext bizCtx, SubscriberRegister request) throws Exception { + if ("subscribeAndRefused".equals(request.getDataId())) { + return response(request, true); + } + + Result result = new Result(); + result.setSuccess(true); + String registId = request.getRegistId(); + if (EventTypeConstants.REGISTER.equals(request.getEventType())) { + subscriberMap.put(registId, request); + } else if (EventTypeConstants.UNREGISTER.equals(request.getEventType())) { + subscriberMap.remove(registId); + } + return response(request); } - /** - * Stop. - */ - public void stop() { - rpcServer.stop(); + @Override + public String interest() { + return SubscriberRegister.class.getName(); } - - /** - * Getter method for property ip. - * - * @return property value of ip - */ - public String getIp() { - return ip; - } - - /** - * Setter method for property ip. - * - * @param ip value to be assigned to property ip - */ - public void setIp(String ip) { - this.ip = ip; + } + + /** The type Mock publisher register processor. */ + class MockPublisherRegisterProcessor extends SyncUserProcessor { + + @Override + public Object handleRequest(BizContext bizCtx, PublisherRegister request) throws Exception { + if ("publishAndRefused".equals(request.getDataId())) { + return response(request, true); + } + String registId = request.getRegistId(); + List dataList = request.getDataList(); + LOGGER.info(registId + " " + request.getEventType() + " " + dataList); + if (EventTypeConstants.REGISTER.equals(request.getEventType())) { + publisherMap.put(registId, request); + } else if (EventTypeConstants.UNREGISTER.equals(request.getEventType())) { + publisherMap.remove(registId); + } + return response(request); } - /** - * Getter method for property port. - * - * @return property value of port - */ - public int getPort() { - return port; + @Override + public String interest() { + return PublisherRegister.class.getName(); } - - /** - * Setter method for property port. - * - * @param port value to be assigned to property port - */ - public void setPort(int port) { - this.port = port; - } - - /** - * Query publisher by registId - * - * @param registId - * @return - */ - public PublisherRegister queryPubliser(String registId) { - return publisherMap.get(registId); - } - - /** - * Query subscriber by registId - * - * @param registId - * @return - */ - public SubscriberRegister querySubscriber(String registId) { - return subscriberMap.get(registId); - } - - /** - * The type Mock subscriber register processor. - */ - class MockSubscriberRegisterProcessor extends SyncUserProcessor { - - @Override - public Object handleRequest(BizContext bizCtx, SubscriberRegister request) throws Exception { - if ("subscribeAndRefused".equals(request.getDataId())) { - return response(request, true); - } - - Result result = new Result(); - result.setSuccess(true); - String registId = request.getRegistId(); - if (EventTypeConstants.REGISTER.equals(request.getEventType())) { - subscriberMap.put(registId, request); - } else if (EventTypeConstants.UNREGISTER.equals(request.getEventType())) { - subscriberMap.remove(registId); - } - return response(request); - } - - @Override - public String interest() { - return SubscriberRegister.class.getName(); - } - } - - /** - * The type Mock publisher register processor. - */ - class MockPublisherRegisterProcessor extends SyncUserProcessor { - - @Override - public Object handleRequest(BizContext bizCtx, PublisherRegister request) throws Exception { - if ("publishAndRefused".equals(request.getDataId())) { - return response(request, true); - } - String registId = request.getRegistId(); - List dataList = request.getDataList(); - LOGGER.info(registId + " " + request.getEventType() + " " + dataList); - if (EventTypeConstants.REGISTER.equals(request.getEventType())) { - publisherMap.put(registId, request); - } else if (EventTypeConstants.UNREGISTER.equals(request.getEventType())) { - publisherMap.remove(registId); - } - return response(request); - } - - @Override - public String interest() { - return PublisherRegister.class.getName(); - } - } - - private RegisterResponse response(BaseRegister register) { - return response(register, false); - } - - private RegisterResponse response(BaseRegister register, boolean refused) { - RegisterResponse response = new RegisterResponse(); - response.setSuccess(true); - response.setVersion(register.getVersion()); - response.setRegistId(register.getRegistId()); - response.setRefused(refused); - return response; + } + + private RegisterResponse response(BaseRegister register) { + return response(register, false); + } + + private RegisterResponse response(BaseRegister register, boolean refused) { + RegisterResponse response = new RegisterResponse(); + response.setSuccess(true); + response.setVersion(register.getVersion()); + response.setRegistId(register.getRegistId()); + response.setRefused(refused); + return response; + } + + class MockConfiguratorRegisterProcesor extends SyncUserProcessor { + + @Override + public Object handleRequest(BizContext bizCtx, ConfiguratorRegister request) throws Exception { + if ("subscribeAndRefused".equals(request.getDataId())) { + return response(request, true); + } + + String registId = request.getRegistId(); + LOGGER.info("dataId: {} registId: {}", request.getDataId(), registId); + if (EventTypeConstants.REGISTER.equals(request.getEventType())) { + configuratorMap.put(registId, request); + } else if (EventTypeConstants.UNREGISTER.equals(request.getEventType())) { + configuratorMap.remove(registId); + } + return response(request); } - class MockConfiguratorRegisterProcesor extends SyncUserProcessor { - - @Override - public Object handleRequest(BizContext bizCtx, ConfiguratorRegister request) - throws Exception { - if ("subscribeAndRefused".equals(request.getDataId())) { - return response(request, true); - } - - String registId = request.getRegistId(); - LOGGER.info("dataId: {} registId: {}", request.getDataId(), registId); - if (EventTypeConstants.REGISTER.equals(request.getEventType())) { - configuratorMap.put(registId, request); - } else if (EventTypeConstants.UNREGISTER.equals(request.getEventType())) { - configuratorMap.remove(registId); - } - return response(request); - } - - @Override - public String interest() { - return ConfiguratorRegister.class.getName(); - } + @Override + public String interest() { + return ConfiguratorRegister.class.getName(); } + } } diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/base/BaseTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/base/BaseTest.java index c32d42500..7bc4d846b 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/base/BaseTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/base/BaseTest.java @@ -16,6 +16,11 @@ */ package com.alipay.sofa.registry.client.base; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyMapOf; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.client.MockServer; import com.alipay.sofa.registry.client.api.RegistryClientConfig; import com.alipay.sofa.registry.client.provider.DefaultRegistryClient; @@ -28,13 +33,7 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMapOf; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.when; - /** - * * @author zhuoyu.sjw * @version $Id: BaseTest.java, v 0.1 2018-03-24 14:58 zhuoyu.sjw Exp $$ */ @@ -42,31 +41,34 @@ @PrepareForTest(HttpClientUtils.class) public abstract class BaseTest { - protected DefaultRegistryClient registryClient; + protected DefaultRegistryClient registryClient; - protected String appName = "registry-test"; + protected String appName = "registry-test"; - protected String dataCenter = "HZ"; + protected String dataCenter = "HZ"; - protected String instanceId = "testInstanceId"; + protected String instanceId = "testInstanceId"; - protected MockServer mockServer; + protected MockServer mockServer; - @Before - public void setUp() throws Exception { - mockServer = new MockServer(); - mockServer.start(); + @Before + public void setUp() throws Exception { + mockServer = new MockServer(); + mockServer.start(); - PowerMockito.mockStatic(HttpClientUtils.class); - when( - HttpClientUtils.get(anyString(), anyMapOf(String.class, String.class), - any(RegistryClientConfig.class))).thenReturn( - mockServer.getIp() + ":" + mockServer.getPort()); + PowerMockito.mockStatic(HttpClientUtils.class); + when(HttpClientUtils.get( + anyString(), anyMapOf(String.class, String.class), any(RegistryClientConfig.class))) + .thenReturn(mockServer.getIp() + ":" + mockServer.getPort()); - DefaultRegistryClientConfig config = DefaultRegistryClientConfigBuilder.start() - .setAppName(appName).setDataCenter(dataCenter).setInstanceId(instanceId) - .setRegistryEndpoint(mockServer.getIp()).build(); - registryClient = new DefaultRegistryClient(config); - registryClient.init(); - } + DefaultRegistryClientConfig config = + DefaultRegistryClientConfigBuilder.start() + .setAppName(appName) + .setDataCenter(dataCenter) + .setInstanceId(instanceId) + .setRegistryEndpoint(mockServer.getIp()) + .build(); + registryClient = new DefaultRegistryClient(config); + registryClient.init(); + } } diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/event/DefaultEventBusTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/event/DefaultEventBusTest.java index 794f0751f..676b08334 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/event/DefaultEventBusTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/event/DefaultEventBusTest.java @@ -16,75 +16,74 @@ */ package com.alipay.sofa.registry.client.event; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + import com.alipay.sofa.registry.client.api.RegistryClientConfig; import com.alipay.sofa.registry.client.provider.DefaultRegistryClientConfigBuilder; import org.junit.Before; import org.junit.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - /** - * * @author zhuoyu.sjw * @version $Id: DefaultEventBusTest.java, v 0.1 2018-07-15 22:31 zhuoyu.sjw Exp $$ */ public class DefaultEventBusTest { - private DefaultEventBus eventBus; + private DefaultEventBus eventBus; - @Before - public void setUp() { - RegistryClientConfig config = DefaultRegistryClientConfigBuilder.start() - .setEventBusEnable(true).build(); - eventBus = new DefaultEventBus(config); - } + @Before + public void setUp() { + RegistryClientConfig config = + DefaultRegistryClientConfigBuilder.start().setEventBusEnable(true).build(); + eventBus = new DefaultEventBus(config); + } - @Test - public void isEnable0() { - RegistryClientConfig config = DefaultRegistryClientConfigBuilder.start() - .setEventBusEnable(false).build(); - eventBus = new DefaultEventBus(config); - assertFalse(eventBus.isEnable()); - } + @Test + public void isEnable0() { + RegistryClientConfig config = + DefaultRegistryClientConfigBuilder.start().setEventBusEnable(false).build(); + eventBus = new DefaultEventBus(config); + assertFalse(eventBus.isEnable()); + } - @Test - public void isEnable1() { - RegistryClientConfig config = DefaultRegistryClientConfigBuilder.start() - .setEventBusEnable(true).build(); - eventBus = new DefaultEventBus(config); - assertTrue(eventBus.isEnable()); - } + @Test + public void isEnable1() { + RegistryClientConfig config = + DefaultRegistryClientConfigBuilder.start().setEventBusEnable(true).build(); + eventBus = new DefaultEventBus(config); + assertTrue(eventBus.isEnable()); + } - @Test - public void register() { - TestEventSubscriber testEventSubscriber = new TestEventSubscriber(true); + @Test + public void register() { + TestEventSubscriber testEventSubscriber = new TestEventSubscriber(true); - try { - assertFalse(eventBus.isEnable(TestEvent.class)); - eventBus.register(TestEvent.class, testEventSubscriber); - assertTrue(eventBus.isEnable(TestEvent.class)); - } finally { - eventBus.unRegister(TestEvent.class, testEventSubscriber); - } - assertFalse(eventBus.isEnable(TestEvent.class)); + try { + assertFalse(eventBus.isEnable(TestEvent.class)); + eventBus.register(TestEvent.class, testEventSubscriber); + assertTrue(eventBus.isEnable(TestEvent.class)); + } finally { + eventBus.unRegister(TestEvent.class, testEventSubscriber); } + assertFalse(eventBus.isEnable(TestEvent.class)); + } - @Test - public void post() { - TestEventSubscriber testEventSubscriber = new TestEventSubscriber(true); + @Test + public void post() { + TestEventSubscriber testEventSubscriber = new TestEventSubscriber(true); - try { - assertFalse(eventBus.isEnable(TestEvent.class)); - eventBus.register(TestEvent.class, testEventSubscriber); - assertTrue(eventBus.isEnable(TestEvent.class)); - final String data = "test-data"; - eventBus.post(new TestEvent(data)); - assertEquals(data, testEventSubscriber.getCache()); - } finally { - eventBus.unRegister(TestEvent.class, testEventSubscriber); - } - assertFalse(eventBus.isEnable(TestEvent.class)); + try { + assertFalse(eventBus.isEnable(TestEvent.class)); + eventBus.register(TestEvent.class, testEventSubscriber); + assertTrue(eventBus.isEnable(TestEvent.class)); + final String data = "test-data"; + eventBus.post(new TestEvent(data)); + assertEquals(data, testEventSubscriber.getCache()); + } finally { + eventBus.unRegister(TestEvent.class, testEventSubscriber); } -} \ No newline at end of file + assertFalse(eventBus.isEnable(TestEvent.class)); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/event/LookoutSubscriberTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/event/LookoutSubscriberTest.java index 258125c06..7dbb2296d 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/event/LookoutSubscriberTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/event/LookoutSubscriberTest.java @@ -16,67 +16,66 @@ */ package com.alipay.sofa.registry.client.event; -import com.alipay.sofa.registry.client.api.Configurator; -import com.alipay.sofa.registry.client.api.Subscriber; -import com.alipay.sofa.registry.client.provider.DefaultRegistryClientConfigBuilder; -import org.junit.Test; - import static org.junit.Assert.assertFalse; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import com.alipay.sofa.registry.client.api.Configurator; +import com.alipay.sofa.registry.client.api.Subscriber; +import com.alipay.sofa.registry.client.provider.DefaultRegistryClientConfigBuilder; +import org.junit.Test; + /** - * * @author zhuoyu.sjw * @version $Id: LookoutSubscriberTest.java, v 0.1 2018-07-15 23:04 zhuoyu.sjw Exp $$ */ public class LookoutSubscriberTest { - private LookoutSubscriber lookoutSubscriber; + private LookoutSubscriber lookoutSubscriber; - @Test - public void isSync() { - lookoutSubscriber = new LookoutSubscriber(); - assertFalse(lookoutSubscriber.isSync()); - } + @Test + public void isSync() { + lookoutSubscriber = new LookoutSubscriber(); + assertFalse(lookoutSubscriber.isSync()); + } - @Test - public void onSubscriberProcessEvent() { - lookoutSubscriber = new LookoutSubscriber(); + @Test + public void onSubscriberProcessEvent() { + lookoutSubscriber = new LookoutSubscriber(); - SubscriberProcessEvent event = new SubscriberProcessEvent(); - Subscriber subscriber = mock(Subscriber.class); - event.setSubscriber(subscriber); - event.setConfig(DefaultRegistryClientConfigBuilder.start().setInstanceId("000001").build()); - event.setStart(System.currentTimeMillis()); - event.setEnd(System.currentTimeMillis() + 1); - event.setThrowable(null); + SubscriberProcessEvent event = new SubscriberProcessEvent(); + Subscriber subscriber = mock(Subscriber.class); + event.setSubscriber(subscriber); + event.setConfig(DefaultRegistryClientConfigBuilder.start().setInstanceId("000001").build()); + event.setStart(System.currentTimeMillis()); + event.setEnd(System.currentTimeMillis() + 1); + event.setThrowable(null); - when(subscriber.getDataId()).thenReturn("test-dataId"); + when(subscriber.getDataId()).thenReturn("test-dataId"); - lookoutSubscriber.onEvent(event); + lookoutSubscriber.onEvent(event); - verify(subscriber, times(1)).getDataId(); - } + verify(subscriber, times(1)).getDataId(); + } - @Test - public void onConfiguratorProcessEvent() { - lookoutSubscriber = new LookoutSubscriber(); + @Test + public void onConfiguratorProcessEvent() { + lookoutSubscriber = new LookoutSubscriber(); - ConfiguratorProcessEvent event = new ConfiguratorProcessEvent(); - Configurator configurator = mock(Configurator.class); - event.setConfigurator(configurator); - event.setConfig(DefaultRegistryClientConfigBuilder.start().setInstanceId("000001").build()); - event.setStart(System.currentTimeMillis()); - event.setEnd(System.currentTimeMillis() + 1); - event.setThrowable(null); + ConfiguratorProcessEvent event = new ConfiguratorProcessEvent(); + Configurator configurator = mock(Configurator.class); + event.setConfigurator(configurator); + event.setConfig(DefaultRegistryClientConfigBuilder.start().setInstanceId("000001").build()); + event.setStart(System.currentTimeMillis()); + event.setEnd(System.currentTimeMillis() + 1); + event.setThrowable(null); - when(configurator.getDataId()).thenReturn("test-dataId"); + when(configurator.getDataId()).thenReturn("test-dataId"); - lookoutSubscriber.onEvent(event); + lookoutSubscriber.onEvent(event); - verify(configurator, times(1)).getDataId(); - } -} \ No newline at end of file + verify(configurator, times(1)).getDataId(); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/event/TestEvent.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/event/TestEvent.java index cc1fcf52b..4ae5cf82b 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/event/TestEvent.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/event/TestEvent.java @@ -19,34 +19,32 @@ import com.alipay.sofa.registry.client.api.model.Event; /** - * * @author zhuoyu.sjw * @version $Id: TestEvent.java, v 0.1 2018-07-15 22:38 zhuoyu.sjw Exp $$ */ public class TestEvent implements Event { - private String data; + private String data; - public TestEvent(String data) { - this.data = data; - } + public TestEvent(String data) { + this.data = data; + } - /** - * Getter method for property data. - * - * @return property value of data - */ - public String getData() { - return data; - } + /** + * Getter method for property data. + * + * @return property value of data + */ + public String getData() { + return data; + } - /** - * Setter method for property data. - * - * @param data - * value to be assigned to property data - */ - public void setData(String data) { - this.data = data; - } + /** + * Setter method for property data. + * + * @param data value to be assigned to property data + */ + public void setData(String data) { + this.data = data; + } } diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/event/TestEventSubscriber.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/event/TestEventSubscriber.java index bd80884ca..57b86e1e6 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/event/TestEventSubscriber.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/event/TestEventSubscriber.java @@ -20,38 +20,37 @@ import com.alipay.sofa.registry.client.api.model.Event; /** - * * @author zhuoyu.sjw * @version $Id: TestEventSubscriber.java, v 0.1 2018-07-15 22:39 zhuoyu.sjw Exp $$ */ public class TestEventSubscriber implements EventSubscriber { - private boolean sync; + private boolean sync; - private String cache; + private String cache; - public TestEventSubscriber(boolean sync) { - this.sync = sync; - } + public TestEventSubscriber(boolean sync) { + this.sync = sync; + } - @Override - public boolean isSync() { - return sync; - } - - @Override - public void onEvent(Event event) { - if (event instanceof TestEvent) { - cache = ((TestEvent) event).getData(); - } - } + @Override + public boolean isSync() { + return sync; + } - /** - * Getter method for property cache. - * - * @return property value of cache - */ - public String getCache() { - return cache; + @Override + public void onEvent(Event event) { + if (event instanceof TestEvent) { + cache = ((TestEvent) event).getData(); } + } + + /** + * Getter method for property cache. + * + * @return property value of cache + */ + public String getCache() { + return cache; + } } diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/model/ConfiguratorDataTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/model/ConfiguratorDataTest.java index f96462995..17b80a825 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/model/ConfiguratorDataTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/model/ConfiguratorDataTest.java @@ -20,18 +20,15 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class ConfiguratorDataTest { - @Test - public void testAll() { - ConfiguratorData data = new ConfiguratorData(); - data.setDataBox(new DataBox()); - data.setVersion(1234L); - Assert.assertNotNull(data.getDataBox()); - Assert.assertTrue(1234L == data.getVersion()); - } - -} \ No newline at end of file + @Test + public void testAll() { + ConfiguratorData data = new ConfiguratorData(); + data.setDataBox(new DataBox()); + data.setVersion(1234L); + Assert.assertNotNull(data.getDataBox()); + Assert.assertTrue(1234L == data.getVersion()); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientTest.java index aba3677dc..18e14f8d3 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultRegistryClientTest.java @@ -22,11 +22,6 @@ import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; -import org.junit.After; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alipay.sofa.registry.client.api.ConfigDataObserver; import com.alipay.sofa.registry.client.api.Configurator; import com.alipay.sofa.registry.client.api.Publisher; @@ -42,6 +37,10 @@ import com.alipay.sofa.registry.core.model.PublisherRegister; import com.alipay.sofa.registry.core.model.ScopeEnum; import com.alipay.sofa.registry.core.model.SubscriberRegister; +import org.junit.After; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** * The type Default registry client test. @@ -51,251 +50,243 @@ */ public class DefaultRegistryClientTest extends BaseTest { - /** LOGGER */ - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRegistryClientTest.class); - - private String dataId = "com.alipay.sofa.registry.client.provider.DefaultRegistryClientTest"; - - private String appName = "registry-test"; - - /** - * Teardown. - */ - @After - public void teardown() { - mockServer.stop(); - } - - /** - * Register publisher. - */ - @Test - public void registerPublisher() throws InterruptedException { - PublisherRegistration registration = new PublisherRegistration(dataId); - Publisher publisher = registryClient.register(registration); - assertNotNull(publisher); - assertEquals(dataId, publisher.getDataId()); - - Thread.sleep(1000L); - - RegisterCache registerCache = registryClient.getRegisterCache(); - - Publisher publisherCache = registerCache.getPublisherByRegistId(publisher.getRegistId()); - assertNotNull(publisherCache); - assertTrue(publisher instanceof DefaultPublisher); - // set cache success - assertEquals(publisher.getRegistId(), publisherCache.getRegistId()); - DefaultPublisher defaultPublisher = (DefaultPublisher) publisher; - assertTrue(defaultPublisher.isRegistered()); - - defaultPublisher.republish("republish test"); - - Thread.sleep(2000L); - // register success when republish - assertTrue(defaultPublisher.isRegistered()); - } - - /** - * Register subscriber. - */ - @Test - public void registerSubscriber() throws InterruptedException { - SubscriberDataObserver dataObserver = new SubscriberDataObserver() { - @Override - public void handleData(String dataId, UserData data) { - LOGGER.info("handle data, dataId: {}, data: {}", dataId, data); - } + /** LOGGER */ + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRegistryClientTest.class); + + private String dataId = "com.alipay.sofa.registry.client.provider.DefaultRegistryClientTest"; + + private String appName = "registry-test"; + + /** Teardown. */ + @After + public void teardown() { + mockServer.stop(); + } + + /** Register publisher. */ + @Test + public void registerPublisher() throws InterruptedException { + PublisherRegistration registration = new PublisherRegistration(dataId); + Publisher publisher = registryClient.register(registration); + assertNotNull(publisher); + assertEquals(dataId, publisher.getDataId()); + + Thread.sleep(1000L); + + RegisterCache registerCache = registryClient.getRegisterCache(); + + Publisher publisherCache = registerCache.getPublisherByRegistId(publisher.getRegistId()); + assertNotNull(publisherCache); + assertTrue(publisher instanceof DefaultPublisher); + // set cache success + assertEquals(publisher.getRegistId(), publisherCache.getRegistId()); + DefaultPublisher defaultPublisher = (DefaultPublisher) publisher; + assertTrue(defaultPublisher.isRegistered()); + + defaultPublisher.republish("republish test"); + + Thread.sleep(2000L); + // register success when republish + assertTrue(defaultPublisher.isRegistered()); + } + + /** Register subscriber. */ + @Test + public void registerSubscriber() throws InterruptedException { + SubscriberDataObserver dataObserver = + new SubscriberDataObserver() { + @Override + public void handleData(String dataId, UserData data) { + LOGGER.info("handle data, dataId: {}, data: {}", dataId, data); + } }; - SubscriberRegistration registration = new SubscriberRegistration(dataId, dataObserver); - registration.setScopeEnum(ScopeEnum.dataCenter); - Subscriber subscriber = registryClient.register(registration); - assertNotNull(subscriber); - assertEquals(dataId, subscriber.getDataId()); - - Thread.sleep(2000L); - - RegisterCache registerCache = registryClient.getRegisterCache(); - - Subscriber register = registerCache.getSubscriberByRegistId(subscriber.getRegistId()); - assertNotNull(register); - // set cache success - assertEquals(subscriber.getRegistId(), register.getRegistId()); - // register success - assertTrue(register.isRegistered()); - } - - /** - * Register configurator. - */ - @Test - public void registerConfigurator() throws InterruptedException { - ConfigDataObserver dataObserver = new ConfigDataObserver() { - @Override - public void handleData(String dataId, ConfigData configData) { - LOGGER.info("handle data, dataId: {}, data: {}", dataId, configData); - - } + SubscriberRegistration registration = new SubscriberRegistration(dataId, dataObserver); + registration.setScopeEnum(ScopeEnum.dataCenter); + Subscriber subscriber = registryClient.register(registration); + assertNotNull(subscriber); + assertEquals(dataId, subscriber.getDataId()); + + Thread.sleep(2000L); + + RegisterCache registerCache = registryClient.getRegisterCache(); + + Subscriber register = registerCache.getSubscriberByRegistId(subscriber.getRegistId()); + assertNotNull(register); + // set cache success + assertEquals(subscriber.getRegistId(), register.getRegistId()); + // register success + assertTrue(register.isRegistered()); + } + + /** Register configurator. */ + @Test + public void registerConfigurator() throws InterruptedException { + ConfigDataObserver dataObserver = + new ConfigDataObserver() { + @Override + public void handleData(String dataId, ConfigData configData) { + LOGGER.info("handle data, dataId: {}, data: {}", dataId, configData); + } }; - ConfiguratorRegistration registration = new ConfiguratorRegistration(dataId, dataObserver); - - Configurator configurator = registryClient.register(registration); - assertNotNull(configurator); - assertEquals(dataId, configurator.getDataId()); + ConfiguratorRegistration registration = new ConfiguratorRegistration(dataId, dataObserver); - Thread.sleep(2000L); + Configurator configurator = registryClient.register(registration); + assertNotNull(configurator); + assertEquals(dataId, configurator.getDataId()); - RegisterCache registerCache = registryClient.getRegisterCache(); + Thread.sleep(2000L); - Configurator register = registerCache.getConfiguratorByRegistId(configurator.getRegistId()); - assertNotNull(register); - // set cache success - assertEquals(configurator.getRegistId(), register.getRegistId()); - // register success - assertTrue(register.isRegistered()); - } + RegisterCache registerCache = registryClient.getRegisterCache(); - @Test - public void unregisterSinglePublisherTest() throws InterruptedException { - String dataId = "unregister-test-data-id"; + Configurator register = registerCache.getConfiguratorByRegistId(configurator.getRegistId()); + assertNotNull(register); + // set cache success + assertEquals(configurator.getRegistId(), register.getRegistId()); + // register success + assertTrue(register.isRegistered()); + } - PublisherRegistration publisherRegistration = new PublisherRegistration(dataId); - Publisher publisher = registryClient.register(publisherRegistration); + @Test + public void unregisterSinglePublisherTest() throws InterruptedException { + String dataId = "unregister-test-data-id"; - int unregisterCount = registryClient.unregister(dataId, null, RegistryType.PUBLISHER); - assertEquals(1, unregisterCount); + PublisherRegistration publisherRegistration = new PublisherRegistration(dataId); + Publisher publisher = registryClient.register(publisherRegistration); - Thread.sleep(2000L); + int unregisterCount = registryClient.unregister(dataId, null, RegistryType.PUBLISHER); + assertEquals(1, unregisterCount); - Publisher temp = registryClient.getRegisterCache().getPublisherByRegistId( - publisher.getRegistId()); + Thread.sleep(2000L); - assertNull(temp); - } + Publisher temp = + registryClient.getRegisterCache().getPublisherByRegistId(publisher.getRegistId()); - @Test - public void unregisterSingleSubscriberTest() throws InterruptedException { - String dataId = "unregister-test-data-id"; + assertNull(temp); + } - SubscriberDataObserver dataObserver = mock(SubscriberDataObserver.class); - SubscriberRegistration subscriberRegistration = new SubscriberRegistration(dataId, - dataObserver); + @Test + public void unregisterSingleSubscriberTest() throws InterruptedException { + String dataId = "unregister-test-data-id"; - Subscriber subscriber = registryClient.register(subscriberRegistration); + SubscriberDataObserver dataObserver = mock(SubscriberDataObserver.class); + SubscriberRegistration subscriberRegistration = + new SubscriberRegistration(dataId, dataObserver); - int unregisterCount = registryClient.unregister(dataId, null, RegistryType.SUBSCRIBER); - assertEquals(1, unregisterCount); + Subscriber subscriber = registryClient.register(subscriberRegistration); - Thread.sleep(2000L); + int unregisterCount = registryClient.unregister(dataId, null, RegistryType.SUBSCRIBER); + assertEquals(1, unregisterCount); - Subscriber temp = registryClient.getRegisterCache().getSubscriberByRegistId( - subscriber.getRegistId()); + Thread.sleep(2000L); - assertNull(temp); - } + Subscriber temp = + registryClient.getRegisterCache().getSubscriberByRegistId(subscriber.getRegistId()); - @Test - public void unregisterSingleConfiguratorTest() throws InterruptedException { - String dataId = "unregister-test-data-id"; + assertNull(temp); + } - ConfigDataObserver dataObserver = mock(ConfigDataObserver.class); + @Test + public void unregisterSingleConfiguratorTest() throws InterruptedException { + String dataId = "unregister-test-data-id"; - ConfiguratorRegistration registration = new ConfiguratorRegistration(dataId, dataObserver); + ConfigDataObserver dataObserver = mock(ConfigDataObserver.class); - Configurator configurator = registryClient.register(registration); + ConfiguratorRegistration registration = new ConfiguratorRegistration(dataId, dataObserver); - int unregisterCount = registryClient.unregister(dataId, null, RegistryType.CONFIGURATOR); - assertEquals(1, unregisterCount); + Configurator configurator = registryClient.register(registration); - Thread.sleep(2000L); + int unregisterCount = registryClient.unregister(dataId, null, RegistryType.CONFIGURATOR); + assertEquals(1, unregisterCount); - Subscriber temp = registryClient.getRegisterCache().getSubscriberByRegistId( - configurator.getRegistId()); + Thread.sleep(2000L); - assertNull(temp); - } + Subscriber temp = + registryClient.getRegisterCache().getSubscriberByRegistId(configurator.getRegistId()); - @Test - public void unregisterMultiTest() throws InterruptedException { - String dataId = "unregister-test-data-id"; + assertNull(temp); + } - // 1. register - PublisherRegistration publisherRegistration1 = new PublisherRegistration(dataId); - Publisher publisher1 = registryClient.register(publisherRegistration1); + @Test + public void unregisterMultiTest() throws InterruptedException { + String dataId = "unregister-test-data-id"; - PublisherRegistration publisherRegistration2 = new PublisherRegistration(dataId); - Publisher publisher2 = registryClient.register(publisherRegistration2); + // 1. register + PublisherRegistration publisherRegistration1 = new PublisherRegistration(dataId); + Publisher publisher1 = registryClient.register(publisherRegistration1); - SubscriberDataObserver dataObserver = mock(SubscriberDataObserver.class); - SubscriberRegistration subscriberRegistration1 = new SubscriberRegistration(dataId, - dataObserver); + PublisherRegistration publisherRegistration2 = new PublisherRegistration(dataId); + Publisher publisher2 = registryClient.register(publisherRegistration2); - Subscriber subscriber1 = registryClient.register(subscriberRegistration1); + SubscriberDataObserver dataObserver = mock(SubscriberDataObserver.class); + SubscriberRegistration subscriberRegistration1 = + new SubscriberRegistration(dataId, dataObserver); - SubscriberRegistration subscriberRegistration2 = new SubscriberRegistration(dataId, - dataObserver); + Subscriber subscriber1 = registryClient.register(subscriberRegistration1); - Subscriber subscriber2 = registryClient.register(subscriberRegistration2); + SubscriberRegistration subscriberRegistration2 = + new SubscriberRegistration(dataId, dataObserver); - Thread.sleep(2000L); + Subscriber subscriber2 = registryClient.register(subscriberRegistration2); - // 2. unregister publisher - int unregisterCount = registryClient.unregister(dataId, null, RegistryType.PUBLISHER); - assertEquals(2, unregisterCount); + Thread.sleep(2000L); - Thread.sleep(2000L); + // 2. unregister publisher + int unregisterCount = registryClient.unregister(dataId, null, RegistryType.PUBLISHER); + assertEquals(2, unregisterCount); - // 3. check publisher register cache - RegisterCache registerCache = registryClient.getRegisterCache(); - Publisher tempPub = registerCache.getPublisherByRegistId(publisher1.getRegistId()); - assertNull(tempPub); + Thread.sleep(2000L); - tempPub = registerCache.getPublisherByRegistId(publisher2.getRegistId()); - assertNull(tempPub); + // 3. check publisher register cache + RegisterCache registerCache = registryClient.getRegisterCache(); + Publisher tempPub = registerCache.getPublisherByRegistId(publisher1.getRegistId()); + assertNull(tempPub); - // 4. unregister subscriber - unregisterCount = registryClient.unregister(dataId, null, RegistryType.SUBSCRIBER); - assertEquals(2, unregisterCount); + tempPub = registerCache.getPublisherByRegistId(publisher2.getRegistId()); + assertNull(tempPub); - Thread.sleep(2000L); + // 4. unregister subscriber + unregisterCount = registryClient.unregister(dataId, null, RegistryType.SUBSCRIBER); + assertEquals(2, unregisterCount); - // 5. check subscriber register cache - Subscriber tempSub = registerCache.getSubscriberByRegistId(subscriber1.getRegistId()); - assertNull(tempSub); + Thread.sleep(2000L); - tempSub = registerCache.getSubscriberByRegistId(subscriber2.getRegistId()); - assertNull(tempSub); - } + // 5. check subscriber register cache + Subscriber tempSub = registerCache.getSubscriberByRegistId(subscriber1.getRegistId()); + assertNull(tempSub); - @Test - public void testSetAppNameByRegistration() { - PublisherRegistration publisherRegistration = new PublisherRegistration(dataId); - final String testApp = "test-app"; - publisherRegistration.setAppName(testApp); + tempSub = registerCache.getSubscriberByRegistId(subscriber2.getRegistId()); + assertNull(tempSub); + } - Publisher publisher = registryClient.register(publisherRegistration); - PublisherRegister register = ((DefaultPublisher) publisher).assembly(); + @Test + public void testSetAppNameByRegistration() { + PublisherRegistration publisherRegistration = new PublisherRegistration(dataId); + final String testApp = "test-app"; + publisherRegistration.setAppName(testApp); - assertEquals(testApp, register.getAppName()); + Publisher publisher = registryClient.register(publisherRegistration); + PublisherRegister register = ((DefaultPublisher) publisher).assembly(); - SubscriberRegistration subscriberRegistration = new SubscriberRegistration(dataId, - mock(SubscriberDataObserver.class)); - subscriberRegistration.setAppName(testApp); + assertEquals(testApp, register.getAppName()); - Subscriber subscriber = registryClient.register(subscriberRegistration); - SubscriberRegister subscriberRegister = ((DefaultSubscriber) subscriber).assembly(); + SubscriberRegistration subscriberRegistration = + new SubscriberRegistration(dataId, mock(SubscriberDataObserver.class)); + subscriberRegistration.setAppName(testApp); - assertEquals(testApp, subscriberRegister.getAppName()); - } + Subscriber subscriber = registryClient.register(subscriberRegistration); + SubscriberRegister subscriberRegister = ((DefaultSubscriber) subscriber).assembly(); - @Test - public void testSetAppNameByConfig() { - PublisherRegistration publisherRegistration = new PublisherRegistration(dataId); + assertEquals(testApp, subscriberRegister.getAppName()); + } - Publisher publisher = registryClient.register(publisherRegistration); - PublisherRegister register = ((DefaultPublisher) publisher).assembly(); + @Test + public void testSetAppNameByConfig() { + PublisherRegistration publisherRegistration = new PublisherRegistration(dataId); - assertEquals(appName, register.getAppName()); + Publisher publisher = registryClient.register(publisherRegistration); + PublisherRegister register = ((DefaultPublisher) publisher).assembly(); - } -} \ No newline at end of file + assertEquals(appName, register.getAppName()); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultServerManagerTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultServerManagerTest.java index 298711b27..1e3e0aff1 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultServerManagerTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultServerManagerTest.java @@ -16,28 +16,26 @@ */ package com.alipay.sofa.registry.client.provider; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyMapOf; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.client.api.RegistryClientConfig; import com.alipay.sofa.registry.client.remoting.ServerManager; import com.alipay.sofa.registry.client.remoting.ServerNode; import com.alipay.sofa.registry.client.util.HttpClientUtils; +import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import java.util.List; - -import static org.junit.Assert.assertNotNull; -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyMapOf; -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.when; - /** - * * @author zhuoyu.sjw * @version $Id: DefaultServerManagerTest.java, v 0.1 2018-03-23 14:54 zhuoyu.sjw Exp $$ */ @@ -45,28 +43,28 @@ @PrepareForTest(HttpClientUtils.class) public class DefaultServerManagerTest { - @Test - public void initServerList() throws Exception { - // given - PowerMockito.mockStatic(HttpClientUtils.class); - RegistryClientConfig config = mock(RegistryClientConfig.class); + @Test + public void initServerList() throws Exception { + // given + PowerMockito.mockStatic(HttpClientUtils.class); + RegistryClientConfig config = mock(RegistryClientConfig.class); - // when - when(config.getSyncConfigRetryInterval()).thenReturn(100); - when( - HttpClientUtils.get(anyString(), anyMapOf(String.class, String.class), - any(RegistryClientConfig.class))).thenReturn("127.0.0.1:9600;127.0.0.2:9600"); + // when + when(config.getSyncConfigRetryInterval()).thenReturn(100); + when(HttpClientUtils.get( + anyString(), anyMapOf(String.class, String.class), any(RegistryClientConfig.class))) + .thenReturn("127.0.0.1:9600;127.0.0.2:9600"); - // then - ServerManager serverManager = new DefaultServerManager(config); + // then + ServerManager serverManager = new DefaultServerManager(config); - List serverList = serverManager.getServerList(); + List serverList = serverManager.getServerList(); - assertNotNull(serverList); + assertNotNull(serverList); - Thread.sleep(450); + Thread.sleep(450); - // verify - PowerMockito.verifyStatic(times(4)); - } -} \ No newline at end of file + // verify + PowerMockito.verifyStatic(times(4)); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultSubscriberTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultSubscriberTest.java index 44cc981dd..e6b3a29f9 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultSubscriberTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/DefaultSubscriberTest.java @@ -16,20 +16,19 @@ */ package com.alipay.sofa.registry.client.provider; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + import com.alipay.sofa.registry.client.api.model.UserData; import com.alipay.sofa.registry.client.model.SegmentData; import com.alipay.sofa.registry.core.model.DataBox; -import org.junit.Test; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import org.junit.Test; /** * To test DefaultSubscriber. @@ -39,246 +38,243 @@ */ public class DefaultSubscriberTest { - public final String ZHEJIANG = "Zhejiang"; - public final String HANGZHOU = "Hangzhou"; - public final String NINGBO = "Ningbo"; - public final String WENZHOU = "Wenzhou"; - - public final String JIANGSU = "Jiangsu"; - public final String NANJING = "Nanjing"; + public final String ZHEJIANG = "Zhejiang"; + public final String HANGZHOU = "Hangzhou"; + public final String NINGBO = "Ningbo"; + public final String WENZHOU = "Wenzhou"; - public final String FUJIAN = "Fujian"; - public final String FUZHOU = "Fuzhou"; - public final String XIAMEN = "Xiamen"; + public final String JIANGSU = "Jiangsu"; + public final String NANJING = "Nanjing"; - public final String segmentA = "a"; + public final String FUJIAN = "Fujian"; + public final String FUZHOU = "Fuzhou"; + public final String XIAMEN = "Xiamen"; - public final String segmentB = "b"; + public final String segmentA = "a"; - @Test - public void testPutReceivedData() { + public final String segmentB = "b"; - String localZone = ZHEJIANG; + @Test + public void testPutReceivedData() { - DefaultRegistryClientConfig config = DefaultRegistryClientConfigBuilder.start().build(); - DefaultSubscriber defaultSubscriber = new DefaultSubscriber(null, null, config); + String localZone = ZHEJIANG; - UserData initUserData = defaultSubscriber.peekData(); + DefaultRegistryClientConfig config = DefaultRegistryClientConfigBuilder.start().build(); + DefaultSubscriber defaultSubscriber = new DefaultSubscriber(null, null, config); - assertNull(initUserData.getLocalZone()); - assertTrue(initUserData.getZoneData().isEmpty()); + UserData initUserData = defaultSubscriber.peekData(); - long versionA = 0; - long versionB = 0; + assertNull(initUserData.getLocalZone()); + assertTrue(initUserData.getZoneData().isEmpty()); - // 1. receive data normally - Map> map1 = new HashMap>(); - addToDataBoxMap(map1, ZHEJIANG, HANGZHOU); - SegmentData sd1 = new SegmentData(); - sd1.setSegment(segmentA); - sd1.setVersion(++versionA); - sd1.setData(map1); + long versionA = 0; + long versionB = 0; - defaultSubscriber.putReceivedData(sd1, localZone); - UserData userData1 = defaultSubscriber.peekData(); + // 1. receive data normally + Map> map1 = new HashMap>(); + addToDataBoxMap(map1, ZHEJIANG, HANGZHOU); + SegmentData sd1 = new SegmentData(); + sd1.setSegment(segmentA); + sd1.setVersion(++versionA); + sd1.setData(map1); - Map> expectedMap1 = new HashMap>(); - addToStringMap(expectedMap1, ZHEJIANG, HANGZHOU); + defaultSubscriber.putReceivedData(sd1, localZone); + UserData userData1 = defaultSubscriber.peekData(); - assertEquals(localZone, userData1.getLocalZone()); - assertZoneDataEquals(expectedMap1, userData1.getZoneData()); + Map> expectedMap1 = new HashMap>(); + addToStringMap(expectedMap1, ZHEJIANG, HANGZHOU); - // 2. receive data normally again - Map> map2 = new HashMap>(); - addToDataBoxMap(map2, ZHEJIANG, NINGBO, WENZHOU); - SegmentData sd2 = new SegmentData(); - sd2.setSegment(segmentA); - sd2.setVersion(++versionA); - sd2.setData(map2); + assertEquals(localZone, userData1.getLocalZone()); + assertZoneDataEquals(expectedMap1, userData1.getZoneData()); - defaultSubscriber.putReceivedData(sd2, localZone); - UserData userData2 = defaultSubscriber.peekData(); + // 2. receive data normally again + Map> map2 = new HashMap>(); + addToDataBoxMap(map2, ZHEJIANG, NINGBO, WENZHOU); + SegmentData sd2 = new SegmentData(); + sd2.setSegment(segmentA); + sd2.setVersion(++versionA); + sd2.setData(map2); - Map> expectedMap2 = new HashMap>(); - addToStringMap(expectedMap2, ZHEJIANG, NINGBO, WENZHOU); + defaultSubscriber.putReceivedData(sd2, localZone); + UserData userData2 = defaultSubscriber.peekData(); - assertEquals(localZone, userData2.getLocalZone()); - assertZoneDataEquals(expectedMap2, userData2.getZoneData()); + Map> expectedMap2 = new HashMap>(); + addToStringMap(expectedMap2, ZHEJIANG, NINGBO, WENZHOU); - // 3. illegal version - Map> map3 = new HashMap>(); - addToDataBoxMap(map3, ZHEJIANG, NINGBO); - SegmentData sd3 = new SegmentData(); - sd3.setSegment(segmentA); - sd3.setVersion(versionA); - sd3.setData(map3); + assertEquals(localZone, userData2.getLocalZone()); + assertZoneDataEquals(expectedMap2, userData2.getZoneData()); - defaultSubscriber.putReceivedData(sd3, localZone); - UserData userData3 = defaultSubscriber.peekData(); + // 3. illegal version + Map> map3 = new HashMap>(); + addToDataBoxMap(map3, ZHEJIANG, NINGBO); + SegmentData sd3 = new SegmentData(); + sd3.setSegment(segmentA); + sd3.setVersion(versionA); + sd3.setData(map3); - assertZoneDataEquals(expectedMap2, userData3.getZoneData()); + defaultSubscriber.putReceivedData(sd3, localZone); + UserData userData3 = defaultSubscriber.peekData(); - // 4. from another segment - Map> map4 = new HashMap>(); - addToDataBoxMap(map4, ZHEJIANG, HANGZHOU); - SegmentData sd4 = new SegmentData(); - sd4.setSegment(segmentB); - sd4.setVersion(++versionB); - sd4.setData(map4); + assertZoneDataEquals(expectedMap2, userData3.getZoneData()); - defaultSubscriber.putReceivedData(sd4, localZone); - UserData userData4 = defaultSubscriber.peekData(); + // 4. from another segment + Map> map4 = new HashMap>(); + addToDataBoxMap(map4, ZHEJIANG, HANGZHOU); + SegmentData sd4 = new SegmentData(); + sd4.setSegment(segmentB); + sd4.setVersion(++versionB); + sd4.setData(map4); - Map> expectedMap4 = new HashMap>(); - addToStringMap(expectedMap4, ZHEJIANG, HANGZHOU, NINGBO, WENZHOU); + defaultSubscriber.putReceivedData(sd4, localZone); + UserData userData4 = defaultSubscriber.peekData(); - assertZoneDataEquals(expectedMap4, userData4.getZoneData()); + Map> expectedMap4 = new HashMap>(); + addToStringMap(expectedMap4, ZHEJIANG, HANGZHOU, NINGBO, WENZHOU); - // 5. another segment, another zone - Map> map5 = new HashMap>(); - addToDataBoxMap(map5, JIANGSU, NANJING); - SegmentData sd5 = new SegmentData(); - sd5.setSegment(segmentB); - sd5.setVersion(++versionB); - sd5.setData(map5); + assertZoneDataEquals(expectedMap4, userData4.getZoneData()); - defaultSubscriber.putReceivedData(sd5, localZone); - UserData userData5 = defaultSubscriber.peekData(); + // 5. another segment, another zone + Map> map5 = new HashMap>(); + addToDataBoxMap(map5, JIANGSU, NANJING); + SegmentData sd5 = new SegmentData(); + sd5.setSegment(segmentB); + sd5.setVersion(++versionB); + sd5.setData(map5); - Map> expectedMap5 = new HashMap>(); - addToStringMap(expectedMap5, ZHEJIANG, NINGBO, WENZHOU); - addToStringMap(expectedMap5, JIANGSU, NANJING); + defaultSubscriber.putReceivedData(sd5, localZone); + UserData userData5 = defaultSubscriber.peekData(); - assertZoneDataEquals(expectedMap5, userData5.getZoneData()); + Map> expectedMap5 = new HashMap>(); + addToStringMap(expectedMap5, ZHEJIANG, NINGBO, WENZHOU); + addToStringMap(expectedMap5, JIANGSU, NANJING); - // 6. push empty - Map> map6 = new HashMap>(); - SegmentData sd6 = new SegmentData(); - sd6.setSegment(segmentA); - sd6.setVersion(++versionA); - sd6.setData(map6); + assertZoneDataEquals(expectedMap5, userData5.getZoneData()); - defaultSubscriber.putReceivedData(sd6, localZone); - UserData userData6 = defaultSubscriber.peekData(); + // 6. push empty + Map> map6 = new HashMap>(); + SegmentData sd6 = new SegmentData(); + sd6.setSegment(segmentA); + sd6.setVersion(++versionA); + sd6.setData(map6); - Map> expectedMap6 = new HashMap>(); - addToStringMap(expectedMap6, JIANGSU, NANJING); + defaultSubscriber.putReceivedData(sd6, localZone); + UserData userData6 = defaultSubscriber.peekData(); - assertZoneDataEquals(expectedMap6, userData6.getZoneData()); + Map> expectedMap6 = new HashMap>(); + addToStringMap(expectedMap6, JIANGSU, NANJING); - // 7. different segments without intersection - Map> map7 = new HashMap>(); - addToDataBoxMap(map7, ZHEJIANG, NINGBO, WENZHOU); - addToDataBoxMap(map7, FUJIAN, XIAMEN); + assertZoneDataEquals(expectedMap6, userData6.getZoneData()); - SegmentData sd7 = new SegmentData(); - sd7.setSegment(segmentA); - sd7.setVersion(++versionA); - sd7.setData(map7); + // 7. different segments without intersection + Map> map7 = new HashMap>(); + addToDataBoxMap(map7, ZHEJIANG, NINGBO, WENZHOU); + addToDataBoxMap(map7, FUJIAN, XIAMEN); - defaultSubscriber.putReceivedData(sd7, localZone); - UserData userData7 = defaultSubscriber.peekData(); + SegmentData sd7 = new SegmentData(); + sd7.setSegment(segmentA); + sd7.setVersion(++versionA); + sd7.setData(map7); - Map> expectedMap7 = new HashMap>(); - addToStringMap(expectedMap7, ZHEJIANG, NINGBO, WENZHOU); - addToStringMap(expectedMap7, JIANGSU, NANJING); - addToStringMap(expectedMap7, FUJIAN, XIAMEN); + defaultSubscriber.putReceivedData(sd7, localZone); + UserData userData7 = defaultSubscriber.peekData(); - assertZoneDataEquals(expectedMap7, userData7.getZoneData()); + Map> expectedMap7 = new HashMap>(); + addToStringMap(expectedMap7, ZHEJIANG, NINGBO, WENZHOU); + addToStringMap(expectedMap7, JIANGSU, NANJING); + addToStringMap(expectedMap7, FUJIAN, XIAMEN); - // 8. different segments with intersection - Map> map8 = new HashMap>(); - addToDataBoxMap(map8, ZHEJIANG, HANGZHOU); - addToDataBoxMap(map8, JIANGSU, NANJING); - addToDataBoxMap(map8, FUJIAN, FUZHOU); + assertZoneDataEquals(expectedMap7, userData7.getZoneData()); - SegmentData sd8 = new SegmentData(); - sd8.setSegment(segmentB); - sd8.setVersion(++versionB); - sd8.setData(map8); + // 8. different segments with intersection + Map> map8 = new HashMap>(); + addToDataBoxMap(map8, ZHEJIANG, HANGZHOU); + addToDataBoxMap(map8, JIANGSU, NANJING); + addToDataBoxMap(map8, FUJIAN, FUZHOU); - defaultSubscriber.putReceivedData(sd8, localZone); - UserData userData8 = defaultSubscriber.peekData(); + SegmentData sd8 = new SegmentData(); + sd8.setSegment(segmentB); + sd8.setVersion(++versionB); + sd8.setData(map8); - Map> expectedMap8 = new HashMap>(); - addToStringMap(expectedMap8, ZHEJIANG, HANGZHOU, NINGBO, WENZHOU); - addToStringMap(expectedMap8, JIANGSU, NANJING); - addToStringMap(expectedMap8, FUJIAN, FUZHOU, XIAMEN); + defaultSubscriber.putReceivedData(sd8, localZone); + UserData userData8 = defaultSubscriber.peekData(); - assertZoneDataEquals(expectedMap8, userData8.getZoneData()); + Map> expectedMap8 = new HashMap>(); + addToStringMap(expectedMap8, ZHEJIANG, HANGZHOU, NINGBO, WENZHOU); + addToStringMap(expectedMap8, JIANGSU, NANJING); + addToStringMap(expectedMap8, FUJIAN, FUZHOU, XIAMEN); - // 9. set available segments + assertZoneDataEquals(expectedMap8, userData8.getZoneData()); - List availableSegments9 = new ArrayList(); - availableSegments9.add(segmentB); - defaultSubscriber.setAvailableSegments(availableSegments9); + // 9. set available segments - UserData userData9 = defaultSubscriber.peekData(); + List availableSegments9 = new ArrayList(); + availableSegments9.add(segmentB); + defaultSubscriber.setAvailableSegments(availableSegments9); - Map> expectedMap9 = new HashMap>(); - addToStringMap(expectedMap9, ZHEJIANG, HANGZHOU); - addToStringMap(expectedMap9, JIANGSU, NANJING); - addToStringMap(expectedMap9, FUJIAN, FUZHOU); + UserData userData9 = defaultSubscriber.peekData(); - assertZoneDataEquals(expectedMap9, userData9.getZoneData()); + Map> expectedMap9 = new HashMap>(); + addToStringMap(expectedMap9, ZHEJIANG, HANGZHOU); + addToStringMap(expectedMap9, JIANGSU, NANJING); + addToStringMap(expectedMap9, FUJIAN, FUZHOU); - // 10. add available segments + assertZoneDataEquals(expectedMap9, userData9.getZoneData()); - List availableSegments10 = new ArrayList(); - availableSegments10.add(segmentA); - availableSegments10.add(segmentB); - defaultSubscriber.setAvailableSegments(availableSegments10); + // 10. add available segments - UserData userData10 = defaultSubscriber.peekData(); + List availableSegments10 = new ArrayList(); + availableSegments10.add(segmentA); + availableSegments10.add(segmentB); + defaultSubscriber.setAvailableSegments(availableSegments10); - assertZoneDataEquals(expectedMap8, userData10.getZoneData()); - } + UserData userData10 = defaultSubscriber.peekData(); - private void addToDataBoxMap(Map> map, String key, String... values) { - List list = map.get(key); - if (list == null) { - list = new ArrayList(); - map.put(key, list); - } - for (String value : values) { - DataBox dataBox = new DataBox(); - dataBox.setData(value); - list.add(dataBox); - } + assertZoneDataEquals(expectedMap8, userData10.getZoneData()); + } + private void addToDataBoxMap(Map> map, String key, String... values) { + List list = map.get(key); + if (list == null) { + list = new ArrayList(); + map.put(key, list); } - - private void addToStringMap(Map> map, String key, String... values) { - List list = map.get(key); - if (list == null) { - list = new ArrayList(); - map.put(key, list); - } - for (String value : values) { - list.add(value); - } - + for (String value : values) { + DataBox dataBox = new DataBox(); + dataBox.setData(value); + list.add(dataBox); } + } - private void assertZoneDataEquals(Map> a, Map> b) { - assertEquals(sortAllList(a), sortAllList(b)); + private void addToStringMap(Map> map, String key, String... values) { + List list = map.get(key); + if (list == null) { + list = new ArrayList(); + map.put(key, list); } - - private Map> sortAllList(Map> map) { - if (map == null) { - return null; - } - Map> copyMap = new HashMap>(); - for (Map.Entry> entry : map.entrySet()) { - if (entry.getValue() == null) { - copyMap.put(entry.getKey(), null); - } else { - List copyList = new ArrayList(entry.getValue()); - Collections.sort(copyList); - copyMap.put(entry.getKey(), copyList); - } - } - return copyMap; + for (String value : values) { + list.add(value); } + } + + private void assertZoneDataEquals(Map> a, Map> b) { + assertEquals(sortAllList(a), sortAllList(b)); + } -} \ No newline at end of file + private Map> sortAllList(Map> map) { + if (map == null) { + return null; + } + Map> copyMap = new HashMap>(); + for (Map.Entry> entry : map.entrySet()) { + if (entry.getValue() == null) { + copyMap.put(entry.getKey(), null); + } else { + List copyList = new ArrayList(entry.getValue()); + Collections.sort(copyList); + copyMap.put(entry.getKey(), copyList); + } + } + return copyMap; + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/RegisterOrderTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/RegisterOrderTest.java index 2e23dd731..cab9cdeea 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/RegisterOrderTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/provider/RegisterOrderTest.java @@ -23,13 +23,6 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import java.util.List; - -import org.junit.After; -import org.junit.Test; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alipay.sofa.registry.client.api.Publisher; import com.alipay.sofa.registry.client.api.Subscriber; import com.alipay.sofa.registry.client.api.SubscriberDataObserver; @@ -40,9 +33,13 @@ import com.alipay.sofa.registry.core.model.DataBox; import com.alipay.sofa.registry.core.model.PublisherRegister; import com.alipay.sofa.registry.core.model.SubscriberRegister; +import java.util.List; +import org.junit.After; +import org.junit.Test; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; /** - * * To test all kinds of sequence of register action * * @author hui.shih @@ -50,176 +47,172 @@ */ public class RegisterOrderTest extends BaseTest { - /** LOGGER */ - private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRegistryClientTest.class); + /** LOGGER */ + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultRegistryClientTest.class); - private String dataId = "com.alipay.sofa.registry.client.provider.RegisterOrderTest"; + private String dataId = "com.alipay.sofa.registry.client.provider.RegisterOrderTest"; - /** - * Teardown. - */ - @After - public void teardown() { - mockServer.stop(); - } - - @Test - public void publishFrequently() throws InterruptedException { - - String dataPrefix = "publishFrequently"; + /** Teardown. */ + @After + public void teardown() { + mockServer.stop(); + } - Publisher publisher = registryClient.register(new PublisherRegistration(dataId), - dataPrefix + 0); + @Test + public void publishFrequently() throws InterruptedException { - int republishCount = 100; - for (int i = 1; i <= republishCount; i++) { - publisher.republish(dataPrefix + i); - } + String dataPrefix = "publishFrequently"; - Thread.sleep(1000L); + Publisher publisher = + registryClient.register(new PublisherRegistration(dataId), dataPrefix + 0); - DefaultPublisher defaultPublisher = (DefaultPublisher) publisher; - String registeId = defaultPublisher.getRegistId(); - - // check client status - assertTrue(defaultPublisher.isRegistered()); - assertTrue(defaultPublisher.isEnabled()); - assertEquals(republishCount + 1, defaultPublisher.getPubVersion().intValue()); - - // check server status - List data = mockServer.queryPubliser(registeId).getDataList(); - assertEquals(1, data.size()); - assertEquals(dataPrefix + republishCount, data.get(0).getData()); + int republishCount = 100; + for (int i = 1; i <= republishCount; i++) { + publisher.republish(dataPrefix + i); } - @Test - public void unregisterAndRepublish() throws InterruptedException { + Thread.sleep(1000L); + + DefaultPublisher defaultPublisher = (DefaultPublisher) publisher; + String registeId = defaultPublisher.getRegistId(); - String dataPrefix = "unregisterAndRepublish"; + // check client status + assertTrue(defaultPublisher.isRegistered()); + assertTrue(defaultPublisher.isEnabled()); + assertEquals(republishCount + 1, defaultPublisher.getPubVersion().intValue()); - // step 1 - Publisher publisher = registryClient.register(new PublisherRegistration(dataId), - dataPrefix + 0); - // step 2 - publisher.unregister(); + // check server status + List data = mockServer.queryPubliser(registeId).getDataList(); + assertEquals(1, data.size()); + assertEquals(dataPrefix + republishCount, data.get(0).getData()); + } - try { - // step 3 - publisher.republish(dataPrefix + 1); - fail("No exception thrown."); - } catch (Exception ex) { - // Must throw a RuntimeException - assertTrue(ex instanceof IllegalStateException); - } + @Test + public void unregisterAndRepublish() throws InterruptedException { - Thread.sleep(1000L); + String dataPrefix = "unregisterAndRepublish"; - assertTrue(publisher.isRegistered()); - assertFalse(publisher.isEnabled()); + // step 1 + Publisher publisher = + registryClient.register(new PublisherRegistration(dataId), dataPrefix + 0); + // step 2 + publisher.unregister(); + try { + // step 3 + publisher.republish(dataPrefix + 1); + fail("No exception thrown."); + } catch (Exception ex) { + // Must throw a RuntimeException + assertTrue(ex instanceof IllegalStateException); } - @Test - public void publishAndUnregister() throws InterruptedException { + Thread.sleep(1000L); - String data = "publishAndUnregister"; + assertTrue(publisher.isRegistered()); + assertFalse(publisher.isEnabled()); + } - // step 1 - Publisher publisher = registryClient.register(new PublisherRegistration(dataId), data); + @Test + public void publishAndUnregister() throws InterruptedException { - Thread.sleep(2000L); + String data = "publishAndUnregister"; - String registId = publisher.getRegistId(); - PublisherRegister publisherRegister = mockServer.queryPubliser(registId); + // step 1 + Publisher publisher = registryClient.register(new PublisherRegistration(dataId), data); - assertNotNull(publisherRegister); - assertEquals(data, publisherRegister.getDataList().get(0).getData()); + Thread.sleep(2000L); - // step 2 - publisher.unregister(); + String registId = publisher.getRegistId(); + PublisherRegister publisherRegister = mockServer.queryPubliser(registId); - Thread.sleep(2000L); + assertNotNull(publisherRegister); + assertEquals(data, publisherRegister.getDataList().get(0).getData()); - assertNull(mockServer.queryPubliser(registId)); + // step 2 + publisher.unregister(); - } + Thread.sleep(2000L); + + assertNull(mockServer.queryPubliser(registId)); + } - @Test - public void publishAndRefused() throws InterruptedException { + @Test + public void publishAndRefused() throws InterruptedException { - String data = "publishAndRefused"; + String data = "publishAndRefused"; - // step 1 - Publisher publisher = registryClient.register(new PublisherRegistration(data), data); + // step 1 + Publisher publisher = registryClient.register(new PublisherRegistration(data), data); - Thread.sleep(2000L); + Thread.sleep(2000L); - String registId = publisher.getRegistId(); - PublisherRegister publisherRegister = mockServer.queryPubliser(registId); + String registId = publisher.getRegistId(); + PublisherRegister publisherRegister = mockServer.queryPubliser(registId); - assertNull(publisherRegister); + assertNull(publisherRegister); - // step 2 - try { - publisher.republish(data); - } catch (Exception e) { - assertTrue(e instanceof IllegalStateException); - assertEquals("Publisher is refused by server. Try to check your configuration.", - e.getMessage()); - } + // step 2 + try { + publisher.republish(data); + } catch (Exception e) { + assertTrue(e instanceof IllegalStateException); + assertEquals( + "Publisher is refused by server. Try to check your configuration.", e.getMessage()); } + } - @Test - public void subscribeAndUnregister() throws InterruptedException { + @Test + public void subscribeAndUnregister() throws InterruptedException { - SubscriberDataObserver dataObserver = new SubscriberDataObserver() { - @Override - public void handleData(String dataId, UserData data) { - LOGGER.info("handle data, dataId: {}, data: {}", dataId, data); - } + SubscriberDataObserver dataObserver = + new SubscriberDataObserver() { + @Override + public void handleData(String dataId, UserData data) { + LOGGER.info("handle data, dataId: {}, data: {}", dataId, data); + } }; - // step 1 - Subscriber subscriber = registryClient.register(new SubscriberRegistration(dataId, - dataObserver)); - - Thread.sleep(2000L); + // step 1 + Subscriber subscriber = + registryClient.register(new SubscriberRegistration(dataId, dataObserver)); - String registId = subscriber.getRegistId(); - SubscriberRegister subscriberRegister = mockServer.querySubscriber(registId); - assertNotNull(subscriberRegister); + Thread.sleep(2000L); - // step 2 - subscriber.unregister(); + String registId = subscriber.getRegistId(); + SubscriberRegister subscriberRegister = mockServer.querySubscriber(registId); + assertNotNull(subscriberRegister); - Thread.sleep(2000L); + // step 2 + subscriber.unregister(); - assertNull(mockServer.queryPubliser(registId)); + Thread.sleep(2000L); - } + assertNull(mockServer.queryPubliser(registId)); + } - @Test - public void subscribeAndRefused() throws InterruptedException { + @Test + public void subscribeAndRefused() throws InterruptedException { - SubscriberDataObserver dataObserver = new SubscriberDataObserver() { - @Override - public void handleData(String dataId, UserData data) { - LOGGER.info("handle data, dataId: {}, data: {}", dataId, data); - } + SubscriberDataObserver dataObserver = + new SubscriberDataObserver() { + @Override + public void handleData(String dataId, UserData data) { + LOGGER.info("handle data, dataId: {}, data: {}", dataId, data); + } }; - // step 1 - Subscriber subscriber = registryClient.register(new SubscriberRegistration( - "subscribeAndRefused", dataObserver)); - - Thread.sleep(2000L); + // step 1 + Subscriber subscriber = + registryClient.register(new SubscriberRegistration("subscribeAndRefused", dataObserver)); - String registId = subscriber.getRegistId(); - SubscriberRegister subscriberRegister = mockServer.querySubscriber(registId); - assertNull(subscriberRegister); + Thread.sleep(2000L); - assertTrue(subscriber instanceof AbstractInternalRegister); - assertTrue(((AbstractInternalRegister) subscriber).isRefused()); - } + String registId = subscriber.getRegistId(); + SubscriberRegister subscriberRegister = mockServer.querySubscriber(registId); + assertNull(subscriberRegister); -} \ No newline at end of file + assertTrue(subscriber instanceof AbstractInternalRegister); + assertTrue(((AbstractInternalRegister) subscriber).isRefused()); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/remoting/ReceivedConfigDataProcessorTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/remoting/ReceivedConfigDataProcessorTest.java index 6794e638b..c726098cf 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/remoting/ReceivedConfigDataProcessorTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/remoting/ReceivedConfigDataProcessorTest.java @@ -16,6 +16,10 @@ */ package com.alipay.sofa.registry.client.remoting; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.client.api.Configurator; import com.alipay.sofa.registry.client.provider.DefaultConfigurator; import com.alipay.sofa.registry.client.provider.RegisterCache; @@ -23,59 +27,52 @@ import com.alipay.sofa.registry.core.model.DataBox; import com.alipay.sofa.registry.core.model.ReceivedConfigData; import com.alipay.sofa.registry.core.model.Result; +import java.util.Arrays; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import java.util.Arrays; - -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @author GengZhang - */ +/** @author GengZhang */ public class ReceivedConfigDataProcessorTest { - private static ReceivedConfigDataProcessor processor; + private static ReceivedConfigDataProcessor processor; - @BeforeClass - public static void init() { - RegisterCache registerCache = mock(RegisterCache.class); - ObserverHandler handler = mock(ObserverHandler.class); - Configurator configurator2 = mock(Configurator.class); - when(registerCache.getConfiguratorByRegistId("11")).thenReturn(null); - when(registerCache.getConfiguratorByRegistId("22")).thenReturn(configurator2); - DefaultConfigurator configurator3 = mock(DefaultConfigurator.class); - when(registerCache.getConfiguratorByRegistId("33")).thenReturn(configurator3); - doThrow(new RuntimeException()).when(handler).notify(configurator3); + @BeforeClass + public static void init() { + RegisterCache registerCache = mock(RegisterCache.class); + ObserverHandler handler = mock(ObserverHandler.class); + Configurator configurator2 = mock(Configurator.class); + when(registerCache.getConfiguratorByRegistId("11")).thenReturn(null); + when(registerCache.getConfiguratorByRegistId("22")).thenReturn(configurator2); + DefaultConfigurator configurator3 = mock(DefaultConfigurator.class); + when(registerCache.getConfiguratorByRegistId("33")).thenReturn(configurator3); + doThrow(new RuntimeException()).when(handler).notify(configurator3); - processor = new ReceivedConfigDataProcessor(registerCache, handler); - } + processor = new ReceivedConfigDataProcessor(registerCache, handler); + } - @Test - public void handleRequest() { - Result result = (Result) processor.handleRequest(null, null); - Assert.assertTrue(result.isSuccess()); - Assert.assertNull(result.getMessage()); + @Test + public void handleRequest() { + Result result = (Result) processor.handleRequest(null, null); + Assert.assertTrue(result.isSuccess()); + Assert.assertNull(result.getMessage()); - ReceivedConfigData request = new ReceivedConfigData(); - request.setDataBox(new DataBox()); - request.setVersion(1234L); - request.setConfiguratorRegistIds(null); - result = (Result) processor.handleRequest(null, request); - Assert.assertFalse(result.isSuccess()); - Assert.assertEquals("", result.getMessage()); + ReceivedConfigData request = new ReceivedConfigData(); + request.setDataBox(new DataBox()); + request.setVersion(1234L); + request.setConfiguratorRegistIds(null); + result = (Result) processor.handleRequest(null, request); + Assert.assertFalse(result.isSuccess()); + Assert.assertEquals("", result.getMessage()); - request.setConfiguratorRegistIds(Arrays.asList("11", "22", "33")); - result = (Result) processor.handleRequest(null, request); - Assert.assertTrue(result.isSuccess()); - Assert.assertNull(result.getMessage()); - } + request.setConfiguratorRegistIds(Arrays.asList("11", "22", "33")); + result = (Result) processor.handleRequest(null, request); + Assert.assertTrue(result.isSuccess()); + Assert.assertNull(result.getMessage()); + } - @Test - public void interest() { - Assert.assertEquals(ReceivedConfigData.class.getName(), processor.interest()); - } -} \ No newline at end of file + @Test + public void interest() { + Assert.assertEquals(ReceivedConfigData.class.getName(), processor.interest()); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/remoting/ReceivedDataProcessorTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/remoting/ReceivedDataProcessorTest.java index cbdd22ffa..3fa2fa1b5 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/remoting/ReceivedDataProcessorTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/remoting/ReceivedDataProcessorTest.java @@ -16,6 +16,10 @@ */ package com.alipay.sofa.registry.client.remoting; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.client.api.Subscriber; import com.alipay.sofa.registry.client.provider.DefaultSubscriber; import com.alipay.sofa.registry.client.provider.RegisterCache; @@ -23,69 +27,62 @@ import com.alipay.sofa.registry.core.model.DataBox; import com.alipay.sofa.registry.core.model.ReceivedData; import com.alipay.sofa.registry.core.model.Result; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - import java.util.Arrays; import java.util.HashMap; import java.util.List; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @author GengZhang - */ +/** @author GengZhang */ public class ReceivedDataProcessorTest { - private static ReceivedDataProcessor processor; + private static ReceivedDataProcessor processor; - @BeforeClass - public static void init() { - RegisterCache registerCache = mock(RegisterCache.class); - ObserverHandler handler = mock(ObserverHandler.class); - Subscriber configurator2 = mock(Subscriber.class); - when(registerCache.getSubscriberByRegistId("11")).thenReturn(null); - when(registerCache.getSubscriberByRegistId("22")).thenReturn(configurator2); - DefaultSubscriber configurator3 = mock(DefaultSubscriber.class); - when(registerCache.getSubscriberByRegistId("33")).thenReturn(configurator3); - doThrow(new RuntimeException()).when(handler).notify(configurator3); + @BeforeClass + public static void init() { + RegisterCache registerCache = mock(RegisterCache.class); + ObserverHandler handler = mock(ObserverHandler.class); + Subscriber configurator2 = mock(Subscriber.class); + when(registerCache.getSubscriberByRegistId("11")).thenReturn(null); + when(registerCache.getSubscriberByRegistId("22")).thenReturn(configurator2); + DefaultSubscriber configurator3 = mock(DefaultSubscriber.class); + when(registerCache.getSubscriberByRegistId("33")).thenReturn(configurator3); + doThrow(new RuntimeException()).when(handler).notify(configurator3); - processor = new ReceivedDataProcessor(registerCache, handler); - } + processor = new ReceivedDataProcessor(registerCache, handler); + } - @Test - public void handleRequest() { - Result result = (Result) processor.handleRequest(null, null); - Assert.assertTrue(result.isSuccess()); - Assert.assertNull(result.getMessage()); + @Test + public void handleRequest() { + Result result = (Result) processor.handleRequest(null, null); + Assert.assertTrue(result.isSuccess()); + Assert.assertNull(result.getMessage()); - ReceivedData request = new ReceivedData(); - result = (Result) processor.handleRequest(null, request); - Assert.assertTrue(result.isSuccess()); - Assert.assertNull(result.getMessage()); + ReceivedData request = new ReceivedData(); + result = (Result) processor.handleRequest(null, request); + Assert.assertTrue(result.isSuccess()); + Assert.assertNull(result.getMessage()); - request = new ReceivedData(); - request.setSubscriberRegistIds(null); - request.setData(new HashMap>()); - request.setVersion(1234L); - request.setSegment("seg1"); - request.setLocalZone("local"); + request = new ReceivedData(); + request.setSubscriberRegistIds(null); + request.setData(new HashMap>()); + request.setVersion(1234L); + request.setSegment("seg1"); + request.setLocalZone("local"); - result = (Result) processor.handleRequest(null, request); - Assert.assertFalse(result.isSuccess()); - Assert.assertEquals("", result.getMessage()); + result = (Result) processor.handleRequest(null, request); + Assert.assertFalse(result.isSuccess()); + Assert.assertEquals("", result.getMessage()); - request.setSubscriberRegistIds(Arrays.asList("11", "22", "33")); - result = (Result) processor.handleRequest(null, request); - Assert.assertTrue(result.isSuccess()); - Assert.assertNull(result.getMessage()); - } + request.setSubscriberRegistIds(Arrays.asList("11", "22", "33")); + result = (Result) processor.handleRequest(null, request); + Assert.assertTrue(result.isSuccess()); + Assert.assertNull(result.getMessage()); + } - @Test - public void interest() { - Assert.assertEquals(ReceivedData.class.getName(), processor.interest()); - } -} \ No newline at end of file + @Test + public void interest() { + Assert.assertEquals(ReceivedData.class.getName(), processor.interest()); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/task/SyncConfigThreadTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/task/SyncConfigThreadTest.java index 2ecafa770..be8def592 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/task/SyncConfigThreadTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/task/SyncConfigThreadTest.java @@ -16,6 +16,15 @@ */ package com.alipay.sofa.registry.client.task; +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyListOf; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Matchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import com.alipay.remoting.exception.RemotingException; import com.alipay.sofa.registry.client.api.RegistryClientConfig; import com.alipay.sofa.registry.client.api.Subscriber; @@ -24,70 +33,62 @@ import com.alipay.sofa.registry.client.provider.RegisterCache; import com.alipay.sofa.registry.client.remoting.Client; import com.alipay.sofa.registry.core.model.SyncConfigResponse; -import org.junit.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.List; - -import static org.mockito.Matchers.any; -import static org.mockito.Matchers.anyListOf; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; +import org.junit.Test; /** - * * @author zhuoyu.sjw * @version $Id: SyncConfigThreadTest.java, v 0.1 2018-03-15 14:33 zhuoyu.sjw Exp $$ */ public class SyncConfigThreadTest { - @Test - public void syncConfigTest() throws RemotingException, InterruptedException { + @Test + public void syncConfigTest() throws RemotingException, InterruptedException { - // mock - RegistryClientConfig config = DefaultRegistryClientConfigBuilder.start() - .setDataCenter("test-data-center").setZone("test-zone") - .setSyncConfigRetryInterval(1000).build(); + // mock + RegistryClientConfig config = + DefaultRegistryClientConfigBuilder.start() + .setDataCenter("test-data-center") + .setZone("test-zone") + .setSyncConfigRetryInterval(1000) + .build(); - Client client = mock(Client.class); - RegisterCache registerCache = mock(RegisterCache.class); - ObserverHandler observerHandler = mock(ObserverHandler.class); - DefaultSubscriber subscriber = mock(DefaultSubscriber.class); + Client client = mock(Client.class); + RegisterCache registerCache = mock(RegisterCache.class); + ObserverHandler observerHandler = mock(ObserverHandler.class); + DefaultSubscriber subscriber = mock(DefaultSubscriber.class); - // when - when(client.isConnected()).thenReturn(true); + // when + when(client.isConnected()).thenReturn(true); - SyncConfigResponse response = new SyncConfigResponse(); - response.setSuccess(true); - response.setAvailableSegments(Arrays.asList("segment1", "segment2")); - response.setRetryInterval(3000000); - when(client.invokeSync(anyObject())).thenReturn(response); + SyncConfigResponse response = new SyncConfigResponse(); + response.setSuccess(true); + response.setAvailableSegments(Arrays.asList("segment1", "segment2")); + response.setRetryInterval(3000000); + when(client.invokeSync(anyObject())).thenReturn(response); - List subscribers = new ArrayList(); - subscribers.add(subscriber); - when(registerCache.getAllSubscribers()).thenReturn(subscribers); + List subscribers = new ArrayList(); + subscribers.add(subscriber); + when(registerCache.getAllSubscribers()).thenReturn(subscribers); - when(subscriber.getAvailableSegments()).thenReturn(new ArrayList()); - when(subscriber.isInited()).thenReturn(true); + when(subscriber.getAvailableSegments()).thenReturn(new ArrayList()); + when(subscriber.isInited()).thenReturn(true); - // do - SyncConfigThread configThread = new SyncConfigThread(client, registerCache, config, - observerHandler); - configThread.start(); + // do + SyncConfigThread configThread = + new SyncConfigThread(client, registerCache, config, observerHandler); + configThread.start(); - Thread.sleep(2000L); + Thread.sleep(2000L); - // verify - verify(client, times(1)).isConnected(); - verify(client, times(1)).invokeSync(any()); + // verify + verify(client, times(1)).isConnected(); + verify(client, times(1)).invokeSync(any()); - verify(subscriber, times(1)).setAvailableSegments(anyListOf(String.class)); + verify(subscriber, times(1)).setAvailableSegments(anyListOf(String.class)); - verify(observerHandler, times(1)).notify(eq(subscriber)); - } -} \ No newline at end of file + verify(observerHandler, times(1)).notify(eq(subscriber)); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/task/TaskEventTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/task/TaskEventTest.java index e6ad7b310..72a0fcd50 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/task/TaskEventTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/task/TaskEventTest.java @@ -16,93 +16,91 @@ */ package com.alipay.sofa.registry.client.task; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.client.api.Register; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; -import static org.mockito.Mockito.when; - -/** - * @author GengZhang - */ +/** @author GengZhang */ public class TaskEventTest { - @Test - public void delayTime() { - TaskEvent event1 = new TaskEvent(null); - Assert.assertTrue(event1.delayTime() <= 200); - event1.incSendCount(); - Assert.assertTrue(event1.delayTime() <= 400); - event1.incSendCount(); - Assert.assertTrue(event1.delayTime() <= 600); - event1.incSendCount(); - Assert.assertTrue(event1.delayTime() <= 800); - event1.incSendCount(); - Assert.assertTrue(event1.delayTime() <= 1000); - event1.incSendCount(); - Assert.assertTrue(event1.delayTime() <= 1000); - } + @Test + public void delayTime() { + TaskEvent event1 = new TaskEvent(null); + Assert.assertTrue(event1.delayTime() <= 200); + event1.incSendCount(); + Assert.assertTrue(event1.delayTime() <= 400); + event1.incSendCount(); + Assert.assertTrue(event1.delayTime() <= 600); + event1.incSendCount(); + Assert.assertTrue(event1.delayTime() <= 800); + event1.incSendCount(); + Assert.assertTrue(event1.delayTime() <= 1000); + event1.incSendCount(); + Assert.assertTrue(event1.delayTime() <= 1000); + } - @Test - public void testCompare() { - TaskEvent event1 = new TaskEvent(null); - TaskEvent event2 = new TaskEvent(null); - Assert.assertEquals(0, event1.compareTo(event2)); + @Test + public void testCompare() { + TaskEvent event1 = new TaskEvent(null); + TaskEvent event2 = new TaskEvent(null); + Assert.assertEquals(0, event1.compareTo(event2)); - event1.incSendCount(); - Assert.assertEquals(1, event1.compareTo(event2)); - Assert.assertEquals(-1, event2.compareTo(event1)); - event2.incSendCount(); + event1.incSendCount(); + Assert.assertEquals(1, event1.compareTo(event2)); + Assert.assertEquals(-1, event2.compareTo(event1)); + event2.incSendCount(); - Register register = Mockito.mock(Register.class); - TaskEvent event3 = new TaskEvent(register); - TaskEvent event4 = new TaskEvent(register); - TaskEvent event5 = new TaskEvent(null); - Assert.assertEquals(1, event4.compareTo(event5)); - Assert.assertEquals(-1, event5.compareTo(event3)); + Register register = Mockito.mock(Register.class); + TaskEvent event3 = new TaskEvent(register); + TaskEvent event4 = new TaskEvent(register); + TaskEvent event5 = new TaskEvent(null); + Assert.assertEquals(1, event4.compareTo(event5)); + Assert.assertEquals(-1, event5.compareTo(event3)); - Register register6 = Mockito.mock(Register.class); - when(register6.getTimestamp()).thenReturn(123L); - Register register7 = Mockito.mock(Register.class); - when(register7.getTimestamp()).thenReturn(234L); - TaskEvent event6 = new TaskEvent(register6); - TaskEvent event7 = new TaskEvent(register7); - TaskEvent event8 = new TaskEvent(register7); - Assert.assertEquals(1, event7.compareTo(event6)); - Assert.assertEquals(-1, event6.compareTo(event7)); - Assert.assertEquals(0, event8.compareTo(event7)); - } + Register register6 = Mockito.mock(Register.class); + when(register6.getTimestamp()).thenReturn(123L); + Register register7 = Mockito.mock(Register.class); + when(register7.getTimestamp()).thenReturn(234L); + TaskEvent event6 = new TaskEvent(register6); + TaskEvent event7 = new TaskEvent(register7); + TaskEvent event8 = new TaskEvent(register7); + Assert.assertEquals(1, event7.compareTo(event6)); + Assert.assertEquals(-1, event6.compareTo(event7)); + Assert.assertEquals(0, event8.compareTo(event7)); + } - @Test - public void testEquals() { - TaskEvent event1 = new TaskEvent(null); - TaskEvent event2 = new TaskEvent(null); + @Test + public void testEquals() { + TaskEvent event1 = new TaskEvent(null); + TaskEvent event2 = new TaskEvent(null); - Assert.assertTrue(event1.equals(event1)); - Assert.assertFalse(event1.equals("xxxx")); - Assert.assertTrue(event1.equals(event2)); + Assert.assertTrue(event1.equals(event1)); + Assert.assertFalse(event1.equals("xxxx")); + Assert.assertTrue(event1.equals(event2)); - event1.incSendCount(); - Assert.assertFalse(event1.equals(event2)); - event2.incSendCount(); + event1.incSendCount(); + Assert.assertFalse(event1.equals(event2)); + event2.incSendCount(); - event1.setTriggerTime(123); - Assert.assertFalse(event1.equals(event2)); - event2.setTriggerTime(123); + event1.setTriggerTime(123); + Assert.assertFalse(event1.equals(event2)); + event2.setTriggerTime(123); - Register register = Mockito.mock(Register.class); - TaskEvent event3 = new TaskEvent(register); - TaskEvent event4 = new TaskEvent(register); - Assert.assertTrue(event3.equals(event4)); - } + Register register = Mockito.mock(Register.class); + TaskEvent event3 = new TaskEvent(register); + TaskEvent event4 = new TaskEvent(register); + Assert.assertTrue(event3.equals(event4)); + } - @Test - public void testHashCode() { - TaskEvent event1 = new TaskEvent(null); - TaskEvent event2 = new TaskEvent(null); - Assert.assertEquals(event1.hashCode(), event2.hashCode()); - event1.setTriggerTime(1234); - Assert.assertNotEquals(event1.hashCode(), event2.hashCode()); - } -} \ No newline at end of file + @Test + public void testHashCode() { + TaskEvent event1 = new TaskEvent(null); + TaskEvent event2 = new TaskEvent(null); + Assert.assertEquals(event1.hashCode(), event2.hashCode()); + event1.setTriggerTime(1234); + Assert.assertNotEquals(event1.hashCode(), event2.hashCode()); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/util/CommonUtilsTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/util/CommonUtilsTest.java index e66d4e8e2..1ac940e9e 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/util/CommonUtilsTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/util/CommonUtilsTest.java @@ -16,20 +16,17 @@ */ package com.alipay.sofa.registry.client.util; +import java.util.Collections; import org.junit.Assert; import org.junit.Test; -import java.util.Collections; - -/** - * @author GengZhang - */ +/** @author GengZhang */ public class CommonUtilsTest { - @Test - public void isNotEmpty() { - Assert.assertTrue(CommonUtils.isNotEmpty(Collections.singletonList("xxx"))); - Assert.assertFalse(CommonUtils.isNotEmpty(null)); - Assert.assertFalse(CommonUtils.isNotEmpty(Collections.emptyList())); - } -} \ No newline at end of file + @Test + public void isNotEmpty() { + Assert.assertTrue(CommonUtils.isNotEmpty(Collections.singletonList("xxx"))); + Assert.assertFalse(CommonUtils.isNotEmpty(null)); + Assert.assertFalse(CommonUtils.isNotEmpty(Collections.emptyList())); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/util/HttpClientUtilsTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/util/HttpClientUtilsTest.java index b45da2ed7..bfa19631a 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/util/HttpClientUtilsTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/util/HttpClientUtilsTest.java @@ -21,86 +21,83 @@ import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; - import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Map; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class HttpClientUtilsTest { - private static HttpServer httpServer; + private static HttpServer httpServer; - @BeforeClass - public static void start() throws IOException { - httpServer = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(5678), 0); - httpServer.createContext("/xxx", new MockHandler()); - httpServer.createContext("/yyy", new ErrorHandler()); - httpServer.setExecutor(null); - httpServer.start(); - } + @BeforeClass + public static void start() throws IOException { + httpServer = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(5678), 0); + httpServer.createContext("/xxx", new MockHandler()); + httpServer.createContext("/yyy", new ErrorHandler()); + httpServer.setExecutor(null); + httpServer.start(); + } - @AfterClass - public static void stop() { - httpServer.stop(1); - } + @AfterClass + public static void stop() { + httpServer.stop(1); + } - @Test - public void testGet() { - String url = "http://127.0.0.1:56789/xxx"; - Map map = new HashMap(); - map.put("x", "1"); - map.put("y", "2"); - RegistryClientConfig clientConfig = new DefaultRegistryClientConfigBuilder().build(); - try { - // wrong url - HttpClientUtils.get(url, map, clientConfig); - Assert.fail(); - } catch (Exception e) { - } + @Test + public void testGet() { + String url = "http://127.0.0.1:56789/xxx"; + Map map = new HashMap(); + map.put("x", "1"); + map.put("y", "2"); + RegistryClientConfig clientConfig = new DefaultRegistryClientConfigBuilder().build(); + try { + // wrong url + HttpClientUtils.get(url, map, clientConfig); + Assert.fail(); + } catch (Exception e) { + } - url = "http://127.0.0.1:5678/xxx"; - try { - HttpClientUtils.get(url, map, clientConfig); - } catch (Exception e) { - Assert.fail(e.getMessage()); - } + url = "http://127.0.0.1:5678/xxx"; + try { + HttpClientUtils.get(url, map, clientConfig); + } catch (Exception e) { + Assert.fail(e.getMessage()); + } - url = "http://127.0.0.1:5678/yyy"; - try { - Assert.assertNull(HttpClientUtils.get(url, map, clientConfig)); - } catch (Exception e) { - Assert.fail(e.getMessage()); - } + url = "http://127.0.0.1:5678/yyy"; + try { + Assert.assertNull(HttpClientUtils.get(url, map, clientConfig)); + } catch (Exception e) { + Assert.fail(e.getMessage()); } + } - static class MockHandler implements HttpHandler { - @Override - public void handle(HttpExchange exchange) throws IOException { - String response = "hello world"; - exchange.sendResponseHeaders(200, response.getBytes().length); - OutputStream os = exchange.getResponseBody(); - os.write(response.getBytes()); - os.close(); - } + static class MockHandler implements HttpHandler { + @Override + public void handle(HttpExchange exchange) throws IOException { + String response = "hello world"; + exchange.sendResponseHeaders(200, response.getBytes().length); + OutputStream os = exchange.getResponseBody(); + os.write(response.getBytes()); + os.close(); } + } - static class ErrorHandler implements HttpHandler { - @Override - public void handle(HttpExchange exchange) throws IOException { - String response = "ServerDown"; - exchange.sendResponseHeaders(500, response.getBytes().length); - OutputStream os = exchange.getResponseBody(); - os.write(response.getBytes()); - os.close(); - } + static class ErrorHandler implements HttpHandler { + @Override + public void handle(HttpExchange exchange) throws IOException { + String response = "ServerDown"; + exchange.sendResponseHeaders(500, response.getBytes().length); + OutputStream os = exchange.getResponseBody(); + os.write(response.getBytes()); + os.close(); } -} \ No newline at end of file + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/util/ServerNodeParserTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/util/ServerNodeParserTest.java index 5fdb579f1..09976849c 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/util/ServerNodeParserTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/util/ServerNodeParserTest.java @@ -20,87 +20,84 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class ServerNodeParserTest { - @Test - public void parse() { - boolean error = false; - try { - ServerNodeParser.parse(null); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - error = true; - } - Assert.assertTrue(error); - - error = false; - try { - ServerNodeParser.parse("127.0.0.1:"); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - error = true; - } - Assert.assertTrue(error); + @Test + public void parse() { + boolean error = false; + try { + ServerNodeParser.parse(null); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalArgumentException); + error = true; + } + Assert.assertTrue(error); - error = false; - try { - ServerNodeParser.parse("127.0.0.1"); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - error = true; - } - Assert.assertTrue(error); + error = false; + try { + ServerNodeParser.parse("127.0.0.1:"); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalArgumentException); + error = true; + } + Assert.assertTrue(error); - error = false; - try { - ServerNodeParser.parse("127.0.0.1:12345?"); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - error = true; - } - Assert.assertTrue(error); + error = false; + try { + ServerNodeParser.parse("127.0.0.1"); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalArgumentException); + error = true; + } + Assert.assertTrue(error); - error = false; - try { - ServerNodeParser.parse("127.0.0.1:12345?x"); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - error = true; - } - Assert.assertTrue(error); + error = false; + try { + ServerNodeParser.parse("127.0.0.1:12345?"); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalArgumentException); + error = true; + } + Assert.assertTrue(error); - error = false; - try { - ServerNodeParser.parse("127.0.0.1:12345?x="); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - error = true; - } - Assert.assertTrue(error); + error = false; + try { + ServerNodeParser.parse("127.0.0.1:12345?x"); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalArgumentException); + error = true; + } + Assert.assertTrue(error); - error = false; - try { - ServerNodeParser.parse("127.0.0.1:12345?x=1&"); - } catch (Exception e) { - Assert.assertTrue(e instanceof IllegalArgumentException); - error = true; - } - Assert.assertTrue(error); + error = false; + try { + ServerNodeParser.parse("127.0.0.1:12345?x="); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalArgumentException); + error = true; + } + Assert.assertTrue(error); - error = false; - String url = "127.0.0.2:12345"; - ServerNode node = ServerNodeParser.parse(url); + error = false; + try { + ServerNodeParser.parse("127.0.0.1:12345?x=1&"); + } catch (Exception e) { + Assert.assertTrue(e instanceof IllegalArgumentException); + error = true; + } + Assert.assertTrue(error); - Assert.assertEquals("127.0.0.2", node.getHost()); - Assert.assertEquals(12345, node.getPort()); + error = false; + String url = "127.0.0.2:12345"; + ServerNode node = ServerNodeParser.parse(url); - url = "127.0.0.3:23456?x=1&y=2&z=3"; - node = ServerNodeParser.parse(url); - Assert.assertEquals("127.0.0.3", node.getHost()); - Assert.assertEquals(23456, node.getPort()); + Assert.assertEquals("127.0.0.2", node.getHost()); + Assert.assertEquals(12345, node.getPort()); - } -} \ No newline at end of file + url = "127.0.0.3:23456?x=1&y=2&z=3"; + node = ServerNodeParser.parse(url); + Assert.assertEquals("127.0.0.3", node.getHost()); + Assert.assertEquals(23456, node.getPort()); + } +} diff --git a/client/impl/src/test/java/com/alipay/sofa/registry/client/util/StringUtilsTest.java b/client/impl/src/test/java/com/alipay/sofa/registry/client/util/StringUtilsTest.java index f60ca729b..f77dc8413 100644 --- a/client/impl/src/test/java/com/alipay/sofa/registry/client/util/StringUtilsTest.java +++ b/client/impl/src/test/java/com/alipay/sofa/registry/client/util/StringUtilsTest.java @@ -19,71 +19,67 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class StringUtilsTest { - @Test - public void isEmpty() { - Assert.assertTrue(StringUtils.isEmpty(null)); - Assert.assertTrue(StringUtils.isEmpty("")); - Assert.assertFalse(StringUtils.isEmpty(" ")); - } + @Test + public void isEmpty() { + Assert.assertTrue(StringUtils.isEmpty(null)); + Assert.assertTrue(StringUtils.isEmpty("")); + Assert.assertFalse(StringUtils.isEmpty(" ")); + } - @Test - public void isNotEmpty() { - Assert.assertFalse(StringUtils.isNotEmpty(null)); - Assert.assertFalse(StringUtils.isNotEmpty("")); - Assert.assertTrue(StringUtils.isNotEmpty(" ")); - } + @Test + public void isNotEmpty() { + Assert.assertFalse(StringUtils.isNotEmpty(null)); + Assert.assertFalse(StringUtils.isNotEmpty("")); + Assert.assertTrue(StringUtils.isNotEmpty(" ")); + } - @Test - public void isBlank() { - Assert.assertTrue(StringUtils.isBlank(null)); - Assert.assertTrue(StringUtils.isBlank("")); - Assert.assertTrue(StringUtils.isBlank(" ")); - Assert.assertFalse(StringUtils.isBlank(" 1")); - } + @Test + public void isBlank() { + Assert.assertTrue(StringUtils.isBlank(null)); + Assert.assertTrue(StringUtils.isBlank("")); + Assert.assertTrue(StringUtils.isBlank(" ")); + Assert.assertFalse(StringUtils.isBlank(" 1")); + } - @Test - public void isNotBlank() { - Assert.assertFalse(StringUtils.isNotBlank(null)); - Assert.assertFalse(StringUtils.isNotBlank("")); - Assert.assertFalse(StringUtils.isNotBlank(" ")); - Assert.assertTrue(StringUtils.isNotBlank(" 1")); - } + @Test + public void isNotBlank() { + Assert.assertFalse(StringUtils.isNotBlank(null)); + Assert.assertFalse(StringUtils.isNotBlank("")); + Assert.assertFalse(StringUtils.isNotBlank(" ")); + Assert.assertTrue(StringUtils.isNotBlank(" 1")); + } - @Test - public void defaultString() { - Assert.assertEquals("", StringUtils.defaultString(null)); - Assert.assertEquals("x", StringUtils.defaultString("x")); - } - - @Test - public void testToString() { - Assert.assertEquals(null, StringUtils.toString(null)); - Assert.assertEquals("Bean:11", StringUtils.toString(new Bean("11"))); + @Test + public void defaultString() { + Assert.assertEquals("", StringUtils.defaultString(null)); + Assert.assertEquals("x", StringUtils.defaultString("x")); + } - Assert.assertEquals(null, StringUtils.toString((Object) null, null)); - Assert.assertEquals("1", StringUtils.toString((Object) null, "1")); - Assert.assertEquals("Bean:11", StringUtils.toString(new Bean("11"), null)); - } + @Test + public void testToString() { + Assert.assertEquals(null, StringUtils.toString(null)); + Assert.assertEquals("Bean:11", StringUtils.toString(new Bean("11"))); - class Bean { - private String s; + Assert.assertEquals(null, StringUtils.toString((Object) null, null)); + Assert.assertEquals("1", StringUtils.toString((Object) null, "1")); + Assert.assertEquals("Bean:11", StringUtils.toString(new Bean("11"), null)); + } - public Bean() { + class Bean { + private String s; - } + public Bean() {} - public Bean(String s) { - this.s = s; - } + public Bean(String s) { + this.s = s; + } - @Override - public String toString() { - return "Bean:" + s; - } + @Override + public String toString() { + return "Bean:" + s; } -} \ No newline at end of file + } +} diff --git a/client/log/src/main/java/com/alipay/sofa/registry/client/log/LoggerFactory.java b/client/log/src/main/java/com/alipay/sofa/registry/client/log/LoggerFactory.java index ba80b7480..d1bcd5fc5 100644 --- a/client/log/src/main/java/com/alipay/sofa/registry/client/log/LoggerFactory.java +++ b/client/log/src/main/java/com/alipay/sofa/registry/client/log/LoggerFactory.java @@ -17,85 +17,85 @@ package com.alipay.sofa.registry.client.log; import com.alipay.sofa.common.log.LoggerSpaceManager; -import org.slf4j.Logger; - import java.io.File; +import org.slf4j.Logger; /** * The type Logger factory. + * * @author zhuoyu.sjw * @version $Id : LoggerFactory.java, v 0.1 2018-03-24 12:06 zhuoyu.sjw Exp $$ */ public class LoggerFactory { - private static final String LOG_SPACE_PROPERTY = "registry.client.log.space"; - private static final String LOG_PATH = "logging.path"; - private static final String LOG_PATH_DEFAULT = System.getProperty("user.home") - + File.separator + "logs"; - private static final String CLIENT_LOG_LEVEL = "com.alipay.sofa.registry.client.log.level"; - private static final String CLIENT_LOG_LEVEL_DEFAULT = "INFO"; - private static final String CLIENT_LOG_ENCODE = "com.alipay.sofa.registry.client.log.encode"; - private static final String CLIENT_LOG_ENCODE_DEFAULT = "UTF-8"; - private static String logSpace = "com.alipay.sofa.registry.client"; + private static final String LOG_SPACE_PROPERTY = "registry.client.log.space"; + private static final String LOG_PATH = "logging.path"; + private static final String LOG_PATH_DEFAULT = + System.getProperty("user.home") + File.separator + "logs"; + private static final String CLIENT_LOG_LEVEL = "com.alipay.sofa.registry.client.log.level"; + private static final String CLIENT_LOG_LEVEL_DEFAULT = "INFO"; + private static final String CLIENT_LOG_ENCODE = "com.alipay.sofa.registry.client.log.encode"; + private static final String CLIENT_LOG_ENCODE_DEFAULT = "UTF-8"; + private static String logSpace = "com.alipay.sofa.registry.client"; - static { - LoggerFactory.logSpace = getLogSpace(); + static { + LoggerFactory.logSpace = getLogSpace(); - String logPath = System.getProperty(LOG_PATH); - String logLevel = System.getProperty(CLIENT_LOG_LEVEL); - String logEncode = System.getProperty(CLIENT_LOG_ENCODE); - if (isBlank(logPath)) { - System.setProperty(LOG_PATH, LOG_PATH_DEFAULT); - } - if (isBlank(logLevel)) { - System.setProperty(CLIENT_LOG_LEVEL, CLIENT_LOG_LEVEL_DEFAULT); - } - if (isBlank(logEncode)) { - System.setProperty(CLIENT_LOG_ENCODE, CLIENT_LOG_ENCODE_DEFAULT); - } + String logPath = System.getProperty(LOG_PATH); + String logLevel = System.getProperty(CLIENT_LOG_LEVEL); + String logEncode = System.getProperty(CLIENT_LOG_ENCODE); + if (isBlank(logPath)) { + System.setProperty(LOG_PATH, LOG_PATH_DEFAULT); } - - static String getLogSpace() { - String sysLogSpace = System.getProperty(LOG_SPACE_PROPERTY); - return (null != sysLogSpace && !sysLogSpace.isEmpty()) ? sysLogSpace : logSpace; + if (isBlank(logLevel)) { + System.setProperty(CLIENT_LOG_LEVEL, CLIENT_LOG_LEVEL_DEFAULT); + } + if (isBlank(logEncode)) { + System.setProperty(CLIENT_LOG_ENCODE, CLIENT_LOG_ENCODE_DEFAULT); } + } - /** - * Gets logger. - * - * @param clazz the clazz - * @return the logger - */ - public static Logger getLogger(Class clazz) { - if (clazz == null) { - return null; - } - return getLogger(clazz.getCanonicalName()); + static String getLogSpace() { + String sysLogSpace = System.getProperty(LOG_SPACE_PROPERTY); + return (null != sysLogSpace && !sysLogSpace.isEmpty()) ? sysLogSpace : logSpace; + } + + /** + * Gets logger. + * + * @param clazz the clazz + * @return the logger + */ + public static Logger getLogger(Class clazz) { + if (clazz == null) { + return null; } + return getLogger(clazz.getCanonicalName()); + } - /** - * Gets logger. - * - * @param name the name - * @return the logger - */ - public static Logger getLogger(String name) { - if (name == null || name.isEmpty()) { - return null; - } - return LoggerSpaceManager.getLoggerBySpace(name, logSpace); + /** + * Gets logger. + * + * @param name the name + * @return the logger + */ + public static Logger getLogger(String name) { + if (name == null || name.isEmpty()) { + return null; } + return LoggerSpaceManager.getLoggerBySpace(name, logSpace); + } - static boolean isBlank(CharSequence cs) { - int strLen; - if (cs == null || (strLen = cs.length()) == 0) { - return true; - } - for (int i = 0; i < strLen; i++) { - if (!Character.isWhitespace(cs.charAt(i))) { - return false; - } - } - return true; + static boolean isBlank(CharSequence cs) { + int strLen; + if (cs == null || (strLen = cs.length()) == 0) { + return true; + } + for (int i = 0; i < strLen; i++) { + if (!Character.isWhitespace(cs.charAt(i))) { + return false; + } } -} \ No newline at end of file + return true; + } +} diff --git a/client/log/src/test/java/com/alipay/sofa/registry/client/log/LoggerFactoryTest.java b/client/log/src/test/java/com/alipay/sofa/registry/client/log/LoggerFactoryTest.java index 208cb3dbf..0d1848ade 100644 --- a/client/log/src/test/java/com/alipay/sofa/registry/client/log/LoggerFactoryTest.java +++ b/client/log/src/test/java/com/alipay/sofa/registry/client/log/LoggerFactoryTest.java @@ -19,46 +19,43 @@ import org.junit.Assert; import org.junit.Test; -/** - * @author GengZhang - */ +/** @author GengZhang */ public class LoggerFactoryTest { - @Test - public void getLogger() { - Assert.assertNull(LoggerFactory.getLogger((String) null)); - Assert.assertNull(LoggerFactory.getLogger((Class) null)); - Assert.assertEquals(LoggerFactory.getLogger(LoggerFactoryTest.class), - LoggerFactory.getLogger(LoggerFactoryTest.class.getCanonicalName())); - - } - - @Test - public void getLogSpace() { - Assert.assertEquals("com.alipay.sofa.registry.client", LoggerFactory.getLogSpace()); - String key = "registry.client.log.space"; - String old = System.getProperty(key); // - try { - System.setProperty(key, "xxx"); - Assert.assertEquals("xxx", LoggerFactory.getLogSpace()); - } finally { - if (old == null) { - System.clearProperty(key); - } else { - System.setProperty(key, old); - } - } - Assert.assertEquals("com.alipay.sofa.registry.client", LoggerFactory.getLogSpace()); - } + @Test + public void getLogger() { + Assert.assertNull(LoggerFactory.getLogger((String) null)); + Assert.assertNull(LoggerFactory.getLogger((Class) null)); + Assert.assertEquals( + LoggerFactory.getLogger(LoggerFactoryTest.class), + LoggerFactory.getLogger(LoggerFactoryTest.class.getCanonicalName())); + } - @Test - public void testIsBlank() { - Assert.assertFalse(LoggerFactory.isBlank("123")); - Assert.assertTrue(LoggerFactory.isBlank(" ")); - Assert.assertTrue(LoggerFactory.isBlank("")); - Assert.assertTrue(LoggerFactory.isBlank(null)); - Assert.assertTrue(LoggerFactory.isBlank(" ")); - Assert.assertTrue(LoggerFactory.isBlank("\r\t")); + @Test + public void getLogSpace() { + Assert.assertEquals("com.alipay.sofa.registry.client", LoggerFactory.getLogSpace()); + String key = "registry.client.log.space"; + String old = System.getProperty(key); // + try { + System.setProperty(key, "xxx"); + Assert.assertEquals("xxx", LoggerFactory.getLogSpace()); + } finally { + if (old == null) { + System.clearProperty(key); + } else { + System.setProperty(key, old); + } } + Assert.assertEquals("com.alipay.sofa.registry.client", LoggerFactory.getLogSpace()); + } -} \ No newline at end of file + @Test + public void testIsBlank() { + Assert.assertFalse(LoggerFactory.isBlank("123")); + Assert.assertTrue(LoggerFactory.isBlank(" ")); + Assert.assertTrue(LoggerFactory.isBlank("")); + Assert.assertTrue(LoggerFactory.isBlank(null)); + Assert.assertTrue(LoggerFactory.isBlank(" ")); + Assert.assertTrue(LoggerFactory.isBlank("\r\t")); + } +} diff --git a/core/src/main/java/com/alipay/sofa/registry/core/constants/AttributeKeyConstants.java b/core/src/main/java/com/alipay/sofa/registry/core/constants/AttributeKeyConstants.java index 50021e26e..36495d7fb 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/constants/AttributeKeyConstants.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/constants/AttributeKeyConstants.java @@ -17,27 +17,17 @@ package com.alipay.sofa.registry.core.constants; /** - * * @author zhuoyu.sjw - * @version $Id: AttributeKeyConstants.java, v 0.1 2018-03-30 20:18 zhuoyu.sjw - * Exp $$ + * @version $Id: AttributeKeyConstants.java, v 0.1 2018-03-30 20:18 zhuoyu.sjw Exp $$ */ public class AttributeKeyConstants { - /** - * Access Key - */ - public static final String ATTRIBUTE_ACCESS_KEY = "!AccessKey"; - /** - * Algorithm Key - */ - public static final String ATTRIBUTE_ALGORITHM = "!Algorithm"; - /** - * Signature Key - */ - public static final String ATTRIBUTE_SIGNATURE = "!Signature"; - /** - * Timestamp Key - */ - public static final String ATTRIBUTE_TIMESTAMP = "!Timestamp"; + /** Access Key */ + public static final String ATTRIBUTE_ACCESS_KEY = "!AccessKey"; + /** Algorithm Key */ + public static final String ATTRIBUTE_ALGORITHM = "!Algorithm"; + /** Signature Key */ + public static final String ATTRIBUTE_SIGNATURE = "!Signature"; + /** Timestamp Key */ + public static final String ATTRIBUTE_TIMESTAMP = "!Timestamp"; } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/constants/EventTypeConstants.java b/core/src/main/java/com/alipay/sofa/registry/core/constants/EventTypeConstants.java index fc94cbf5c..b1f3c6713 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/constants/EventTypeConstants.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/constants/EventTypeConstants.java @@ -17,25 +17,22 @@ package com.alipay.sofa.registry.core.constants; /** - * * @author zhuoyu.sjw - * @version $Id: EventTypeConstants.java, v 0.1 2018-03-01 19:15 zhuoyu.sjw Exp - * $$ + * @version $Id: EventTypeConstants.java, v 0.1 2018-03-01 19:15 zhuoyu.sjw Exp $$ */ public final class EventTypeConstants { - private EventTypeConstants() { - } + private EventTypeConstants() {} - public static final String REGISTER = "REGISTER"; + public static final String REGISTER = "REGISTER"; - public static final String UNREGISTER = "UNREGISTER"; + public static final String UNREGISTER = "UNREGISTER"; - public static char getEventTypeFlag(String eventType) { - if (EventTypeConstants.REGISTER.equals(eventType)) { - return 'R'; - } else if (EventTypeConstants.UNREGISTER.equals(eventType)) { - return 'U'; - } - return 'N'; - } + public static char getEventTypeFlag(String eventType) { + if (EventTypeConstants.REGISTER.equals(eventType)) { + return 'R'; + } else if (EventTypeConstants.UNREGISTER.equals(eventType)) { + return 'U'; + } + return 'N'; + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/AppRevisionInterface.java b/core/src/main/java/com/alipay/sofa/registry/core/model/AppRevisionInterface.java index 5503405cc..3b8efdb7c 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/AppRevisionInterface.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/AppRevisionInterface.java @@ -23,43 +23,43 @@ public class AppRevisionInterface implements Serializable { - private String id; + private String id; - private Map> serviceParams = new HashMap>(); + private Map> serviceParams = new HashMap>(); - /** - * Getter method for property id. - * - * @return property value of id - */ - public String getId() { - return id; - } + /** + * Getter method for property id. + * + * @return property value of id + */ + public String getId() { + return id; + } - /** - * Setter method for property id. - * - * @param id value to be assigned to property id - */ - public void setId(String id) { - this.id = id; - } + /** + * Setter method for property id. + * + * @param id value to be assigned to property id + */ + public void setId(String id) { + this.id = id; + } - /** - * Getter method for property serviceParams. - * - * @return property value of serviceParams - */ - public Map> getServiceParams() { - return serviceParams; - } + /** + * Getter method for property serviceParams. + * + * @return property value of serviceParams + */ + public Map> getServiceParams() { + return serviceParams; + } - /** - * Setter method for property serviceParams. - * - * @param serviceParams value to be assigned to property serviceParams - */ - public void setServiceParams(Map> serviceParams) { - this.serviceParams = serviceParams; - } + /** + * Setter method for property serviceParams. + * + * @param serviceParams value to be assigned to property serviceParams + */ + public void setServiceParams(Map> serviceParams) { + this.serviceParams = serviceParams; + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/BaseRegister.java b/core/src/main/java/com/alipay/sofa/registry/core/model/BaseRegister.java index fe5a6c5ad..26283db08 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/BaseRegister.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/BaseRegister.java @@ -21,327 +21,362 @@ import java.util.Map; /** - * * @author zhuoyu.sjw * @version $Id: BaseRegister.java, v 0.1 2017-11-28 14:32 zhuoyu.sjw Exp $$ */ public class BaseRegister implements Serializable { - private static final long serialVersionUID = -3825175839851738346L; - - private String instanceId; - - private String zone; - - private String appName; - - private String dataId; - - private String group; - - private String processId; - - private String registId; - - private String clientId; - - private String dataInfoId; - - private String ip; - - private Integer port; - - private String eventType; - - private Long version; - - private Long timestamp; - - private Map attributes = new HashMap(); - - /** - * Getter method for property instanceId. - * - * @return property value of instanceId - */ - public String getInstanceId() { - return instanceId; - } - - /** - * Setter method for property instanceId. - * - * @param instanceId value to be assigned to property instanceId - */ - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; - } - - /** - * Getter method for property zone. - * - * @return property value of zone - */ - public String getZone() { - return zone; - } - - /** - * Setter method for property zone. - * - * @param zone value to be assigned to property zone - */ - public void setZone(String zone) { - this.zone = zone; - } - - /** - * Getter method for property appName. - * - * @return property value of appName - */ - public String getAppName() { - return appName; - } - - /** - * Setter method for property appName. - * - * @param appName value to be assigned to property appName - */ - public void setAppName(String appName) { - this.appName = appName; - } - - /** - * Getter method for property dataId. - * - * @return property value of dataId - */ - public String getDataId() { - return dataId; - } - - /** - * Setter method for property dataId. - * - * @param dataId value to be assigned to property dataId - */ - public void setDataId(String dataId) { - this.dataId = dataId; - } - - /** - * Getter method for property group. - * - * @return property value of group - */ - public String getGroup() { - return group; - } - - /** - * Setter method for property group. - * - * @param group value to be assigned to property group - */ - public void setGroup(String group) { - this.group = group; - } - - /** - * Getter method for property processId. - * - * @return property value of processId - */ - public String getProcessId() { - return processId; - } - - /** - * Setter method for property processId. - * - * @param processId value to be assigned to property processId - */ - public void setProcessId(String processId) { - this.processId = processId; - } - - /** - * Getter method for property registId. - * - * @return property value of registId - */ - public String getRegistId() { - return registId; - } - - /** - * Setter method for property registId. - * - * @param registId value to be assigned to property registId - */ - public void setRegistId(String registId) { - this.registId = registId; - } - - /** - * Getter method for property version. - * - * @return property value of version - */ - public Long getVersion() { - return version; - } - - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * Getter method for property timestamp. - * - * @return property value of timestamp - */ - public Long getTimestamp() { - return timestamp; - } - - /** - * Setter method for property timestamp. - * - * @param timestamp value to be assigned to property timestamp - */ - public void setTimestamp(Long timestamp) { - this.timestamp = timestamp; - } - - /** - * Getter method for property eventType. - * - * @return property value of eventType - */ - public String getEventType() { - return eventType; - } - - /** - * Setter method for property eventType. - * - * @param eventType value to be assigned to property eventType - */ - public void setEventType(String eventType) { - this.eventType = eventType; - } - - /** - * Getter method for property clientId. - * - * @return property value of clientId - */ - public String getClientId() { - return clientId; - } - - /** - * Setter method for property clientId. - * - * @param clientId value to be assigned to property clientId - */ - public void setClientId(String clientId) { - this.clientId = clientId; - } - - /** - * Getter method for property ip. - * - * @return property value of ip - */ - public String getIp() { - return ip; - } - - /** - * Setter method for property ip. - * - * @param ip value to be assigned to property ip - */ - public void setIp(String ip) { - this.ip = ip; - } - - /** - * Getter method for property port. - * - * @return property value of port - */ - public Integer getPort() { - return port; - } - - /** - * Setter method for property port. - * - * @param port value to be assigned to property port - */ - public void setPort(Integer port) { - this.port = port; - } - - /** - * Getter method for property dataInfoId. - * - * @return property value of dataInfoId - */ - public String getDataInfoId() { - return dataInfoId; - } - - /** - * Setter method for property dataInfoId. - * - * @param dataInfoId value to be assigned to property dataInfoId - */ - public void setDataInfoId(String dataInfoId) { - this.dataInfoId = dataInfoId; - } - - /** - * Getter method for property attributes. - * - * @return property value of attributes - */ - public Map getAttributes() { - return attributes; - } - - /** - * Setter method for property attributes. - * - * @param attributes value to be assigned to property attributes - */ - public void setAttributes(Map attributes) { - this.attributes = attributes; - } - - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "BaseRegister{" + "instanceId='" + instanceId + '\'' + ", zone='" + zone + '\'' - + ", appName='" + appName + '\'' + ", dataId='" + dataId + '\'' + ", group='" - + group + '\'' + ", processId='" + processId + '\'' + ", registId='" + registId - + '\'' + ", clientId='" + clientId + '\'' + ", dataInfoId='" + dataInfoId + '\'' - + ", ip='" + ip + '\'' + ", port=" + port + ", eventType='" + eventType + '\'' - + ", version=" + version + ", timestamp=" + timestamp + ", attributes=" + attributes - + '}'; - } + private static final long serialVersionUID = -3825175839851738346L; + + private String instanceId; + + private String zone; + + private String appName; + + private String dataId; + + private String group; + + private String processId; + + private String registId; + + private String clientId; + + private String dataInfoId; + + private String ip; + + private Integer port; + + private String eventType; + + private Long version; + + private Long timestamp; + + private Map attributes = new HashMap(); + + /** + * Getter method for property instanceId. + * + * @return property value of instanceId + */ + public String getInstanceId() { + return instanceId; + } + + /** + * Setter method for property instanceId. + * + * @param instanceId value to be assigned to property instanceId + */ + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + /** + * Getter method for property zone. + * + * @return property value of zone + */ + public String getZone() { + return zone; + } + + /** + * Setter method for property zone. + * + * @param zone value to be assigned to property zone + */ + public void setZone(String zone) { + this.zone = zone; + } + + /** + * Getter method for property appName. + * + * @return property value of appName + */ + public String getAppName() { + return appName; + } + + /** + * Setter method for property appName. + * + * @param appName value to be assigned to property appName + */ + public void setAppName(String appName) { + this.appName = appName; + } + + /** + * Getter method for property dataId. + * + * @return property value of dataId + */ + public String getDataId() { + return dataId; + } + + /** + * Setter method for property dataId. + * + * @param dataId value to be assigned to property dataId + */ + public void setDataId(String dataId) { + this.dataId = dataId; + } + + /** + * Getter method for property group. + * + * @return property value of group + */ + public String getGroup() { + return group; + } + + /** + * Setter method for property group. + * + * @param group value to be assigned to property group + */ + public void setGroup(String group) { + this.group = group; + } + + /** + * Getter method for property processId. + * + * @return property value of processId + */ + public String getProcessId() { + return processId; + } + + /** + * Setter method for property processId. + * + * @param processId value to be assigned to property processId + */ + public void setProcessId(String processId) { + this.processId = processId; + } + + /** + * Getter method for property registId. + * + * @return property value of registId + */ + public String getRegistId() { + return registId; + } + + /** + * Setter method for property registId. + * + * @param registId value to be assigned to property registId + */ + public void setRegistId(String registId) { + this.registId = registId; + } + + /** + * Getter method for property version. + * + * @return property value of version + */ + public Long getVersion() { + return version; + } + + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * Getter method for property timestamp. + * + * @return property value of timestamp + */ + public Long getTimestamp() { + return timestamp; + } + + /** + * Setter method for property timestamp. + * + * @param timestamp value to be assigned to property timestamp + */ + public void setTimestamp(Long timestamp) { + this.timestamp = timestamp; + } + + /** + * Getter method for property eventType. + * + * @return property value of eventType + */ + public String getEventType() { + return eventType; + } + + /** + * Setter method for property eventType. + * + * @param eventType value to be assigned to property eventType + */ + public void setEventType(String eventType) { + this.eventType = eventType; + } + + /** + * Getter method for property clientId. + * + * @return property value of clientId + */ + public String getClientId() { + return clientId; + } + + /** + * Setter method for property clientId. + * + * @param clientId value to be assigned to property clientId + */ + public void setClientId(String clientId) { + this.clientId = clientId; + } + + /** + * Getter method for property ip. + * + * @return property value of ip + */ + public String getIp() { + return ip; + } + + /** + * Setter method for property ip. + * + * @param ip value to be assigned to property ip + */ + public void setIp(String ip) { + this.ip = ip; + } + + /** + * Getter method for property port. + * + * @return property value of port + */ + public Integer getPort() { + return port; + } + + /** + * Setter method for property port. + * + * @param port value to be assigned to property port + */ + public void setPort(Integer port) { + this.port = port; + } + + /** + * Getter method for property dataInfoId. + * + * @return property value of dataInfoId + */ + public String getDataInfoId() { + return dataInfoId; + } + + /** + * Setter method for property dataInfoId. + * + * @param dataInfoId value to be assigned to property dataInfoId + */ + public void setDataInfoId(String dataInfoId) { + this.dataInfoId = dataInfoId; + } + + /** + * Getter method for property attributes. + * + * @return property value of attributes + */ + public Map getAttributes() { + return attributes; + } + + /** + * Setter method for property attributes. + * + * @param attributes value to be assigned to property attributes + */ + public void setAttributes(Map attributes) { + this.attributes = attributes; + } + + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "BaseRegister{" + + "instanceId='" + + instanceId + + '\'' + + ", zone='" + + zone + + '\'' + + ", appName='" + + appName + + '\'' + + ", dataId='" + + dataId + + '\'' + + ", group='" + + group + + '\'' + + ", processId='" + + processId + + '\'' + + ", registId='" + + registId + + '\'' + + ", clientId='" + + clientId + + '\'' + + ", dataInfoId='" + + dataInfoId + + '\'' + + ", ip='" + + ip + + '\'' + + ", port=" + + port + + ", eventType='" + + eventType + + '\'' + + ", version=" + + version + + ", timestamp=" + + timestamp + + ", attributes=" + + attributes + + '}'; + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/ConfiguratorRegister.java b/core/src/main/java/com/alipay/sofa/registry/core/model/ConfiguratorRegister.java index a1a97ea41..a48053d2e 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/ConfiguratorRegister.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/ConfiguratorRegister.java @@ -17,12 +17,9 @@ package com.alipay.sofa.registry.core.model; /** - * * @author zhuoyu.sjw - * @version $Id: ConfiguratorRegister.java, v 0.1 2018-04-17 17:45 zhuoyu.sjw - * Exp $$ + * @version $Id: ConfiguratorRegister.java, v 0.1 2018-04-17 17:45 zhuoyu.sjw Exp $$ */ public class ConfiguratorRegister extends BaseRegister { - private static final long serialVersionUID = 3636660681387698721L; - + private static final long serialVersionUID = 3636660681387698721L; } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/DataBox.java b/core/src/main/java/com/alipay/sofa/registry/core/model/DataBox.java index 98dd01ad7..ef0a70aff 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/DataBox.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/DataBox.java @@ -20,52 +20,50 @@ /** * The type DataBox. + * * @author zhuoyu.sjw * @version $Id : DataBox.java, v 0.1 2017-11-28 17:47 zhuoyu.sjw Exp $$ */ public class DataBox implements Serializable { - /** UID */ - private static final long serialVersionUID = 2817539491173993030L; + /** UID */ + private static final long serialVersionUID = 2817539491173993030L; - /** Actual data */ - private String data; + /** Actual data */ + private String data; - /** - * Instantiates a new DataBox. - */ - public DataBox() { - } + /** Instantiates a new DataBox. */ + public DataBox() {} - /** - * Instantiates a new Data box. - * - * @param data the data - */ - public DataBox(String data) { - this.data = data; - } + /** + * Instantiates a new Data box. + * + * @param data the data + */ + public DataBox(String data) { + this.data = data; + } - /** - * Getter method for property data. - * - * @return property value of data - */ - public String getData() { - return data; - } + /** + * Getter method for property data. + * + * @return property value of data + */ + public String getData() { + return data; + } - /** - * Setter method for property data. - * - * @param data value to be assigned to property data - */ - public void setData(String data) { - this.data = data; - } + /** + * Setter method for property data. + * + * @param data value to be assigned to property data + */ + public void setData(String data) { + this.data = data; + } - @Override - public String toString() { - return "DataBox{data='" + data + "'}"; - } + @Override + public String toString() { + return "DataBox{data='" + data + "'}"; + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/PublisherRegister.java b/core/src/main/java/com/alipay/sofa/registry/core/model/PublisherRegister.java index 7bdc25015..346836934 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/PublisherRegister.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/PublisherRegister.java @@ -20,40 +20,41 @@ /** * The type Publisher register. + * * @author zhuoyu.sjw * @version $Id : PublisherRegister.java, v 0.1 2017-11-28 15:39 zhuoyu.sjw Exp $$ */ public class PublisherRegister extends BaseRegister { - private static final long serialVersionUID = 17084511452627565L; + private static final long serialVersionUID = 17084511452627565L; - private List dataList; + private List dataList; - /** - * Getter method for property dataList. - * - * @return property value of dataList - */ - public List getDataList() { - return dataList; - } + /** + * Getter method for property dataList. + * + * @return property value of dataList + */ + public List getDataList() { + return dataList; + } - /** - * Setter method for property dataList. - * - * @param dataList value to be assigned to property dataList - */ - public void setDataList(List dataList) { - this.dataList = dataList; - } + /** + * Setter method for property dataList. + * + * @param dataList value to be assigned to property dataList + */ + public void setDataList(List dataList) { + this.dataList = dataList; + } - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "PublisherRegister{" + "dataList=" + dataList + '}' + super.toString(); - } + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "PublisherRegister{" + "dataList=" + dataList + '}' + super.toString(); + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/ReceivedConfigData.java b/core/src/main/java/com/alipay/sofa/registry/core/model/ReceivedConfigData.java index a7c1e182c..e85ddeb13 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/ReceivedConfigData.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/ReceivedConfigData.java @@ -21,140 +21,153 @@ /** * The type Received config data. + * * @author zhuoyu.sjw * @version $Id : ReceivedConfigData.java, v 0.1 2018-04-17 18:00 zhuoyu.sjw Exp $$ */ public class ReceivedConfigData implements Serializable { - private static final long serialVersionUID = 4077554672965455808L; - - private String dataId; - - private String group; - - private String instanceId; - - private List configuratorRegistIds; - - private DataBox dataBox; - - private Long version; - - /** - * Getter method for property dataId. - * - * @return property value of dataId - */ - public String getDataId() { - return dataId; - } - - /** - * Setter method for property dataId. - * - * @param dataId value to be assigned to property dataId - */ - public void setDataId(String dataId) { - this.dataId = dataId; - } - - /** - * Getter method for property group. - * - * @return property value of group - */ - public String getGroup() { - return group; - } - - /** - * Setter method for property group. - * - * @param group value to be assigned to property group - */ - public void setGroup(String group) { - this.group = group; - } - - /** - * Getter method for property instanceId. - * - * @return property value of instanceId - */ - public String getInstanceId() { - return instanceId; - } - - /** - * Setter method for property instanceId. - * - * @param instanceId value to be assigned to property instanceId - */ - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; - } - - /** - * Getter method for property dataBox. - * - * @return property value of dataBox - */ - public DataBox getDataBox() { - return dataBox; - } - - /** - * Setter method for property dataBox. - * - * @param dataBox value to be assigned to property dataBox - */ - public void setDataBox(DataBox dataBox) { - this.dataBox = dataBox; - } - - /** - * Getter method for property version. - * - * @return property value of version - */ - public Long getVersion() { - return version; - } - - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * Getter method for property configuratorRegistIds. - * - * @return property value of configuratorRegistIds - */ - public List getConfiguratorRegistIds() { - return configuratorRegistIds; - } - - /** - * Setter method for property configuratorRegistIds. - * - * @param configuratorRegistIds value to be assigned to property configuratorRegistIds - */ - public void setConfiguratorRegistIds(List configuratorRegistIds) { - this.configuratorRegistIds = configuratorRegistIds; - } - - /** - * @see Object#toString() - */ - @Override - public String toString() { - return "ReceivedConfigData{" + "dataId='" + dataId + '\'' + ", group='" + group + '\'' - + ", instanceId='" + instanceId + '\'' + ", configuratorRegistIds=" - + configuratorRegistIds + ", dataBox=" + dataBox + ", version=" + version + '}'; - } + private static final long serialVersionUID = 4077554672965455808L; + + private String dataId; + + private String group; + + private String instanceId; + + private List configuratorRegistIds; + + private DataBox dataBox; + + private Long version; + + /** + * Getter method for property dataId. + * + * @return property value of dataId + */ + public String getDataId() { + return dataId; + } + + /** + * Setter method for property dataId. + * + * @param dataId value to be assigned to property dataId + */ + public void setDataId(String dataId) { + this.dataId = dataId; + } + + /** + * Getter method for property group. + * + * @return property value of group + */ + public String getGroup() { + return group; + } + + /** + * Setter method for property group. + * + * @param group value to be assigned to property group + */ + public void setGroup(String group) { + this.group = group; + } + + /** + * Getter method for property instanceId. + * + * @return property value of instanceId + */ + public String getInstanceId() { + return instanceId; + } + + /** + * Setter method for property instanceId. + * + * @param instanceId value to be assigned to property instanceId + */ + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + /** + * Getter method for property dataBox. + * + * @return property value of dataBox + */ + public DataBox getDataBox() { + return dataBox; + } + + /** + * Setter method for property dataBox. + * + * @param dataBox value to be assigned to property dataBox + */ + public void setDataBox(DataBox dataBox) { + this.dataBox = dataBox; + } + + /** + * Getter method for property version. + * + * @return property value of version + */ + public Long getVersion() { + return version; + } + + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * Getter method for property configuratorRegistIds. + * + * @return property value of configuratorRegistIds + */ + public List getConfiguratorRegistIds() { + return configuratorRegistIds; + } + + /** + * Setter method for property configuratorRegistIds. + * + * @param configuratorRegistIds value to be assigned to property configuratorRegistIds + */ + public void setConfiguratorRegistIds(List configuratorRegistIds) { + this.configuratorRegistIds = configuratorRegistIds; + } + + /** @see Object#toString() */ + @Override + public String toString() { + return "ReceivedConfigData{" + + "dataId='" + + dataId + + '\'' + + ", group='" + + group + + '\'' + + ", instanceId='" + + instanceId + + '\'' + + ", configuratorRegistIds=" + + configuratorRegistIds + + ", dataBox=" + + dataBox + + ", version=" + + version + + '}'; + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/ReceivedData.java b/core/src/main/java/com/alipay/sofa/registry/core/model/ReceivedData.java index f4ef744c5..139a5084b 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/ReceivedData.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/ReceivedData.java @@ -22,232 +22,255 @@ /** * The type Received data multi. + * * @author zhuoyu.sjw * @version $Id : ReceivedData.java, v 0.1 2017-11-23 22:23 zhuoyu.sjw Exp $$ */ public class ReceivedData implements Serializable { - private static final long serialVersionUID = -7322781873212812819L; - - private String dataId; - - private String group; - - private String instanceId; - - private String segment; - - private String scope; - - private List subscriberRegistIds; - - private Map> data; - - private Long version; - - private String localZone; - - /** - * Instantiates a new Received data multi. - */ - public ReceivedData() { - } - - /** - * Instantiates a new Received data multi. - * - * @param dataId the data id - * @param group the group - * @param instanceId the instance id - * @param segment the data center - * @param subscriberRegistIds the subscriber regist ids - * @param data the data - * @param version the version - */ - public ReceivedData(String dataId, String group, String instanceId, String segment, - List subscriberRegistIds, Map> data, - Long version) { - this.dataId = dataId; - this.group = group; - this.instanceId = instanceId; - this.segment = segment; - this.subscriberRegistIds = subscriberRegistIds; - this.data = data; - this.version = version; - } - - /** - * Getter method for property dataId. - * - * @return property value of dataId - */ - public String getDataId() { - return dataId; - } - - /** - * Setter method for property dataId. - * - * @param dataId value to be assigned to property dataId - */ - public void setDataId(String dataId) { - this.dataId = dataId; - } - - /** - * Getter method for property group. - * - * @return property value of group - */ - public String getGroup() { - return group; - } - - /** - * Setter method for property group. - * - * @param group value to be assigned to property group - */ - public void setGroup(String group) { - this.group = group; - } - - /** - * Getter method for property instanceId. - * - * @return property value of instanceId - */ - public String getInstanceId() { - return instanceId; - } - - /** - * Setter method for property instanceId. - * - * @param instanceId value to be assigned to property instanceId - */ - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; - } - - /** - * Getter method for property segment. - * - * @return property value of segment - */ - public String getSegment() { - return segment; - } - - /** - * Setter method for property segment. - * - * @param segment value to be assigned to property segment - */ - public void setSegment(String segment) { - this.segment = segment; - } - - /** - * Getter method for property scope. - * - * @return property value of scope - */ - public String getScope() { - return scope; - } - - /** - * Setter method for property scope. - * - * @param scope value to be assigned to property scope - */ - public void setScope(String scope) { - this.scope = scope; - } - - /** - * Getter method for property subscriberRegistIds. - * - * @return property value of subscriberRegistIds - */ - public List getSubscriberRegistIds() { - return subscriberRegistIds; - } - - /** - * Setter method for property subscriberRegistIds. - * - * @param subscriberRegistIds value to be assigned to property subscriberRegistIds - */ - public void setSubscriberRegistIds(List subscriberRegistIds) { - this.subscriberRegistIds = subscriberRegistIds; - } - - /** - * Getter method for property data. - * - * @return property value of data - */ - public Map> getData() { - return data; - } - - /** - * Setter method for property data. - * - * @param data value to be assigned to property data - */ - public void setData(Map> data) { - this.data = data; - } - - /** - * Getter method for property version. - * - * @return property value of version - */ - public Long getVersion() { - return version; - } - - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * Getter method for property localZone. - * - * @return property value of localZone - */ - public String getLocalZone() { - return localZone; - } - - /** - * Setter method for property localZone. - * - * @param localZone value to be assigned to property localZone - */ - public void setLocalZone(String localZone) { - this.localZone = localZone; - } - - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "ReceivedData{" + "dataId='" + dataId + '\'' + ", group='" + group + '\'' - + ", instanceId='" + instanceId + '\'' + ", segment='" + segment + '\'' - + ", scope='" + scope + '\'' + ", subscriberRegistIds=" + subscriberRegistIds - + ", version=" + version + ", localZone='" + localZone + '\'' + '}'; - } + private static final long serialVersionUID = -7322781873212812819L; + + private String dataId; + + private String group; + + private String instanceId; + + private String segment; + + private String scope; + + private List subscriberRegistIds; + + private Map> data; + + private Long version; + + private String localZone; + + /** Instantiates a new Received data multi. */ + public ReceivedData() {} + + /** + * Instantiates a new Received data multi. + * + * @param dataId the data id + * @param group the group + * @param instanceId the instance id + * @param segment the data center + * @param subscriberRegistIds the subscriber regist ids + * @param data the data + * @param version the version + */ + public ReceivedData( + String dataId, + String group, + String instanceId, + String segment, + List subscriberRegistIds, + Map> data, + Long version) { + this.dataId = dataId; + this.group = group; + this.instanceId = instanceId; + this.segment = segment; + this.subscriberRegistIds = subscriberRegistIds; + this.data = data; + this.version = version; + } + + /** + * Getter method for property dataId. + * + * @return property value of dataId + */ + public String getDataId() { + return dataId; + } + + /** + * Setter method for property dataId. + * + * @param dataId value to be assigned to property dataId + */ + public void setDataId(String dataId) { + this.dataId = dataId; + } + + /** + * Getter method for property group. + * + * @return property value of group + */ + public String getGroup() { + return group; + } + + /** + * Setter method for property group. + * + * @param group value to be assigned to property group + */ + public void setGroup(String group) { + this.group = group; + } + + /** + * Getter method for property instanceId. + * + * @return property value of instanceId + */ + public String getInstanceId() { + return instanceId; + } + + /** + * Setter method for property instanceId. + * + * @param instanceId value to be assigned to property instanceId + */ + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + /** + * Getter method for property segment. + * + * @return property value of segment + */ + public String getSegment() { + return segment; + } + + /** + * Setter method for property segment. + * + * @param segment value to be assigned to property segment + */ + public void setSegment(String segment) { + this.segment = segment; + } + + /** + * Getter method for property scope. + * + * @return property value of scope + */ + public String getScope() { + return scope; + } + + /** + * Setter method for property scope. + * + * @param scope value to be assigned to property scope + */ + public void setScope(String scope) { + this.scope = scope; + } + + /** + * Getter method for property subscriberRegistIds. + * + * @return property value of subscriberRegistIds + */ + public List getSubscriberRegistIds() { + return subscriberRegistIds; + } + + /** + * Setter method for property subscriberRegistIds. + * + * @param subscriberRegistIds value to be assigned to property subscriberRegistIds + */ + public void setSubscriberRegistIds(List subscriberRegistIds) { + this.subscriberRegistIds = subscriberRegistIds; + } + + /** + * Getter method for property data. + * + * @return property value of data + */ + public Map> getData() { + return data; + } + + /** + * Setter method for property data. + * + * @param data value to be assigned to property data + */ + public void setData(Map> data) { + this.data = data; + } + + /** + * Getter method for property version. + * + * @return property value of version + */ + public Long getVersion() { + return version; + } + + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * Getter method for property localZone. + * + * @return property value of localZone + */ + public String getLocalZone() { + return localZone; + } + + /** + * Setter method for property localZone. + * + * @param localZone value to be assigned to property localZone + */ + public void setLocalZone(String localZone) { + this.localZone = localZone; + } + + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "ReceivedData{" + + "dataId='" + + dataId + + '\'' + + ", group='" + + group + + '\'' + + ", instanceId='" + + instanceId + + '\'' + + ", segment='" + + segment + + '\'' + + ", scope='" + + scope + + '\'' + + ", subscriberRegistIds=" + + subscriberRegistIds + + ", version=" + + version + + ", localZone='" + + localZone + + '\'' + + '}'; + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/RegisterResponse.java b/core/src/main/java/com/alipay/sofa/registry/core/model/RegisterResponse.java index 33ce9e5dd..8bf700944 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/RegisterResponse.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/RegisterResponse.java @@ -19,121 +19,129 @@ import java.io.Serializable; /** - * * @author zhuoyu.sjw * @version $Id: RegisterResponse.java, v 0.1 2018-03-05 18:11 zhuoyu.sjw Exp $$ */ public class RegisterResponse implements Serializable { - private static final long serialVersionUID = -3692498042919432434L; - - private boolean success; - - private String registId; - - private long version; - - private boolean refused; - - private String message; - - /** - * Getter method for property success. - * - * @return property value of success - */ - public boolean isSuccess() { - return success; - } - - /** - * Setter method for property success. - * - * @param success value to be assigned to property success - */ - public void setSuccess(boolean success) { - this.success = success; - } - - /** - * Getter method for property registId. - * - * @return property value of registId - */ - public String getRegistId() { - return registId; - } - - /** - * Setter method for property registId. - * - * @param registId value to be assigned to property registId - */ - public void setRegistId(String registId) { - this.registId = registId; - } - - /** - * Getter method for property version. - * - * @return property value of version - */ - public long getVersion() { - return version; - } - - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(long version) { - this.version = version; - } - - /** - * Getter method for property refused. - * - * @return property value of refused - */ - public boolean isRefused() { - return refused; - } - - /** - * Setter method for property refused. - * - * @param refused value to be assigned to property refused - */ - public void setRefused(boolean refused) { - this.refused = refused; - } - - /** - * Getter method for property message. - * - * @return property value of message - */ - public String getMessage() { - return message; - } - - /** - * Setter method for property message. - * - * @param message value to be assigned to property message - */ - public void setMessage(String message) { - this.message = message; - } - - /** - * @see Object#toString() - */ - @Override - public String toString() { - return "RegisterResponse{" + "success=" + success + ", registId='" + registId + '\'' - + ", version=" + version + ", refused=" + refused + ", message='" + message + '\'' - + '}'; - } + private static final long serialVersionUID = -3692498042919432434L; + + private boolean success; + + private String registId; + + private long version; + + private boolean refused; + + private String message; + + /** + * Getter method for property success. + * + * @return property value of success + */ + public boolean isSuccess() { + return success; + } + + /** + * Setter method for property success. + * + * @param success value to be assigned to property success + */ + public void setSuccess(boolean success) { + this.success = success; + } + + /** + * Getter method for property registId. + * + * @return property value of registId + */ + public String getRegistId() { + return registId; + } + + /** + * Setter method for property registId. + * + * @param registId value to be assigned to property registId + */ + public void setRegistId(String registId) { + this.registId = registId; + } + + /** + * Getter method for property version. + * + * @return property value of version + */ + public long getVersion() { + return version; + } + + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(long version) { + this.version = version; + } + + /** + * Getter method for property refused. + * + * @return property value of refused + */ + public boolean isRefused() { + return refused; + } + + /** + * Setter method for property refused. + * + * @param refused value to be assigned to property refused + */ + public void setRefused(boolean refused) { + this.refused = refused; + } + + /** + * Getter method for property message. + * + * @return property value of message + */ + public String getMessage() { + return message; + } + + /** + * Setter method for property message. + * + * @param message value to be assigned to property message + */ + public void setMessage(String message) { + this.message = message; + } + + /** @see Object#toString() */ + @Override + public String toString() { + return "RegisterResponse{" + + "success=" + + success + + ", registId='" + + registId + + '\'' + + ", version=" + + version + + ", refused=" + + refused + + ", message='" + + message + + '\'' + + '}'; + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/Result.java b/core/src/main/java/com/alipay/sofa/registry/core/model/Result.java index 12d077b7e..cd412f79a 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/Result.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/Result.java @@ -19,77 +19,75 @@ import java.io.Serializable; /** - * * @author zhuoyu.sjw * @version $Id: Result.java, v 0.1 2017-11-30 15:48 zhuoyu.sjw Exp $$ */ public class Result implements Serializable { - private static final long serialVersionUID = -3861771860629530576L; + private static final long serialVersionUID = -3861771860629530576L; - private boolean success; + private boolean success; - private String message; + private String message; - public Result() { - } + public Result() {} - public Result(boolean success, String message) { - this.success = success; - this.message = message; - } + public Result(boolean success, String message) { + this.success = success; + this.message = message; + } - public static Result failed(String message) { - return new Result(false, message); - } + public static Result failed(String message) { + return new Result(false, message); + } - public static Result success() { - return new Result(true, null); - } + public static Result success() { + return new Result(true, null); + } - /** - * Getter method for property success. - * - * @return property value of success - */ - public boolean isSuccess() { - return success; - } + /** + * Getter method for property success. + * + * @return property value of success + */ + public boolean isSuccess() { + return success; + } - /** - * Setter method for property success. - * - * @param success value to be assigned to property success - */ - public void setSuccess(boolean success) { - this.success = success; - } + /** + * Setter method for property success. + * + * @param success value to be assigned to property success + */ + public void setSuccess(boolean success) { + this.success = success; + } - /** - * Getter method for property message. - * - * @return property value of message - */ - public String getMessage() { - return message; - } + /** + * Getter method for property message. + * + * @return property value of message + */ + public String getMessage() { + return message; + } - /** - * Setter method for property message. - * - * @param message value to be assigned to property message - */ - public void setMessage(String message) { - this.message = message; - } + /** + * Setter method for property message. + * + * @param message value to be assigned to property message + */ + public void setMessage(String message) { + this.message = message; + } - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "Result{" + "success=" + success + ", message='" + message + '\'' + '}'; - } + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "Result{" + "success=" + success + ", message='" + message + '\'' + '}'; + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/ScopeEnum.java b/core/src/main/java/com/alipay/sofa/registry/core/model/ScopeEnum.java index aad4f628b..fdb067119 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/ScopeEnum.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/ScopeEnum.java @@ -24,19 +24,19 @@ */ public enum ScopeEnum { - /** zone scope: only can receive pub list at same zone */ - zone, - /** dataCenter scope: only can receive pub list at same dataCenter (multi zone) */ - dataCenter, - /** global scope: can receive pub list at all dataCenter (multi zone) */ - global; + /** zone scope: only can receive pub list at same zone */ + zone, + /** dataCenter scope: only can receive pub list at same dataCenter (multi zone) */ + dataCenter, + /** global scope: can receive pub list at all dataCenter (multi zone) */ + global; - public static boolean contains(String name) { - for (ScopeEnum scopeEnum : values()) { - if (scopeEnum.name().equals(name)) { - return true; - } - } - return false; + public static boolean contains(String name) { + for (ScopeEnum scopeEnum : values()) { + if (scopeEnum.name().equals(name)) { + return true; + } } + return false; + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/SubscriberRegister.java b/core/src/main/java/com/alipay/sofa/registry/core/model/SubscriberRegister.java index 11d117ce8..2c18059a4 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/SubscriberRegister.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/SubscriberRegister.java @@ -21,35 +21,35 @@ * @version $Id: SubscriberRegister.java, v 0.1 2017-11-28 15:40 zhuoyu.sjw Exp $$ */ public class SubscriberRegister extends BaseRegister { - private static final long serialVersionUID = 5884257055097046886L; + private static final long serialVersionUID = 5884257055097046886L; - private String scope; + private String scope; - /** - * Getter method for property scope. - * - * @return property value of scope - */ - public String getScope() { - return scope; - } + /** + * Getter method for property scope. + * + * @return property value of scope + */ + public String getScope() { + return scope; + } - /** - * Setter method for property scope. - * - * @param scope value to be assigned to property scope - */ - public void setScope(String scope) { - this.scope = scope; - } + /** + * Setter method for property scope. + * + * @param scope value to be assigned to property scope + */ + public void setScope(String scope) { + this.scope = scope; + } - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "SubscriberRegister{" + "scope='" + scope + '\'' + '}' + super.toString(); - } + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "SubscriberRegister{" + "scope='" + scope + '\'' + '}' + super.toString(); + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/SyncConfigRequest.java b/core/src/main/java/com/alipay/sofa/registry/core/model/SyncConfigRequest.java index fa3be30f7..5023ae69d 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/SyncConfigRequest.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/SyncConfigRequest.java @@ -19,62 +19,67 @@ import java.io.Serializable; /** - * * @author zhuoyu.sjw * @version $Id: SyncConfigRequest.java, v 0.1 2018-03-14 23:06 zhuoyu.sjw Exp $$ */ public class SyncConfigRequest implements Serializable { - private static final long serialVersionUID = -843642420869816713L; + private static final long serialVersionUID = -843642420869816713L; - private String dataCenter; + private String dataCenter; - private String zone; + private String zone; - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } - /** - * Setter method for property dataCenter. - * - * @param dataCenter value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } + /** + * Setter method for property dataCenter. + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } - /** - * Getter method for property zone. - * - * @return property value of zone - */ - public String getZone() { - return zone; - } + /** + * Getter method for property zone. + * + * @return property value of zone + */ + public String getZone() { + return zone; + } - /** - * Setter method for property zone. - * - * @param zone value to be assigned to property zone - */ - public void setZone(String zone) { - this.zone = zone; - } + /** + * Setter method for property zone. + * + * @param zone value to be assigned to property zone + */ + public void setZone(String zone) { + this.zone = zone; + } - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "SyncConfigRequest{" + "dataCenter='" + dataCenter + '\'' + ", zone='" + zone + '\'' - + '}'; - } + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "SyncConfigRequest{" + + "dataCenter='" + + dataCenter + + '\'' + + ", zone='" + + zone + + '\'' + + '}'; + } } diff --git a/core/src/main/java/com/alipay/sofa/registry/core/model/SyncConfigResponse.java b/core/src/main/java/com/alipay/sofa/registry/core/model/SyncConfigResponse.java index 70d9d972c..daa01b175 100644 --- a/core/src/main/java/com/alipay/sofa/registry/core/model/SyncConfigResponse.java +++ b/core/src/main/java/com/alipay/sofa/registry/core/model/SyncConfigResponse.java @@ -20,62 +20,65 @@ import java.util.List; /** - * * @author zhuoyu.sjw * @version $Id: SyncConfigResponse.java, v 0.1 2018-03-14 23:08 zhuoyu.sjw Exp $$ */ public class SyncConfigResponse extends Result implements Serializable { - private static final long serialVersionUID = 5407436619633166827L; + private static final long serialVersionUID = 5407436619633166827L; - private List availableSegments; + private List availableSegments; - private int retryInterval; + private int retryInterval; - /** - * Getter method for property availableSegments. - * - * @return property value of availableSegments - */ - public List getAvailableSegments() { - return availableSegments; - } + /** + * Getter method for property availableSegments. + * + * @return property value of availableSegments + */ + public List getAvailableSegments() { + return availableSegments; + } - /** - * Setter method for property availableSegments. - * - * @param availableSegments value to be assigned to property availableSegments - */ - public void setAvailableSegments(List availableSegments) { - this.availableSegments = availableSegments; - } + /** + * Setter method for property availableSegments. + * + * @param availableSegments value to be assigned to property availableSegments + */ + public void setAvailableSegments(List availableSegments) { + this.availableSegments = availableSegments; + } - /** - * Getter method for property retryInterval. - * - * @return property value of retryInterval - */ - public int getRetryInterval() { - return retryInterval; - } + /** + * Getter method for property retryInterval. + * + * @return property value of retryInterval + */ + public int getRetryInterval() { + return retryInterval; + } - /** - * Setter method for property retryInterval. - * - * @param retryInterval value to be assigned to property retryInterval - */ - public void setRetryInterval(int retryInterval) { - this.retryInterval = retryInterval; - } + /** + * Setter method for property retryInterval. + * + * @param retryInterval value to be assigned to property retryInterval + */ + public void setRetryInterval(int retryInterval) { + this.retryInterval = retryInterval; + } - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "SyncConfigResponse{" + "availableSegments=" + availableSegments - + ", retryInterval=" + retryInterval + '}'; - } + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "SyncConfigResponse{" + + "availableSegments=" + + availableSegments + + ", retryInterval=" + + retryInterval + + '}'; + } } diff --git a/pom.xml b/pom.xml index f74dc7e0d..fbbb5aadc 100644 --- a/pom.xml +++ b/pom.xml @@ -437,46 +437,45 @@ - com.mycila - license-maven-plugin - 3.0 + com.diffplug.spotless + spotless-maven-plugin + 1.20.0 - - generate-sources - - remove - format - - - - - true -
${main.user.dir}/tools/codestyle/HEADER
- - **/src/main/java/** - **/src/test/java/** - - true - - SLASHSTAR_STYLE - -
-
- - com.googlecode.maven-java-formatter-plugin - maven-java-formatter-plugin - 0.4 - - - - format - - + + + apply + + compile + - - ${main.user.dir}/tools/codestyle/formatter.xml - UTF-8 - + + + + + + .xml + .gitignore + .properties + + + + + + + + + src/**/java/**/*.java + + + + 1.7 + + + + ${user.dir}/tools/codestyle/HEADER + + + org.jacoco diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ClientOffPublishers.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ClientOffPublishers.java index 9ee2ce611..104409471 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ClientOffPublishers.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ClientOffPublishers.java @@ -18,28 +18,27 @@ import com.alipay.sofa.registry.common.model.store.Publisher; import com.google.common.collect.Lists; - import java.util.Collections; import java.util.List; public class ClientOffPublishers { - private final ConnectId connectId; - private final List publishers; + private final ConnectId connectId; + private final List publishers; - public ClientOffPublishers(ConnectId connectId, List publishers) { - this.connectId = connectId; - this.publishers = Collections.unmodifiableList(Lists.newArrayList(publishers)); - } + public ClientOffPublishers(ConnectId connectId, List publishers) { + this.connectId = connectId; + this.publishers = Collections.unmodifiableList(Lists.newArrayList(publishers)); + } - public ConnectId getConnectId() { - return connectId; - } + public ConnectId getConnectId() { + return connectId; + } - public boolean isEmpty() { - return publishers.isEmpty(); - } + public boolean isEmpty() { + return publishers.isEmpty(); + } - public List getPublishers() { - return publishers; - } + public List getPublishers() { + return publishers; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/CommonResponse.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/CommonResponse.java index 72f7d5591..3072b1575 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/CommonResponse.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/CommonResponse.java @@ -26,98 +26,97 @@ */ public class CommonResponse implements Serializable { - private static final long serialVersionUID = 8269764971983130557L; + private static final long serialVersionUID = 8269764971983130557L; - private boolean success; + private boolean success; - private String message; + private String message; - /** - * constructor - */ - public CommonResponse() { - } + /** constructor */ + public CommonResponse() {} - /** - * constructor - * @param success - * @param message - */ - public CommonResponse(boolean success, String message) { - this.success = success; - this.message = message; - } + /** + * constructor + * + * @param success + * @param message + */ + public CommonResponse(boolean success, String message) { + this.success = success; + this.message = message; + } - /** - * build success resp - * @return - */ - public static CommonResponse buildSuccessResponse() { - return new CommonResponse(true, ""); - } + /** + * build success resp + * + * @return + */ + public static CommonResponse buildSuccessResponse() { + return new CommonResponse(true, ""); + } - /** - * build success resp - * @return - */ - public static CommonResponse buildSuccessResponse(String msg) { - return new CommonResponse(true, msg); - } + /** + * build success resp + * + * @return + */ + public static CommonResponse buildSuccessResponse(String msg) { + return new CommonResponse(true, msg); + } - /** - * build fail resp - * @param msg - * @return - */ - public static CommonResponse buildFailedResponse(String msg) { - return new CommonResponse(false, msg); - } + /** + * build fail resp + * + * @param msg + * @return + */ + public static CommonResponse buildFailedResponse(String msg) { + return new CommonResponse(false, msg); + } - /** - * Getter method for property success. - * - * @return property value of success - */ - public boolean isSuccess() { - return success; - } + /** + * Getter method for property success. + * + * @return property value of success + */ + public boolean isSuccess() { + return success; + } - /** - * Setter method for property success. - * - * @param success value to be assigned to property success - */ - public void setSuccess(boolean success) { - this.success = success; - } + /** + * Setter method for property success. + * + * @param success value to be assigned to property success + */ + public void setSuccess(boolean success) { + this.success = success; + } - /** - * Getter method for property message. - * - * @return property value of message - */ - public String getMessage() { - return message; - } + /** + * Getter method for property message. + * + * @return property value of message + */ + public String getMessage() { + return message; + } - /** - * Setter method for property message. - * - * @param message value to be assigned to property message - */ - public void setMessage(String message) { - this.message = message; - } + /** + * Setter method for property message. + * + * @param message value to be assigned to property message + */ + public void setMessage(String message) { + this.message = message; + } - /** - * @see Object#toString() - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("CommonResponse{"); - sb.append("success=").append(success); - sb.append(", message='").append(message).append('\''); - sb.append('}'); - return sb.toString(); - } -} \ No newline at end of file + /** @see Object#toString() */ + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("CommonResponse{"); + sb.append("success=").append(success); + sb.append(", message='").append(message).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ConnectId.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ConnectId.java index 4f0c90a42..c52adc41e 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ConnectId.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ConnectId.java @@ -20,117 +20,128 @@ import com.alipay.sofa.registry.common.model.store.URL; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; - import java.io.Serializable; -import java.net.InetAddress; import java.net.InetSocketAddress; import java.util.Objects; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-02 21:32 yuzhi.lyz Exp $ */ public final class ConnectId implements Serializable { - private final String clientHostAddress; - private final int clientPort; - private final String sessionHostAddress; - private final int sessionPort; - - @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) - public ConnectId(@JsonProperty("clientHostAddress") String clientHostAddress, - @JsonProperty("clientPort") int clientPort, - @JsonProperty("sessionHostAddress") String sessionHostAddress, - @JsonProperty("sessionPort") int sessionPort) { - this.clientHostAddress = clientHostAddress; - this.clientPort = clientPort; - this.sessionHostAddress = sessionHostAddress; - this.sessionPort = sessionPort; - } - - public static ConnectId of(String clientAddress, String sessionAddress) { - URL clientURL = URL.valueOf(clientAddress); - URL sessionURL = URL.valueOf(sessionAddress); - return new ConnectId(clientURL.getIpAddress(), clientURL.getPort(), - sessionURL.getIpAddress(), sessionURL.getPort()); - } - - public static ConnectId of(InetSocketAddress clientAddress, InetSocketAddress sessionAddress) { - return new ConnectId(clientAddress.getAddress().getHostAddress(), clientAddress.getPort(), - sessionAddress.getAddress().getHostAddress(), sessionAddress.getPort()); - } - - public static ConnectId parse(String str) { - String[] strs = str.split(ValueConstants.CONNECT_ID_SPLIT); - if (strs.length != 2) { - throw new IllegalArgumentException("unknow format of ConnectId:" + str); - } - return of(strs[0], strs[1]); - } - - /** - * Getter method for property clientAddress. - * @return property value of clientAddress - */ - public String getClientHostAddress() { - return clientHostAddress; - } - - /** - * Getter method for property clientPort. - * @return property value of clientPort - */ - public int getClientPort() { - return clientPort; - } - - /** - * Getter method for property sessionAddress. - * @return property value of sessionAddress - */ - public String getSessionHostAddress() { - return sessionHostAddress; - } - - /** - * Getter method for property sessionPort. - * @return property value of sessionPort - */ - public int getSessionPort() { - return sessionPort; - } - - public String clientAddress() { - return clientHostAddress + URL.COLON + clientPort; - } - - public String sessionAddress() { - return sessionHostAddress + URL.COLON + sessionPort; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof ConnectId)) - return false; - ConnectId connectId = (ConnectId) o; - return clientPort == connectId.clientPort && sessionPort == connectId.sessionPort - && Objects.equals(clientHostAddress, connectId.clientHostAddress) - && Objects.equals(sessionHostAddress, connectId.sessionHostAddress); - } - - @Override - public int hashCode() { - return Objects.hash(clientHostAddress, clientPort, sessionHostAddress, sessionPort); - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(64); - sb.append(clientHostAddress).append(URL.COLON).append(clientPort) - .append(ValueConstants.CONNECT_ID_SPLIT).append(sessionHostAddress).append(URL.COLON) - .append(sessionPort); - return sb.toString(); + private final String clientHostAddress; + private final int clientPort; + private final String sessionHostAddress; + private final int sessionPort; + + @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) + public ConnectId( + @JsonProperty("clientHostAddress") String clientHostAddress, + @JsonProperty("clientPort") int clientPort, + @JsonProperty("sessionHostAddress") String sessionHostAddress, + @JsonProperty("sessionPort") int sessionPort) { + this.clientHostAddress = clientHostAddress; + this.clientPort = clientPort; + this.sessionHostAddress = sessionHostAddress; + this.sessionPort = sessionPort; + } + + public static ConnectId of(String clientAddress, String sessionAddress) { + URL clientURL = URL.valueOf(clientAddress); + URL sessionURL = URL.valueOf(sessionAddress); + return new ConnectId( + clientURL.getIpAddress(), + clientURL.getPort(), + sessionURL.getIpAddress(), + sessionURL.getPort()); + } + + public static ConnectId of(InetSocketAddress clientAddress, InetSocketAddress sessionAddress) { + return new ConnectId( + clientAddress.getAddress().getHostAddress(), + clientAddress.getPort(), + sessionAddress.getAddress().getHostAddress(), + sessionAddress.getPort()); + } + + public static ConnectId parse(String str) { + String[] strs = str.split(ValueConstants.CONNECT_ID_SPLIT); + if (strs.length != 2) { + throw new IllegalArgumentException("unknow format of ConnectId:" + str); } + return of(strs[0], strs[1]); + } + + /** + * Getter method for property clientAddress. + * + * @return property value of clientAddress + */ + public String getClientHostAddress() { + return clientHostAddress; + } + + /** + * Getter method for property clientPort. + * + * @return property value of clientPort + */ + public int getClientPort() { + return clientPort; + } + + /** + * Getter method for property sessionAddress. + * + * @return property value of sessionAddress + */ + public String getSessionHostAddress() { + return sessionHostAddress; + } + + /** + * Getter method for property sessionPort. + * + * @return property value of sessionPort + */ + public int getSessionPort() { + return sessionPort; + } + + public String clientAddress() { + return clientHostAddress + URL.COLON + clientPort; + } + + public String sessionAddress() { + return sessionHostAddress + URL.COLON + sessionPort; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ConnectId)) return false; + ConnectId connectId = (ConnectId) o; + return clientPort == connectId.clientPort + && sessionPort == connectId.sessionPort + && Objects.equals(clientHostAddress, connectId.clientHostAddress) + && Objects.equals(sessionHostAddress, connectId.sessionHostAddress); + } + + @Override + public int hashCode() { + return Objects.hash(clientHostAddress, clientPort, sessionHostAddress, sessionPort); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(64); + sb.append(clientHostAddress) + .append(URL.COLON) + .append(clientPort) + .append(ValueConstants.CONNECT_ID_SPLIT) + .append(sessionHostAddress) + .append(URL.COLON) + .append(sessionPort); + return sb.toString(); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/DataUtils.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/DataUtils.java index f374e2726..c08fa8f41 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/DataUtils.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/DataUtils.java @@ -18,45 +18,46 @@ import com.alipay.sofa.registry.common.model.store.BaseInfo; import com.google.common.collect.Maps; -import org.apache.commons.lang.StringUtils; - import java.util.Collection; import java.util.Map; +import org.apache.commons.lang.StringUtils; public final class DataUtils { - private DataUtils() { - } + private DataUtils() {} - public static Map>> countGroupByInstanceIdGroupApp(Collection infos) { - // instanceId/group/app - > count - Map>> counts = Maps.newHashMap(); - for (T info : infos) { - Map> groupCount = counts.computeIfAbsent( - info.getInstanceId(), k -> Maps.newHashMap()); - Map appCount = groupCount.computeIfAbsent(info.getGroup(), - k -> Maps.newHashMap()); - String appName = info.getAppName(); - if (StringUtils.isBlank(appName)) { - appName = ""; - } - Integer count = appCount.getOrDefault(appName, 0); - count++; - appCount.put(appName, count); - } - return counts; + public static + Map>> countGroupByInstanceIdGroupApp( + Collection infos) { + // instanceId/group/app - > count + Map>> counts = Maps.newHashMap(); + for (T info : infos) { + Map> groupCount = + counts.computeIfAbsent(info.getInstanceId(), k -> Maps.newHashMap()); + Map appCount = + groupCount.computeIfAbsent(info.getGroup(), k -> Maps.newHashMap()); + String appName = info.getAppName(); + if (StringUtils.isBlank(appName)) { + appName = ""; + } + Integer count = appCount.getOrDefault(appName, 0); + count++; + appCount.put(appName, count); } + return counts; + } - public static Map> countGroupByInstanceIdGroup(Collection infos) { - // instanceId/group - > count - Map> counts = Maps.newHashMap(); - for (T info : infos) { - Map groupCount = counts.computeIfAbsent( - info.getInstanceId(), k -> Maps.newHashMap()); - Integer count = groupCount.getOrDefault(info.getGroup(), 0); - count++; - groupCount.put(info.getGroup(), count); - } - return counts; + public static Map> countGroupByInstanceIdGroup( + Collection infos) { + // instanceId/group - > count + Map> counts = Maps.newHashMap(); + for (T info : infos) { + Map groupCount = + counts.computeIfAbsent(info.getInstanceId(), k -> Maps.newHashMap()); + Integer count = groupCount.getOrDefault(info.getGroup(), 0); + count++; + groupCount.put(info.getGroup(), count); } + return counts; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ElementType.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ElementType.java index 69adfbcdf..4587b1d31 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ElementType.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ElementType.java @@ -17,20 +17,15 @@ package com.alipay.sofa.registry.common.model; /** - * * @author shangyu.wh * @version $Id: ElementType.java, v 0.1 2018-08-17 16:22 shangyu.wh Exp $ */ public enum ElementType { - /** - * sub zone scope,@see DefaultSubscriber - */ - SUBSCRIBER, - /** - * multiple zone sub,@see DefaultSubscriberMulti - */ - MULTISUBSCRIBER, - /** */ - PUBLISHER -} \ No newline at end of file + /** sub zone scope,@see DefaultSubscriber */ + SUBSCRIBER, + /** multiple zone sub,@see DefaultSubscriberMulti */ + MULTISUBSCRIBER, + /** */ + PUBLISHER +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/GenericResponse.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/GenericResponse.java index 8494468e5..61b6d663e 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/GenericResponse.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/GenericResponse.java @@ -24,48 +24,50 @@ */ public class GenericResponse extends CommonResponse { - private static final long serialVersionUID = -3986568405174281303L; + private static final long serialVersionUID = -3986568405174281303L; - private T data; + private T data; - /** - * get success response - * @param data - * @return - */ - public GenericResponse fillSucceed(T data) { - this.setSuccess(true); - this.setData(data); - return this; - } + /** + * get success response + * + * @param data + * @return + */ + public GenericResponse fillSucceed(T data) { + this.setSuccess(true); + this.setData(data); + return this; + } - /** - * get fail response - * @param msg - * @return - */ - public GenericResponse fillFailed(String msg) { - this.setSuccess(false); - this.setMessage(msg); - return this; - } + /** + * get fail response + * + * @param msg + * @return + */ + public GenericResponse fillFailed(String msg) { + this.setSuccess(false); + this.setMessage(msg); + return this; + } - /** - * Getter method for property data. - * - * @return property value of data - */ - public T getData() { - return data; - } + /** + * Getter method for property data. + * + * @return property value of data + */ + public T getData() { + return data; + } - /** - * Setter method for property data. - * - * @param data value to be assigned to property data - */ - public GenericResponse setData(T data) { - this.data = data; - return this; - } -} \ No newline at end of file + /** + * Setter method for property data. + * + * @param data value to be assigned to property data + */ + public GenericResponse setData(T data) { + this.data = data; + return this; + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/IPPort.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/IPPort.java index 19ff4b84e..c276b1274 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/IPPort.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/IPPort.java @@ -17,63 +17,61 @@ package com.alipay.sofa.registry.common.model; import com.alipay.sofa.registry.util.ParaCheckUtil; - import java.io.Serializable; import java.util.Objects; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-21 11:14 yuzhi.lyz Exp $ */ public final class IPPort implements Serializable { - private final String ip; - private final int port; + private final String ip; + private final int port; - private IPPort(String ip, int port) { - this.ip = ip; - this.port = port; - } + private IPPort(String ip, int port) { + this.ip = ip; + this.port = port; + } - /** - * Getter method for property ip. - * @return property value of ip - */ - public String getIp() { - return ip; - } + /** + * Getter method for property ip. + * + * @return property value of ip + */ + public String getIp() { + return ip; + } - /** - * Getter method for property port. - * @return property value of port - */ - public int getPort() { - return port; - } + /** + * Getter method for property port. + * + * @return property value of port + */ + public int getPort() { + return port; + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof IPPort)) - return false; - IPPort ipPort = (IPPort) o; - return port == ipPort.port && Objects.equals(ip, ipPort.ip); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof IPPort)) return false; + IPPort ipPort = (IPPort) o; + return port == ipPort.port && Objects.equals(ip, ipPort.ip); + } - @Override - public int hashCode() { - return Objects.hash(ip, port); - } + @Override + public int hashCode() { + return Objects.hash(ip, port); + } - @Override - public String toString() { - return ip + ":" + port; - } + @Override + public String toString() { + return ip + ":" + port; + } - public static IPPort of(String ip, int port) { - ParaCheckUtil.checkNotBlank(ip, "ip"); - ParaCheckUtil.checkIsPositive(port, "port"); - return new IPPort(ip, port); - } + public static IPPort of(String ip, int port) { + ParaCheckUtil.checkNotBlank(ip, "ip"); + ParaCheckUtil.checkIsPositive(port, "port"); + return new IPPort(ip, port); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Node.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Node.java index b0bdec8a1..d47a482c6 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Node.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Node.java @@ -17,32 +17,34 @@ package com.alipay.sofa.registry.common.model; import com.alipay.sofa.registry.common.model.store.URL; - import java.io.Serializable; /** - * * @author shangyu.wh * @version $Id: node.java, v 0.1 2017-11-28 11:59 shangyu.wh Exp $ */ public interface Node extends Serializable { - /** - * node type enum - */ - enum NodeType { - CLIENT, SESSION, META, DATA, CONSOLE - } + /** node type enum */ + enum NodeType { + CLIENT, + SESSION, + META, + DATA, + CONSOLE + } - /** - * get node type - * @return - */ - NodeType getNodeType(); + /** + * get node type + * + * @return + */ + NodeType getNodeType(); - /** - * get node url - * @return - */ - URL getNodeUrl(); -} \ No newline at end of file + /** + * get node url + * + * @return + */ + URL getNodeUrl(); +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ProcessId.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ProcessId.java index f7c6470ff..5fb79c88e 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ProcessId.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ProcessId.java @@ -20,75 +20,84 @@ import java.util.Objects; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-30 10:44 yuzhi.lyz Exp $ */ public final class ProcessId implements Serializable { - private final String hostAddress; - private final long timestamp; - private final int pid; - private final int rand; + private final String hostAddress; + private final long timestamp; + private final int pid; + private final int rand; - public ProcessId(String hostAddress, long timestamp, int pid, int rand) { - this.hostAddress = hostAddress; - this.timestamp = timestamp; - this.pid = pid; - this.rand = rand; - } + public ProcessId(String hostAddress, long timestamp, int pid, int rand) { + this.hostAddress = hostAddress; + this.timestamp = timestamp; + this.pid = pid; + this.rand = rand; + } - /** - * Getter method for property address. - * @return property value of address - */ - public String getHostAddress() { - return hostAddress; - } + /** + * Getter method for property address. + * + * @return property value of address + */ + public String getHostAddress() { + return hostAddress; + } - /** - * Getter method for property timestamp. - * @return property value of timestamp - */ - public long getTimestamp() { - return timestamp; - } + /** + * Getter method for property timestamp. + * + * @return property value of timestamp + */ + public long getTimestamp() { + return timestamp; + } - /** - * Getter method for property pid. - * @return property value of pid - */ - public int getPid() { - return pid; - } + /** + * Getter method for property pid. + * + * @return property value of pid + */ + public int getPid() { + return pid; + } - /** - * Getter method for property rand. - * @return property value of rand - */ - public int getRand() { - return rand; - } + /** + * Getter method for property rand. + * + * @return property value of rand + */ + public int getRand() { + return rand; + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof ProcessId)) - return false; - ProcessId processId = (ProcessId) o; - return timestamp == processId.timestamp && pid == processId.pid && rand == processId.rand - && Objects.equals(hostAddress, processId.hostAddress); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof ProcessId)) return false; + ProcessId processId = (ProcessId) o; + return timestamp == processId.timestamp + && pid == processId.pid + && rand == processId.rand + && Objects.equals(hostAddress, processId.hostAddress); + } - @Override - public int hashCode() { - return Objects.hash(hostAddress, timestamp, pid, rand); - } + @Override + public int hashCode() { + return Objects.hash(hostAddress, timestamp, pid, rand); + } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(64); - return sb.append(hostAddress).append('-').append(pid).append('-').append(timestamp) - .append('-').append(rand).toString(); - } + @Override + public String toString() { + StringBuilder sb = new StringBuilder(64); + return sb.append(hostAddress) + .append('-') + .append(pid) + .append('-') + .append(timestamp) + .append('-') + .append(rand) + .toString(); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublishType.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublishType.java index d32dea92d..e20ca19ba 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublishType.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublishType.java @@ -17,19 +17,13 @@ package com.alipay.sofa.registry.common.model; /** - * * @author shangyu.wh * @version $Id: PublishType.java, v 0.1 2018-08-29 17:11 shangyu.wh Exp $ */ public enum PublishType { - /** - * normally publisher - */ - NORMAL, - /** - * TEMPORARY publisher - */ - TEMPORARY - -} \ No newline at end of file + /** normally publisher */ + NORMAL, + /** TEMPORARY publisher */ + TEMPORARY +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublisherDigestUtil.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublisherDigestUtil.java index 19ce23ebc..e996078c2 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublisherDigestUtil.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublisherDigestUtil.java @@ -16,10 +16,9 @@ */ package com.alipay.sofa.registry.common.model; -import com.alipay.sofa.registry.common.model.dataserver.DatumSummary; import com.alipay.sofa.registry.common.model.dataserver.DatumDigest; +import com.alipay.sofa.registry.common.model.dataserver.DatumSummary; import com.google.common.collect.Maps; - import java.util.*; /** @@ -28,49 +27,49 @@ * @version $Id: PublisherDigestUtil.java, v 0.1 2019-05-30 20:58 shangyu.wh Exp $ */ public final class PublisherDigestUtil { - private PublisherDigestUtil() { - } + private PublisherDigestUtil() {} - public static Map digest(Map summaryMap) { - if (summaryMap.isEmpty()) { - return Collections.emptyMap(); - } - Map> sorted = Maps.newTreeMap(); - for (Map.Entry summaryEntry : summaryMap.entrySet()) { - sorted.put(summaryEntry.getKey(), new TreeMap<>(summaryEntry.getValue() - .getPublisherVersions())); - } + public static Map digest(Map summaryMap) { + if (summaryMap.isEmpty()) { + return Collections.emptyMap(); + } + Map> sorted = Maps.newTreeMap(); + for (Map.Entry summaryEntry : summaryMap.entrySet()) { + sorted.put( + summaryEntry.getKey(), new TreeMap<>(summaryEntry.getValue().getPublisherVersions())); + } - final Map ret = Maps.newHashMapWithExpectedSize(summaryMap.size()); - for (Map.Entry> e : sorted.entrySet()) { - int publisherNum = 0; - long publisherIdSign = 0; - long publisherVerSign = 0; - long publisherTimestampSign = 0; + final Map ret = Maps.newHashMapWithExpectedSize(summaryMap.size()); + for (Map.Entry> e : sorted.entrySet()) { + int publisherNum = 0; + long publisherIdSign = 0; + long publisherVerSign = 0; + long publisherTimestampSign = 0; - final String dataInfoId = e.getKey(); - publisherNum += e.getValue().size(); + final String dataInfoId = e.getKey(); + publisherNum += e.getValue().size(); - for (Map.Entry pub : e.getValue().entrySet()) { - final String registerId = pub.getKey(); - final long digestRegisterId = digest(registerId); - publisherIdSign = publisherIdSign * 31 + digestRegisterId; - final RegisterVersion ver = pub.getValue(); - publisherVerSign = 31 * publisherVerSign + ver.getVersion(); - publisherTimestampSign = 31 * publisherTimestampSign + ver.getRegisterTimestamp(); - } - ret.put(dataInfoId, new DatumDigest(publisherNum, publisherIdSign, publisherVerSign, - publisherTimestampSign)); - } - return ret; + for (Map.Entry pub : e.getValue().entrySet()) { + final String registerId = pub.getKey(); + final long digestRegisterId = digest(registerId); + publisherIdSign = publisherIdSign * 31 + digestRegisterId; + final RegisterVersion ver = pub.getValue(); + publisherVerSign = 31 * publisherVerSign + ver.getVersion(); + publisherTimestampSign = 31 * publisherTimestampSign + ver.getRegisterTimestamp(); + } + ret.put( + dataInfoId, + new DatumDigest(publisherNum, publisherIdSign, publisherVerSign, publisherTimestampSign)); } + return ret; + } - private static int digest(String str) { - // use string.hashCode, it's the fastest. the calc result has cached. - // but must pay attention to the compatibility of different jdk versions - // after jdk1.2, the java doc promise: - // The hash code for a String object is computed as - // s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] - return str.hashCode(); - } -} \ No newline at end of file + private static int digest(String str) { + // use string.hashCode, it's the fastest. the calc result has cached. + // but must pay attention to the compatibility of different jdk versions + // after jdk1.2, the java doc promise: + // The hash code for a String object is computed as + // s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] + return str.hashCode(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublisherUtils.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublisherUtils.java index e83d70403..98e83c480 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublisherUtils.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublisherUtils.java @@ -19,7 +19,6 @@ import com.alipay.sofa.registry.common.model.dataserver.DatumSummary; import com.alipay.sofa.registry.common.model.store.Publisher; import com.google.common.collect.Maps; - import java.util.*; /** @@ -27,34 +26,34 @@ * @version $Id: PublisherUtils.java, v 0.1 2020年11月12日 16:53 xiaojian.xj Exp $ */ public final class PublisherUtils { - private PublisherUtils() { - } + private PublisherUtils() {} - /** - * change publisher word cache - * - * @param publisher - * @return - */ - public static Publisher internPublisher(Publisher publisher) { - publisher.setRegisterId(publisher.getRegisterId()); - publisher.setDataInfoId(publisher.getDataInfoId()); - publisher.setInstanceId(publisher.getInstanceId()); - publisher.setGroup(publisher.getGroup()); - publisher.setDataId(publisher.getDataId()); - publisher.setClientId(publisher.getClientId()); - publisher.setCell(publisher.getCell()); - publisher.setProcessId(publisher.getProcessId()); - publisher.setAppName(publisher.getAppName()); - return publisher; - } + /** + * change publisher word cache + * + * @param publisher + * @return + */ + public static Publisher internPublisher(Publisher publisher) { + publisher.setRegisterId(publisher.getRegisterId()); + publisher.setDataInfoId(publisher.getDataInfoId()); + publisher.setInstanceId(publisher.getInstanceId()); + publisher.setGroup(publisher.getGroup()); + publisher.setDataId(publisher.getDataId()); + publisher.setClientId(publisher.getClientId()); + publisher.setCell(publisher.getCell()); + publisher.setProcessId(publisher.getProcessId()); + publisher.setAppName(publisher.getAppName()); + return publisher; + } - public static Map getDatumSummary(Map> publisherMap) { - Map sourceSummaryMap = Maps.newHashMapWithExpectedSize(publisherMap - .size()); - for (Map.Entry> e : publisherMap.entrySet()) { - sourceSummaryMap.put(e.getKey(), DatumSummary.of(e.getKey(), e.getValue())); - } - return sourceSummaryMap; + public static Map getDatumSummary( + Map> publisherMap) { + Map sourceSummaryMap = + Maps.newHashMapWithExpectedSize(publisherMap.size()); + for (Map.Entry> e : publisherMap.entrySet()) { + sourceSummaryMap.put(e.getKey(), DatumSummary.of(e.getKey(), e.getValue())); } -} \ No newline at end of file + return sourceSummaryMap; + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/RegisterVersion.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/RegisterVersion.java index 7f820b0a7..475d852db 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/RegisterVersion.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/RegisterVersion.java @@ -20,83 +20,86 @@ import java.util.Objects; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-02 21:44 yuzhi.lyz Exp $ */ public final class RegisterVersion implements Serializable, Comparable { - private final long version; - private final long registerTimestamp; + private final long version; + private final long registerTimestamp; - public RegisterVersion(long version, long registerTimestamp) { - this.version = version; - this.registerTimestamp = registerTimestamp; - } + public RegisterVersion(long version, long registerTimestamp) { + this.version = version; + this.registerTimestamp = registerTimestamp; + } - public static RegisterVersion of(long version, long registerTimestamp) { - return new RegisterVersion(version, registerTimestamp); - } + public static RegisterVersion of(long version, long registerTimestamp) { + return new RegisterVersion(version, registerTimestamp); + } - /** - * Getter method for property version. - * @return property value of version - */ - public long getVersion() { - return version; - } + /** + * Getter method for property version. + * + * @return property value of version + */ + public long getVersion() { + return version; + } - /** - * Getter method for property registerTimestamp. - * @return property value of registerTimestamp - */ - public long getRegisterTimestamp() { - return registerTimestamp; - } + /** + * Getter method for property registerTimestamp. + * + * @return property value of registerTimestamp + */ + public long getRegisterTimestamp() { + return registerTimestamp; + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof RegisterVersion)) - return false; - RegisterVersion that = (RegisterVersion) o; - return version == that.version && registerTimestamp == that.registerTimestamp; - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof RegisterVersion)) return false; + RegisterVersion that = (RegisterVersion) o; + return version == that.version && registerTimestamp == that.registerTimestamp; + } - @Override - public int hashCode() { - return Objects.hash(version, registerTimestamp); - } + @Override + public int hashCode() { + return Objects.hash(version, registerTimestamp); + } - @Override - public int compareTo(RegisterVersion o) { - if (version < o.version) { - return -1; - } - if (version > o.version) { - return 1; - } - - if (registerTimestamp < o.registerTimestamp) { - return -1; - } - if (registerTimestamp > o.registerTimestamp) { - return 1; - } - return 0; + @Override + public int compareTo(RegisterVersion o) { + if (version < o.version) { + return -1; } - - public boolean orderThan(RegisterVersion o) { - return compareTo(o) < 0; + if (version > o.version) { + return 1; } - @Override - public String toString() { - return "RegisterVersion{" + "version=" + version + ", registerTimestamp=" - + registerTimestamp + '}'; + if (registerTimestamp < o.registerTimestamp) { + return -1; } - - public RegisterVersion incrRegisterTimestamp() { - return RegisterVersion.of(this.version, this.registerTimestamp + 1); + if (registerTimestamp > o.registerTimestamp) { + return 1; } + return 0; + } + + public boolean orderThan(RegisterVersion o) { + return compareTo(o) < 0; + } + + @Override + public String toString() { + return "RegisterVersion{" + + "version=" + + version + + ", registerTimestamp=" + + registerTimestamp + + '}'; + } + + public RegisterVersion incrRegisterTimestamp() { + return RegisterVersion.of(this.version, this.registerTimestamp + 1); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ServerDataBox.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ServerDataBox.java index 99539f65b..49441d06a 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ServerDataBox.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ServerDataBox.java @@ -16,6 +16,7 @@ */ package com.alipay.sofa.registry.common.model; +import com.fasterxml.jackson.annotation.JsonIgnore; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -23,197 +24,192 @@ import java.io.ObjectOutputStream; import java.io.Serializable; -import com.fasterxml.jackson.annotation.JsonIgnore; - /** - * * @author zhuoyu.sjw * @version $Id: ServerDataBox.java, v 0.1 2018-03-03 17:44 zhuoyu.sjw Exp $$ */ public class ServerDataBox implements Serializable { - /** UID */ - private static final long serialVersionUID = 2817539491173993030L; - /** */ - private static final int SERIALIZED_BY_JAVA = 1; - /** Null for locally instantiated, otherwise for internalized */ - private byte[] bytes; - /** Only available if bytes != null */ - private int serialization; - /** Actual object, lazy deserialized */ - private Object object; - - /** - * Instantiates a new DataBox. - */ - public ServerDataBox() { - } - - /** - * Instantiates a new DataBox. - * - * @param object the object - */ - public ServerDataBox(Object object) { - this.object = object; - } - - /** - * Instantiates a new DataBox. - * - * @param bytes the bytes - */ - public ServerDataBox(byte[] bytes) { - this.bytes = bytes; - this.serialization = SERIALIZED_BY_JAVA; - } - - /** - * Is in bytes boolean. - * - * @return boolean boolean - */ - @JsonIgnore - public boolean isInBytes() { - return bytes != null; - } - - /** - * Only when isInBytes() == false - * @return Object object - */ - public Object getObject() { - return object; - } - - /** - * transfer bytes to object - * @return Object object - * @throws IOException the io exception - * @throws ClassNotFoundException the class not found exception - */ - public Object extract() throws IOException, ClassNotFoundException { - if (object == null && isInBytes()) { - ByteArrayInputStream bis = new ByteArrayInputStream(bytes); - if (serialization != SERIALIZED_BY_JAVA) { - throw new IOException("Unsupported serialization type: " + serialization); - } - ServerDataBoxInputStream input = null; - try { - input = new ServerDataBoxInputStream(bis); - object = input.readObject(); - } finally { - if (input != null) { - input.close(); - } - } + /** UID */ + private static final long serialVersionUID = 2817539491173993030L; + /** */ + private static final int SERIALIZED_BY_JAVA = 1; + /** Null for locally instantiated, otherwise for internalized */ + private byte[] bytes; + /** Only available if bytes != null */ + private int serialization; + /** Actual object, lazy deserialized */ + private Object object; + + /** Instantiates a new DataBox. */ + public ServerDataBox() {} + + /** + * Instantiates a new DataBox. + * + * @param object the object + */ + public ServerDataBox(Object object) { + this.object = object; + } + + /** + * Instantiates a new DataBox. + * + * @param bytes the bytes + */ + public ServerDataBox(byte[] bytes) { + this.bytes = bytes; + this.serialization = SERIALIZED_BY_JAVA; + } + + /** + * Is in bytes boolean. + * + * @return boolean boolean + */ + @JsonIgnore + public boolean isInBytes() { + return bytes != null; + } + + /** + * Only when isInBytes() == false + * + * @return Object object + */ + public Object getObject() { + return object; + } + + /** + * transfer bytes to object + * + * @return Object object + * @throws IOException the io exception + * @throws ClassNotFoundException the class not found exception + */ + public Object extract() throws IOException, ClassNotFoundException { + if (object == null && isInBytes()) { + ByteArrayInputStream bis = new ByteArrayInputStream(bytes); + if (serialization != SERIALIZED_BY_JAVA) { + throw new IOException("Unsupported serialization type: " + serialization); + } + ServerDataBoxInputStream input = null; + try { + input = new ServerDataBoxInputStream(bis); + object = input.readObject(); + } finally { + if (input != null) { + input.close(); } - - return object; + } } - /** - * change object to bytes - * - * @return NSwizzle swizzle - */ - public ServerDataBox object2bytes() { - if (!isInBytes()) { - bytes = getBytes(object); - serialization = SERIALIZED_BY_JAVA; + return object; + } + + /** + * change object to bytes + * + * @return NSwizzle swizzle + */ + public ServerDataBox object2bytes() { + if (!isInBytes()) { + bytes = getBytes(object); + serialization = SERIALIZED_BY_JAVA; + } + return this; + } + + public static byte[] getBytes(Object object) { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream javaos = null; + try { + javaos = new ObjectOutputStream(bos); + javaos.writeObject(object); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } finally { + try { + if (null != javaos) { + javaos.close(); } - return this; + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } } - - public static byte[] getBytes(Object object) { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream javaos = null; + return bos.toByteArray(); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + serialization = in.readByte(); // Read serialization type + int size = in.readInt(); // Read byte stream size + bytes = new byte[size]; + in.readFully(bytes); // Read the byte stream + } + + private void writeObject(ObjectOutputStream out) throws IOException { + if (isInBytes()) { + out.writeByte(serialization); // Write serialization type + out.writeInt(bytes.length); // Write byte stream size + out.write(bytes); // Write the byte stream + } else { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream javaos = new ObjectOutputStream(bos); + try { + javaos.writeObject(object); + } finally { try { - javaos = new ObjectOutputStream(bos); - javaos.writeObject(object); + javaos.close(); } catch (IOException ioe) { - throw new RuntimeException(ioe); - } finally { - try { - if (null != javaos) { - javaos.close(); - } - } catch (IOException ioe) { - throw new RuntimeException(ioe); - } + throw new RuntimeException(ioe); } - return bos.toByteArray(); + } + out.writeByte(SERIALIZED_BY_JAVA); // Write serialization type + out.writeInt(bos.size()); // Write byte stream size + out.write(bos.toByteArray()); // Write the byte stream } - - private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { - serialization = in.readByte(); // Read serialization type - int size = in.readInt(); // Read byte stream size - bytes = new byte[size]; - in.readFully(bytes); // Read the byte stream - } - - private void writeObject(ObjectOutputStream out) throws IOException { - if (isInBytes()) { - out.writeByte(serialization); // Write serialization type - out.writeInt(bytes.length); // Write byte stream size - out.write(bytes); // Write the byte stream - } else { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream javaos = new ObjectOutputStream(bos); - try { - javaos.writeObject(object); - } finally { - try { - javaos.close(); - } catch (IOException ioe) { - throw new RuntimeException(ioe); - } - } - out.writeByte(SERIALIZED_BY_JAVA); // Write serialization type - out.writeInt(bos.size()); // Write byte stream size - out.write(bos.toByteArray()); // Write the byte stream - } - } - - public int byteSize() { - final byte[] b = bytes; - return b != null ? b.length : 0; - } - - /** - * Get bytes byte [ ]. - * - * @return byte[] byte [ ] - */ - public byte[] getBytes() { - return bytes; - } - - /** - * Set bytes byte [ ]. - * - * @return byte[] byte [ ] - */ - public void setBytes(byte[] bytes) { - this.bytes = bytes; - } - - /** - * Gets serialization. - * - * @return int serialization - */ - public int getSerialization() { - return this.serialization; - } - - /** - * Sets serialization. - * - * @param serial the serial - */ - public void setSerialization(int serial) { - this.serialization = serial; - } - + } + + public int byteSize() { + final byte[] b = bytes; + return b != null ? b.length : 0; + } + + /** + * Get bytes byte [ ]. + * + * @return byte[] byte [ ] + */ + public byte[] getBytes() { + return bytes; + } + + /** + * Set bytes byte [ ]. + * + * @return byte[] byte [ ] + */ + public void setBytes(byte[] bytes) { + this.bytes = bytes; + } + + /** + * Gets serialization. + * + * @return int serialization + */ + public int getSerialization() { + return this.serialization; + } + + /** + * Sets serialization. + * + * @param serial the serial + */ + public void setSerialization(int serial) { + this.serialization = serial; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ServerDataBoxInputStream.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ServerDataBoxInputStream.java index 302cf80ef..ced94fe31 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ServerDataBoxInputStream.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/ServerDataBoxInputStream.java @@ -23,33 +23,32 @@ /** * The type DataBox input stream. + * * @author zhuoyu.sjw * @version $Id : ServerDataBoxInputStream.java, v 0.1 2017-11-28 17:48 zhuoyu.sjw Exp $$ */ public class ServerDataBoxInputStream extends ObjectInputStream { - /** - * Instantiates a new DataBox input stream. - * - * @param in the in - * @throws IOException the io exception - */ - public ServerDataBoxInputStream(InputStream in) throws IOException { - super(in); - } + /** + * Instantiates a new DataBox input stream. + * + * @param in the in + * @throws IOException the io exception + */ + public ServerDataBoxInputStream(InputStream in) throws IOException { + super(in); + } - /** - * @see ObjectInputStream#resolveClass(ObjectStreamClass) - */ - @Override - protected Class resolveClass(ObjectStreamClass desc) throws IOException, - ClassNotFoundException { - String name = desc.getName(); - try { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - return Class.forName(name, false, classLoader); - } catch (ClassNotFoundException ex) { - return super.resolveClass(desc); - } + /** @see ObjectInputStream#resolveClass(ObjectStreamClass) */ + @Override + protected Class resolveClass(ObjectStreamClass desc) + throws IOException, ClassNotFoundException { + String name = desc.getName(); + try { + ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + return Class.forName(name, false, classLoader); + } catch (ClassNotFoundException ex) { + return super.resolveClass(desc); } + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/SubscriberUtils.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/SubscriberUtils.java index 4328acde2..ff431f8f7 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/SubscriberUtils.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/SubscriberUtils.java @@ -22,66 +22,67 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; - import java.net.InetSocketAddress; import java.util.*; public final class SubscriberUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(SubscriberUtils.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SubscriberUtils.class); - private SubscriberUtils() { - } + private SubscriberUtils() {} - public static Map> groupBySourceAddress(Collection subscribers) { - if (subscribers.isEmpty()) { - return Collections.emptyMap(); - } - Map> ret = Maps.newHashMap(); - subscribers.forEach(s -> { - InetSocketAddress address = new InetSocketAddress(s.getSourceAddress() - .getIpAddress(), s.getSourceAddress().getPort()); - Map subs = ret.computeIfAbsent(address, k -> Maps.newHashMap()); - subs.put(s.getRegisterId(), s); - }); - return ret; + public static Map> groupBySourceAddress( + Collection subscribers) { + if (subscribers.isEmpty()) { + return Collections.emptyMap(); } + Map> ret = Maps.newHashMap(); + subscribers.forEach( + s -> { + InetSocketAddress address = + new InetSocketAddress( + s.getSourceAddress().getIpAddress(), s.getSourceAddress().getPort()); + Map subs = ret.computeIfAbsent(address, k -> Maps.newHashMap()); + subs.put(s.getRegisterId(), s); + }); + return ret; + } - public static Map> groupByScope(Collection subscribers) { - if (subscribers.isEmpty()) { - return Collections.emptyMap(); - } - Map> ret = Maps.newHashMap(); - for (Subscriber subscriber : subscribers) { - final ScopeEnum scopeEnum = subscriber.getScope(); - if (scopeEnum == null) { - LOGGER.warn("Nil ScopeEnum, {}", subscriber); - continue; - } - List subList = ret.computeIfAbsent(scopeEnum, k -> Lists.newArrayList()); - subList.add(subscriber); - } - return ret; + public static Map> groupByScope(Collection subscribers) { + if (subscribers.isEmpty()) { + return Collections.emptyMap(); + } + Map> ret = Maps.newHashMap(); + for (Subscriber subscriber : subscribers) { + final ScopeEnum scopeEnum = subscriber.getScope(); + if (scopeEnum == null) { + LOGGER.warn("Nil ScopeEnum, {}", subscriber); + continue; + } + List subList = ret.computeIfAbsent(scopeEnum, k -> Lists.newArrayList()); + subList.add(subscriber); } + return ret; + } - public static ScopeEnum getAndAssertHasSameScope(Collection subscribers) { - ScopeEnum scope = subscribers.stream().findFirst().get().getScope(); - for (Subscriber subscriber : subscribers) { - if (scope != subscriber.getScope()) { - throw new RuntimeException(String.format("conflict scope, first={}, one is {}", - scope, subscriber)); - } - } - return scope; + public static ScopeEnum getAndAssertHasSameScope(Collection subscribers) { + ScopeEnum scope = subscribers.stream().findFirst().get().getScope(); + for (Subscriber subscriber : subscribers) { + if (scope != subscriber.getScope()) { + throw new RuntimeException( + String.format("conflict scope, first={}, one is {}", scope, subscriber)); + } } + return scope; + } - public static long getMaxPushedVersion(String dataCenter, Collection subscribers) { - long max = 0; - for (Subscriber sub : subscribers) { - long v = sub.getPushVersion(dataCenter); - if (max < v) { - max = v; - } - } - return max; + public static long getMaxPushedVersion(String dataCenter, Collection subscribers) { + long max = 0; + for (Subscriber sub : subscribers) { + long v = sub.getPushVersion(dataCenter); + if (max < v) { + max = v; + } } + return max; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Triple.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Triple.java index 112ae1555..858bddb47 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Triple.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Triple.java @@ -20,61 +20,59 @@ /** * @author chen.zhu - *

- * Jan 12, 2021 + *

Jan 12, 2021 */ public final class Triple { - private final F first; + private final F first; - private final M middle; + private final M middle; - private final L last; + private final L last; - public Triple(F first, M middle, L last) { - this.first = first; - this.middle = middle; - this.last = last; - } + public Triple(F first, M middle, L last) { + this.first = first; + this.middle = middle; + this.last = last; + } - public static Triple from(F first, M middle, L last) { - return new Triple(first, middle, last); - } + public static Triple from(F first, M middle, L last) { + return new Triple(first, middle, last); + } - public F getFirst() { - return this.first; - } + public F getFirst() { + return this.first; + } - public L getLast() { - return this.last; - } + public L getLast() { + return this.last; + } - public M getMiddle() { - return this.middle; - } + public M getMiddle() { + return this.middle; + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - Triple triple = (Triple) o; - return Objects.equals(first, triple.first) && Objects.equals(middle, triple.middle) - && Objects.equals(last, triple.last); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Triple triple = (Triple) o; + return Objects.equals(first, triple.first) + && Objects.equals(middle, triple.middle) + && Objects.equals(last, triple.last); + } - @Override - public int hashCode() { - return Objects.hash(first, middle, last); - } + @Override + public int hashCode() { + return Objects.hash(first, middle, last); + } - public int size() { - return 3; - } + public int size() { + return 3; + } - public String toString() { - return String.format("Triple[first=%s, middle=%s, last=%s]", this.first, this.middle, - this.last); - } + public String toString() { + return String.format( + "Triple[first=%s, middle=%s, last=%s]", this.first, this.middle, this.last); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Tuple.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Tuple.java index cf1048baf..281b2dcf2 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Tuple.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/Tuple.java @@ -19,48 +19,45 @@ import java.util.Objects; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-15 10:28 yuzhi.lyz Exp $ */ public final class Tuple { - public final T1 o1; - public final T2 o2; - - public Tuple(T1 o1, T2 o2) { - this.o1 = o1; - this.o2 = o2; - } - - public static Tuple of(T1 t1, T2 t2) { - return new Tuple<>(t1, t2); - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof Tuple)) - return false; - Tuple tuple = (Tuple) o; - return Objects.equals(o1, tuple.o1) && Objects.equals(o2, tuple.o2); - } - - public T1 getFirst() { - return o1; - } - - public T2 getSecond() { - return o2; - } - - @Override - public int hashCode() { - return Objects.hash(o1, o2); - } - - @Override - public String toString() { - return "Tuple{" + "o1=" + o1 + ", o2=" + o2 + '}'; - } + public final T1 o1; + public final T2 o2; + + public Tuple(T1 o1, T2 o2) { + this.o1 = o1; + this.o2 = o2; + } + + public static Tuple of(T1 t1, T2 t2) { + return new Tuple<>(t1, t2); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Tuple)) return false; + Tuple tuple = (Tuple) o; + return Objects.equals(o1, tuple.o1) && Objects.equals(o2, tuple.o2); + } + + public T1 getFirst() { + return o1; + } + + public T2 getSecond() { + return o2; + } + + @Override + public int hashCode() { + return Objects.hash(o1, o2); + } + + @Override + public String toString() { + return "Tuple{" + "o1=" + o1 + ", o2=" + o2 + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/appmeta/InterfaceMapping.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/appmeta/InterfaceMapping.java index fb8496f95..28dbe9bbe 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/appmeta/InterfaceMapping.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/appmeta/InterfaceMapping.java @@ -17,45 +17,44 @@ package com.alipay.sofa.registry.common.model.appmeta; import com.google.common.collect.Sets; - import java.util.Collections; import java.util.Set; public final class InterfaceMapping { - private final long nanosVersion; - private final Set apps; - - public InterfaceMapping(long nanosVersion) { - this.nanosVersion = nanosVersion; - this.apps = Collections.EMPTY_SET; - } - - public InterfaceMapping(long nanosVersion, String app) { - this.nanosVersion = nanosVersion; - this.apps = Sets.newHashSet(app); - } - - public InterfaceMapping(long nanosVersion, Set apps) { - this.nanosVersion = nanosVersion; - this.apps = Sets.newHashSet(apps); - } - - public InterfaceMapping(long nanosVersion, Set copyApp, String newApp) { - this.nanosVersion = nanosVersion; - this.apps = Sets.newHashSet(copyApp); - this.apps.add(newApp); - } - - public long getNanosVersion() { - return nanosVersion; - } - - public Set getApps() { - return Collections.unmodifiableSet(apps); - } - - @Override - public String toString() { - return "InterfaceMapping{" + "nanosVersion=" + nanosVersion + ", appSets=" + apps + '}'; - } + private final long nanosVersion; + private final Set apps; + + public InterfaceMapping(long nanosVersion) { + this.nanosVersion = nanosVersion; + this.apps = Collections.EMPTY_SET; + } + + public InterfaceMapping(long nanosVersion, String app) { + this.nanosVersion = nanosVersion; + this.apps = Sets.newHashSet(app); + } + + public InterfaceMapping(long nanosVersion, Set apps) { + this.nanosVersion = nanosVersion; + this.apps = Sets.newHashSet(apps); + } + + public InterfaceMapping(long nanosVersion, Set copyApp, String newApp) { + this.nanosVersion = nanosVersion; + this.apps = Sets.newHashSet(copyApp); + this.apps.add(newApp); + } + + public long getNanosVersion() { + return nanosVersion; + } + + public Set getApps() { + return Collections.unmodifiableSet(apps); + } + + @Override + public String toString() { + return "InterfaceMapping{" + "nanosVersion=" + nanosVersion + ", appSets=" + apps + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppDiscoveryMetaPb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppDiscoveryMetaPb.java index fe295ef06..907deb6bf 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppDiscoveryMetaPb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppDiscoveryMetaPb.java @@ -14,181 +14,235 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class AppDiscoveryMetaPb { - private AppDiscoveryMetaPb() { - } + private AppDiscoveryMetaPb() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor internal_static_MetaRegister_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_MetaRegister_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_MetaRegister_BaseParamsEntry_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_MetaRegister_BaseParamsEntry_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_MetaRegister_ServicesEntry_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_MetaRegister_ServicesEntry_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor internal_static_MetaService_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_MetaService_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_MetaService_ParamsEntry_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_MetaService_ParamsEntry_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor internal_static_StringList_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_StringList_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor internal_static_AppList_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_AppList_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_ServiceAppMappingRequest_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_ServiceAppMappingRequest_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_ServiceAppMappingResponse_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_ServiceAppMappingResponse_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_GetRevisionsRequest_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_GetRevisionsRequest_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_GetRevisionsResponse_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_GetRevisionsResponse_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_GetRevisionsResponse_RevisionsEntry_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_GetRevisionsResponse_RevisionsEntry_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_MetaHeartbeatRequest_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_MetaHeartbeatRequest_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_MetaHeartbeatResponse_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_MetaHeartbeatResponse_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_MetaRegister_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_MetaRegister_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_MetaRegister_BaseParamsEntry_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_MetaRegister_BaseParamsEntry_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_MetaRegister_ServicesEntry_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_MetaRegister_ServicesEntry_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_MetaService_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_MetaService_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_MetaService_ParamsEntry_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_MetaService_ParamsEntry_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_StringList_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_StringList_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_AppList_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_AppList_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_ServiceAppMappingRequest_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ServiceAppMappingRequest_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_ServiceAppMappingResponse_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ServiceAppMappingResponse_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_GetRevisionsRequest_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_GetRevisionsRequest_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_GetRevisionsResponse_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_GetRevisionsResponse_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_GetRevisionsResponse_RevisionsEntry_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_GetRevisionsResponse_RevisionsEntry_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_MetaHeartbeatRequest_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_MetaHeartbeatRequest_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_MetaHeartbeatResponse_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_MetaHeartbeatResponse_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\030AppDiscoveryMetaPb.proto\"\255\002\n\014MetaRegis" - + "ter\022\023\n\013application\030\001 \001(\t\022\020\n\010revision\030\002 \001" - + "(\t\022\025\n\rclientVersion\030\003 \001(\t\0221\n\nbaseParams\030" - + "\004 \003(\0132\035.MetaRegister.BaseParamsEntry\022-\n\010" - + "services\030\005 \003(\0132\033.MetaRegister.ServicesEn" - + "try\032>\n\017BaseParamsEntry\022\013\n\003key\030\001 \001(\t\022\032\n\005v" - + "alue\030\002 \001(\0132\013.StringList:\0028\001\032=\n\rServicesE" - + "ntry\022\013\n\003key\030\001 \001(\t\022\033\n\005value\030\002 \001(\0132\014.MetaS" - + "ervice:\0028\001\"\222\001\n\013MetaService\022\n\n\002id\030\001 \001(\t\022\021" - + "\n\tserviceId\030\002 \001(\t\022(\n\006params\030\003 \003(\0132\030.Meta" - + "Service.ParamsEntry\032:\n\013ParamsEntry\022\013\n\003ke" - + "y\030\001 \001(\t\022\032\n\005value\030\002 \001(\0132\013.StringList:\0028\001\"" - + "\034\n\nStringList\022\016\n\006values\030\001 \003(\t\"(\n\007AppList" - + "\022\017\n\007version\030\001 \001(\003\022\014\n\004apps\030\002 \003(\t\".\n\030Servi" - + "ceAppMappingRequest\022\022\n\nserviceIds\030\001 \003(\t\"" - + "\322\001\n\031ServiceAppMappingResponse\022L\n\021service" - + "AppMapping\030\001 \003(\01321.ServiceAppMappingResp" - + "onse.ServiceAppMappingEntry\022\022\n\nstatusCod" - + "e\030\002 \001(\005\022\017\n\007message\030\003 \001(\t\032B\n\026ServiceAppMa" - + "ppingEntry\022\013\n\003key\030\001 \001(\t\022\027\n\005value\030\002 \001(\0132\010" - + ".AppList:\0028\001\"(\n\023GetRevisionsRequest\022\021\n\tr" - + "evisions\030\001 \003(\t\"\265\001\n\024GetRevisionsResponse\022" - + "7\n\trevisions\030\001 \003(\0132$.GetRevisionsRespons" - + "e.RevisionsEntry\022\022\n\nstatusCode\030\002 \001(\005\022\017\n\007" - + "message\030\003 \001(\t\032?\n\016RevisionsEntry\022\013\n\003key\030\001" - + " \001(\t\022\034\n\005value\030\002 \001(\0132\r.MetaRegister:\0028\001\")" - + "\n\024MetaHeartbeatRequest\022\021\n\trevisions\030\001 \003(" - + "\t\"<\n\025MetaHeartbeatResponse\022\022\n\nstatusCode" - + "\030\001 \001(\005\022\017\n\007message\030\002 \001(\tB:\n/com.alipay.so" - + "fa.registry.common.model.client.pbP\001Z\005pr" - + "otob\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{}, - assigner); - internal_static_MetaRegister_descriptor = getDescriptor() - .getMessageTypes().get(0); - internal_static_MetaRegister_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_MetaRegister_descriptor, - new java.lang.String[]{"Application", "Revision", - "ClientVersion", "BaseParams", "Services",}); - internal_static_MetaRegister_BaseParamsEntry_descriptor = internal_static_MetaRegister_descriptor - .getNestedTypes().get(0); - internal_static_MetaRegister_BaseParamsEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_MetaRegister_BaseParamsEntry_descriptor, - new java.lang.String[]{"Key", "Value",}); - internal_static_MetaRegister_ServicesEntry_descriptor = internal_static_MetaRegister_descriptor - .getNestedTypes().get(1); - internal_static_MetaRegister_ServicesEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_MetaRegister_ServicesEntry_descriptor, - new java.lang.String[]{"Key", "Value",}); - internal_static_MetaService_descriptor = getDescriptor() - .getMessageTypes().get(1); - internal_static_MetaService_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_MetaService_descriptor, new java.lang.String[]{ - "Id", "ServiceId", "Params",}); - internal_static_MetaService_ParamsEntry_descriptor = internal_static_MetaService_descriptor - .getNestedTypes().get(0); - internal_static_MetaService_ParamsEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_MetaService_ParamsEntry_descriptor, - new java.lang.String[]{"Key", "Value",}); - internal_static_StringList_descriptor = getDescriptor() - .getMessageTypes().get(2); - internal_static_StringList_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_StringList_descriptor, - new java.lang.String[]{"Values",}); - internal_static_AppList_descriptor = getDescriptor().getMessageTypes() - .get(3); - internal_static_AppList_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_AppList_descriptor, new java.lang.String[]{ - "Version", "Apps",}); - internal_static_ServiceAppMappingRequest_descriptor = getDescriptor() - .getMessageTypes().get(4); - internal_static_ServiceAppMappingRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_ServiceAppMappingRequest_descriptor, - new java.lang.String[]{"ServiceIds",}); - internal_static_ServiceAppMappingResponse_descriptor = getDescriptor() - .getMessageTypes().get(5); - internal_static_ServiceAppMappingResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_ServiceAppMappingResponse_descriptor, - new java.lang.String[]{"ServiceAppMapping", "StatusCode", - "Message",}); - internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_descriptor = internal_static_ServiceAppMappingResponse_descriptor - .getNestedTypes().get(0); - internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_descriptor, - new java.lang.String[]{"Key", "Value",}); - internal_static_GetRevisionsRequest_descriptor = getDescriptor() - .getMessageTypes().get(6); - internal_static_GetRevisionsRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_GetRevisionsRequest_descriptor, - new java.lang.String[]{"Revisions",}); - internal_static_GetRevisionsResponse_descriptor = getDescriptor() - .getMessageTypes().get(7); - internal_static_GetRevisionsResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_GetRevisionsResponse_descriptor, - new java.lang.String[]{"Revisions", "StatusCode", "Message",}); - internal_static_GetRevisionsResponse_RevisionsEntry_descriptor = internal_static_GetRevisionsResponse_descriptor - .getNestedTypes().get(0); - internal_static_GetRevisionsResponse_RevisionsEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_GetRevisionsResponse_RevisionsEntry_descriptor, - new java.lang.String[]{"Key", "Value",}); - internal_static_MetaHeartbeatRequest_descriptor = getDescriptor() - .getMessageTypes().get(8); - internal_static_MetaHeartbeatRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_MetaHeartbeatRequest_descriptor, - new java.lang.String[]{"Revisions",}); - internal_static_MetaHeartbeatResponse_descriptor = getDescriptor() - .getMessageTypes().get(9); - internal_static_MetaHeartbeatResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_MetaHeartbeatResponse_descriptor, - new java.lang.String[]{"StatusCode", "Message",}); - } + static { + java.lang.String[] descriptorData = { + "\n\030AppDiscoveryMetaPb.proto\"\255\002\n\014MetaRegis" + + "ter\022\023\n\013application\030\001 \001(\t\022\020\n\010revision\030\002 \001" + + "(\t\022\025\n\rclientVersion\030\003 \001(\t\0221\n\nbaseParams\030" + + "\004 \003(\0132\035.MetaRegister.BaseParamsEntry\022-\n\010" + + "services\030\005 \003(\0132\033.MetaRegister.ServicesEn" + + "try\032>\n\017BaseParamsEntry\022\013\n\003key\030\001 \001(\t\022\032\n\005v" + + "alue\030\002 \001(\0132\013.StringList:\0028\001\032=\n\rServicesE" + + "ntry\022\013\n\003key\030\001 \001(\t\022\033\n\005value\030\002 \001(\0132\014.MetaS" + + "ervice:\0028\001\"\222\001\n\013MetaService\022\n\n\002id\030\001 \001(\t\022\021" + + "\n\tserviceId\030\002 \001(\t\022(\n\006params\030\003 \003(\0132\030.Meta" + + "Service.ParamsEntry\032:\n\013ParamsEntry\022\013\n\003ke" + + "y\030\001 \001(\t\022\032\n\005value\030\002 \001(\0132\013.StringList:\0028\001\"" + + "\034\n\nStringList\022\016\n\006values\030\001 \003(\t\"(\n\007AppList" + + "\022\017\n\007version\030\001 \001(\003\022\014\n\004apps\030\002 \003(\t\".\n\030Servi" + + "ceAppMappingRequest\022\022\n\nserviceIds\030\001 \003(\t\"" + + "\322\001\n\031ServiceAppMappingResponse\022L\n\021service" + + "AppMapping\030\001 \003(\01321.ServiceAppMappingResp" + + "onse.ServiceAppMappingEntry\022\022\n\nstatusCod" + + "e\030\002 \001(\005\022\017\n\007message\030\003 \001(\t\032B\n\026ServiceAppMa" + + "ppingEntry\022\013\n\003key\030\001 \001(\t\022\027\n\005value\030\002 \001(\0132\010" + + ".AppList:\0028\001\"(\n\023GetRevisionsRequest\022\021\n\tr" + + "evisions\030\001 \003(\t\"\265\001\n\024GetRevisionsResponse\022" + + "7\n\trevisions\030\001 \003(\0132$.GetRevisionsRespons" + + "e.RevisionsEntry\022\022\n\nstatusCode\030\002 \001(\005\022\017\n\007" + + "message\030\003 \001(\t\032?\n\016RevisionsEntry\022\013\n\003key\030\001" + + " \001(\t\022\034\n\005value\030\002 \001(\0132\r.MetaRegister:\0028\001\")" + + "\n\024MetaHeartbeatRequest\022\021\n\trevisions\030\001 \003(" + + "\t\"<\n\025MetaHeartbeatResponse\022\022\n\nstatusCode" + + "\030\001 \001(\005\022\017\n\007message\030\002 \001(\tB:\n/com.alipay.so" + + "fa.registry.common.model.client.pbP\001Z\005pr" + + "otob\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_MetaRegister_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_MetaRegister_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_MetaRegister_descriptor, + new java.lang.String[] { + "Application", "Revision", "ClientVersion", "BaseParams", "Services", + }); + internal_static_MetaRegister_BaseParamsEntry_descriptor = + internal_static_MetaRegister_descriptor.getNestedTypes().get(0); + internal_static_MetaRegister_BaseParamsEntry_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_MetaRegister_BaseParamsEntry_descriptor, + new java.lang.String[] { + "Key", "Value", + }); + internal_static_MetaRegister_ServicesEntry_descriptor = + internal_static_MetaRegister_descriptor.getNestedTypes().get(1); + internal_static_MetaRegister_ServicesEntry_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_MetaRegister_ServicesEntry_descriptor, + new java.lang.String[] { + "Key", "Value", + }); + internal_static_MetaService_descriptor = getDescriptor().getMessageTypes().get(1); + internal_static_MetaService_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_MetaService_descriptor, + new java.lang.String[] { + "Id", "ServiceId", "Params", + }); + internal_static_MetaService_ParamsEntry_descriptor = + internal_static_MetaService_descriptor.getNestedTypes().get(0); + internal_static_MetaService_ParamsEntry_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_MetaService_ParamsEntry_descriptor, + new java.lang.String[] { + "Key", "Value", + }); + internal_static_StringList_descriptor = getDescriptor().getMessageTypes().get(2); + internal_static_StringList_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_StringList_descriptor, + new java.lang.String[] { + "Values", + }); + internal_static_AppList_descriptor = getDescriptor().getMessageTypes().get(3); + internal_static_AppList_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_AppList_descriptor, + new java.lang.String[] { + "Version", "Apps", + }); + internal_static_ServiceAppMappingRequest_descriptor = getDescriptor().getMessageTypes().get(4); + internal_static_ServiceAppMappingRequest_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_ServiceAppMappingRequest_descriptor, + new java.lang.String[] { + "ServiceIds", + }); + internal_static_ServiceAppMappingResponse_descriptor = getDescriptor().getMessageTypes().get(5); + internal_static_ServiceAppMappingResponse_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_ServiceAppMappingResponse_descriptor, + new java.lang.String[] { + "ServiceAppMapping", "StatusCode", "Message", + }); + internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_descriptor = + internal_static_ServiceAppMappingResponse_descriptor.getNestedTypes().get(0); + internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_descriptor, + new java.lang.String[] { + "Key", "Value", + }); + internal_static_GetRevisionsRequest_descriptor = getDescriptor().getMessageTypes().get(6); + internal_static_GetRevisionsRequest_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_GetRevisionsRequest_descriptor, + new java.lang.String[] { + "Revisions", + }); + internal_static_GetRevisionsResponse_descriptor = getDescriptor().getMessageTypes().get(7); + internal_static_GetRevisionsResponse_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_GetRevisionsResponse_descriptor, + new java.lang.String[] { + "Revisions", "StatusCode", "Message", + }); + internal_static_GetRevisionsResponse_RevisionsEntry_descriptor = + internal_static_GetRevisionsResponse_descriptor.getNestedTypes().get(0); + internal_static_GetRevisionsResponse_RevisionsEntry_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_GetRevisionsResponse_RevisionsEntry_descriptor, + new java.lang.String[] { + "Key", "Value", + }); + internal_static_MetaHeartbeatRequest_descriptor = getDescriptor().getMessageTypes().get(8); + internal_static_MetaHeartbeatRequest_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_MetaHeartbeatRequest_descriptor, + new java.lang.String[] { + "Revisions", + }); + internal_static_MetaHeartbeatResponse_descriptor = getDescriptor().getMessageTypes().get(9); + internal_static_MetaHeartbeatResponse_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_MetaHeartbeatResponse_descriptor, + new java.lang.String[] { + "StatusCode", "Message", + }); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppList.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppList.java index d321c50d2..f48925b62 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppList.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppList.java @@ -14,637 +14,608 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code AppList} - */ -public final class AppList extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:AppList) - AppListOrBuilder { - private static final long serialVersionUID = 0L; +/** Protobuf type {@code AppList} */ +public final class AppList extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:AppList) + AppListOrBuilder { + private static final long serialVersionUID = 0L; + + // Use AppList.newBuilder() to construct. + private AppList(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private AppList() { + version_ = 0L; + apps_ = com.google.protobuf.LazyStringArrayList.EMPTY; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private AppList( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: + { + version_ = input.readInt64(); + break; + } + case 18: + { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + apps_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000002; + } + apps_.add(s); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + apps_ = apps_.getUnmodifiableView(); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_AppList_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_AppList_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.AppList.class, + com.alipay.sofa.registry.common.model.client.pb.AppList.Builder.class); + } + + private int bitField0_; + public static final int VERSION_FIELD_NUMBER = 1; + private long version_; + + /** int64 version = 1; */ + public long getVersion() { + return version_; + } + + public static final int APPS_FIELD_NUMBER = 2; + private com.google.protobuf.LazyStringList apps_; + + /** repeated string apps = 2; */ + public com.google.protobuf.ProtocolStringList getAppsList() { + return apps_; + } + + /** repeated string apps = 2; */ + public int getAppsCount() { + return apps_.size(); + } + + /** repeated string apps = 2; */ + public java.lang.String getApps(int index) { + return apps_.get(index); + } + + /** repeated string apps = 2; */ + public com.google.protobuf.ByteString getAppsBytes(int index) { + return apps_.getByteString(index); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (version_ != 0L) { + output.writeInt64(1, version_); + } + for (int i = 0; i < apps_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, apps_.getRaw(i)); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (version_ != 0L) { + size += com.google.protobuf.CodedOutputStream.computeInt64Size(1, version_); + } + { + int dataSize = 0; + for (int i = 0; i < apps_.size(); i++) { + dataSize += computeStringSizeNoTag(apps_.getRaw(i)); + } + size += dataSize; + size += 1 * getAppsList().size(); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.AppList)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.AppList other = + (com.alipay.sofa.registry.common.model.client.pb.AppList) obj; + + boolean result = true; + result = result && (getVersion() == other.getVersion()); + result = result && getAppsList().equals(other.getAppsList()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + VERSION_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getVersion()); + if (getAppsCount() > 0) { + hash = (37 * hash) + APPS_FIELD_NUMBER; + hash = (53 * hash) + getAppsList().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.AppList prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code AppList} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:AppList) + com.alipay.sofa.registry.common.model.client.pb.AppListOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_AppList_descriptor; + } - // Use AppList.newBuilder() to construct. - private AppList(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_AppList_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.AppList.class, + com.alipay.sofa.registry.common.model.client.pb.AppList.Builder.class); } - private AppList() { - version_ = 0L; - apps_ = com.google.protobuf.LazyStringArrayList.EMPTY; + // Construct using com.alipay.sofa.registry.common.model.client.pb.AppList.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - private AppList(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 8: { - - version_ = input.readInt64(); - break; - } - case 18: { - java.lang.String s = input.readStringRequireUtf8(); - if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { - apps_ = new com.google.protobuf.LazyStringArrayList(); - mutable_bitField0_ |= 0x00000002; - } - apps_.add(s); - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { - apps_ = apps_.getUnmodifiableView(); - } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_AppList_descriptor; + public Builder clear() { + super.clear(); + version_ = 0L; + + apps_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000002); + return this; } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_AppList_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.AppList.class, - com.alipay.sofa.registry.common.model.client.pb.AppList.Builder.class); + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_AppList_descriptor; } - private int bitField0_; - public static final int VERSION_FIELD_NUMBER = 1; - private long version_; + public com.alipay.sofa.registry.common.model.client.pb.AppList getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.AppList.getDefaultInstance(); + } - /** - * int64 version = 1; - */ - public long getVersion() { - return version_; + public com.alipay.sofa.registry.common.model.client.pb.AppList build() { + com.alipay.sofa.registry.common.model.client.pb.AppList result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public static final int APPS_FIELD_NUMBER = 2; - private com.google.protobuf.LazyStringList apps_; + public com.alipay.sofa.registry.common.model.client.pb.AppList buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.AppList result = + new com.alipay.sofa.registry.common.model.client.pb.AppList(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + result.version_ = version_; + if (((bitField0_ & 0x00000002) == 0x00000002)) { + apps_ = apps_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000002); + } + result.apps_ = apps_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } - /** - * repeated string apps = 2; - */ - public com.google.protobuf.ProtocolStringList getAppsList() { - return apps_; + public Builder clone() { + return (Builder) super.clone(); } - /** - * repeated string apps = 2; - */ - public int getAppsCount() { - return apps_.size(); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - /** - * repeated string apps = 2; - */ - public java.lang.String getApps(int index) { - return apps_.get(index); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - /** - * repeated string apps = 2; - */ - public com.google.protobuf.ByteString getAppsBytes(int index) { - return apps_.getByteString(index); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - private byte memoizedIsInitialized = -1; + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } - memoizedIsInitialized = 1; - return true; + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.AppList) { + return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.AppList) other); + } else { + super.mergeFrom(other); + return this; + } } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (version_ != 0L) { - output.writeInt64(1, version_); - } - for (int i = 0; i < apps_.size(); i++) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, apps_.getRaw(i)); + public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.AppList other) { + if (other == com.alipay.sofa.registry.common.model.client.pb.AppList.getDefaultInstance()) + return this; + if (other.getVersion() != 0L) { + setVersion(other.getVersion()); + } + if (!other.apps_.isEmpty()) { + if (apps_.isEmpty()) { + apps_ = other.apps_; + bitField0_ = (bitField0_ & ~0x00000002); + } else { + ensureAppsIsMutable(); + apps_.addAll(other.apps_); } - unknownFields.writeTo(output); + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; + public final boolean isInitialized() { + return true; + } - size = 0; - if (version_ != 0L) { - size += com.google.protobuf.CodedOutputStream.computeInt64Size(1, version_); - } - { - int dataSize = 0; - for (int i = 0; i < apps_.size(); i++) { - dataSize += computeStringSizeNoTag(apps_.getRaw(i)); - } - size += dataSize; - size += 1 * getAppsList().size(); + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.AppList parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.AppList) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + } + return this; } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.AppList)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.AppList other = (com.alipay.sofa.registry.common.model.client.pb.AppList) obj; + private int bitField0_; - boolean result = true; - result = result && (getVersion() == other.getVersion()); - result = result && getAppsList().equals(other.getAppsList()); - result = result && unknownFields.equals(other.unknownFields); - return result; - } + private long version_; - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + VERSION_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getVersion()); - if (getAppsCount() > 0) { - hash = (37 * hash) + APPS_FIELD_NUMBER; - hash = (53 * hash) + getAppsList().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + /** int64 version = 1; */ + public long getVersion() { + return version_; } - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } + /** int64 version = 1; */ + public Builder setVersion(long value) { - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + version_ = value; + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } + /** int64 version = 1; */ + public Builder clearVersion() { - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + version_ = 0L; + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } + private com.google.protobuf.LazyStringList apps_ = + com.google.protobuf.LazyStringArrayList.EMPTY; - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + private void ensureAppsIsMutable() { + if (!((bitField0_ & 0x00000002) == 0x00000002)) { + apps_ = new com.google.protobuf.LazyStringArrayList(apps_); + bitField0_ |= 0x00000002; + } } - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + /** repeated string apps = 2; */ + public com.google.protobuf.ProtocolStringList getAppsList() { + return apps_.getUnmodifiableView(); } - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + /** repeated string apps = 2; */ + public int getAppsCount() { + return apps_.size(); } - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + /** repeated string apps = 2; */ + public java.lang.String getApps(int index) { + return apps_.get(index); } - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + /** repeated string apps = 2; */ + public com.google.protobuf.ByteString getAppsBytes(int index) { + return apps_.getByteString(index); } - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + /** repeated string apps = 2; */ + public Builder setApps(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureAppsIsMutable(); + apps_.set(index, value); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.AppList parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + /** repeated string apps = 2; */ + public Builder addApps(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureAppsIsMutable(); + apps_.add(value); + onChanged(); + return this; } - public Builder newBuilderForType() { - return newBuilder(); + /** repeated string apps = 2; */ + public Builder addAllApps(java.lang.Iterable values) { + ensureAppsIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, apps_); + onChanged(); + return this; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); + /** repeated string apps = 2; */ + public Builder clearApps() { + apps_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000002); + onChanged(); + return this; } - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.AppList prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + /** repeated string apps = 2; */ + public Builder addAppsBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureAppsIsMutable(); + apps_.add(value); + onChanged(); + return this; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); } - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); } - /** - * Protobuf type {@code AppList} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:AppList) - com.alipay.sofa.registry.common.model.client.pb.AppListOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_AppList_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_AppList_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.AppList.class, - com.alipay.sofa.registry.common.model.client.pb.AppList.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.AppList.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - version_ = 0L; - - apps_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000002); - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_AppList_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.AppList getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.AppList.getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.AppList build() { - com.alipay.sofa.registry.common.model.client.pb.AppList result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.AppList buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.AppList result = new com.alipay.sofa.registry.common.model.client.pb.AppList( - this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - result.version_ = version_; - if (((bitField0_ & 0x00000002) == 0x00000002)) { - apps_ = apps_.getUnmodifiableView(); - bitField0_ = (bitField0_ & ~0x00000002); - } - result.apps_ = apps_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.AppList) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.AppList) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.AppList other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.AppList - .getDefaultInstance()) - return this; - if (other.getVersion() != 0L) { - setVersion(other.getVersion()); - } - if (!other.apps_.isEmpty()) { - if (apps_.isEmpty()) { - apps_ = other.apps_; - bitField0_ = (bitField0_ & ~0x00000002); - } else { - ensureAppsIsMutable(); - apps_.addAll(other.apps_); - } - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.AppList parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.AppList) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private long version_; - - /** - * int64 version = 1; - */ - public long getVersion() { - return version_; - } - - /** - * int64 version = 1; - */ - public Builder setVersion(long value) { - - version_ = value; - onChanged(); - return this; - } - - /** - * int64 version = 1; - */ - public Builder clearVersion() { - - version_ = 0L; - onChanged(); - return this; - } - - private com.google.protobuf.LazyStringList apps_ = com.google.protobuf.LazyStringArrayList.EMPTY; - - private void ensureAppsIsMutable() { - if (!((bitField0_ & 0x00000002) == 0x00000002)) { - apps_ = new com.google.protobuf.LazyStringArrayList(apps_); - bitField0_ |= 0x00000002; - } - } - - /** - * repeated string apps = 2; - */ - public com.google.protobuf.ProtocolStringList getAppsList() { - return apps_.getUnmodifiableView(); - } - - /** - * repeated string apps = 2; - */ - public int getAppsCount() { - return apps_.size(); - } - - /** - * repeated string apps = 2; - */ - public java.lang.String getApps(int index) { - return apps_.get(index); - } - - /** - * repeated string apps = 2; - */ - public com.google.protobuf.ByteString getAppsBytes(int index) { - return apps_.getByteString(index); - } - - /** - * repeated string apps = 2; - */ - public Builder setApps(int index, java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureAppsIsMutable(); - apps_.set(index, value); - onChanged(); - return this; - } - - /** - * repeated string apps = 2; - */ - public Builder addApps(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureAppsIsMutable(); - apps_.add(value); - onChanged(); - return this; - } - - /** - * repeated string apps = 2; - */ - public Builder addAllApps(java.lang.Iterable values) { - ensureAppsIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll(values, apps_); - onChanged(); - return this; - } + // @@protoc_insertion_point(builder_scope:AppList) + } - /** - * repeated string apps = 2; - */ - public Builder clearApps() { - apps_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000002); - onChanged(); - return this; - } + // @@protoc_insertion_point(class_scope:AppList) + private static final com.alipay.sofa.registry.common.model.client.pb.AppList DEFAULT_INSTANCE; - /** - * repeated string apps = 2; - */ - public Builder addAppsBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - ensureAppsIsMutable(); - apps_.add(value); - onChanged(); - return this; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.AppList(); + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + public static com.alipay.sofa.registry.common.model.client.pb.AppList getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public AppList parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new AppList(input, extensionRegistry); } + }; - // @@protoc_insertion_point(builder_scope:AppList) - } - - // @@protoc_insertion_point(class_scope:AppList) - private static final com.alipay.sofa.registry.common.model.client.pb.AppList DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.AppList(); - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - public static com.alipay.sofa.registry.common.model.client.pb.AppList getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public AppList parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new AppList( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public com.alipay.sofa.registry.common.model.client.pb.AppList getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.AppList getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppListOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppListOrBuilder.java index 31412368e..6765d2d23 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppListOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/AppListOrBuilder.java @@ -14,37 +14,25 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface AppListOrBuilder extends -// @@protoc_insertion_point(interface_extends:AppList) - com.google.protobuf.MessageOrBuilder { +public interface AppListOrBuilder + extends + // @@protoc_insertion_point(interface_extends:AppList) + com.google.protobuf.MessageOrBuilder { - /** - * int64 version = 1; - */ - long getVersion(); + /** int64 version = 1; */ + long getVersion(); - /** - * repeated string apps = 2; - */ - java.util.List getAppsList(); + /** repeated string apps = 2; */ + java.util.List getAppsList(); - /** - * repeated string apps = 2; - */ - int getAppsCount(); + /** repeated string apps = 2; */ + int getAppsCount(); - /** - * repeated string apps = 2; - */ - java.lang.String getApps(int index); + /** repeated string apps = 2; */ + java.lang.String getApps(int index); - /** - * repeated string apps = 2; - */ - com.google.protobuf.ByteString getAppsBytes(int index); + /** repeated string apps = 2; */ + com.google.protobuf.ByteString getAppsBytes(int index); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPb.java index 121e72e2b..940fb2ec5 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPb.java @@ -14,2233 +14,2041 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: BaseRegisterPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code BaseRegisterPb} - */ -public final class BaseRegisterPb extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:BaseRegisterPb) - BaseRegisterPbOrBuilder { - private static final long serialVersionUID = 0L; - - // Use BaseRegisterPb.newBuilder() to construct. - private BaseRegisterPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private BaseRegisterPb() { - instanceId_ = ""; - zone_ = ""; - appName_ = ""; - dataId_ = ""; - group_ = ""; - processId_ = ""; - registId_ = ""; - clientId_ = ""; - dataInfoId_ = ""; - ip_ = ""; - port_ = 0; - eventType_ = ""; - version_ = 0L; - timestamp_ = 0L; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } - - private BaseRegisterPb(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - - instanceId_ = s; - break; - } - case 18: { - java.lang.String s = input.readStringRequireUtf8(); - - zone_ = s; - break; - } - case 26: { - java.lang.String s = input.readStringRequireUtf8(); - - appName_ = s; - break; - } - case 34: { - java.lang.String s = input.readStringRequireUtf8(); - - dataId_ = s; - break; - } - case 42: { - java.lang.String s = input.readStringRequireUtf8(); - - group_ = s; - break; - } - case 50: { - java.lang.String s = input.readStringRequireUtf8(); - - processId_ = s; - break; - } - case 58: { - java.lang.String s = input.readStringRequireUtf8(); - - registId_ = s; - break; - } - case 66: { - java.lang.String s = input.readStringRequireUtf8(); - - clientId_ = s; - break; - } - case 74: { - java.lang.String s = input.readStringRequireUtf8(); - - dataInfoId_ = s; - break; - } - case 82: { - java.lang.String s = input.readStringRequireUtf8(); - - ip_ = s; - break; - } - case 88: { - - port_ = input.readInt32(); - break; - } - case 98: { - java.lang.String s = input.readStringRequireUtf8(); - - eventType_ = s; - break; - } - case 104: { - - version_ = input.readInt64(); - break; - } - case 112: { - - timestamp_ = input.readInt64(); - break; - } - case 122: { - if (!((mutable_bitField0_ & 0x00004000) == 0x00004000)) { - attributes_ = com.google.protobuf.MapField - .newMapField(AttributesDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00004000; - } - com.google.protobuf.MapEntry attributes__ = input - .readMessage( - AttributesDefaultEntryHolder.defaultEntry.getParserForType(), - extensionRegistry); - attributes_.getMutableMap().put(attributes__.getKey(), - attributes__.getValue()); - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } +/** Protobuf type {@code BaseRegisterPb} */ +public final class BaseRegisterPb extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:BaseRegisterPb) + BaseRegisterPbOrBuilder { + private static final long serialVersionUID = 0L; + + // Use BaseRegisterPb.newBuilder() to construct. + private BaseRegisterPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private BaseRegisterPb() { + instanceId_ = ""; + zone_ = ""; + appName_ = ""; + dataId_ = ""; + group_ = ""; + processId_ = ""; + registId_ = ""; + clientId_ = ""; + dataInfoId_ = ""; + ip_ = ""; + port_ = 0; + eventType_ = ""; + version_ = 0L; + timestamp_ = 0L; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private BaseRegisterPb( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); + + instanceId_ = s; + break; + } + case 18: + { + java.lang.String s = input.readStringRequireUtf8(); + + zone_ = s; + break; + } + case 26: + { + java.lang.String s = input.readStringRequireUtf8(); + + appName_ = s; + break; + } + case 34: + { + java.lang.String s = input.readStringRequireUtf8(); + + dataId_ = s; + break; + } + case 42: + { + java.lang.String s = input.readStringRequireUtf8(); + + group_ = s; + break; + } + case 50: + { + java.lang.String s = input.readStringRequireUtf8(); + + processId_ = s; + break; + } + case 58: + { + java.lang.String s = input.readStringRequireUtf8(); + + registId_ = s; + break; + } + case 66: + { + java.lang.String s = input.readStringRequireUtf8(); + + clientId_ = s; + break; + } + case 74: + { + java.lang.String s = input.readStringRequireUtf8(); + + dataInfoId_ = s; + break; + } + case 82: + { + java.lang.String s = input.readStringRequireUtf8(); + + ip_ = s; + break; + } + case 88: + { + port_ = input.readInt32(); + break; + } + case 98: + { + java.lang.String s = input.readStringRequireUtf8(); + + eventType_ = s; + break; + } + case 104: + { + version_ = input.readInt64(); + break; + } + case 112: + { + timestamp_ = input.readInt64(); + break; + } + case 122: + { + if (!((mutable_bitField0_ & 0x00004000) == 0x00004000)) { + attributes_ = + com.google.protobuf.MapField.newMapField( + AttributesDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00004000; + } + com.google.protobuf.MapEntry attributes__ = + input.readMessage( + AttributesDefaultEntryHolder.defaultEntry.getParserForType(), + extensionRegistry); + attributes_.getMutableMap().put(attributes__.getKey(), attributes__.getValue()); + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass + .internal_static_BaseRegisterPb_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 15: + return internalGetAttributes(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass + .internal_static_BaseRegisterPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.class, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder.class); + } + + private int bitField0_; + public static final int INSTANCEID_FIELD_NUMBER = 1; + private volatile java.lang.Object instanceId_; + + /** string instanceId = 1; */ + public java.lang.String getInstanceId() { + java.lang.Object ref = instanceId_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + instanceId_ = s; + return s; + } + } + + /** string instanceId = 1; */ + public com.google.protobuf.ByteString getInstanceIdBytes() { + java.lang.Object ref = instanceId_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + instanceId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int ZONE_FIELD_NUMBER = 2; + private volatile java.lang.Object zone_; + + /** string zone = 2; */ + public java.lang.String getZone() { + java.lang.Object ref = zone_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + zone_ = s; + return s; + } + } + + /** string zone = 2; */ + public com.google.protobuf.ByteString getZoneBytes() { + java.lang.Object ref = zone_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + zone_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int APPNAME_FIELD_NUMBER = 3; + private volatile java.lang.Object appName_; + + /** string appName = 3; */ + public java.lang.String getAppName() { + java.lang.Object ref = appName_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + appName_ = s; + return s; + } + } + + /** string appName = 3; */ + public com.google.protobuf.ByteString getAppNameBytes() { + java.lang.Object ref = appName_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + appName_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int DATAID_FIELD_NUMBER = 4; + private volatile java.lang.Object dataId_; + + /** string dataId = 4; */ + public java.lang.String getDataId() { + java.lang.Object ref = dataId_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + dataId_ = s; + return s; + } + } + + /** string dataId = 4; */ + public com.google.protobuf.ByteString getDataIdBytes() { + java.lang.Object ref = dataId_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + dataId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int GROUP_FIELD_NUMBER = 5; + private volatile java.lang.Object group_; + + /** string group = 5; */ + public java.lang.String getGroup() { + java.lang.Object ref = group_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + group_ = s; + return s; + } + } + + /** string group = 5; */ + public com.google.protobuf.ByteString getGroupBytes() { + java.lang.Object ref = group_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + group_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int PROCESSID_FIELD_NUMBER = 6; + private volatile java.lang.Object processId_; + + /** string processId = 6; */ + public java.lang.String getProcessId() { + java.lang.Object ref = processId_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + processId_ = s; + return s; + } + } + + /** string processId = 6; */ + public com.google.protobuf.ByteString getProcessIdBytes() { + java.lang.Object ref = processId_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + processId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int REGISTID_FIELD_NUMBER = 7; + private volatile java.lang.Object registId_; + + /** string registId = 7; */ + public java.lang.String getRegistId() { + java.lang.Object ref = registId_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + registId_ = s; + return s; + } + } + + /** string registId = 7; */ + public com.google.protobuf.ByteString getRegistIdBytes() { + java.lang.Object ref = registId_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + registId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int CLIENTID_FIELD_NUMBER = 8; + private volatile java.lang.Object clientId_; + + /** string clientId = 8; */ + public java.lang.String getClientId() { + java.lang.Object ref = clientId_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + clientId_ = s; + return s; + } + } + + /** string clientId = 8; */ + public com.google.protobuf.ByteString getClientIdBytes() { + java.lang.Object ref = clientId_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + clientId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int DATAINFOID_FIELD_NUMBER = 9; + private volatile java.lang.Object dataInfoId_; + + /** string dataInfoId = 9; */ + public java.lang.String getDataInfoId() { + java.lang.Object ref = dataInfoId_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + dataInfoId_ = s; + return s; + } + } + + /** string dataInfoId = 9; */ + public com.google.protobuf.ByteString getDataInfoIdBytes() { + java.lang.Object ref = dataInfoId_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + dataInfoId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int IP_FIELD_NUMBER = 10; + private volatile java.lang.Object ip_; + + /** string ip = 10; */ + public java.lang.String getIp() { + java.lang.Object ref = ip_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + ip_ = s; + return s; + } + } + + /** string ip = 10; */ + public com.google.protobuf.ByteString getIpBytes() { + java.lang.Object ref = ip_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + ip_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int PORT_FIELD_NUMBER = 11; + private int port_; + + /** int32 port = 11; */ + public int getPort() { + return port_; + } + + public static final int EVENTTYPE_FIELD_NUMBER = 12; + private volatile java.lang.Object eventType_; + + /** string eventType = 12; */ + public java.lang.String getEventType() { + java.lang.Object ref = eventType_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + eventType_ = s; + return s; + } + } + + /** string eventType = 12; */ + public com.google.protobuf.ByteString getEventTypeBytes() { + java.lang.Object ref = eventType_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + eventType_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int VERSION_FIELD_NUMBER = 13; + private long version_; + + /** int64 version = 13; */ + public long getVersion() { + return version_; + } + + public static final int TIMESTAMP_FIELD_NUMBER = 14; + private long timestamp_; + + /** int64 timestamp = 14; */ + public long getTimestamp() { + return timestamp_; + } + + public static final int ATTRIBUTES_FIELD_NUMBER = 15; + + private static final class AttributesDefaultEntryHolder { + static final com.google.protobuf.MapEntry defaultEntry = + com.google.protobuf.MapEntry.newDefaultInstance( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass + .internal_static_BaseRegisterPb_AttributesEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.STRING, + ""); + } + + private com.google.protobuf.MapField attributes_; + + private com.google.protobuf.MapField internalGetAttributes() { + if (attributes_ == null) { + return com.google.protobuf.MapField.emptyMapField(AttributesDefaultEntryHolder.defaultEntry); + } + return attributes_; + } + + public int getAttributesCount() { + return internalGetAttributes().getMap().size(); + } + + /** map<string, string> attributes = 15; */ + public boolean containsAttributes(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetAttributes().getMap().containsKey(key); + } + + /** Use {@link #getAttributesMap()} instead. */ + @java.lang.Deprecated + public java.util.Map getAttributes() { + return getAttributesMap(); + } - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass.internal_static_BaseRegisterPb_descriptor; - } + /** map<string, string> attributes = 15; */ + public java.util.Map getAttributesMap() { + return internalGetAttributes().getMap(); + } - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 15: - return internalGetAttributes(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } + /** map<string, string> attributes = 15; */ + public java.lang.String getAttributesOrDefault( + java.lang.String key, java.lang.String defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); } + java.util.Map map = internalGetAttributes().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass.internal_static_BaseRegisterPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.class, - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder.class); + /** map<string, string> attributes = 15; */ + public java.lang.String getAttributesOrThrow(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); } - - private int bitField0_; - public static final int INSTANCEID_FIELD_NUMBER = 1; - private volatile java.lang.Object instanceId_; - - /** - * string instanceId = 1; - */ - public java.lang.String getInstanceId() { - java.lang.Object ref = instanceId_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - instanceId_ = s; - return s; - } + java.util.Map map = internalGetAttributes().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); } + return map.get(key); + } - /** - * string instanceId = 1; - */ - public com.google.protobuf.ByteString getInstanceIdBytes() { - java.lang.Object ref = instanceId_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - instanceId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + private byte memoizedIsInitialized = -1; - public static final int ZONE_FIELD_NUMBER = 2; - private volatile java.lang.Object zone_; + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; - /** - * string zone = 2; - */ - public java.lang.String getZone() { - java.lang.Object ref = zone_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - zone_ = s; - return s; - } - } + memoizedIsInitialized = 1; + return true; + } - /** - * string zone = 2; - */ - public com.google.protobuf.ByteString getZoneBytes() { - java.lang.Object ref = zone_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - zone_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getInstanceIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, instanceId_); } - - public static final int APPNAME_FIELD_NUMBER = 3; - private volatile java.lang.Object appName_; - - /** - * string appName = 3; - */ - public java.lang.String getAppName() { - java.lang.Object ref = appName_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - appName_ = s; - return s; - } + if (!getZoneBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, zone_); } - - /** - * string appName = 3; - */ - public com.google.protobuf.ByteString getAppNameBytes() { - java.lang.Object ref = appName_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - appName_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + if (!getAppNameBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 3, appName_); } - - public static final int DATAID_FIELD_NUMBER = 4; - private volatile java.lang.Object dataId_; - - /** - * string dataId = 4; - */ - public java.lang.String getDataId() { - java.lang.Object ref = dataId_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - dataId_ = s; - return s; - } + if (!getDataIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 4, dataId_); } - - /** - * string dataId = 4; - */ - public com.google.protobuf.ByteString getDataIdBytes() { - java.lang.Object ref = dataId_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - dataId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + if (!getGroupBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 5, group_); } - - public static final int GROUP_FIELD_NUMBER = 5; - private volatile java.lang.Object group_; - - /** - * string group = 5; - */ - public java.lang.String getGroup() { - java.lang.Object ref = group_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - group_ = s; - return s; - } + if (!getProcessIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 6, processId_); } - - /** - * string group = 5; - */ - public com.google.protobuf.ByteString getGroupBytes() { - java.lang.Object ref = group_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - group_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + if (!getRegistIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 7, registId_); } - - public static final int PROCESSID_FIELD_NUMBER = 6; - private volatile java.lang.Object processId_; - - /** - * string processId = 6; - */ - public java.lang.String getProcessId() { - java.lang.Object ref = processId_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - processId_ = s; - return s; - } + if (!getClientIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 8, clientId_); } - - /** - * string processId = 6; - */ - public com.google.protobuf.ByteString getProcessIdBytes() { - java.lang.Object ref = processId_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - processId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + if (!getDataInfoIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 9, dataInfoId_); } - - public static final int REGISTID_FIELD_NUMBER = 7; - private volatile java.lang.Object registId_; - - /** - * string registId = 7; - */ - public java.lang.String getRegistId() { - java.lang.Object ref = registId_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - registId_ = s; - return s; - } + if (!getIpBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 10, ip_); } - - /** - * string registId = 7; - */ - public com.google.protobuf.ByteString getRegistIdBytes() { - java.lang.Object ref = registId_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - registId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + if (port_ != 0) { + output.writeInt32(11, port_); } - - public static final int CLIENTID_FIELD_NUMBER = 8; - private volatile java.lang.Object clientId_; - - /** - * string clientId = 8; - */ - public java.lang.String getClientId() { - java.lang.Object ref = clientId_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - clientId_ = s; - return s; - } + if (!getEventTypeBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 12, eventType_); } - - /** - * string clientId = 8; - */ - public com.google.protobuf.ByteString getClientIdBytes() { - java.lang.Object ref = clientId_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - clientId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + if (version_ != 0L) { + output.writeInt64(13, version_); } - - public static final int DATAINFOID_FIELD_NUMBER = 9; - private volatile java.lang.Object dataInfoId_; - - /** - * string dataInfoId = 9; - */ - public java.lang.String getDataInfoId() { - java.lang.Object ref = dataInfoId_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - dataInfoId_ = s; - return s; - } + if (timestamp_ != 0L) { + output.writeInt64(14, timestamp_); } + com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( + output, internalGetAttributes(), AttributesDefaultEntryHolder.defaultEntry, 15); + unknownFields.writeTo(output); + } - /** - * string dataInfoId = 9; - */ - public com.google.protobuf.ByteString getDataInfoIdBytes() { - java.lang.Object ref = dataInfoId_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - dataInfoId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!getInstanceIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, instanceId_); + } + if (!getZoneBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, zone_); + } + if (!getAppNameBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, appName_); + } + if (!getDataIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, dataId_); + } + if (!getGroupBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, group_); + } + if (!getProcessIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, processId_); + } + if (!getRegistIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, registId_); + } + if (!getClientIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(8, clientId_); + } + if (!getDataInfoIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(9, dataInfoId_); + } + if (!getIpBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(10, ip_); + } + if (port_ != 0) { + size += com.google.protobuf.CodedOutputStream.computeInt32Size(11, port_); + } + if (!getEventTypeBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(12, eventType_); + } + if (version_ != 0L) { + size += com.google.protobuf.CodedOutputStream.computeInt64Size(13, version_); + } + if (timestamp_ != 0L) { + size += com.google.protobuf.CodedOutputStream.computeInt64Size(14, timestamp_); + } + for (java.util.Map.Entry entry : + internalGetAttributes().getMap().entrySet()) { + com.google.protobuf.MapEntry attributes__ = + AttributesDefaultEntryHolder.defaultEntry + .newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream.computeMessageSize(15, attributes__); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb other = + (com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb) obj; + + boolean result = true; + result = result && getInstanceId().equals(other.getInstanceId()); + result = result && getZone().equals(other.getZone()); + result = result && getAppName().equals(other.getAppName()); + result = result && getDataId().equals(other.getDataId()); + result = result && getGroup().equals(other.getGroup()); + result = result && getProcessId().equals(other.getProcessId()); + result = result && getRegistId().equals(other.getRegistId()); + result = result && getClientId().equals(other.getClientId()); + result = result && getDataInfoId().equals(other.getDataInfoId()); + result = result && getIp().equals(other.getIp()); + result = result && (getPort() == other.getPort()); + result = result && getEventType().equals(other.getEventType()); + result = result && (getVersion() == other.getVersion()); + result = result && (getTimestamp() == other.getTimestamp()); + result = result && internalGetAttributes().equals(other.internalGetAttributes()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + INSTANCEID_FIELD_NUMBER; + hash = (53 * hash) + getInstanceId().hashCode(); + hash = (37 * hash) + ZONE_FIELD_NUMBER; + hash = (53 * hash) + getZone().hashCode(); + hash = (37 * hash) + APPNAME_FIELD_NUMBER; + hash = (53 * hash) + getAppName().hashCode(); + hash = (37 * hash) + DATAID_FIELD_NUMBER; + hash = (53 * hash) + getDataId().hashCode(); + hash = (37 * hash) + GROUP_FIELD_NUMBER; + hash = (53 * hash) + getGroup().hashCode(); + hash = (37 * hash) + PROCESSID_FIELD_NUMBER; + hash = (53 * hash) + getProcessId().hashCode(); + hash = (37 * hash) + REGISTID_FIELD_NUMBER; + hash = (53 * hash) + getRegistId().hashCode(); + hash = (37 * hash) + CLIENTID_FIELD_NUMBER; + hash = (53 * hash) + getClientId().hashCode(); + hash = (37 * hash) + DATAINFOID_FIELD_NUMBER; + hash = (53 * hash) + getDataInfoId().hashCode(); + hash = (37 * hash) + IP_FIELD_NUMBER; + hash = (53 * hash) + getIp().hashCode(); + hash = (37 * hash) + PORT_FIELD_NUMBER; + hash = (53 * hash) + getPort(); + hash = (37 * hash) + EVENTTYPE_FIELD_NUMBER; + hash = (53 * hash) + getEventType().hashCode(); + hash = (37 * hash) + VERSION_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getVersion()); + hash = (37 * hash) + TIMESTAMP_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getTimestamp()); + if (!internalGetAttributes().getMap().isEmpty()) { + hash = (37 * hash) + ATTRIBUTES_FIELD_NUMBER; + hash = (53 * hash) + internalGetAttributes().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code BaseRegisterPb} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:BaseRegisterPb) + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass + .internal_static_BaseRegisterPb_descriptor; } - public static final int IP_FIELD_NUMBER = 10; - private volatile java.lang.Object ip_; - - /** - * string ip = 10; - */ - public java.lang.String getIp() { - java.lang.Object ref = ip_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - ip_ = s; - return s; - } + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 15: + return internalGetAttributes(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - /** - * string ip = 10; - */ - public com.google.protobuf.ByteString getIpBytes() { - java.lang.Object ref = ip_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - ip_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField(int number) { + switch (number) { + case 15: + return internalGetMutableAttributes(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - public static final int PORT_FIELD_NUMBER = 11; - private int port_; - - /** - * int32 port = 11; - */ - public int getPort() { - return port_; + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass + .internal_static_BaseRegisterPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.class, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder.class); } - public static final int EVENTTYPE_FIELD_NUMBER = 12; - private volatile java.lang.Object eventType_; - - /** - * string eventType = 12; - */ - public java.lang.String getEventType() { - java.lang.Object ref = eventType_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - eventType_ = s; - return s; - } + // Construct using com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - /** - * string eventType = 12; - */ - public com.google.protobuf.ByteString getEventTypeBytes() { - java.lang.Object ref = eventType_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - eventType_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - public static final int VERSION_FIELD_NUMBER = 13; - private long version_; - - /** - * int64 version = 13; - */ - public long getVersion() { - return version_; + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - public static final int TIMESTAMP_FIELD_NUMBER = 14; - private long timestamp_; + public Builder clear() { + super.clear(); + instanceId_ = ""; - /** - * int64 timestamp = 14; - */ - public long getTimestamp() { - return timestamp_; - } + zone_ = ""; - public static final int ATTRIBUTES_FIELD_NUMBER = 15; + appName_ = ""; - private static final class AttributesDefaultEntryHolder { - static final com.google.protobuf.MapEntry defaultEntry = com.google.protobuf.MapEntry - . newDefaultInstance( - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass.internal_static_BaseRegisterPb_AttributesEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.STRING, - ""); - } + dataId_ = ""; - private com.google.protobuf.MapField attributes_; + group_ = ""; - private com.google.protobuf.MapField internalGetAttributes() { - if (attributes_ == null) { - return com.google.protobuf.MapField - .emptyMapField(AttributesDefaultEntryHolder.defaultEntry); - } - return attributes_; - } + processId_ = ""; - public int getAttributesCount() { - return internalGetAttributes().getMap().size(); - } + registId_ = ""; - /** - * map<string, string> attributes = 15; - */ + clientId_ = ""; - public boolean containsAttributes(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetAttributes().getMap().containsKey(key); - } + dataInfoId_ = ""; - /** - * Use {@link #getAttributesMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getAttributes() { - return getAttributesMap(); - } + ip_ = ""; - /** - * map<string, string> attributes = 15; - */ + port_ = 0; - public java.util.Map getAttributesMap() { - return internalGetAttributes().getMap(); - } + eventType_ = ""; - /** - * map<string, string> attributes = 15; - */ + version_ = 0L; - public java.lang.String getAttributesOrDefault(java.lang.String key, - java.lang.String defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetAttributes().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } + timestamp_ = 0L; - /** - * map<string, string> attributes = 15; - */ - - public java.lang.String getAttributesOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetAttributes().getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); + internalGetMutableAttributes().clear(); + return this; } - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass + .internal_static_BaseRegisterPb_descriptor; } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (!getInstanceIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, instanceId_); - } - if (!getZoneBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, zone_); - } - if (!getAppNameBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 3, appName_); - } - if (!getDataIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 4, dataId_); - } - if (!getGroupBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 5, group_); - } - if (!getProcessIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 6, processId_); - } - if (!getRegistIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 7, registId_); - } - if (!getClientIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 8, clientId_); - } - if (!getDataInfoIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 9, dataInfoId_); - } - if (!getIpBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 10, ip_); - } - if (port_ != 0) { - output.writeInt32(11, port_); - } - if (!getEventTypeBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 12, eventType_); - } - if (version_ != 0L) { - output.writeInt64(13, version_); - } - if (timestamp_ != 0L) { - output.writeInt64(14, timestamp_); - } - com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(output, - internalGetAttributes(), AttributesDefaultEntryHolder.defaultEntry, 15); - unknownFields.writeTo(output); + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.getDefaultInstance(); } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - if (!getInstanceIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, instanceId_); - } - if (!getZoneBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, zone_); - } - if (!getAppNameBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, appName_); - } - if (!getDataIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, dataId_); - } - if (!getGroupBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, group_); - } - if (!getProcessIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(6, processId_); - } - if (!getRegistIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(7, registId_); - } - if (!getClientIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(8, clientId_); - } - if (!getDataInfoIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(9, dataInfoId_); - } - if (!getIpBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(10, ip_); - } - if (port_ != 0) { - size += com.google.protobuf.CodedOutputStream.computeInt32Size(11, port_); - } - if (!getEventTypeBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(12, eventType_); - } - if (version_ != 0L) { - size += com.google.protobuf.CodedOutputStream.computeInt64Size(13, version_); - } - if (timestamp_ != 0L) { - size += com.google.protobuf.CodedOutputStream.computeInt64Size(14, timestamp_); - } - for (java.util.Map.Entry entry : internalGetAttributes() - .getMap().entrySet()) { - com.google.protobuf.MapEntry attributes__ = AttributesDefaultEntryHolder.defaultEntry - .newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build(); - size += com.google.protobuf.CodedOutputStream.computeMessageSize(15, attributes__); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb build() { + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb other = (com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb) obj; - - boolean result = true; - result = result && getInstanceId().equals(other.getInstanceId()); - result = result && getZone().equals(other.getZone()); - result = result && getAppName().equals(other.getAppName()); - result = result && getDataId().equals(other.getDataId()); - result = result && getGroup().equals(other.getGroup()); - result = result && getProcessId().equals(other.getProcessId()); - result = result && getRegistId().equals(other.getRegistId()); - result = result && getClientId().equals(other.getClientId()); - result = result && getDataInfoId().equals(other.getDataInfoId()); - result = result && getIp().equals(other.getIp()); - result = result && (getPort() == other.getPort()); - result = result && getEventType().equals(other.getEventType()); - result = result && (getVersion() == other.getVersion()); - result = result && (getTimestamp() == other.getTimestamp()); - result = result && internalGetAttributes().equals(other.internalGetAttributes()); - result = result && unknownFields.equals(other.unknownFields); - return result; - } - - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + INSTANCEID_FIELD_NUMBER; - hash = (53 * hash) + getInstanceId().hashCode(); - hash = (37 * hash) + ZONE_FIELD_NUMBER; - hash = (53 * hash) + getZone().hashCode(); - hash = (37 * hash) + APPNAME_FIELD_NUMBER; - hash = (53 * hash) + getAppName().hashCode(); - hash = (37 * hash) + DATAID_FIELD_NUMBER; - hash = (53 * hash) + getDataId().hashCode(); - hash = (37 * hash) + GROUP_FIELD_NUMBER; - hash = (53 * hash) + getGroup().hashCode(); - hash = (37 * hash) + PROCESSID_FIELD_NUMBER; - hash = (53 * hash) + getProcessId().hashCode(); - hash = (37 * hash) + REGISTID_FIELD_NUMBER; - hash = (53 * hash) + getRegistId().hashCode(); - hash = (37 * hash) + CLIENTID_FIELD_NUMBER; - hash = (53 * hash) + getClientId().hashCode(); - hash = (37 * hash) + DATAINFOID_FIELD_NUMBER; - hash = (53 * hash) + getDataInfoId().hashCode(); - hash = (37 * hash) + IP_FIELD_NUMBER; - hash = (53 * hash) + getIp().hashCode(); - hash = (37 * hash) + PORT_FIELD_NUMBER; - hash = (53 * hash) + getPort(); - hash = (37 * hash) + EVENTTYPE_FIELD_NUMBER; - hash = (53 * hash) + getEventType().hashCode(); - hash = (37 * hash) + VERSION_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getVersion()); - hash = (37 * hash) + TIMESTAMP_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getTimestamp()); - if (!internalGetAttributes().getMap().isEmpty()) { - hash = (37 * hash) + ATTRIBUTES_FIELD_NUMBER; - hash = (53 * hash) + internalGetAttributes().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb result = + new com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + result.instanceId_ = instanceId_; + result.zone_ = zone_; + result.appName_ = appName_; + result.dataId_ = dataId_; + result.group_ = group_; + result.processId_ = processId_; + result.registId_ = registId_; + result.clientId_ = clientId_; + result.dataInfoId_ = dataInfoId_; + result.ip_ = ip_; + result.port_ = port_; + result.eventType_ = eventType_; + result.version_ = version_; + result.timestamp_ = timestamp_; + result.attributes_ = internalGetAttributes(); + result.attributes_.makeImmutable(); + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); + } + + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb) { + return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.getDefaultInstance()) + return this; + if (!other.getInstanceId().isEmpty()) { + instanceId_ = other.instanceId_; + onChanged(); + } + if (!other.getZone().isEmpty()) { + zone_ = other.zone_; + onChanged(); + } + if (!other.getAppName().isEmpty()) { + appName_ = other.appName_; + onChanged(); + } + if (!other.getDataId().isEmpty()) { + dataId_ = other.dataId_; + onChanged(); + } + if (!other.getGroup().isEmpty()) { + group_ = other.group_; + onChanged(); + } + if (!other.getProcessId().isEmpty()) { + processId_ = other.processId_; + onChanged(); + } + if (!other.getRegistId().isEmpty()) { + registId_ = other.registId_; + onChanged(); + } + if (!other.getClientId().isEmpty()) { + clientId_ = other.clientId_; + onChanged(); + } + if (!other.getDataInfoId().isEmpty()) { + dataInfoId_ = other.dataInfoId_; + onChanged(); + } + if (!other.getIp().isEmpty()) { + ip_ = other.ip_; + onChanged(); + } + if (other.getPort() != 0) { + setPort(other.getPort()); + } + if (!other.getEventType().isEmpty()) { + eventType_ = other.eventType_; + onChanged(); + } + if (other.getVersion() != 0L) { + setVersion(other.getVersion()); + } + if (other.getTimestamp() != 0L) { + setTimestamp(other.getTimestamp()); + } + internalGetMutableAttributes().mergeFrom(other.internalGetAttributes()); + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public final boolean isInitialized() { + return true; } - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } + private int bitField0_; - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } + private java.lang.Object instanceId_ = ""; - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + /** string instanceId = 1; */ + public java.lang.String getInstanceId() { + java.lang.Object ref = instanceId_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + instanceId_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string instanceId = 1; */ + public com.google.protobuf.ByteString getInstanceIdBytes() { + java.lang.Object ref = instanceId_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + instanceId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } + /** string instanceId = 1; */ + public Builder setInstanceId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + instanceId_ = value; + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + /** string instanceId = 1; */ + public Builder clearInstanceId() { - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + instanceId_ = getDefaultInstance().getInstanceId(); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); - } + /** string instanceId = 1; */ + public Builder setInstanceIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + instanceId_ = value; + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + private java.lang.Object zone_ = ""; - public Builder newBuilderForType() { - return newBuilder(); + /** string zone = 2; */ + public java.lang.String getZone() { + java.lang.Object ref = zone_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + zone_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string zone = 2; */ + public com.google.protobuf.ByteString getZoneBytes() { + java.lang.Object ref = zone_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + zone_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } + /** string zone = 2; */ + public Builder setZone(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + zone_ = value; + onChanged(); + return this; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } + /** string zone = 2; */ + public Builder clearZone() { - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + zone_ = getDefaultInstance().getZone(); + onChanged(); + return this; } - /** - * Protobuf type {@code BaseRegisterPb} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:BaseRegisterPb) - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass.internal_static_BaseRegisterPb_descriptor; - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 15: - return internalGetAttributes(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMutableMapField(int number) { - switch (number) { - case 15: - return internalGetMutableAttributes(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass.internal_static_BaseRegisterPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.class, - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - instanceId_ = ""; - - zone_ = ""; - - appName_ = ""; - - dataId_ = ""; - - group_ = ""; - - processId_ = ""; - - registId_ = ""; - - clientId_ = ""; + /** string zone = 2; */ + public Builder setZoneBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - dataInfoId_ = ""; - - ip_ = ""; - - port_ = 0; - - eventType_ = ""; - - version_ = 0L; - - timestamp_ = 0L; - - internalGetMutableAttributes().clear(); - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass.internal_static_BaseRegisterPb_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb build() { - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb result = new com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb( - this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - result.instanceId_ = instanceId_; - result.zone_ = zone_; - result.appName_ = appName_; - result.dataId_ = dataId_; - result.group_ = group_; - result.processId_ = processId_; - result.registId_ = registId_; - result.clientId_ = clientId_; - result.dataInfoId_ = dataInfoId_; - result.ip_ = ip_; - result.port_ = port_; - result.eventType_ = eventType_; - result.version_ = version_; - result.timestamp_ = timestamp_; - result.attributes_ = internalGetAttributes(); - result.attributes_.makeImmutable(); - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .getDefaultInstance()) - return this; - if (!other.getInstanceId().isEmpty()) { - instanceId_ = other.instanceId_; - onChanged(); - } - if (!other.getZone().isEmpty()) { - zone_ = other.zone_; - onChanged(); - } - if (!other.getAppName().isEmpty()) { - appName_ = other.appName_; - onChanged(); - } - if (!other.getDataId().isEmpty()) { - dataId_ = other.dataId_; - onChanged(); - } - if (!other.getGroup().isEmpty()) { - group_ = other.group_; - onChanged(); - } - if (!other.getProcessId().isEmpty()) { - processId_ = other.processId_; - onChanged(); - } - if (!other.getRegistId().isEmpty()) { - registId_ = other.registId_; - onChanged(); - } - if (!other.getClientId().isEmpty()) { - clientId_ = other.clientId_; - onChanged(); - } - if (!other.getDataInfoId().isEmpty()) { - dataInfoId_ = other.dataInfoId_; - onChanged(); - } - if (!other.getIp().isEmpty()) { - ip_ = other.ip_; - onChanged(); - } - if (other.getPort() != 0) { - setPort(other.getPort()); - } - if (!other.getEventType().isEmpty()) { - eventType_ = other.eventType_; - onChanged(); - } - if (other.getVersion() != 0L) { - setVersion(other.getVersion()); - } - if (other.getTimestamp() != 0L) { - setTimestamp(other.getTimestamp()); - } - internalGetMutableAttributes().mergeFrom(other.internalGetAttributes()); - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private java.lang.Object instanceId_ = ""; - - /** - * string instanceId = 1; - */ - public java.lang.String getInstanceId() { - java.lang.Object ref = instanceId_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - instanceId_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } - - /** - * string instanceId = 1; - */ - public com.google.protobuf.ByteString getInstanceIdBytes() { - java.lang.Object ref = instanceId_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - instanceId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - /** - * string instanceId = 1; - */ - public Builder setInstanceId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - - instanceId_ = value; - onChanged(); - return this; - } - - /** - * string instanceId = 1; - */ - public Builder clearInstanceId() { - - instanceId_ = getDefaultInstance().getInstanceId(); - onChanged(); - return this; - } - - /** - * string instanceId = 1; - */ - public Builder setInstanceIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - instanceId_ = value; - onChanged(); - return this; - } - - private java.lang.Object zone_ = ""; - - /** - * string zone = 2; - */ - public java.lang.String getZone() { - java.lang.Object ref = zone_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - zone_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } - - /** - * string zone = 2; - */ - public com.google.protobuf.ByteString getZoneBytes() { - java.lang.Object ref = zone_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - zone_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - /** - * string zone = 2; - */ - public Builder setZone(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - - zone_ = value; - onChanged(); - return this; - } - - /** - * string zone = 2; - */ - public Builder clearZone() { - - zone_ = getDefaultInstance().getZone(); - onChanged(); - return this; - } - - /** - * string zone = 2; - */ - public Builder setZoneBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - zone_ = value; - onChanged(); - return this; - } - - private java.lang.Object appName_ = ""; - - /** - * string appName = 3; - */ - public java.lang.String getAppName() { - java.lang.Object ref = appName_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - appName_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } - - /** - * string appName = 3; - */ - public com.google.protobuf.ByteString getAppNameBytes() { - java.lang.Object ref = appName_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - appName_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + zone_ = value; + onChanged(); + return this; + } - /** - * string appName = 3; - */ - public Builder setAppName(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + private java.lang.Object appName_ = ""; - appName_ = value; - onChanged(); - return this; - } + /** string appName = 3; */ + public java.lang.String getAppName() { + java.lang.Object ref = appName_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + appName_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string appName = 3; */ + public com.google.protobuf.ByteString getAppNameBytes() { + java.lang.Object ref = appName_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + appName_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string appName = 3; - */ - public Builder clearAppName() { + /** string appName = 3; */ + public Builder setAppName(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - appName_ = getDefaultInstance().getAppName(); - onChanged(); - return this; - } + appName_ = value; + onChanged(); + return this; + } - /** - * string appName = 3; - */ - public Builder setAppNameBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string appName = 3; */ + public Builder clearAppName() { - appName_ = value; - onChanged(); - return this; - } + appName_ = getDefaultInstance().getAppName(); + onChanged(); + return this; + } - private java.lang.Object dataId_ = ""; - - /** - * string dataId = 4; - */ - public java.lang.String getDataId() { - java.lang.Object ref = dataId_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - dataId_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** string appName = 3; */ + public Builder setAppNameBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string dataId = 4; - */ - public com.google.protobuf.ByteString getDataIdBytes() { - java.lang.Object ref = dataId_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - dataId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + appName_ = value; + onChanged(); + return this; + } - /** - * string dataId = 4; - */ - public Builder setDataId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + private java.lang.Object dataId_ = ""; - dataId_ = value; - onChanged(); - return this; - } + /** string dataId = 4; */ + public java.lang.String getDataId() { + java.lang.Object ref = dataId_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + dataId_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string dataId = 4; */ + public com.google.protobuf.ByteString getDataIdBytes() { + java.lang.Object ref = dataId_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + dataId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string dataId = 4; - */ - public Builder clearDataId() { + /** string dataId = 4; */ + public Builder setDataId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - dataId_ = getDefaultInstance().getDataId(); - onChanged(); - return this; - } + dataId_ = value; + onChanged(); + return this; + } - /** - * string dataId = 4; - */ - public Builder setDataIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string dataId = 4; */ + public Builder clearDataId() { - dataId_ = value; - onChanged(); - return this; - } + dataId_ = getDefaultInstance().getDataId(); + onChanged(); + return this; + } - private java.lang.Object group_ = ""; - - /** - * string group = 5; - */ - public java.lang.String getGroup() { - java.lang.Object ref = group_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - group_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** string dataId = 4; */ + public Builder setDataIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string group = 5; - */ - public com.google.protobuf.ByteString getGroupBytes() { - java.lang.Object ref = group_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - group_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + dataId_ = value; + onChanged(); + return this; + } - /** - * string group = 5; - */ - public Builder setGroup(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + private java.lang.Object group_ = ""; - group_ = value; - onChanged(); - return this; - } + /** string group = 5; */ + public java.lang.String getGroup() { + java.lang.Object ref = group_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + group_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string group = 5; */ + public com.google.protobuf.ByteString getGroupBytes() { + java.lang.Object ref = group_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + group_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string group = 5; - */ - public Builder clearGroup() { + /** string group = 5; */ + public Builder setGroup(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - group_ = getDefaultInstance().getGroup(); - onChanged(); - return this; - } + group_ = value; + onChanged(); + return this; + } - /** - * string group = 5; - */ - public Builder setGroupBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string group = 5; */ + public Builder clearGroup() { - group_ = value; - onChanged(); - return this; - } + group_ = getDefaultInstance().getGroup(); + onChanged(); + return this; + } - private java.lang.Object processId_ = ""; - - /** - * string processId = 6; - */ - public java.lang.String getProcessId() { - java.lang.Object ref = processId_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - processId_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** string group = 5; */ + public Builder setGroupBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string processId = 6; - */ - public com.google.protobuf.ByteString getProcessIdBytes() { - java.lang.Object ref = processId_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - processId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + group_ = value; + onChanged(); + return this; + } - /** - * string processId = 6; - */ - public Builder setProcessId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + private java.lang.Object processId_ = ""; - processId_ = value; - onChanged(); - return this; - } + /** string processId = 6; */ + public java.lang.String getProcessId() { + java.lang.Object ref = processId_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + processId_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string processId = 6; */ + public com.google.protobuf.ByteString getProcessIdBytes() { + java.lang.Object ref = processId_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + processId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string processId = 6; - */ - public Builder clearProcessId() { + /** string processId = 6; */ + public Builder setProcessId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - processId_ = getDefaultInstance().getProcessId(); - onChanged(); - return this; - } + processId_ = value; + onChanged(); + return this; + } - /** - * string processId = 6; - */ - public Builder setProcessIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string processId = 6; */ + public Builder clearProcessId() { - processId_ = value; - onChanged(); - return this; - } + processId_ = getDefaultInstance().getProcessId(); + onChanged(); + return this; + } - private java.lang.Object registId_ = ""; - - /** - * string registId = 7; - */ - public java.lang.String getRegistId() { - java.lang.Object ref = registId_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - registId_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** string processId = 6; */ + public Builder setProcessIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string registId = 7; - */ - public com.google.protobuf.ByteString getRegistIdBytes() { - java.lang.Object ref = registId_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - registId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + processId_ = value; + onChanged(); + return this; + } - /** - * string registId = 7; - */ - public Builder setRegistId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + private java.lang.Object registId_ = ""; - registId_ = value; - onChanged(); - return this; - } + /** string registId = 7; */ + public java.lang.String getRegistId() { + java.lang.Object ref = registId_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + registId_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string registId = 7; */ + public com.google.protobuf.ByteString getRegistIdBytes() { + java.lang.Object ref = registId_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + registId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string registId = 7; - */ - public Builder clearRegistId() { + /** string registId = 7; */ + public Builder setRegistId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - registId_ = getDefaultInstance().getRegistId(); - onChanged(); - return this; - } + registId_ = value; + onChanged(); + return this; + } - /** - * string registId = 7; - */ - public Builder setRegistIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string registId = 7; */ + public Builder clearRegistId() { - registId_ = value; - onChanged(); - return this; - } + registId_ = getDefaultInstance().getRegistId(); + onChanged(); + return this; + } - private java.lang.Object clientId_ = ""; - - /** - * string clientId = 8; - */ - public java.lang.String getClientId() { - java.lang.Object ref = clientId_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - clientId_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** string registId = 7; */ + public Builder setRegistIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string clientId = 8; - */ - public com.google.protobuf.ByteString getClientIdBytes() { - java.lang.Object ref = clientId_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - clientId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + registId_ = value; + onChanged(); + return this; + } - /** - * string clientId = 8; - */ - public Builder setClientId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + private java.lang.Object clientId_ = ""; - clientId_ = value; - onChanged(); - return this; - } + /** string clientId = 8; */ + public java.lang.String getClientId() { + java.lang.Object ref = clientId_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + clientId_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string clientId = 8; */ + public com.google.protobuf.ByteString getClientIdBytes() { + java.lang.Object ref = clientId_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + clientId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string clientId = 8; - */ - public Builder clearClientId() { + /** string clientId = 8; */ + public Builder setClientId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - clientId_ = getDefaultInstance().getClientId(); - onChanged(); - return this; - } + clientId_ = value; + onChanged(); + return this; + } - /** - * string clientId = 8; - */ - public Builder setClientIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string clientId = 8; */ + public Builder clearClientId() { - clientId_ = value; - onChanged(); - return this; - } + clientId_ = getDefaultInstance().getClientId(); + onChanged(); + return this; + } - private java.lang.Object dataInfoId_ = ""; - - /** - * string dataInfoId = 9; - */ - public java.lang.String getDataInfoId() { - java.lang.Object ref = dataInfoId_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - dataInfoId_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** string clientId = 8; */ + public Builder setClientIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string dataInfoId = 9; - */ - public com.google.protobuf.ByteString getDataInfoIdBytes() { - java.lang.Object ref = dataInfoId_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - dataInfoId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + clientId_ = value; + onChanged(); + return this; + } - /** - * string dataInfoId = 9; - */ - public Builder setDataInfoId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + private java.lang.Object dataInfoId_ = ""; - dataInfoId_ = value; - onChanged(); - return this; - } + /** string dataInfoId = 9; */ + public java.lang.String getDataInfoId() { + java.lang.Object ref = dataInfoId_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + dataInfoId_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string dataInfoId = 9; */ + public com.google.protobuf.ByteString getDataInfoIdBytes() { + java.lang.Object ref = dataInfoId_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + dataInfoId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string dataInfoId = 9; - */ - public Builder clearDataInfoId() { + /** string dataInfoId = 9; */ + public Builder setDataInfoId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - dataInfoId_ = getDefaultInstance().getDataInfoId(); - onChanged(); - return this; - } + dataInfoId_ = value; + onChanged(); + return this; + } - /** - * string dataInfoId = 9; - */ - public Builder setDataInfoIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string dataInfoId = 9; */ + public Builder clearDataInfoId() { - dataInfoId_ = value; - onChanged(); - return this; - } + dataInfoId_ = getDefaultInstance().getDataInfoId(); + onChanged(); + return this; + } - private java.lang.Object ip_ = ""; - - /** - * string ip = 10; - */ - public java.lang.String getIp() { - java.lang.Object ref = ip_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - ip_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** string dataInfoId = 9; */ + public Builder setDataInfoIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string ip = 10; - */ - public com.google.protobuf.ByteString getIpBytes() { - java.lang.Object ref = ip_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - ip_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + dataInfoId_ = value; + onChanged(); + return this; + } - /** - * string ip = 10; - */ - public Builder setIp(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + private java.lang.Object ip_ = ""; - ip_ = value; - onChanged(); - return this; - } + /** string ip = 10; */ + public java.lang.String getIp() { + java.lang.Object ref = ip_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + ip_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string ip = 10; */ + public com.google.protobuf.ByteString getIpBytes() { + java.lang.Object ref = ip_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + ip_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string ip = 10; - */ - public Builder clearIp() { + /** string ip = 10; */ + public Builder setIp(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - ip_ = getDefaultInstance().getIp(); - onChanged(); - return this; - } + ip_ = value; + onChanged(); + return this; + } - /** - * string ip = 10; - */ - public Builder setIpBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string ip = 10; */ + public Builder clearIp() { - ip_ = value; - onChanged(); - return this; - } + ip_ = getDefaultInstance().getIp(); + onChanged(); + return this; + } - private int port_; + /** string ip = 10; */ + public Builder setIpBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * int32 port = 11; - */ - public int getPort() { - return port_; - } + ip_ = value; + onChanged(); + return this; + } - /** - * int32 port = 11; - */ - public Builder setPort(int value) { + private int port_; - port_ = value; - onChanged(); - return this; - } + /** int32 port = 11; */ + public int getPort() { + return port_; + } - /** - * int32 port = 11; - */ - public Builder clearPort() { + /** int32 port = 11; */ + public Builder setPort(int value) { - port_ = 0; - onChanged(); - return this; - } + port_ = value; + onChanged(); + return this; + } - private java.lang.Object eventType_ = ""; - - /** - * string eventType = 12; - */ - public java.lang.String getEventType() { - java.lang.Object ref = eventType_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - eventType_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** int32 port = 11; */ + public Builder clearPort() { - /** - * string eventType = 12; - */ - public com.google.protobuf.ByteString getEventTypeBytes() { - java.lang.Object ref = eventType_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - eventType_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + port_ = 0; + onChanged(); + return this; + } - /** - * string eventType = 12; - */ - public Builder setEventType(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + private java.lang.Object eventType_ = ""; - eventType_ = value; - onChanged(); - return this; - } + /** string eventType = 12; */ + public java.lang.String getEventType() { + java.lang.Object ref = eventType_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + eventType_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string eventType = 12; */ + public com.google.protobuf.ByteString getEventTypeBytes() { + java.lang.Object ref = eventType_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + eventType_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string eventType = 12; - */ - public Builder clearEventType() { + /** string eventType = 12; */ + public Builder setEventType(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - eventType_ = getDefaultInstance().getEventType(); - onChanged(); - return this; - } + eventType_ = value; + onChanged(); + return this; + } - /** - * string eventType = 12; - */ - public Builder setEventTypeBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string eventType = 12; */ + public Builder clearEventType() { - eventType_ = value; - onChanged(); - return this; - } + eventType_ = getDefaultInstance().getEventType(); + onChanged(); + return this; + } - private long version_; + /** string eventType = 12; */ + public Builder setEventTypeBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * int64 version = 13; - */ - public long getVersion() { - return version_; - } + eventType_ = value; + onChanged(); + return this; + } - /** - * int64 version = 13; - */ - public Builder setVersion(long value) { + private long version_; - version_ = value; - onChanged(); - return this; - } + /** int64 version = 13; */ + public long getVersion() { + return version_; + } - /** - * int64 version = 13; - */ - public Builder clearVersion() { + /** int64 version = 13; */ + public Builder setVersion(long value) { - version_ = 0L; - onChanged(); - return this; - } + version_ = value; + onChanged(); + return this; + } - private long timestamp_; + /** int64 version = 13; */ + public Builder clearVersion() { - /** - * int64 timestamp = 14; - */ - public long getTimestamp() { - return timestamp_; - } + version_ = 0L; + onChanged(); + return this; + } - /** - * int64 timestamp = 14; - */ - public Builder setTimestamp(long value) { + private long timestamp_; - timestamp_ = value; - onChanged(); - return this; - } + /** int64 timestamp = 14; */ + public long getTimestamp() { + return timestamp_; + } - /** - * int64 timestamp = 14; - */ - public Builder clearTimestamp() { + /** int64 timestamp = 14; */ + public Builder setTimestamp(long value) { - timestamp_ = 0L; - onChanged(); - return this; - } + timestamp_ = value; + onChanged(); + return this; + } - private com.google.protobuf.MapField attributes_; + /** int64 timestamp = 14; */ + public Builder clearTimestamp() { - private com.google.protobuf.MapField internalGetAttributes() { - if (attributes_ == null) { - return com.google.protobuf.MapField - .emptyMapField(AttributesDefaultEntryHolder.defaultEntry); - } - return attributes_; - } + timestamp_ = 0L; + onChanged(); + return this; + } - private com.google.protobuf.MapField internalGetMutableAttributes() { - onChanged(); - ; - if (attributes_ == null) { - attributes_ = com.google.protobuf.MapField - .newMapField(AttributesDefaultEntryHolder.defaultEntry); - } - if (!attributes_.isMutable()) { - attributes_ = attributes_.copy(); - } - return attributes_; - } + private com.google.protobuf.MapField attributes_; - public int getAttributesCount() { - return internalGetAttributes().getMap().size(); - } + private com.google.protobuf.MapField + internalGetAttributes() { + if (attributes_ == null) { + return com.google.protobuf.MapField.emptyMapField( + AttributesDefaultEntryHolder.defaultEntry); + } + return attributes_; + } + + private com.google.protobuf.MapField + internalGetMutableAttributes() { + onChanged(); + ; + if (attributes_ == null) { + attributes_ = + com.google.protobuf.MapField.newMapField(AttributesDefaultEntryHolder.defaultEntry); + } + if (!attributes_.isMutable()) { + attributes_ = attributes_.copy(); + } + return attributes_; + } - /** - * map<string, string> attributes = 15; - */ + public int getAttributesCount() { + return internalGetAttributes().getMap().size(); + } - public boolean containsAttributes(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetAttributes().getMap().containsKey(key); - } + /** map<string, string> attributes = 15; */ + public boolean containsAttributes(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetAttributes().getMap().containsKey(key); + } - /** - * Use {@link #getAttributesMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getAttributes() { - return getAttributesMap(); - } + /** Use {@link #getAttributesMap()} instead. */ + @java.lang.Deprecated + public java.util.Map getAttributes() { + return getAttributesMap(); + } - /** - * map<string, string> attributes = 15; - */ + /** map<string, string> attributes = 15; */ + public java.util.Map getAttributesMap() { + return internalGetAttributes().getMap(); + } - public java.util.Map getAttributesMap() { - return internalGetAttributes().getMap(); - } + /** map<string, string> attributes = 15; */ + public java.lang.String getAttributesOrDefault( + java.lang.String key, java.lang.String defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map map = internalGetAttributes().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } - /** - * map<string, string> attributes = 15; - */ + /** map<string, string> attributes = 15; */ + public java.lang.String getAttributesOrThrow(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map map = internalGetAttributes().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } - public java.lang.String getAttributesOrDefault(java.lang.String key, - java.lang.String defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetAttributes() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } + public Builder clearAttributes() { + internalGetMutableAttributes().getMutableMap().clear(); + return this; + } - /** - * map<string, string> attributes = 15; - */ + /** map<string, string> attributes = 15; */ + public Builder removeAttributes(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableAttributes().getMutableMap().remove(key); + return this; + } - public java.lang.String getAttributesOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetAttributes() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } + /** Use alternate mutation accessors instead. */ + @java.lang.Deprecated + public java.util.Map getMutableAttributes() { + return internalGetMutableAttributes().getMutableMap(); + } - public Builder clearAttributes() { - internalGetMutableAttributes().getMutableMap().clear(); - return this; - } + /** map<string, string> attributes = 15; */ + public Builder putAttributes(java.lang.String key, java.lang.String value) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + if (value == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableAttributes().getMutableMap().put(key, value); + return this; + } - /** - * map<string, string> attributes = 15; - */ + /** map<string, string> attributes = 15; */ + public Builder putAllAttributes(java.util.Map values) { + internalGetMutableAttributes().getMutableMap().putAll(values); + return this; + } - public Builder removeAttributes(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableAttributes().getMutableMap().remove(key); - return this; - } + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } - /** - * Use alternate mutation accessors instead. - */ - @java.lang.Deprecated - public java.util.Map getMutableAttributes() { - return internalGetMutableAttributes().getMutableMap(); - } + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - /** - * map<string, string> attributes = 15; - */ - public Builder putAttributes(java.lang.String key, java.lang.String value) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - if (value == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableAttributes().getMutableMap().put(key, value); - return this; - } + // @@protoc_insertion_point(builder_scope:BaseRegisterPb) + } - /** - * map<string, string> attributes = 15; - */ + // @@protoc_insertion_point(class_scope:BaseRegisterPb) + private static final com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb + DEFAULT_INSTANCE; - public Builder putAllAttributes(java.util.Map values) { - internalGetMutableAttributes().getMutableMap().putAll(values); - return this; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb(); + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb + getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public BaseRegisterPb parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new BaseRegisterPb(input, extensionRegistry); } + }; - // @@protoc_insertion_point(builder_scope:BaseRegisterPb) - } - - // @@protoc_insertion_point(class_scope:BaseRegisterPb) - private static final com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb(); - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - public static com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public BaseRegisterPb parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new BaseRegisterPb( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPbOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPbOrBuilder.java index b336edf8f..8f44000a8 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPbOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPbOrBuilder.java @@ -14,170 +14,104 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: BaseRegisterPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface BaseRegisterPbOrBuilder extends -// @@protoc_insertion_point(interface_extends:BaseRegisterPb) - com.google.protobuf.MessageOrBuilder { - - /** - * string instanceId = 1; - */ - java.lang.String getInstanceId(); - - /** - * string instanceId = 1; - */ - com.google.protobuf.ByteString getInstanceIdBytes(); - - /** - * string zone = 2; - */ - java.lang.String getZone(); - - /** - * string zone = 2; - */ - com.google.protobuf.ByteString getZoneBytes(); - - /** - * string appName = 3; - */ - java.lang.String getAppName(); - - /** - * string appName = 3; - */ - com.google.protobuf.ByteString getAppNameBytes(); - - /** - * string dataId = 4; - */ - java.lang.String getDataId(); - - /** - * string dataId = 4; - */ - com.google.protobuf.ByteString getDataIdBytes(); - - /** - * string group = 5; - */ - java.lang.String getGroup(); - - /** - * string group = 5; - */ - com.google.protobuf.ByteString getGroupBytes(); - - /** - * string processId = 6; - */ - java.lang.String getProcessId(); - - /** - * string processId = 6; - */ - com.google.protobuf.ByteString getProcessIdBytes(); - - /** - * string registId = 7; - */ - java.lang.String getRegistId(); - - /** - * string registId = 7; - */ - com.google.protobuf.ByteString getRegistIdBytes(); - - /** - * string clientId = 8; - */ - java.lang.String getClientId(); - - /** - * string clientId = 8; - */ - com.google.protobuf.ByteString getClientIdBytes(); - - /** - * string dataInfoId = 9; - */ - java.lang.String getDataInfoId(); - - /** - * string dataInfoId = 9; - */ - com.google.protobuf.ByteString getDataInfoIdBytes(); - - /** - * string ip = 10; - */ - java.lang.String getIp(); - - /** - * string ip = 10; - */ - com.google.protobuf.ByteString getIpBytes(); - - /** - * int32 port = 11; - */ - int getPort(); - - /** - * string eventType = 12; - */ - java.lang.String getEventType(); - - /** - * string eventType = 12; - */ - com.google.protobuf.ByteString getEventTypeBytes(); - - /** - * int64 version = 13; - */ - long getVersion(); - - /** - * int64 timestamp = 14; - */ - long getTimestamp(); - - /** - * map<string, string> attributes = 15; - */ - int getAttributesCount(); - - /** - * map<string, string> attributes = 15; - */ - boolean containsAttributes(java.lang.String key); - - /** - * Use {@link #getAttributesMap()} instead. - */ - @java.lang.Deprecated - java.util.Map getAttributes(); - - /** - * map<string, string> attributes = 15; - */ - java.util.Map getAttributesMap(); - - /** - * map<string, string> attributes = 15; - */ - - java.lang.String getAttributesOrDefault(java.lang.String key, java.lang.String defaultValue); - - /** - * map<string, string> attributes = 15; - */ - - java.lang.String getAttributesOrThrow(java.lang.String key); +public interface BaseRegisterPbOrBuilder + extends + // @@protoc_insertion_point(interface_extends:BaseRegisterPb) + com.google.protobuf.MessageOrBuilder { + + /** string instanceId = 1; */ + java.lang.String getInstanceId(); + + /** string instanceId = 1; */ + com.google.protobuf.ByteString getInstanceIdBytes(); + + /** string zone = 2; */ + java.lang.String getZone(); + + /** string zone = 2; */ + com.google.protobuf.ByteString getZoneBytes(); + + /** string appName = 3; */ + java.lang.String getAppName(); + + /** string appName = 3; */ + com.google.protobuf.ByteString getAppNameBytes(); + + /** string dataId = 4; */ + java.lang.String getDataId(); + + /** string dataId = 4; */ + com.google.protobuf.ByteString getDataIdBytes(); + + /** string group = 5; */ + java.lang.String getGroup(); + + /** string group = 5; */ + com.google.protobuf.ByteString getGroupBytes(); + + /** string processId = 6; */ + java.lang.String getProcessId(); + + /** string processId = 6; */ + com.google.protobuf.ByteString getProcessIdBytes(); + + /** string registId = 7; */ + java.lang.String getRegistId(); + + /** string registId = 7; */ + com.google.protobuf.ByteString getRegistIdBytes(); + + /** string clientId = 8; */ + java.lang.String getClientId(); + + /** string clientId = 8; */ + com.google.protobuf.ByteString getClientIdBytes(); + + /** string dataInfoId = 9; */ + java.lang.String getDataInfoId(); + + /** string dataInfoId = 9; */ + com.google.protobuf.ByteString getDataInfoIdBytes(); + + /** string ip = 10; */ + java.lang.String getIp(); + + /** string ip = 10; */ + com.google.protobuf.ByteString getIpBytes(); + + /** int32 port = 11; */ + int getPort(); + + /** string eventType = 12; */ + java.lang.String getEventType(); + + /** string eventType = 12; */ + com.google.protobuf.ByteString getEventTypeBytes(); + + /** int64 version = 13; */ + long getVersion(); + + /** int64 timestamp = 14; */ + long getTimestamp(); + + /** map<string, string> attributes = 15; */ + int getAttributesCount(); + + /** map<string, string> attributes = 15; */ + boolean containsAttributes(java.lang.String key); + + /** Use {@link #getAttributesMap()} instead. */ + @java.lang.Deprecated + java.util.Map getAttributes(); + + /** map<string, string> attributes = 15; */ + java.util.Map getAttributesMap(); + + /** map<string, string> attributes = 15; */ + java.lang.String getAttributesOrDefault(java.lang.String key, java.lang.String defaultValue); + + /** map<string, string> attributes = 15; */ + java.lang.String getAttributesOrThrow(java.lang.String key); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPbOuterClass.java index fefbc0c9a..6adc6ffc0 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/BaseRegisterPbOuterClass.java @@ -14,72 +14,86 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: BaseRegisterPb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class BaseRegisterPbOuterClass { - private BaseRegisterPbOuterClass() { - } + private BaseRegisterPbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor internal_static_BaseRegisterPb_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_BaseRegisterPb_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_BaseRegisterPb_AttributesEntry_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_BaseRegisterPb_AttributesEntry_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_BaseRegisterPb_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_BaseRegisterPb_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_BaseRegisterPb_AttributesEntry_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_BaseRegisterPb_AttributesEntry_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\024BaseRegisterPb.proto\"\346\002\n\016BaseRegisterP" - + "b\022\022\n\ninstanceId\030\001 \001(\t\022\014\n\004zone\030\002 \001(\t\022\017\n\007a" - + "ppName\030\003 \001(\t\022\016\n\006dataId\030\004 \001(\t\022\r\n\005group\030\005 " - + "\001(\t\022\021\n\tprocessId\030\006 \001(\t\022\020\n\010registId\030\007 \001(\t" - + "\022\020\n\010clientId\030\010 \001(\t\022\022\n\ndataInfoId\030\t \001(\t\022\n" - + "\n\002ip\030\n \001(\t\022\014\n\004port\030\013 \001(\005\022\021\n\teventType\030\014 " - + "\001(\t\022\017\n\007version\030\r \001(\003\022\021\n\ttimestamp\030\016 \001(\003\022" - + "3\n\nattributes\030\017 \003(\0132\037.BaseRegisterPb.Att" - + "ributesEntry\0321\n\017AttributesEntry\022\013\n\003key\030\001" - + " \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001B7\n/com.alipay.so" - + "fa.registry.common.model.client.pbP\001Z\002pb" - + "b\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{}, - assigner); - internal_static_BaseRegisterPb_descriptor = getDescriptor() - .getMessageTypes().get(0); - internal_static_BaseRegisterPb_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_BaseRegisterPb_descriptor, - new java.lang.String[]{"InstanceId", "Zone", "AppName", - "DataId", "Group", "ProcessId", "RegistId", "ClientId", - "DataInfoId", "Ip", "Port", "EventType", "Version", - "Timestamp", "Attributes",}); - internal_static_BaseRegisterPb_AttributesEntry_descriptor = internal_static_BaseRegisterPb_descriptor - .getNestedTypes().get(0); - internal_static_BaseRegisterPb_AttributesEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_BaseRegisterPb_AttributesEntry_descriptor, - new java.lang.String[]{"Key", "Value",}); - } + static { + java.lang.String[] descriptorData = { + "\n\024BaseRegisterPb.proto\"\346\002\n\016BaseRegisterP" + + "b\022\022\n\ninstanceId\030\001 \001(\t\022\014\n\004zone\030\002 \001(\t\022\017\n\007a" + + "ppName\030\003 \001(\t\022\016\n\006dataId\030\004 \001(\t\022\r\n\005group\030\005 " + + "\001(\t\022\021\n\tprocessId\030\006 \001(\t\022\020\n\010registId\030\007 \001(\t" + + "\022\020\n\010clientId\030\010 \001(\t\022\022\n\ndataInfoId\030\t \001(\t\022\n" + + "\n\002ip\030\n \001(\t\022\014\n\004port\030\013 \001(\005\022\021\n\teventType\030\014 " + + "\001(\t\022\017\n\007version\030\r \001(\003\022\021\n\ttimestamp\030\016 \001(\003\022" + + "3\n\nattributes\030\017 \003(\0132\037.BaseRegisterPb.Att" + + "ributesEntry\0321\n\017AttributesEntry\022\013\n\003key\030\001" + + " \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001B7\n/com.alipay.so" + + "fa.registry.common.model.client.pbP\001Z\002pb" + + "b\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_BaseRegisterPb_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_BaseRegisterPb_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_BaseRegisterPb_descriptor, + new java.lang.String[] { + "InstanceId", + "Zone", + "AppName", + "DataId", + "Group", + "ProcessId", + "RegistId", + "ClientId", + "DataInfoId", + "Ip", + "Port", + "EventType", + "Version", + "Timestamp", + "Attributes", + }); + internal_static_BaseRegisterPb_AttributesEntry_descriptor = + internal_static_BaseRegisterPb_descriptor.getNestedTypes().get(0); + internal_static_BaseRegisterPb_AttributesEntry_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_BaseRegisterPb_AttributesEntry_descriptor, + new java.lang.String[] { + "Key", "Value", + }); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPb.java index 69485b0cc..45a5652c5 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPb.java @@ -14,522 +14,512 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: DataBoxPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code DataBoxPb} - */ -public final class DataBoxPb extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:DataBoxPb) - DataBoxPbOrBuilder { - private static final long serialVersionUID = 0L; - - // Use DataBoxPb.newBuilder() to construct. - private DataBoxPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private DataBoxPb() { - data_ = ""; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } +/** Protobuf type {@code DataBoxPb} */ +public final class DataBoxPb extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:DataBoxPb) + DataBoxPbOrBuilder { + private static final long serialVersionUID = 0L; + + // Use DataBoxPb.newBuilder() to construct. + private DataBoxPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private DataBoxPb() { + data_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private DataBoxPb( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); - private DataBoxPb(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - - data_ = s; - break; - } - } + data_ = s; + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass + .internal_static_DataBoxPb_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass + .internal_static_DataBoxPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.class, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder.class); + } + + public static final int DATA_FIELD_NUMBER = 1; + private volatile java.lang.Object data_; + + /** string data = 1; */ + public java.lang.String getData() { + java.lang.Object ref = data_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + data_ = s; + return s; + } + } + + /** string data = 1; */ + public com.google.protobuf.ByteString getDataBytes() { + java.lang.Object ref = data_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + data_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getDataBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, data_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!getDataBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, data_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.DataBoxPb)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb other = + (com.alipay.sofa.registry.common.model.client.pb.DataBoxPb) obj; + + boolean result = true; + result = result && getData().equals(other.getData()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + DATA_FIELD_NUMBER; + hash = (53 * hash) + getData().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code DataBoxPb} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:DataBoxPb) + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass.internal_static_DataBoxPb_descriptor; + return com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass + .internal_static_DataBoxPb_descriptor; } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass.internal_static_DataBoxPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.class, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder.class); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass + .internal_static_DataBoxPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.class, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder.class); } - public static final int DATA_FIELD_NUMBER = 1; - private volatile java.lang.Object data_; - - /** - * string data = 1; - */ - public java.lang.String getData() { - java.lang.Object ref = data_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - data_ = s; - return s; - } + // Construct using com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - /** - * string data = 1; - */ - public com.google.protobuf.ByteString getDataBytes() { - java.lang.Object ref = data_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - data_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (!getDataBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, data_); - } - unknownFields.writeTo(output); - } - - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - if (!getDataBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, data_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.DataBoxPb)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb other = (com.alipay.sofa.registry.common.model.client.pb.DataBoxPb) obj; + public Builder clear() { + super.clear(); + data_ = ""; - boolean result = true; - result = result && getData().equals(other.getData()); - result = result && unknownFields.equals(other.unknownFields); - return result; + return this; } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + DATA_FIELD_NUMBER; - hash = (53 * hash) + getData().hashCode(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass + .internal_static_DataBoxPb_descriptor; } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance(); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb build() { + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb result = + new com.alipay.sofa.registry.common.model.client.pb.DataBoxPb(this); + result.data_ = data_; + onBuilt(); + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clone() { + return (Builder) super.clone(); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.DataBoxPb) { + return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.DataBoxPb) other); + } else { + super.mergeFrom(other); + return this; + } } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb other) { + if (other == com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance()) + return this; + if (!other.getData().isEmpty()) { + data_ = other.data_; + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public final boolean isInitialized() { + return true; } - public Builder newBuilderForType() { - return newBuilder(); + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.DataBoxPb) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } + private java.lang.Object data_ = ""; - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + /** string data = 1; */ + public java.lang.String getData() { + java.lang.Object ref = data_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + data_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string data = 1; */ + public com.google.protobuf.ByteString getDataBytes() { + java.lang.Object ref = data_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + data_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } + /** string data = 1; */ + public Builder setData(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + data_ = value; + onChanged(); + return this; } - /** - * Protobuf type {@code DataBoxPb} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:DataBoxPb) - com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass.internal_static_DataBoxPb_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass.internal_static_DataBoxPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.class, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - data_ = ""; - - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass.internal_static_DataBoxPb_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb build() { - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb result = new com.alipay.sofa.registry.common.model.client.pb.DataBoxPb( - this); - result.data_ = data_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.DataBoxPb) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.DataBoxPb) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.DataBoxPb - .getDefaultInstance()) - return this; - if (!other.getData().isEmpty()) { - data_ = other.data_; - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.DataBoxPb) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } + /** string data = 1; */ + public Builder clearData() { - private java.lang.Object data_ = ""; - - /** - * string data = 1; - */ - public java.lang.String getData() { - java.lang.Object ref = data_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - data_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + data_ = getDefaultInstance().getData(); + onChanged(); + return this; + } - /** - * string data = 1; - */ - public com.google.protobuf.ByteString getDataBytes() { - java.lang.Object ref = data_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - data_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string data = 1; */ + public Builder setDataBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string data = 1; - */ - public Builder setData(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + data_ = value; + onChanged(); + return this; + } - data_ = value; - onChanged(); - return this; - } + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } - /** - * string data = 1; - */ - public Builder clearData() { + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - data_ = getDefaultInstance().getData(); - onChanged(); - return this; - } + // @@protoc_insertion_point(builder_scope:DataBoxPb) + } - /** - * string data = 1; - */ - public Builder setDataBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + // @@protoc_insertion_point(class_scope:DataBoxPb) + private static final com.alipay.sofa.registry.common.model.client.pb.DataBoxPb DEFAULT_INSTANCE; - data_ = value; - onChanged(); - return this; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.DataBoxPb(); + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public DataBoxPb parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new DataBoxPb(input, extensionRegistry); } + }; - // @@protoc_insertion_point(builder_scope:DataBoxPb) - } - - // @@protoc_insertion_point(class_scope:DataBoxPb) - private static final com.alipay.sofa.registry.common.model.client.pb.DataBoxPb DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.DataBoxPb(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public DataBoxPb parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new DataBoxPb( - input, - extensionRegistry); - } - }; + public static com.google.protobuf.Parser parser() { + return PARSER; + } - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPbOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPbOrBuilder.java index 1b8fa4a68..bb03c8f88 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPbOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPbOrBuilder.java @@ -14,22 +14,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: DataBoxPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface DataBoxPbOrBuilder extends -// @@protoc_insertion_point(interface_extends:DataBoxPb) - com.google.protobuf.MessageOrBuilder { +public interface DataBoxPbOrBuilder + extends + // @@protoc_insertion_point(interface_extends:DataBoxPb) + com.google.protobuf.MessageOrBuilder { - /** - * string data = 1; - */ - java.lang.String getData(); + /** string data = 1; */ + java.lang.String getData(); - /** - * string data = 1; - */ - com.google.protobuf.ByteString getDataBytes(); + /** string data = 1; */ + com.google.protobuf.ByteString getDataBytes(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPbOuterClass.java index 3f7f7f38c..07b87bdd2 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxPbOuterClass.java @@ -14,53 +14,51 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: DataBoxPb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class DataBoxPbOuterClass { - private DataBoxPbOuterClass() { - } + private DataBoxPbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor internal_static_DataBoxPb_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_DataBoxPb_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_DataBoxPb_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_DataBoxPb_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\017DataBoxPb.proto\"\031\n\tDataBoxPb\022\014\n\004data\030\001" - + " \001(\tB7\n/com.alipay.sofa.registry.common." - + "model.client.pbP\001Z\002pbb\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{}, - assigner); - internal_static_DataBoxPb_descriptor = getDescriptor() - .getMessageTypes().get(0); - internal_static_DataBoxPb_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_DataBoxPb_descriptor, - new java.lang.String[]{"Data",}); - } + static { + java.lang.String[] descriptorData = { + "\n\017DataBoxPb.proto\"\031\n\tDataBoxPb\022\014\n\004data\030\001" + + " \001(\tB7\n/com.alipay.sofa.registry.common." + + "model.client.pbP\001Z\002pbb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_DataBoxPb_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_DataBoxPb_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_DataBoxPb_descriptor, + new java.lang.String[] { + "Data", + }); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPb.java index b5dfef38f..66e17bae3 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPb.java @@ -14,751 +14,747 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: DataBoxesPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code DataBoxesPb} - */ -public final class DataBoxesPb extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:DataBoxesPb) - DataBoxesPbOrBuilder { - private static final long serialVersionUID = 0L; - - // Use DataBoxesPb.newBuilder() to construct. - private DataBoxesPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private DataBoxesPb() { - data_ = java.util.Collections.emptyList(); - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } - - private DataBoxesPb(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - data_ = new java.util.ArrayList(); - mutable_bitField0_ |= 0x00000001; - } - data_.add(input.readMessage( - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.parser(), - extensionRegistry)); - break; - } - } +/** Protobuf type {@code DataBoxesPb} */ +public final class DataBoxesPb extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:DataBoxesPb) + DataBoxesPbOrBuilder { + private static final long serialVersionUID = 0L; + + // Use DataBoxesPb.newBuilder() to construct. + private DataBoxesPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private DataBoxesPb() { + data_ = java.util.Collections.emptyList(); + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private DataBoxesPb( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - data_ = java.util.Collections.unmodifiableList(data_); + case 10: + { + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + data_ = + new java.util.ArrayList< + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb>(); + mutable_bitField0_ |= 0x00000001; + } + data_.add( + input.readMessage( + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.parser(), + extensionRegistry)); + break; } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + data_ = java.util.Collections.unmodifiableList(data_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass + .internal_static_DataBoxesPb_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass + .internal_static_DataBoxesPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.class, + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.Builder.class); + } + + public static final int DATA_FIELD_NUMBER = 1; + private java.util.List data_; + + /** repeated .DataBoxPb data = 1; */ + public java.util.List getDataList() { + return data_; + } + + /** repeated .DataBoxPb data = 1; */ + public java.util.List< + ? extends com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder> + getDataOrBuilderList() { + return data_; + } + + /** repeated .DataBoxPb data = 1; */ + public int getDataCount() { + return data_.size(); + } + + /** repeated .DataBoxPb data = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getData(int index) { + return data_.get(index); + } + + /** repeated .DataBoxPb data = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataOrBuilder( + int index) { + return data_.get(index); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + for (int i = 0; i < data_.size(); i++) { + output.writeMessage(1, data_.get(i)); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + for (int i = 0; i < data_.size(); i++) { + size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, data_.get(i)); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb other = + (com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb) obj; + + boolean result = true; + result = result && getDataList().equals(other.getDataList()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (getDataCount() > 0) { + hash = (37 * hash) + DATA_FIELD_NUMBER; + hash = (53 * hash) + getDataList().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code DataBoxesPb} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:DataBoxesPb) + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass.internal_static_DataBoxesPb_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass.internal_static_DataBoxesPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.class, - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.Builder.class); + return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass + .internal_static_DataBoxesPb_descriptor; } - public static final int DATA_FIELD_NUMBER = 1; - private java.util.List data_; - - /** - * repeated .DataBoxPb data = 1; - */ - public java.util.List getDataList() { - return data_; + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass + .internal_static_DataBoxesPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.class, + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.Builder.class); } - /** - * repeated .DataBoxPb data = 1; - */ - public java.util.List getDataOrBuilderList() { - return data_; + // Construct using com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - /** - * repeated .DataBoxPb data = 1; - */ - public int getDataCount() { - return data_.size(); - } - - /** - * repeated .DataBoxPb data = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getData(int index) { - return data_.get(index); + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - /** - * repeated .DataBoxPb data = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataOrBuilder(int index) { - return data_.get(index); + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { + getDataFieldBuilder(); + } } - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; + public Builder clear() { + super.clear(); + if (dataBuilder_ == null) { + data_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000001); + } else { + dataBuilder_.clear(); + } + return this; } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - for (int i = 0; i < data_.size(); i++) { - output.writeMessage(1, data_.get(i)); - } - unknownFields.writeTo(output); + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass + .internal_static_DataBoxesPb_descriptor; } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - for (int i = 0; i < data_.size(); i++) { - size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, data_.get(i)); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.getDefaultInstance(); } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb other = (com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb) obj; - - boolean result = true; - result = result && getDataList().equals(other.getDataList()); - result = result && unknownFields.equals(other.unknownFields); - return result; + public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb build() { + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (getDataCount() > 0) { - hash = (37 * hash) + DATA_FIELD_NUMBER; - hash = (53 * hash) + getDataList().hashCode(); + public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb result = + new com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb(this); + int from_bitField0_ = bitField0_; + if (dataBuilder_ == null) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { + data_ = java.util.Collections.unmodifiableList(data_); + bitField0_ = (bitField0_ & ~0x00000001); } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + result.data_ = data_; + } else { + result.data_ = dataBuilder_.build(); + } + onBuilt(); + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder clone() { + return (Builder) super.clone(); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb) { + return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb) other); + } else { + super.mergeFrom(other); + return this; + } } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } - - public Builder newBuilderForType() { - return newBuilder(); - } - - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } - - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - - /** - * Protobuf type {@code DataBoxesPb} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:DataBoxesPb) - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass.internal_static_DataBoxesPb_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass.internal_static_DataBoxesPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.class, - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - getDataFieldBuilder(); - } - } - - public Builder clear() { - super.clear(); - if (dataBuilder_ == null) { - data_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000001); - } else { - dataBuilder_.clear(); - } - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass.internal_static_DataBoxesPb_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb build() { - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb result = new com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb( - this); - int from_bitField0_ = bitField0_; - if (dataBuilder_ == null) { - if (((bitField0_ & 0x00000001) == 0x00000001)) { - data_ = java.util.Collections.unmodifiableList(data_); - bitField0_ = (bitField0_ & ~0x00000001); - } - result.data_ = data_; - } else { - result.data_ = dataBuilder_.build(); - } - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); + public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb other) { + if (other == com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb.getDefaultInstance()) + return this; + if (dataBuilder_ == null) { + if (!other.data_.isEmpty()) { + if (data_.isEmpty()) { + data_ = other.data_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureDataIsMutable(); + data_.addAll(other.data_); + } + onChanged(); } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb - .getDefaultInstance()) - return this; - if (dataBuilder_ == null) { - if (!other.data_.isEmpty()) { - if (data_.isEmpty()) { - data_ = other.data_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureDataIsMutable(); - data_.addAll(other.data_); - } - onChanged(); - } - } else { - if (!other.data_.isEmpty()) { - if (dataBuilder_.isEmpty()) { - dataBuilder_.dispose(); - dataBuilder_ = null; - data_ = other.data_; - bitField0_ = (bitField0_ & ~0x00000001); - dataBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDataFieldBuilder() - : null; - } else { - dataBuilder_.addAllMessages(other.data_); - } - } - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private java.util.List data_ = java.util.Collections - .emptyList(); - - private void ensureDataIsMutable() { - if (!((bitField0_ & 0x00000001) == 0x00000001)) { - data_ = new java.util.ArrayList( - data_); - bitField0_ |= 0x00000001; - } - } - - private com.google.protobuf.RepeatedFieldBuilderV3 dataBuilder_; - - /** - * repeated .DataBoxPb data = 1; - */ - public java.util.List getDataList() { - if (dataBuilder_ == null) { - return java.util.Collections.unmodifiableList(data_); - } else { - return dataBuilder_.getMessageList(); - } - } - - /** - * repeated .DataBoxPb data = 1; - */ - public int getDataCount() { - if (dataBuilder_ == null) { - return data_.size(); - } else { - return dataBuilder_.getCount(); - } - } - - /** - * repeated .DataBoxPb data = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getData(int index) { - if (dataBuilder_ == null) { - return data_.get(index); - } else { - return dataBuilder_.getMessage(index); - } - } - - /** - * repeated .DataBoxPb data = 1; - */ - public Builder setData(int index, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { - if (dataBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensureDataIsMutable(); - data_.set(index, value); - onChanged(); - } else { - dataBuilder_.setMessage(index, value); - } - return this; - } - - /** - * repeated .DataBoxPb data = 1; - */ - public Builder setData(int index, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { - if (dataBuilder_ == null) { - ensureDataIsMutable(); - data_.set(index, builderForValue.build()); - onChanged(); - } else { - dataBuilder_.setMessage(index, builderForValue.build()); - } - return this; - } - - /** - * repeated .DataBoxPb data = 1; - */ - public Builder addData(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { - if (dataBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensureDataIsMutable(); - data_.add(value); - onChanged(); - } else { - dataBuilder_.addMessage(value); - } - return this; - } - - /** - * repeated .DataBoxPb data = 1; - */ - public Builder addData(int index, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { - if (dataBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensureDataIsMutable(); - data_.add(index, value); - onChanged(); - } else { - dataBuilder_.addMessage(index, value); - } - return this; - } - - /** - * repeated .DataBoxPb data = 1; - */ - public Builder addData(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { - if (dataBuilder_ == null) { - ensureDataIsMutable(); - data_.add(builderForValue.build()); - onChanged(); - } else { - dataBuilder_.addMessage(builderForValue.build()); - } - return this; - } - - /** - * repeated .DataBoxPb data = 1; - */ - public Builder addData(int index, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { - if (dataBuilder_ == null) { - ensureDataIsMutable(); - data_.add(index, builderForValue.build()); - onChanged(); - } else { - dataBuilder_.addMessage(index, builderForValue.build()); - } - return this; - } - - /** - * repeated .DataBoxPb data = 1; - */ - public Builder addAllData(java.lang.Iterable values) { - if (dataBuilder_ == null) { - ensureDataIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll(values, data_); - onChanged(); - } else { - dataBuilder_.addAllMessages(values); - } - return this; - } - - /** - * repeated .DataBoxPb data = 1; - */ - public Builder clearData() { - if (dataBuilder_ == null) { - data_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000001); - onChanged(); - } else { - dataBuilder_.clear(); - } - return this; - } - - /** - * repeated .DataBoxPb data = 1; - */ - public Builder removeData(int index) { - if (dataBuilder_ == null) { - ensureDataIsMutable(); - data_.remove(index); - onChanged(); - } else { - dataBuilder_.remove(index); - } - return this; - } - - /** - * repeated .DataBoxPb data = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder getDataBuilder(int index) { - return getDataFieldBuilder().getBuilder(index); - } - - /** - * repeated .DataBoxPb data = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataOrBuilder(int index) { - if (dataBuilder_ == null) { - return data_.get(index); - } else { - return dataBuilder_.getMessageOrBuilder(index); - } - } - - /** - * repeated .DataBoxPb data = 1; - */ - public java.util.List getDataOrBuilderList() { - if (dataBuilder_ != null) { - return dataBuilder_.getMessageOrBuilderList(); - } else { - return java.util.Collections.unmodifiableList(data_); - } - } - - /** - * repeated .DataBoxPb data = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder addDataBuilder() { - return getDataFieldBuilder().addBuilder( - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance()); - } - - /** - * repeated .DataBoxPb data = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder addDataBuilder(int index) { - return getDataFieldBuilder().addBuilder(index, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance()); + } else { + if (!other.data_.isEmpty()) { + if (dataBuilder_.isEmpty()) { + dataBuilder_.dispose(); + dataBuilder_ = null; + data_ = other.data_; + bitField0_ = (bitField0_ & ~0x00000001); + dataBuilder_ = + com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders + ? getDataFieldBuilder() + : null; + } else { + dataBuilder_.addAllMessages(other.data_); + } } - - /** - * repeated .DataBoxPb data = 1; - */ - public java.util.List getDataBuilderList() { - return getDataFieldBuilder().getBuilderList(); - } - - private com.google.protobuf.RepeatedFieldBuilderV3 getDataFieldBuilder() { - if (dataBuilder_ == null) { - dataBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3( - data_, ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), - isClean()); - data_ = null; - } - return dataBuilder_; - } - - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } - - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - // @@protoc_insertion_point(builder_scope:DataBoxesPb) + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - // @@protoc_insertion_point(class_scope:DataBoxesPb) - private static final com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb(); + public final boolean isInitialized() { + return true; } - public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDefaultInstance() { - return DEFAULT_INSTANCE; + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; } - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public DataBoxesPb parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new DataBoxesPb( - input, - extensionRegistry); - } - }; + private int bitField0_; + + private java.util.List data_ = + java.util.Collections.emptyList(); - public static com.google.protobuf.Parser parser() { - return PARSER; + private void ensureDataIsMutable() { + if (!((bitField0_ & 0x00000001) == 0x00000001)) { + data_ = + new java.util.ArrayList( + data_); + bitField0_ |= 0x00000001; + } } - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; + private com.google.protobuf.RepeatedFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder> + dataBuilder_; + + /** repeated .DataBoxPb data = 1; */ + public java.util.List getDataList() { + if (dataBuilder_ == null) { + return java.util.Collections.unmodifiableList(data_); + } else { + return dataBuilder_.getMessageList(); + } } - public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDefaultInstanceForType() { - return DEFAULT_INSTANCE; + /** repeated .DataBoxPb data = 1; */ + public int getDataCount() { + if (dataBuilder_ == null) { + return data_.size(); + } else { + return dataBuilder_.getCount(); + } } + /** repeated .DataBoxPb data = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getData(int index) { + if (dataBuilder_ == null) { + return data_.get(index); + } else { + return dataBuilder_.getMessage(index); + } + } + + /** repeated .DataBoxPb data = 1; */ + public Builder setData( + int index, com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { + if (dataBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureDataIsMutable(); + data_.set(index, value); + onChanged(); + } else { + dataBuilder_.setMessage(index, value); + } + return this; + } + + /** repeated .DataBoxPb data = 1; */ + public Builder setData( + int index, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { + if (dataBuilder_ == null) { + ensureDataIsMutable(); + data_.set(index, builderForValue.build()); + onChanged(); + } else { + dataBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + + /** repeated .DataBoxPb data = 1; */ + public Builder addData(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { + if (dataBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureDataIsMutable(); + data_.add(value); + onChanged(); + } else { + dataBuilder_.addMessage(value); + } + return this; + } + + /** repeated .DataBoxPb data = 1; */ + public Builder addData( + int index, com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { + if (dataBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureDataIsMutable(); + data_.add(index, value); + onChanged(); + } else { + dataBuilder_.addMessage(index, value); + } + return this; + } + + /** repeated .DataBoxPb data = 1; */ + public Builder addData( + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { + if (dataBuilder_ == null) { + ensureDataIsMutable(); + data_.add(builderForValue.build()); + onChanged(); + } else { + dataBuilder_.addMessage(builderForValue.build()); + } + return this; + } + + /** repeated .DataBoxPb data = 1; */ + public Builder addData( + int index, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { + if (dataBuilder_ == null) { + ensureDataIsMutable(); + data_.add(index, builderForValue.build()); + onChanged(); + } else { + dataBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + + /** repeated .DataBoxPb data = 1; */ + public Builder addAllData( + java.lang.Iterable + values) { + if (dataBuilder_ == null) { + ensureDataIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, data_); + onChanged(); + } else { + dataBuilder_.addAllMessages(values); + } + return this; + } + + /** repeated .DataBoxPb data = 1; */ + public Builder clearData() { + if (dataBuilder_ == null) { + data_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + } else { + dataBuilder_.clear(); + } + return this; + } + + /** repeated .DataBoxPb data = 1; */ + public Builder removeData(int index) { + if (dataBuilder_ == null) { + ensureDataIsMutable(); + data_.remove(index); + onChanged(); + } else { + dataBuilder_.remove(index); + } + return this; + } + + /** repeated .DataBoxPb data = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder getDataBuilder( + int index) { + return getDataFieldBuilder().getBuilder(index); + } + + /** repeated .DataBoxPb data = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataOrBuilder( + int index) { + if (dataBuilder_ == null) { + return data_.get(index); + } else { + return dataBuilder_.getMessageOrBuilder(index); + } + } + + /** repeated .DataBoxPb data = 1; */ + public java.util.List< + ? extends com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder> + getDataOrBuilderList() { + if (dataBuilder_ != null) { + return dataBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(data_); + } + } + + /** repeated .DataBoxPb data = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder addDataBuilder() { + return getDataFieldBuilder() + .addBuilder( + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance()); + } + + /** repeated .DataBoxPb data = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder addDataBuilder( + int index) { + return getDataFieldBuilder() + .addBuilder( + index, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance()); + } + + /** repeated .DataBoxPb data = 1; */ + public java.util.List + getDataBuilderList() { + return getDataFieldBuilder().getBuilderList(); + } + + private com.google.protobuf.RepeatedFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder> + getDataFieldBuilder() { + if (dataBuilder_ == null) { + dataBuilder_ = + new com.google.protobuf.RepeatedFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder>( + data_, + ((bitField0_ & 0x00000001) == 0x00000001), + getParentForChildren(), + isClean()); + data_ = null; + } + return dataBuilder_; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:DataBoxesPb) + } + + // @@protoc_insertion_point(class_scope:DataBoxesPb) + private static final com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb(); + } + + public static com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public DataBoxesPb parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new DataBoxesPb(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPbOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPbOrBuilder.java index 71b088332..6a79b8171 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPbOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPbOrBuilder.java @@ -14,37 +14,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: DataBoxesPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface DataBoxesPbOrBuilder extends -// @@protoc_insertion_point(interface_extends:DataBoxesPb) - com.google.protobuf.MessageOrBuilder { +public interface DataBoxesPbOrBuilder + extends + // @@protoc_insertion_point(interface_extends:DataBoxesPb) + com.google.protobuf.MessageOrBuilder { - /** - * repeated .DataBoxPb data = 1; - */ - java.util.List getDataList(); + /** repeated .DataBoxPb data = 1; */ + java.util.List getDataList(); - /** - * repeated .DataBoxPb data = 1; - */ - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getData(int index); + /** repeated .DataBoxPb data = 1; */ + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getData(int index); - /** - * repeated .DataBoxPb data = 1; - */ - int getDataCount(); + /** repeated .DataBoxPb data = 1; */ + int getDataCount(); - /** - * repeated .DataBoxPb data = 1; - */ - java.util.List getDataOrBuilderList(); + /** repeated .DataBoxPb data = 1; */ + java.util.List + getDataOrBuilderList(); - /** - * repeated .DataBoxPb data = 1; - */ - com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataOrBuilder(int index); + /** repeated .DataBoxPb data = 1; */ + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataOrBuilder(int index); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPbOuterClass.java index 3a5788611..cdad25fdb 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/DataBoxesPbOuterClass.java @@ -14,57 +14,57 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: DataBoxesPb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class DataBoxesPbOuterClass { - private DataBoxesPbOuterClass() { - } + private DataBoxesPbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor internal_static_DataBoxesPb_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_DataBoxesPb_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_DataBoxesPb_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_DataBoxesPb_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\021DataBoxesPb.proto\032\017DataBoxPb.proto\"\'\n\013" - + "DataBoxesPb\022\030\n\004data\030\001 \003(\0132\n.DataBoxPbB7\n" - + "/com.alipay.sofa.registry.common.model.c" - + "lient.pbP\001Z\002pbb\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom( - descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass - .getDescriptor(),}, assigner); - internal_static_DataBoxesPb_descriptor = getDescriptor() - .getMessageTypes().get(0); - internal_static_DataBoxesPb_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_DataBoxesPb_descriptor, - new java.lang.String[]{"Data",}); - com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass - .getDescriptor(); - } + static { + java.lang.String[] descriptorData = { + "\n\021DataBoxesPb.proto\032\017DataBoxPb.proto\"\'\n\013" + + "DataBoxesPb\022\030\n\004data\030\001 \003(\0132\n.DataBoxPbB7\n" + + "/com.alipay.sofa.registry.common.model.c" + + "lient.pbP\001Z\002pbb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass.getDescriptor(), + }, + assigner); + internal_static_DataBoxesPb_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_DataBoxesPb_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_DataBoxesPb_descriptor, + new java.lang.String[] { + "Data", + }); + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass.getDescriptor(); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/EventTypePb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/EventTypePb.java index c78e296f3..4a311b827 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/EventTypePb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/EventTypePb.java @@ -14,102 +14,89 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: EventTypePb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf enum {@code EventTypePb} - */ +/** Protobuf enum {@code EventTypePb} */ public enum EventTypePb implements com.google.protobuf.ProtocolMessageEnum { - /** - * REGISTER = 0; - */ - REGISTER(0), - /** - * UNREGISTER = 1; - */ - UNREGISTER(1), UNRECOGNIZED(-1), ; - - /** - * REGISTER = 0; - */ - public static final int REGISTER_VALUE = 0; - /** - * UNREGISTER = 1; - */ - public static final int UNREGISTER_VALUE = 1; - - public final int getNumber() { - if (this == UNRECOGNIZED) { - throw new java.lang.IllegalArgumentException( - "Can't get the number of an unknown enum value."); - } - return value; + /** REGISTER = 0; */ + REGISTER(0), + /** UNREGISTER = 1; */ + UNREGISTER(1), + UNRECOGNIZED(-1), + ; + + /** REGISTER = 0; */ + public static final int REGISTER_VALUE = 0; + /** UNREGISTER = 1; */ + public static final int UNREGISTER_VALUE = 1; + + public final int getNumber() { + if (this == UNRECOGNIZED) { + throw new java.lang.IllegalArgumentException( + "Can't get the number of an unknown enum value."); } - - /** - * @deprecated Use {@link #forNumber(int)} instead. - */ - @java.lang.Deprecated - public static EventTypePb valueOf(int value) { - return forNumber(value); + return value; + } + + /** @deprecated Use {@link #forNumber(int)} instead. */ + @java.lang.Deprecated + public static EventTypePb valueOf(int value) { + return forNumber(value); + } + + public static EventTypePb forNumber(int value) { + switch (value) { + case 0: + return REGISTER; + case 1: + return UNREGISTER; + default: + return null; } + } - public static EventTypePb forNumber(int value) { - switch (value) { - case 0: - return REGISTER; - case 1: - return UNREGISTER; - default: - return null; + public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { + return internalValueMap; + } + + private static final com.google.protobuf.Internal.EnumLiteMap internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public EventTypePb findValueByNumber(int number) { + return EventTypePb.forNumber(number); } - } + }; - public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { - return internalValueMap; - } + public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { + return getDescriptor().getValues().get(ordinal()); + } - private static final com.google.protobuf.Internal.EnumLiteMap internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { - public EventTypePb findValueByNumber(int number) { - return EventTypePb - .forNumber(number); - } - }; + public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { + return getDescriptor(); + } - public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { - return getDescriptor().getValues().get(ordinal()); - } + public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.EventTypePbOuterClass.getDescriptor() + .getEnumTypes() + .get(0); + } - public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { - return getDescriptor(); - } + private static final EventTypePb[] VALUES = values(); - public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.EventTypePbOuterClass - .getDescriptor().getEnumTypes().get(0); + public static EventTypePb valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } - - private static final EventTypePb[] VALUES = values(); - - public static EventTypePb valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { - if (desc.getType() != getDescriptor()) { - throw new java.lang.IllegalArgumentException( - "EnumValueDescriptor is not for this type."); - } - if (desc.getIndex() == -1) { - return UNRECOGNIZED; - } - return VALUES[desc.getIndex()]; + if (desc.getIndex() == -1) { + return UNRECOGNIZED; } + return VALUES[desc.getIndex()]; + } - private final int value; + private final int value; - private EventTypePb(int value) { - this.value = value; - } + private EventTypePb(int value) { + this.value = value; + } - // @@protoc_insertion_point(enum_scope:EventTypePb) + // @@protoc_insertion_point(enum_scope:EventTypePb) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/EventTypePbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/EventTypePbOuterClass.java index 22ca5368d..e96631c2a 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/EventTypePbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/EventTypePbOuterClass.java @@ -14,46 +14,41 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: EventTypePb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class EventTypePbOuterClass { - private EventTypePbOuterClass() { - } + private EventTypePbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\021EventTypePb.proto*+\n\013EventTypePb\022\014\n\010RE" - + "GISTER\020\000\022\016\n\nUNREGISTER\020\001B7\n/com.alipay.s" - + "ofa.registry.common.model.client.pbP\001Z\002p" - + "bb\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{}, - assigner); - } + static { + java.lang.String[] descriptorData = { + "\n\021EventTypePb.proto*+\n\013EventTypePb\022\014\n\010RE" + + "GISTER\020\000\022\016\n\nUNREGISTER\020\001B7\n/com.alipay.s" + + "ofa.registry.common.model.client.pbP\001Z\002p" + + "bb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsRequest.java index 51d52358f..02b996c5c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsRequest.java @@ -14,575 +14,564 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code GetRevisionsRequest} - */ -public final class GetRevisionsRequest extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:GetRevisionsRequest) - GetRevisionsRequestOrBuilder { - private static final long serialVersionUID = 0L; - - // Use GetRevisionsRequest.newBuilder() to construct. - private GetRevisionsRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private GetRevisionsRequest() { - revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } - - private GetRevisionsRequest(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - revisions_ = new com.google.protobuf.LazyStringArrayList(); - mutable_bitField0_ |= 0x00000001; - } - revisions_.add(s); - break; - } - } +/** Protobuf type {@code GetRevisionsRequest} */ +public final class GetRevisionsRequest extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:GetRevisionsRequest) + GetRevisionsRequestOrBuilder { + private static final long serialVersionUID = 0L; + + // Use GetRevisionsRequest.newBuilder() to construct. + private GetRevisionsRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private GetRevisionsRequest() { + revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private GetRevisionsRequest( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - revisions_ = revisions_.getUnmodifiableView(); + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + revisions_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000001; + } + revisions_.add(s); + break; } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + revisions_ = revisions_.getUnmodifiableView(); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_GetRevisionsRequest_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_GetRevisionsRequest_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest.class, + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest.Builder.class); + } + + public static final int REVISIONS_FIELD_NUMBER = 1; + private com.google.protobuf.LazyStringList revisions_; + + /** repeated string revisions = 1; */ + public com.google.protobuf.ProtocolStringList getRevisionsList() { + return revisions_; + } + + /** repeated string revisions = 1; */ + public int getRevisionsCount() { + return revisions_.size(); + } + + /** repeated string revisions = 1; */ + public java.lang.String getRevisions(int index) { + return revisions_.get(index); + } + + /** repeated string revisions = 1; */ + public com.google.protobuf.ByteString getRevisionsBytes(int index) { + return revisions_.getByteString(index); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + for (int i = 0; i < revisions_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, revisions_.getRaw(i)); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + { + int dataSize = 0; + for (int i = 0; i < revisions_.size(); i++) { + dataSize += computeStringSizeNoTag(revisions_.getRaw(i)); + } + size += dataSize; + size += 1 * getRevisionsList().size(); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest other = + (com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest) obj; + + boolean result = true; + result = result && getRevisionsList().equals(other.getRevisionsList()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (getRevisionsCount() > 0) { + hash = (37 * hash) + REVISIONS_FIELD_NUMBER; + hash = (53 * hash) + getRevisionsList().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code GetRevisionsRequest} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:GetRevisionsRequest) + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_GetRevisionsRequest_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_GetRevisionsRequest_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest.class, - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest.Builder.class); - } - - public static final int REVISIONS_FIELD_NUMBER = 1; - private com.google.protobuf.LazyStringList revisions_; - - /** - * repeated string revisions = 1; - */ - public com.google.protobuf.ProtocolStringList getRevisionsList() { - return revisions_; - } - - /** - * repeated string revisions = 1; - */ - public int getRevisionsCount() { - return revisions_.size(); - } - - /** - * repeated string revisions = 1; - */ - public java.lang.String getRevisions(int index) { - return revisions_.get(index); - } - - /** - * repeated string revisions = 1; - */ - public com.google.protobuf.ByteString getRevisionsBytes(int index) { - return revisions_.getByteString(index); - } - - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - for (int i = 0; i < revisions_.size(); i++) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, revisions_.getRaw(i)); - } - unknownFields.writeTo(output); + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_GetRevisionsRequest_descriptor; } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - { - int dataSize = 0; - for (int i = 0; i < revisions_.size(); i++) { - dataSize += computeStringSizeNoTag(revisions_.getRaw(i)); - } - size += dataSize; - size += 1 * getRevisionsList().size(); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_GetRevisionsRequest_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest.class, + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest.Builder.class); } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest other = (com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest) obj; - - boolean result = true; - result = result && getRevisionsList().equals(other.getRevisionsList()); - result = result && unknownFields.equals(other.unknownFields); - return result; + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (getRevisionsCount() > 0) { - hash = (37 * hash) + REVISIONS_FIELD_NUMBER; - hash = (53 * hash) + getRevisionsList().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clear() { + super.clear(); + revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_GetRevisionsRequest_descriptor; } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest + .getDefaultInstance(); } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest build() { + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest result = + new com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest(this); + int from_bitField0_ = bitField0_; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + revisions_ = revisions_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.revisions_ = revisions_; + onBuilt(); + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + public Builder clone() { + return (Builder) super.clone(); } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public Builder newBuilderForType() { - return newBuilder(); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest) other); + } else { + super.mergeFrom(other); + return this; + } } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest + .getDefaultInstance()) return this; + if (!other.revisions_.isEmpty()) { + if (revisions_.isEmpty()) { + revisions_ = other.revisions_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureRevisionsIsMutable(); + revisions_.addAll(other.revisions_); + } + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + public final boolean isInitialized() { + return true; } - /** - * Protobuf type {@code GetRevisionsRequest} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:GetRevisionsRequest) - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequestOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_GetRevisionsRequest_descriptor; + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_GetRevisionsRequest_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest.class, - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_GetRevisionsRequest_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest build() { - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest result = new com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest( - this); - int from_bitField0_ = bitField0_; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - revisions_ = revisions_.getUnmodifiableView(); - bitField0_ = (bitField0_ & ~0x00000001); - } - result.revisions_ = revisions_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest - .getDefaultInstance()) - return this; - if (!other.revisions_.isEmpty()) { - if (revisions_.isEmpty()) { - revisions_ = other.revisions_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureRevisionsIsMutable(); - revisions_.addAll(other.revisions_); - } - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private com.google.protobuf.LazyStringList revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; - - private void ensureRevisionsIsMutable() { - if (!((bitField0_ & 0x00000001) == 0x00000001)) { - revisions_ = new com.google.protobuf.LazyStringArrayList(revisions_); - bitField0_ |= 0x00000001; - } - } - - /** - * repeated string revisions = 1; - */ - public com.google.protobuf.ProtocolStringList getRevisionsList() { - return revisions_.getUnmodifiableView(); - } - - /** - * repeated string revisions = 1; - */ - public int getRevisionsCount() { - return revisions_.size(); - } - - /** - * repeated string revisions = 1; - */ - public java.lang.String getRevisions(int index) { - return revisions_.get(index); - } - - /** - * repeated string revisions = 1; - */ - public com.google.protobuf.ByteString getRevisionsBytes(int index) { - return revisions_.getByteString(index); - } - - /** - * repeated string revisions = 1; - */ - public Builder setRevisions(int index, java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureRevisionsIsMutable(); - revisions_.set(index, value); - onChanged(); - return this; - } - - /** - * repeated string revisions = 1; - */ - public Builder addRevisions(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureRevisionsIsMutable(); - revisions_.add(value); - onChanged(); - return this; - } - - /** - * repeated string revisions = 1; - */ - public Builder addAllRevisions(java.lang.Iterable values) { - ensureRevisionsIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll(values, revisions_); - onChanged(); - return this; - } - - /** - * repeated string revisions = 1; - */ - public Builder clearRevisions() { - revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - onChanged(); - return this; - } - - /** - * repeated string revisions = 1; - */ - public Builder addRevisionsBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - ensureRevisionsIsMutable(); - revisions_.add(value); - onChanged(); - return this; - } - - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } - - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - // @@protoc_insertion_point(builder_scope:GetRevisionsRequest) + } + return this; } - // @@protoc_insertion_point(class_scope:GetRevisionsRequest) - private static final com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest(); - } + private int bitField0_; - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest getDefaultInstance() { - return DEFAULT_INSTANCE; - } + private com.google.protobuf.LazyStringList revisions_ = + com.google.protobuf.LazyStringArrayList.EMPTY; - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public GetRevisionsRequest parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new GetRevisionsRequest( - input, - extensionRegistry); - } - }; + private void ensureRevisionsIsMutable() { + if (!((bitField0_ & 0x00000001) == 0x00000001)) { + revisions_ = new com.google.protobuf.LazyStringArrayList(revisions_); + bitField0_ |= 0x00000001; + } + } - public static com.google.protobuf.Parser parser() { - return PARSER; + /** repeated string revisions = 1; */ + public com.google.protobuf.ProtocolStringList getRevisionsList() { + return revisions_.getUnmodifiableView(); } - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; + /** repeated string revisions = 1; */ + public int getRevisionsCount() { + return revisions_.size(); } - public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest getDefaultInstanceForType() { - return DEFAULT_INSTANCE; + /** repeated string revisions = 1; */ + public java.lang.String getRevisions(int index) { + return revisions_.get(index); } + /** repeated string revisions = 1; */ + public com.google.protobuf.ByteString getRevisionsBytes(int index) { + return revisions_.getByteString(index); + } + + /** repeated string revisions = 1; */ + public Builder setRevisions(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureRevisionsIsMutable(); + revisions_.set(index, value); + onChanged(); + return this; + } + + /** repeated string revisions = 1; */ + public Builder addRevisions(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureRevisionsIsMutable(); + revisions_.add(value); + onChanged(); + return this; + } + + /** repeated string revisions = 1; */ + public Builder addAllRevisions(java.lang.Iterable values) { + ensureRevisionsIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, revisions_); + onChanged(); + return this; + } + + /** repeated string revisions = 1; */ + public Builder clearRevisions() { + revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + return this; + } + + /** repeated string revisions = 1; */ + public Builder addRevisionsBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureRevisionsIsMutable(); + revisions_.add(value); + onChanged(); + return this; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:GetRevisionsRequest) + } + + // @@protoc_insertion_point(class_scope:GetRevisionsRequest) + private static final com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest + DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest(); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest + getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public GetRevisionsRequest parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new GetRevisionsRequest(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsRequest + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsRequestOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsRequestOrBuilder.java index f58a80494..80a08b33f 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsRequestOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsRequestOrBuilder.java @@ -14,32 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface GetRevisionsRequestOrBuilder extends -// @@protoc_insertion_point(interface_extends:GetRevisionsRequest) - com.google.protobuf.MessageOrBuilder { +public interface GetRevisionsRequestOrBuilder + extends + // @@protoc_insertion_point(interface_extends:GetRevisionsRequest) + com.google.protobuf.MessageOrBuilder { - /** - * repeated string revisions = 1; - */ - java.util.List getRevisionsList(); + /** repeated string revisions = 1; */ + java.util.List getRevisionsList(); - /** - * repeated string revisions = 1; - */ - int getRevisionsCount(); + /** repeated string revisions = 1; */ + int getRevisionsCount(); - /** - * repeated string revisions = 1; - */ - java.lang.String getRevisions(int index); + /** repeated string revisions = 1; */ + java.lang.String getRevisions(int index); - /** - * repeated string revisions = 1; - */ - com.google.protobuf.ByteString getRevisionsBytes(int index); + /** repeated string revisions = 1; */ + com.google.protobuf.ByteString getRevisionsBytes(int index); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsResponse.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsResponse.java index 445f8e2b0..06b1d3432 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsResponse.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsResponse.java @@ -14,867 +14,862 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code GetRevisionsResponse} - */ -public final class GetRevisionsResponse extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:GetRevisionsResponse) - GetRevisionsResponseOrBuilder { - private static final long serialVersionUID = 0L; - - // Use GetRevisionsResponse.newBuilder() to construct. - private GetRevisionsResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private GetRevisionsResponse() { - statusCode_ = 0; - message_ = ""; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } +/** Protobuf type {@code GetRevisionsResponse} */ +public final class GetRevisionsResponse extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:GetRevisionsResponse) + GetRevisionsResponseOrBuilder { + private static final long serialVersionUID = 0L; + + // Use GetRevisionsResponse.newBuilder() to construct. + private GetRevisionsResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private GetRevisionsResponse() { + statusCode_ = 0; + message_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private GetRevisionsResponse( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: + { + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + revisions_ = + com.google.protobuf.MapField.newMapField( + RevisionsDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000001; + } + com.google.protobuf.MapEntry< + java.lang.String, + com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + revisions__ = + input.readMessage( + RevisionsDefaultEntryHolder.defaultEntry.getParserForType(), + extensionRegistry); + revisions_.getMutableMap().put(revisions__.getKey(), revisions__.getValue()); + break; + } + case 16: + { + statusCode_ = input.readInt32(); + break; + } + case 26: + { + java.lang.String s = input.readStringRequireUtf8(); - private GetRevisionsResponse(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - revisions_ = com.google.protobuf.MapField - .newMapField(RevisionsDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000001; - } - com.google.protobuf.MapEntry revisions__ = input - .readMessage( - RevisionsDefaultEntryHolder.defaultEntry.getParserForType(), - extensionRegistry); - revisions_.getMutableMap() - .put(revisions__.getKey(), revisions__.getValue()); - break; - } - case 16: { - - statusCode_ = input.readInt32(); - break; - } - case 26: { - java.lang.String s = input.readStringRequireUtf8(); - - message_ = s; - break; - } - } + message_ = s; + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_GetRevisionsResponse_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 1: + return internalGetRevisions(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_GetRevisionsResponse_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse.class, + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse.Builder.class); + } + + private int bitField0_; + public static final int REVISIONS_FIELD_NUMBER = 1; + + private static final class RevisionsDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + defaultEntry = + com.google.protobuf.MapEntry + . + newDefaultInstance( + com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_GetRevisionsResponse_RevisionsEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.MESSAGE, + com.alipay.sofa.registry.common.model.client.pb.MetaRegister + .getDefaultInstance()); + } + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + revisions_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + internalGetRevisions() { + if (revisions_ == null) { + return com.google.protobuf.MapField.emptyMapField(RevisionsDefaultEntryHolder.defaultEntry); + } + return revisions_; + } + + public int getRevisionsCount() { + return internalGetRevisions().getMap().size(); + } + + /** map<string, .MetaRegister> revisions = 1; */ + public boolean containsRevisions(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetRevisions().getMap().containsKey(key); + } + + /** Use {@link #getRevisionsMap()} instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + getRevisions() { + return getRevisionsMap(); + } + + /** map<string, .MetaRegister> revisions = 1; */ + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + getRevisionsMap() { + return internalGetRevisions().getMap(); + } + + /** map<string, .MetaRegister> revisions = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.MetaRegister defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetRevisions().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + + /** map<string, .MetaRegister> revisions = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetRevisions().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } + + public static final int STATUSCODE_FIELD_NUMBER = 2; + private int statusCode_; + + /** int32 statusCode = 2; */ + public int getStatusCode() { + return statusCode_; + } + + public static final int MESSAGE_FIELD_NUMBER = 3; + private volatile java.lang.Object message_; + + /** string message = 3; */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + message_ = s; + return s; + } + } + + /** string message = 3; */ + public com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( + output, internalGetRevisions(), RevisionsDefaultEntryHolder.defaultEntry, 1); + if (statusCode_ != 0) { + output.writeInt32(2, statusCode_); + } + if (!getMessageBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 3, message_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + for (java.util.Map.Entry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + entry : internalGetRevisions().getMap().entrySet()) { + com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + revisions__ = + RevisionsDefaultEntryHolder.defaultEntry + .newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, revisions__); + } + if (statusCode_ != 0) { + size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, statusCode_); + } + if (!getMessageBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, message_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse other = + (com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse) obj; + + boolean result = true; + result = result && internalGetRevisions().equals(other.internalGetRevisions()); + result = result && (getStatusCode() == other.getStatusCode()); + result = result && getMessage().equals(other.getMessage()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (!internalGetRevisions().getMap().isEmpty()) { + hash = (37 * hash) + REVISIONS_FIELD_NUMBER; + hash = (53 * hash) + internalGetRevisions().hashCode(); + } + hash = (37 * hash) + STATUSCODE_FIELD_NUMBER; + hash = (53 * hash) + getStatusCode(); + hash = (37 * hash) + MESSAGE_FIELD_NUMBER; + hash = (53 * hash) + getMessage().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code GetRevisionsResponse} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:GetRevisionsResponse) + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_GetRevisionsResponse_descriptor; + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_GetRevisionsResponse_descriptor; } - @SuppressWarnings({ "rawtypes" }) + @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 1: - return internalGetRevisions(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } + switch (number) { + case 1: + return internalGetRevisions(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_GetRevisionsResponse_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse.class, - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse.Builder.class); + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField(int number) { + switch (number) { + case 1: + return internalGetMutableRevisions(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - private int bitField0_; - public static final int REVISIONS_FIELD_NUMBER = 1; - - private static final class RevisionsDefaultEntryHolder { - static final com.google.protobuf.MapEntry defaultEntry = com.google.protobuf.MapEntry - . newDefaultInstance( - com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_GetRevisionsResponse_RevisionsEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.MESSAGE, - com.alipay.sofa.registry.common.model.client.pb.MetaRegister - .getDefaultInstance()); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_GetRevisionsResponse_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse.class, + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse.Builder.class); } - private com.google.protobuf.MapField revisions_; - - private com.google.protobuf.MapField internalGetRevisions() { - if (revisions_ == null) { - return com.google.protobuf.MapField - .emptyMapField(RevisionsDefaultEntryHolder.defaultEntry); - } - return revisions_; + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - public int getRevisionsCount() { - return internalGetRevisions().getMap().size(); + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - /** - * map<string, .MetaRegister> revisions = 1; - */ - - public boolean containsRevisions(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetRevisions().getMap().containsKey(key); + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - /** - * Use {@link #getRevisionsMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getRevisions() { - return getRevisionsMap(); - } + public Builder clear() { + super.clear(); + internalGetMutableRevisions().clear(); + statusCode_ = 0; - /** - * map<string, .MetaRegister> revisions = 1; - */ + message_ = ""; - public java.util.Map getRevisionsMap() { - return internalGetRevisions().getMap(); + return this; } - /** - * map<string, .MetaRegister> revisions = 1; - */ - - public com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.MetaRegister defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetRevisions() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_GetRevisionsResponse_descriptor; } - /** - * map<string, .MetaRegister> revisions = 1; - */ - - public com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetRevisions() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); + public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse + .getDefaultInstance(); } - public static final int STATUSCODE_FIELD_NUMBER = 2; - private int statusCode_; - - /** - * int32 statusCode = 2; - */ - public int getStatusCode() { - return statusCode_; + public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse build() { + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public static final int MESSAGE_FIELD_NUMBER = 3; - private volatile java.lang.Object message_; - - /** - * string message = 3; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - message_ = s; - return s; - } + public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse result = + new com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + result.revisions_ = internalGetRevisions(); + result.revisions_.makeImmutable(); + result.statusCode_ = statusCode_; + result.message_ = message_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } - /** - * string message = 3; - */ - public com.google.protobuf.ByteString getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + public Builder clone() { + return (Builder) super.clone(); } - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(output, internalGetRevisions(), - RevisionsDefaultEntryHolder.defaultEntry, 1); - if (statusCode_ != 0) { - output.writeInt32(2, statusCode_); - } - if (!getMessageBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 3, message_); - } - unknownFields.writeTo(output); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - for (java.util.Map.Entry entry : internalGetRevisions() - .getMap().entrySet()) { - com.google.protobuf.MapEntry revisions__ = RevisionsDefaultEntryHolder.defaultEntry - .newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build(); - size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, revisions__); - } - if (statusCode_ != 0) { - size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, statusCode_); - } - if (!getMessageBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, message_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse other = (com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse) obj; - - boolean result = true; - result = result && internalGetRevisions().equals(other.internalGetRevisions()); - result = result && (getStatusCode() == other.getStatusCode()); - result = result && getMessage().equals(other.getMessage()); - result = result && unknownFields.equals(other.unknownFields); - return result; + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (!internalGetRevisions().getMap().isEmpty()) { - hash = (37 * hash) + REVISIONS_FIELD_NUMBER; - hash = (53 * hash) + internalGetRevisions().hashCode(); - } - hash = (37 * hash) + STATUSCODE_FIELD_NUMBER; - hash = (53 * hash) + getStatusCode(); - hash = (37 * hash) + MESSAGE_FIELD_NUMBER; - hash = (53 * hash) + getMessage().hashCode(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse) other); + } else { + super.mergeFrom(other); + return this; + } } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse + .getDefaultInstance()) return this; + internalGetMutableRevisions().mergeFrom(other.internalGetRevisions()); + if (other.getStatusCode() != 0) { + setStatusCode(other.getStatusCode()); + } + if (!other.getMessage().isEmpty()) { + message_ = other.message_; + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + revisions_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + internalGetRevisions() { + if (revisions_ == null) { + return com.google.protobuf.MapField.emptyMapField(RevisionsDefaultEntryHolder.defaultEntry); + } + return revisions_; + } + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + internalGetMutableRevisions() { + onChanged(); + ; + if (revisions_ == null) { + revisions_ = + com.google.protobuf.MapField.newMapField(RevisionsDefaultEntryHolder.defaultEntry); + } + if (!revisions_.isMutable()) { + revisions_ = revisions_.copy(); + } + return revisions_; } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public int getRevisionsCount() { + return internalGetRevisions().getMap().size(); } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + /** map<string, .MetaRegister> revisions = 1; */ + public boolean containsRevisions(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetRevisions().getMap().containsKey(key); } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + /** Use {@link #getRevisionsMap()} instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + getRevisions() { + return getRevisionsMap(); + } + + /** map<string, .MetaRegister> revisions = 1; */ + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + getRevisionsMap() { + return internalGetRevisions().getMap(); + } + + /** map<string, .MetaRegister> revisions = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.MetaRegister defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetRevisions().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + + /** map<string, .MetaRegister> revisions = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetRevisions().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearRevisions() { + internalGetMutableRevisions().getMutableMap().clear(); + return this; + } + + /** map<string, .MetaRegister> revisions = 1; */ + public Builder removeRevisions(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableRevisions().getMutableMap().remove(key); + return this; + } + + /** Use alternate mutation accessors instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + getMutableRevisions() { + return internalGetMutableRevisions().getMutableMap(); } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + /** map<string, .MetaRegister> revisions = 1; */ + public Builder putRevisions( + java.lang.String key, com.alipay.sofa.registry.common.model.client.pb.MetaRegister value) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + if (value == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableRevisions().getMutableMap().put(key, value); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + /** map<string, .MetaRegister> revisions = 1; */ + public Builder putAllRevisions( + java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaRegister> + values) { + internalGetMutableRevisions().getMutableMap().putAll(values); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); - } + private int statusCode_; - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + /** int32 statusCode = 2; */ + public int getStatusCode() { + return statusCode_; } - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + /** int32 statusCode = 2; */ + public Builder setStatusCode(int value) { - public Builder newBuilderForType() { - return newBuilder(); + statusCode_ = value; + onChanged(); + return this; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } + /** int32 statusCode = 2; */ + public Builder clearStatusCode() { - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + statusCode_ = 0; + onChanged(); + return this; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } + private java.lang.Object message_ = ""; - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + /** string message = 3; */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + message_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string message = 3; */ + public com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - /** - * Protobuf type {@code GetRevisionsResponse} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:GetRevisionsResponse) - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponseOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_GetRevisionsResponse_descriptor; - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 1: - return internalGetRevisions(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMutableMapField(int number) { - switch (number) { - case 1: - return internalGetMutableRevisions(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_GetRevisionsResponse_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse.class, - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - internalGetMutableRevisions().clear(); - statusCode_ = 0; - - message_ = ""; - - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_GetRevisionsResponse_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse build() { - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse result = new com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse( - this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - result.revisions_ = internalGetRevisions(); - result.revisions_.makeImmutable(); - result.statusCode_ = statusCode_; - result.message_ = message_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse - .getDefaultInstance()) - return this; - internalGetMutableRevisions().mergeFrom(other.internalGetRevisions()); - if (other.getStatusCode() != 0) { - setStatusCode(other.getStatusCode()); - } - if (!other.getMessage().isEmpty()) { - message_ = other.message_; - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private com.google.protobuf.MapField revisions_; - - private com.google.protobuf.MapField internalGetRevisions() { - if (revisions_ == null) { - return com.google.protobuf.MapField - .emptyMapField(RevisionsDefaultEntryHolder.defaultEntry); - } - return revisions_; - } - - private com.google.protobuf.MapField internalGetMutableRevisions() { - onChanged(); - ; - if (revisions_ == null) { - revisions_ = com.google.protobuf.MapField - .newMapField(RevisionsDefaultEntryHolder.defaultEntry); - } - if (!revisions_.isMutable()) { - revisions_ = revisions_.copy(); - } - return revisions_; - } - - public int getRevisionsCount() { - return internalGetRevisions().getMap().size(); - } - - /** - * map<string, .MetaRegister> revisions = 1; - */ - - public boolean containsRevisions(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetRevisions().getMap().containsKey(key); - } - - /** - * Use {@link #getRevisionsMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getRevisions() { - return getRevisionsMap(); - } - - /** - * map<string, .MetaRegister> revisions = 1; - */ - - public java.util.Map getRevisionsMap() { - return internalGetRevisions().getMap(); - } - - /** - * map<string, .MetaRegister> revisions = 1; - */ - - public com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.MetaRegister defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetRevisions() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - - /** - * map<string, .MetaRegister> revisions = 1; - */ - - public com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetRevisions() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } + /** string message = 3; */ + public Builder setMessage(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - public Builder clearRevisions() { - internalGetMutableRevisions().getMutableMap().clear(); - return this; - } - - /** - * map<string, .MetaRegister> revisions = 1; - */ - - public Builder removeRevisions(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableRevisions().getMutableMap().remove(key); - return this; - } - - /** - * Use alternate mutation accessors instead. - */ - @java.lang.Deprecated - public java.util.Map getMutableRevisions() { - return internalGetMutableRevisions().getMutableMap(); - } - - /** - * map<string, .MetaRegister> revisions = 1; - */ - public Builder putRevisions(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.MetaRegister value) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - if (value == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableRevisions().getMutableMap().put(key, value); - return this; - } - - /** - * map<string, .MetaRegister> revisions = 1; - */ - - public Builder putAllRevisions(java.util.Map values) { - internalGetMutableRevisions().getMutableMap().putAll(values); - return this; - } - - private int statusCode_; - - /** - * int32 statusCode = 2; - */ - public int getStatusCode() { - return statusCode_; - } - - /** - * int32 statusCode = 2; - */ - public Builder setStatusCode(int value) { - - statusCode_ = value; - onChanged(); - return this; - } - - /** - * int32 statusCode = 2; - */ - public Builder clearStatusCode() { + message_ = value; + onChanged(); + return this; + } - statusCode_ = 0; - onChanged(); - return this; - } + /** string message = 3; */ + public Builder clearMessage() { - private java.lang.Object message_ = ""; - - /** - * string message = 3; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - message_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + message_ = getDefaultInstance().getMessage(); + onChanged(); + return this; + } - /** - * string message = 3; - */ - public com.google.protobuf.ByteString getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string message = 3; */ + public Builder setMessageBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string message = 3; - */ - public Builder setMessage(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + message_ = value; + onChanged(); + return this; + } - message_ = value; - onChanged(); - return this; - } + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } - /** - * string message = 3; - */ - public Builder clearMessage() { + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - message_ = getDefaultInstance().getMessage(); - onChanged(); - return this; - } + // @@protoc_insertion_point(builder_scope:GetRevisionsResponse) + } - /** - * string message = 3; - */ - public Builder setMessageBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + // @@protoc_insertion_point(class_scope:GetRevisionsResponse) + private static final com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse + DEFAULT_INSTANCE; - message_ = value; - onChanged(); - return this; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse(); + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse + getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public GetRevisionsResponse parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new GetRevisionsResponse(input, extensionRegistry); } + }; - // @@protoc_insertion_point(builder_scope:GetRevisionsResponse) - } - - // @@protoc_insertion_point(class_scope:GetRevisionsResponse) - private static final com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public GetRevisionsResponse parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new GetRevisionsResponse( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.GetRevisionsResponse + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsResponseOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsResponseOrBuilder.java index 5c9ba47c3..36412d905 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsResponseOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/GetRevisionsResponseOrBuilder.java @@ -14,61 +14,43 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface GetRevisionsResponseOrBuilder extends -// @@protoc_insertion_point(interface_extends:GetRevisionsResponse) - com.google.protobuf.MessageOrBuilder { - - /** - * map<string, .MetaRegister> revisions = 1; - */ - int getRevisionsCount(); - - /** - * map<string, .MetaRegister> revisions = 1; - */ - boolean containsRevisions(java.lang.String key); +public interface GetRevisionsResponseOrBuilder + extends + // @@protoc_insertion_point(interface_extends:GetRevisionsResponse) + com.google.protobuf.MessageOrBuilder { - /** - * Use {@link #getRevisionsMap()} instead. - */ - @java.lang.Deprecated - java.util.Map getRevisions(); + /** map<string, .MetaRegister> revisions = 1; */ + int getRevisionsCount(); - /** - * map<string, .MetaRegister> revisions = 1; - */ - java.util.Map getRevisionsMap(); + /** map<string, .MetaRegister> revisions = 1; */ + boolean containsRevisions(java.lang.String key); - /** - * map<string, .MetaRegister> revisions = 1; - */ + /** Use {@link #getRevisionsMap()} instead. */ + @java.lang.Deprecated + java.util.Map + getRevisions(); - com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.MetaRegister defaultValue); + /** map<string, .MetaRegister> revisions = 1; */ + java.util.Map + getRevisionsMap(); - /** - * map<string, .MetaRegister> revisions = 1; - */ + /** map<string, .MetaRegister> revisions = 1; */ + com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.MetaRegister defaultValue); - com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrThrow(java.lang.String key); + /** map<string, .MetaRegister> revisions = 1; */ + com.alipay.sofa.registry.common.model.client.pb.MetaRegister getRevisionsOrThrow( + java.lang.String key); - /** - * int32 statusCode = 2; - */ - int getStatusCode(); + /** int32 statusCode = 2; */ + int getStatusCode(); - /** - * string message = 3; - */ - java.lang.String getMessage(); + /** string message = 3; */ + java.lang.String getMessage(); - /** - * string message = 3; - */ - com.google.protobuf.ByteString getMessageBytes(); + /** string message = 3; */ + com.google.protobuf.ByteString getMessageBytes(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatRequest.java index 1b3e20aa7..bb35dab9f 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatRequest.java @@ -14,575 +14,564 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code MetaHeartbeatRequest} - */ -public final class MetaHeartbeatRequest extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:MetaHeartbeatRequest) - MetaHeartbeatRequestOrBuilder { - private static final long serialVersionUID = 0L; - - // Use MetaHeartbeatRequest.newBuilder() to construct. - private MetaHeartbeatRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private MetaHeartbeatRequest() { - revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } - - private MetaHeartbeatRequest(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - revisions_ = new com.google.protobuf.LazyStringArrayList(); - mutable_bitField0_ |= 0x00000001; - } - revisions_.add(s); - break; - } - } +/** Protobuf type {@code MetaHeartbeatRequest} */ +public final class MetaHeartbeatRequest extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:MetaHeartbeatRequest) + MetaHeartbeatRequestOrBuilder { + private static final long serialVersionUID = 0L; + + // Use MetaHeartbeatRequest.newBuilder() to construct. + private MetaHeartbeatRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private MetaHeartbeatRequest() { + revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private MetaHeartbeatRequest( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - revisions_ = revisions_.getUnmodifiableView(); + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + revisions_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000001; + } + revisions_.add(s); + break; } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + revisions_ = revisions_.getUnmodifiableView(); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaHeartbeatRequest_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaHeartbeatRequest_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest.class, + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest.Builder.class); + } + + public static final int REVISIONS_FIELD_NUMBER = 1; + private com.google.protobuf.LazyStringList revisions_; + + /** repeated string revisions = 1; */ + public com.google.protobuf.ProtocolStringList getRevisionsList() { + return revisions_; + } + + /** repeated string revisions = 1; */ + public int getRevisionsCount() { + return revisions_.size(); + } + + /** repeated string revisions = 1; */ + public java.lang.String getRevisions(int index) { + return revisions_.get(index); + } + + /** repeated string revisions = 1; */ + public com.google.protobuf.ByteString getRevisionsBytes(int index) { + return revisions_.getByteString(index); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + for (int i = 0; i < revisions_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, revisions_.getRaw(i)); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + { + int dataSize = 0; + for (int i = 0; i < revisions_.size(); i++) { + dataSize += computeStringSizeNoTag(revisions_.getRaw(i)); + } + size += dataSize; + size += 1 * getRevisionsList().size(); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest other = + (com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest) obj; + + boolean result = true; + result = result && getRevisionsList().equals(other.getRevisionsList()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (getRevisionsCount() > 0) { + hash = (37 * hash) + REVISIONS_FIELD_NUMBER; + hash = (53 * hash) + getRevisionsList().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code MetaHeartbeatRequest} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:MetaHeartbeatRequest) + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaHeartbeatRequest_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaHeartbeatRequest_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest.class, - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest.Builder.class); - } - - public static final int REVISIONS_FIELD_NUMBER = 1; - private com.google.protobuf.LazyStringList revisions_; - - /** - * repeated string revisions = 1; - */ - public com.google.protobuf.ProtocolStringList getRevisionsList() { - return revisions_; - } - - /** - * repeated string revisions = 1; - */ - public int getRevisionsCount() { - return revisions_.size(); - } - - /** - * repeated string revisions = 1; - */ - public java.lang.String getRevisions(int index) { - return revisions_.get(index); - } - - /** - * repeated string revisions = 1; - */ - public com.google.protobuf.ByteString getRevisionsBytes(int index) { - return revisions_.getByteString(index); - } - - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - for (int i = 0; i < revisions_.size(); i++) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, revisions_.getRaw(i)); - } - unknownFields.writeTo(output); + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaHeartbeatRequest_descriptor; } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - { - int dataSize = 0; - for (int i = 0; i < revisions_.size(); i++) { - dataSize += computeStringSizeNoTag(revisions_.getRaw(i)); - } - size += dataSize; - size += 1 * getRevisionsList().size(); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaHeartbeatRequest_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest.class, + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest.Builder.class); } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest other = (com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest) obj; - - boolean result = true; - result = result && getRevisionsList().equals(other.getRevisionsList()); - result = result && unknownFields.equals(other.unknownFields); - return result; + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (getRevisionsCount() > 0) { - hash = (37 * hash) + REVISIONS_FIELD_NUMBER; - hash = (53 * hash) + getRevisionsList().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clear() { + super.clear(); + revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaHeartbeatRequest_descriptor; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest + .getDefaultInstance(); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest build() { + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest result = + new com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest(this); + int from_bitField0_ = bitField0_; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + revisions_ = revisions_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.revisions_ = revisions_; + onBuilt(); + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + public Builder clone() { + return (Builder) super.clone(); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public Builder newBuilderForType() { - return newBuilder(); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest) other); + } else { + super.mergeFrom(other); + return this; + } } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest + .getDefaultInstance()) return this; + if (!other.revisions_.isEmpty()) { + if (revisions_.isEmpty()) { + revisions_ = other.revisions_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureRevisionsIsMutable(); + revisions_.addAll(other.revisions_); + } + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + public final boolean isInitialized() { + return true; } - /** - * Protobuf type {@code MetaHeartbeatRequest} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:MetaHeartbeatRequest) - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequestOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaHeartbeatRequest_descriptor; + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaHeartbeatRequest_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest.class, - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaHeartbeatRequest_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest build() { - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest result = new com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest( - this); - int from_bitField0_ = bitField0_; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - revisions_ = revisions_.getUnmodifiableView(); - bitField0_ = (bitField0_ & ~0x00000001); - } - result.revisions_ = revisions_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest - .getDefaultInstance()) - return this; - if (!other.revisions_.isEmpty()) { - if (revisions_.isEmpty()) { - revisions_ = other.revisions_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureRevisionsIsMutable(); - revisions_.addAll(other.revisions_); - } - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private com.google.protobuf.LazyStringList revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; - - private void ensureRevisionsIsMutable() { - if (!((bitField0_ & 0x00000001) == 0x00000001)) { - revisions_ = new com.google.protobuf.LazyStringArrayList(revisions_); - bitField0_ |= 0x00000001; - } - } - - /** - * repeated string revisions = 1; - */ - public com.google.protobuf.ProtocolStringList getRevisionsList() { - return revisions_.getUnmodifiableView(); - } - - /** - * repeated string revisions = 1; - */ - public int getRevisionsCount() { - return revisions_.size(); - } - - /** - * repeated string revisions = 1; - */ - public java.lang.String getRevisions(int index) { - return revisions_.get(index); - } - - /** - * repeated string revisions = 1; - */ - public com.google.protobuf.ByteString getRevisionsBytes(int index) { - return revisions_.getByteString(index); - } - - /** - * repeated string revisions = 1; - */ - public Builder setRevisions(int index, java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureRevisionsIsMutable(); - revisions_.set(index, value); - onChanged(); - return this; - } - - /** - * repeated string revisions = 1; - */ - public Builder addRevisions(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureRevisionsIsMutable(); - revisions_.add(value); - onChanged(); - return this; - } - - /** - * repeated string revisions = 1; - */ - public Builder addAllRevisions(java.lang.Iterable values) { - ensureRevisionsIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll(values, revisions_); - onChanged(); - return this; - } - - /** - * repeated string revisions = 1; - */ - public Builder clearRevisions() { - revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - onChanged(); - return this; - } - - /** - * repeated string revisions = 1; - */ - public Builder addRevisionsBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - ensureRevisionsIsMutable(); - revisions_.add(value); - onChanged(); - return this; - } - - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } - - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - // @@protoc_insertion_point(builder_scope:MetaHeartbeatRequest) + } + return this; } - // @@protoc_insertion_point(class_scope:MetaHeartbeatRequest) - private static final com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest(); - } + private int bitField0_; - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest getDefaultInstance() { - return DEFAULT_INSTANCE; - } + private com.google.protobuf.LazyStringList revisions_ = + com.google.protobuf.LazyStringArrayList.EMPTY; - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public MetaHeartbeatRequest parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new MetaHeartbeatRequest( - input, - extensionRegistry); - } - }; + private void ensureRevisionsIsMutable() { + if (!((bitField0_ & 0x00000001) == 0x00000001)) { + revisions_ = new com.google.protobuf.LazyStringArrayList(revisions_); + bitField0_ |= 0x00000001; + } + } - public static com.google.protobuf.Parser parser() { - return PARSER; + /** repeated string revisions = 1; */ + public com.google.protobuf.ProtocolStringList getRevisionsList() { + return revisions_.getUnmodifiableView(); } - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; + /** repeated string revisions = 1; */ + public int getRevisionsCount() { + return revisions_.size(); } - public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest getDefaultInstanceForType() { - return DEFAULT_INSTANCE; + /** repeated string revisions = 1; */ + public java.lang.String getRevisions(int index) { + return revisions_.get(index); } + /** repeated string revisions = 1; */ + public com.google.protobuf.ByteString getRevisionsBytes(int index) { + return revisions_.getByteString(index); + } + + /** repeated string revisions = 1; */ + public Builder setRevisions(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureRevisionsIsMutable(); + revisions_.set(index, value); + onChanged(); + return this; + } + + /** repeated string revisions = 1; */ + public Builder addRevisions(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureRevisionsIsMutable(); + revisions_.add(value); + onChanged(); + return this; + } + + /** repeated string revisions = 1; */ + public Builder addAllRevisions(java.lang.Iterable values) { + ensureRevisionsIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, revisions_); + onChanged(); + return this; + } + + /** repeated string revisions = 1; */ + public Builder clearRevisions() { + revisions_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + return this; + } + + /** repeated string revisions = 1; */ + public Builder addRevisionsBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureRevisionsIsMutable(); + revisions_.add(value); + onChanged(); + return this; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:MetaHeartbeatRequest) + } + + // @@protoc_insertion_point(class_scope:MetaHeartbeatRequest) + private static final com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest + DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest(); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest + getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public MetaHeartbeatRequest parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new MetaHeartbeatRequest(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatRequest + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatRequestOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatRequestOrBuilder.java index abc85d429..7508941df 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatRequestOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatRequestOrBuilder.java @@ -14,32 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface MetaHeartbeatRequestOrBuilder extends -// @@protoc_insertion_point(interface_extends:MetaHeartbeatRequest) - com.google.protobuf.MessageOrBuilder { +public interface MetaHeartbeatRequestOrBuilder + extends + // @@protoc_insertion_point(interface_extends:MetaHeartbeatRequest) + com.google.protobuf.MessageOrBuilder { - /** - * repeated string revisions = 1; - */ - java.util.List getRevisionsList(); + /** repeated string revisions = 1; */ + java.util.List getRevisionsList(); - /** - * repeated string revisions = 1; - */ - int getRevisionsCount(); + /** repeated string revisions = 1; */ + int getRevisionsCount(); - /** - * repeated string revisions = 1; - */ - java.lang.String getRevisions(int index); + /** repeated string revisions = 1; */ + java.lang.String getRevisions(int index); - /** - * repeated string revisions = 1; - */ - com.google.protobuf.ByteString getRevisionsBytes(int index); + /** repeated string revisions = 1; */ + com.google.protobuf.ByteString getRevisionsBytes(int index); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatResponse.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatResponse.java index 44a6d2aee..82cb6f1b4 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatResponse.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatResponse.java @@ -14,583 +14,575 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code MetaHeartbeatResponse} - */ -public final class MetaHeartbeatResponse extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:MetaHeartbeatResponse) - MetaHeartbeatResponseOrBuilder { - private static final long serialVersionUID = 0L; - - // Use MetaHeartbeatResponse.newBuilder() to construct. - private MetaHeartbeatResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private MetaHeartbeatResponse() { - statusCode_ = 0; - message_ = ""; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } +/** Protobuf type {@code MetaHeartbeatResponse} */ +public final class MetaHeartbeatResponse extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:MetaHeartbeatResponse) + MetaHeartbeatResponseOrBuilder { + private static final long serialVersionUID = 0L; + + // Use MetaHeartbeatResponse.newBuilder() to construct. + private MetaHeartbeatResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private MetaHeartbeatResponse() { + statusCode_ = 0; + message_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private MetaHeartbeatResponse( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: + { + statusCode_ = input.readInt32(); + break; + } + case 18: + { + java.lang.String s = input.readStringRequireUtf8(); - private MetaHeartbeatResponse(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 8: { - - statusCode_ = input.readInt32(); - break; - } - case 18: { - java.lang.String s = input.readStringRequireUtf8(); - - message_ = s; - break; - } - } + message_ = s; + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaHeartbeatResponse_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaHeartbeatResponse_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse.class, + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse.Builder.class); + } + + public static final int STATUSCODE_FIELD_NUMBER = 1; + private int statusCode_; + + /** int32 statusCode = 1; */ + public int getStatusCode() { + return statusCode_; + } + + public static final int MESSAGE_FIELD_NUMBER = 2; + private volatile java.lang.Object message_; + + /** string message = 2; */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + message_ = s; + return s; + } + } + + /** string message = 2; */ + public com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (statusCode_ != 0) { + output.writeInt32(1, statusCode_); + } + if (!getMessageBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, message_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (statusCode_ != 0) { + size += com.google.protobuf.CodedOutputStream.computeInt32Size(1, statusCode_); + } + if (!getMessageBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, message_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse other = + (com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse) obj; + + boolean result = true; + result = result && (getStatusCode() == other.getStatusCode()); + result = result && getMessage().equals(other.getMessage()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + STATUSCODE_FIELD_NUMBER; + hash = (53 * hash) + getStatusCode(); + hash = (37 * hash) + MESSAGE_FIELD_NUMBER; + hash = (53 * hash) + getMessage().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code MetaHeartbeatResponse} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:MetaHeartbeatResponse) + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaHeartbeatResponse_descriptor; + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaHeartbeatResponse_descriptor; } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaHeartbeatResponse_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse.class, - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse.Builder.class); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaHeartbeatResponse_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse.class, + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse.Builder.class); } - public static final int STATUSCODE_FIELD_NUMBER = 1; - private int statusCode_; - - /** - * int32 statusCode = 1; - */ - public int getStatusCode() { - return statusCode_; + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - public static final int MESSAGE_FIELD_NUMBER = 2; - private volatile java.lang.Object message_; - - /** - * string message = 2; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - message_ = s; - return s; - } + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - /** - * string message = 2; - */ - public com.google.protobuf.ByteString getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - private byte memoizedIsInitialized = -1; + public Builder clear() { + super.clear(); + statusCode_ = 0; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; + message_ = ""; - memoizedIsInitialized = 1; - return true; + return this; } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (statusCode_ != 0) { - output.writeInt32(1, statusCode_); - } - if (!getMessageBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, message_); - } - unknownFields.writeTo(output); + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaHeartbeatResponse_descriptor; } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - if (statusCode_ != 0) { - size += com.google.protobuf.CodedOutputStream.computeInt32Size(1, statusCode_); - } - if (!getMessageBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, message_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse other = (com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse) obj; - - boolean result = true; - result = result && (getStatusCode() == other.getStatusCode()); - result = result && getMessage().equals(other.getMessage()); - result = result && unknownFields.equals(other.unknownFields); - return result; + public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse + .getDefaultInstance(); } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + STATUSCODE_FIELD_NUMBER; - hash = (53 * hash) + getStatusCode(); - hash = (37 * hash) + MESSAGE_FIELD_NUMBER; - hash = (53 * hash) + getMessage().hashCode(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse build() { + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse result = + new com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse(this); + result.statusCode_ = statusCode_; + result.message_ = message_; + onBuilt(); + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clone() { + return (Builder) super.clone(); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse) other); + } else { + super.mergeFrom(other); + return this; + } } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse + .getDefaultInstance()) return this; + if (other.getStatusCode() != 0) { + setStatusCode(other.getStatusCode()); + } + if (!other.getMessage().isEmpty()) { + message_ = other.message_; + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + public final boolean isInitialized() { + return true; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + private int statusCode_; - public Builder newBuilderForType() { - return newBuilder(); + /** int32 statusCode = 1; */ + public int getStatusCode() { + return statusCode_; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } + /** int32 statusCode = 1; */ + public Builder setStatusCode(int value) { - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + statusCode_ = value; + onChanged(); + return this; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } + /** int32 statusCode = 1; */ + public Builder clearStatusCode() { - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + statusCode_ = 0; + onChanged(); + return this; } - /** - * Protobuf type {@code MetaHeartbeatResponse} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:MetaHeartbeatResponse) - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponseOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaHeartbeatResponse_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaHeartbeatResponse_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse.class, - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - statusCode_ = 0; + private java.lang.Object message_ = ""; - message_ = ""; - - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaHeartbeatResponse_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse build() { - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse result = new com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse( - this); - result.statusCode_ = statusCode_; - result.message_ = message_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse - .getDefaultInstance()) - return this; - if (other.getStatusCode() != 0) { - setStatusCode(other.getStatusCode()); - } - if (!other.getMessage().isEmpty()) { - message_ = other.message_; - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int statusCode_; - - /** - * int32 statusCode = 1; - */ - public int getStatusCode() { - return statusCode_; - } - - /** - * int32 statusCode = 1; - */ - public Builder setStatusCode(int value) { + /** string message = 2; */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + message_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string message = 2; */ + public com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - statusCode_ = value; - onChanged(); - return this; - } + /** string message = 2; */ + public Builder setMessage(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - /** - * int32 statusCode = 1; - */ - public Builder clearStatusCode() { + message_ = value; + onChanged(); + return this; + } - statusCode_ = 0; - onChanged(); - return this; - } + /** string message = 2; */ + public Builder clearMessage() { - private java.lang.Object message_ = ""; - - /** - * string message = 2; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - message_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + message_ = getDefaultInstance().getMessage(); + onChanged(); + return this; + } - /** - * string message = 2; - */ - public com.google.protobuf.ByteString getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string message = 2; */ + public Builder setMessageBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string message = 2; - */ - public Builder setMessage(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + message_ = value; + onChanged(); + return this; + } - message_ = value; - onChanged(); - return this; - } + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } - /** - * string message = 2; - */ - public Builder clearMessage() { + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - message_ = getDefaultInstance().getMessage(); - onChanged(); - return this; - } + // @@protoc_insertion_point(builder_scope:MetaHeartbeatResponse) + } - /** - * string message = 2; - */ - public Builder setMessageBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + // @@protoc_insertion_point(class_scope:MetaHeartbeatResponse) + private static final com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse + DEFAULT_INSTANCE; - message_ = value; - onChanged(); - return this; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse(); + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse + getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public MetaHeartbeatResponse parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new MetaHeartbeatResponse(input, extensionRegistry); } + }; - // @@protoc_insertion_point(builder_scope:MetaHeartbeatResponse) - } - - // @@protoc_insertion_point(class_scope:MetaHeartbeatResponse) - private static final com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public MetaHeartbeatResponse parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new MetaHeartbeatResponse( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.MetaHeartbeatResponse + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatResponseOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatResponseOrBuilder.java index 76c5b8da8..e7c1ce55e 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatResponseOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaHeartbeatResponseOrBuilder.java @@ -14,27 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface MetaHeartbeatResponseOrBuilder extends -// @@protoc_insertion_point(interface_extends:MetaHeartbeatResponse) - com.google.protobuf.MessageOrBuilder { +public interface MetaHeartbeatResponseOrBuilder + extends + // @@protoc_insertion_point(interface_extends:MetaHeartbeatResponse) + com.google.protobuf.MessageOrBuilder { - /** - * int32 statusCode = 1; - */ - int getStatusCode(); + /** int32 statusCode = 1; */ + int getStatusCode(); - /** - * string message = 2; - */ - java.lang.String getMessage(); + /** string message = 2; */ + java.lang.String getMessage(); - /** - * string message = 2; - */ - com.google.protobuf.ByteString getMessageBytes(); + /** string message = 2; */ + com.google.protobuf.ByteString getMessageBytes(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaRegister.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaRegister.java index e943a54fc..4b430da60 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaRegister.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaRegister.java @@ -14,1310 +14,1278 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code MetaRegister} - */ -public final class MetaRegister extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:MetaRegister) - MetaRegisterOrBuilder { - private static final long serialVersionUID = 0L; - - // Use MetaRegister.newBuilder() to construct. - private MetaRegister(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); +/** Protobuf type {@code MetaRegister} */ +public final class MetaRegister extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:MetaRegister) + MetaRegisterOrBuilder { + private static final long serialVersionUID = 0L; + + // Use MetaRegister.newBuilder() to construct. + private MetaRegister(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private MetaRegister() { + application_ = ""; + revision_ = ""; + clientVersion_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private MetaRegister( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); - private MetaRegister() { - application_ = ""; - revision_ = ""; - clientVersion_ = ""; - } + application_ = s; + break; + } + case 18: + { + java.lang.String s = input.readStringRequireUtf8(); - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } + revision_ = s; + break; + } + case 26: + { + java.lang.String s = input.readStringRequireUtf8(); - private MetaRegister(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - - application_ = s; - break; - } - case 18: { - java.lang.String s = input.readStringRequireUtf8(); - - revision_ = s; - break; - } - case 26: { - java.lang.String s = input.readStringRequireUtf8(); - - clientVersion_ = s; - break; - } - case 34: { - if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { - baseParams_ = com.google.protobuf.MapField - .newMapField(BaseParamsDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000008; - } - com.google.protobuf.MapEntry baseParams__ = input - .readMessage( - BaseParamsDefaultEntryHolder.defaultEntry.getParserForType(), - extensionRegistry); - baseParams_.getMutableMap().put(baseParams__.getKey(), - baseParams__.getValue()); - break; - } - case 42: { - if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) { - services_ = com.google.protobuf.MapField - .newMapField(ServicesDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000010; - } - com.google.protobuf.MapEntry services__ = input - .readMessage( - ServicesDefaultEntryHolder.defaultEntry.getParserForType(), - extensionRegistry); - services_.getMutableMap().put(services__.getKey(), services__.getValue()); - break; - } - } + clientVersion_ = s; + break; + } + case 34: + { + if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + baseParams_ = + com.google.protobuf.MapField.newMapField( + BaseParamsDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000008; + } + com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + baseParams__ = + input.readMessage( + BaseParamsDefaultEntryHolder.defaultEntry.getParserForType(), + extensionRegistry); + baseParams_.getMutableMap().put(baseParams__.getKey(), baseParams__.getValue()); + break; + } + case 42: + { + if (!((mutable_bitField0_ & 0x00000010) == 0x00000010)) { + services_ = + com.google.protobuf.MapField.newMapField( + ServicesDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000010; + } + com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + services__ = + input.readMessage( + ServicesDefaultEntryHolder.defaultEntry.getParserForType(), + extensionRegistry); + services_.getMutableMap().put(services__.getKey(), services__.getValue()); + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); } - - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaRegister_descriptor; + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaRegister_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 4: + return internalGetBaseParams(); + case 5: + return internalGetServices(); + default: + throw new RuntimeException("Invalid map field number: " + number); } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 4: - return internalGetBaseParams(); - case 5: - return internalGetServices(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaRegister_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.MetaRegister.class, + com.alipay.sofa.registry.common.model.client.pb.MetaRegister.Builder.class); + } + + private int bitField0_; + public static final int APPLICATION_FIELD_NUMBER = 1; + private volatile java.lang.Object application_; + + /** string application = 1; */ + public java.lang.String getApplication() { + java.lang.Object ref = application_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + application_ = s; + return s; } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaRegister_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.MetaRegister.class, - com.alipay.sofa.registry.common.model.client.pb.MetaRegister.Builder.class); + } + + /** string application = 1; */ + public com.google.protobuf.ByteString getApplicationBytes() { + java.lang.Object ref = application_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + application_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; } - - private int bitField0_; - public static final int APPLICATION_FIELD_NUMBER = 1; - private volatile java.lang.Object application_; - - /** - * string application = 1; - */ - public java.lang.String getApplication() { - java.lang.Object ref = application_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - application_ = s; - return s; - } + } + + public static final int REVISION_FIELD_NUMBER = 2; + private volatile java.lang.Object revision_; + + /** string revision = 2; */ + public java.lang.String getRevision() { + java.lang.Object ref = revision_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + revision_ = s; + return s; } - - /** - * string application = 1; - */ - public com.google.protobuf.ByteString getApplicationBytes() { - java.lang.Object ref = application_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - application_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + } + + /** string revision = 2; */ + public com.google.protobuf.ByteString getRevisionBytes() { + java.lang.Object ref = revision_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + revision_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; } - - public static final int REVISION_FIELD_NUMBER = 2; - private volatile java.lang.Object revision_; - - /** - * string revision = 2; - */ - public java.lang.String getRevision() { - java.lang.Object ref = revision_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - revision_ = s; - return s; - } + } + + public static final int CLIENTVERSION_FIELD_NUMBER = 3; + private volatile java.lang.Object clientVersion_; + + /** string clientVersion = 3; */ + public java.lang.String getClientVersion() { + java.lang.Object ref = clientVersion_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + clientVersion_ = s; + return s; } - - /** - * string revision = 2; - */ - public com.google.protobuf.ByteString getRevisionBytes() { - java.lang.Object ref = revision_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - revision_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + } + + /** string clientVersion = 3; */ + public com.google.protobuf.ByteString getClientVersionBytes() { + java.lang.Object ref = clientVersion_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + clientVersion_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int BASEPARAMS_FIELD_NUMBER = 4; + + private static final class BaseParamsDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + defaultEntry = + com.google.protobuf.MapEntry + . + newDefaultInstance( + com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaRegister_BaseParamsEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.MESSAGE, + com.alipay.sofa.registry.common.model.client.pb.StringList + .getDefaultInstance()); + } + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + baseParams_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + internalGetBaseParams() { + if (baseParams_ == null) { + return com.google.protobuf.MapField.emptyMapField(BaseParamsDefaultEntryHolder.defaultEntry); } + return baseParams_; + } - public static final int CLIENTVERSION_FIELD_NUMBER = 3; - private volatile java.lang.Object clientVersion_; + public int getBaseParamsCount() { + return internalGetBaseParams().getMap().size(); + } - /** - * string clientVersion = 3; - */ - public java.lang.String getClientVersion() { - java.lang.Object ref = clientVersion_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - clientVersion_ = s; - return s; - } + /** map<string, .StringList> baseParams = 4; */ + public boolean containsBaseParams(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); } - - /** - * string clientVersion = 3; - */ - public com.google.protobuf.ByteString getClientVersionBytes() { - java.lang.Object ref = clientVersion_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - clientVersion_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + return internalGetBaseParams().getMap().containsKey(key); + } + + /** Use {@link #getBaseParamsMap()} instead. */ + @java.lang.Deprecated + public java.util.Map + getBaseParams() { + return getBaseParamsMap(); + } + + /** map<string, .StringList> baseParams = 4; */ + public java.util.Map + getBaseParamsMap() { + return internalGetBaseParams().getMap(); + } + + /** map<string, .StringList> baseParams = 4; */ + public com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); } - - public static final int BASEPARAMS_FIELD_NUMBER = 4; - - private static final class BaseParamsDefaultEntryHolder { - static final com.google.protobuf.MapEntry defaultEntry = com.google.protobuf.MapEntry - . newDefaultInstance( - com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaRegister_BaseParamsEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.MESSAGE, - com.alipay.sofa.registry.common.model.client.pb.StringList - .getDefaultInstance()); + java.util.Map + map = internalGetBaseParams().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + + /** map<string, .StringList> baseParams = 4; */ + public com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); } - - private com.google.protobuf.MapField baseParams_; - - private com.google.protobuf.MapField internalGetBaseParams() { - if (baseParams_ == null) { - return com.google.protobuf.MapField - .emptyMapField(BaseParamsDefaultEntryHolder.defaultEntry); - } - return baseParams_; + java.util.Map + map = internalGetBaseParams().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); } - - public int getBaseParamsCount() { - return internalGetBaseParams().getMap().size(); + return map.get(key); + } + + public static final int SERVICES_FIELD_NUMBER = 5; + + private static final class ServicesDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + defaultEntry = + com.google.protobuf.MapEntry + . + newDefaultInstance( + com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaRegister_ServicesEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.MESSAGE, + com.alipay.sofa.registry.common.model.client.pb.MetaService + .getDefaultInstance()); + } + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + services_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + internalGetServices() { + if (services_ == null) { + return com.google.protobuf.MapField.emptyMapField(ServicesDefaultEntryHolder.defaultEntry); } + return services_; + } - /** - * map<string, .StringList> baseParams = 4; - */ + public int getServicesCount() { + return internalGetServices().getMap().size(); + } - public boolean containsBaseParams(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetBaseParams().getMap().containsKey(key); + /** map<string, .MetaService> services = 5; */ + public boolean containsServices(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); } - - /** - * Use {@link #getBaseParamsMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getBaseParams() { - return getBaseParamsMap(); + return internalGetServices().getMap().containsKey(key); + } + + /** Use {@link #getServicesMap()} instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + getServices() { + return getServicesMap(); + } + + /** map<string, .MetaService> services = 5; */ + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + getServicesMap() { + return internalGetServices().getMap(); + } + + /** map<string, .MetaService> services = 5; */ + public com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.MetaService defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); } - - /** - * map<string, .StringList> baseParams = 4; - */ - - public java.util.Map getBaseParamsMap() { - return internalGetBaseParams().getMap(); + java.util.Map + map = internalGetServices().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + + /** map<string, .MetaService> services = 5; */ + public com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); } - - /** - * map<string, .StringList> baseParams = 4; - */ - - public com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetBaseParams() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; + java.util.Map + map = internalGetServices().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); } + return map.get(key); + } - /** - * map<string, .StringList> baseParams = 4; - */ + private byte memoizedIsInitialized = -1; - public com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetBaseParams() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; - public static final int SERVICES_FIELD_NUMBER = 5; + memoizedIsInitialized = 1; + return true; + } - private static final class ServicesDefaultEntryHolder { - static final com.google.protobuf.MapEntry defaultEntry = com.google.protobuf.MapEntry - . newDefaultInstance( - com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaRegister_ServicesEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.MESSAGE, - com.alipay.sofa.registry.common.model.client.pb.MetaService - .getDefaultInstance()); + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getApplicationBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, application_); } - - private com.google.protobuf.MapField services_; - - private com.google.protobuf.MapField internalGetServices() { - if (services_ == null) { - return com.google.protobuf.MapField - .emptyMapField(ServicesDefaultEntryHolder.defaultEntry); - } - return services_; + if (!getRevisionBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, revision_); } - - public int getServicesCount() { - return internalGetServices().getMap().size(); + if (!getClientVersionBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 3, clientVersion_); } - - /** - * map<string, .MetaService> services = 5; - */ - - public boolean containsServices(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetServices().getMap().containsKey(key); + com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( + output, internalGetBaseParams(), BaseParamsDefaultEntryHolder.defaultEntry, 4); + com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( + output, internalGetServices(), ServicesDefaultEntryHolder.defaultEntry, 5); + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!getApplicationBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, application_); } - - /** - * Use {@link #getServicesMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getServices() { - return getServicesMap(); + if (!getRevisionBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, revision_); } - - /** - * map<string, .MetaService> services = 5; - */ - - public java.util.Map getServicesMap() { - return internalGetServices().getMap(); + if (!getClientVersionBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, clientVersion_); } - - /** - * map<string, .MetaService> services = 5; - */ - - public com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.MetaService defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetServices() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; + for (java.util.Map.Entry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + entry : internalGetBaseParams().getMap().entrySet()) { + com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + baseParams__ = + BaseParamsDefaultEntryHolder.defaultEntry + .newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, baseParams__); } - - /** - * map<string, .MetaService> services = 5; - */ - - public com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetServices() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); + for (java.util.Map.Entry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + entry : internalGetServices().getMap().entrySet()) { + com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + services__ = + ServicesDefaultEntryHolder.defaultEntry + .newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream.computeMessageSize(5, services__); } - - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; } - - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (!getApplicationBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, application_); - } - if (!getRevisionBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, revision_); - } - if (!getClientVersionBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 3, clientVersion_); - } - com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(output, - internalGetBaseParams(), BaseParamsDefaultEntryHolder.defaultEntry, 4); - com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(output, internalGetServices(), - ServicesDefaultEntryHolder.defaultEntry, 5); - unknownFields.writeTo(output); + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.MetaRegister)) { + return super.equals(obj); } - - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - if (!getApplicationBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, application_); - } - if (!getRevisionBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, revision_); - } - if (!getClientVersionBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, clientVersion_); - } - for (java.util.Map.Entry entry : internalGetBaseParams() - .getMap().entrySet()) { - com.google.protobuf.MapEntry baseParams__ = BaseParamsDefaultEntryHolder.defaultEntry - .newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build(); - size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, baseParams__); - } - for (java.util.Map.Entry entry : internalGetServices() - .getMap().entrySet()) { - com.google.protobuf.MapEntry services__ = ServicesDefaultEntryHolder.defaultEntry - .newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build(); - size += com.google.protobuf.CodedOutputStream.computeMessageSize(5, services__); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + com.alipay.sofa.registry.common.model.client.pb.MetaRegister other = + (com.alipay.sofa.registry.common.model.client.pb.MetaRegister) obj; + + boolean result = true; + result = result && getApplication().equals(other.getApplication()); + result = result && getRevision().equals(other.getRevision()); + result = result && getClientVersion().equals(other.getClientVersion()); + result = result && internalGetBaseParams().equals(other.internalGetBaseParams()); + result = result && internalGetServices().equals(other.internalGetServices()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; } - - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.MetaRegister)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.MetaRegister other = (com.alipay.sofa.registry.common.model.client.pb.MetaRegister) obj; - - boolean result = true; - result = result && getApplication().equals(other.getApplication()); - result = result && getRevision().equals(other.getRevision()); - result = result && getClientVersion().equals(other.getClientVersion()); - result = result && internalGetBaseParams().equals(other.internalGetBaseParams()); - result = result && internalGetServices().equals(other.internalGetServices()); - result = result && unknownFields.equals(other.unknownFields); - return result; - } - - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + APPLICATION_FIELD_NUMBER; - hash = (53 * hash) + getApplication().hashCode(); - hash = (37 * hash) + REVISION_FIELD_NUMBER; - hash = (53 * hash) + getRevision().hashCode(); - hash = (37 * hash) + CLIENTVERSION_FIELD_NUMBER; - hash = (53 * hash) + getClientVersion().hashCode(); - if (!internalGetBaseParams().getMap().isEmpty()) { - hash = (37 * hash) + BASEPARAMS_FIELD_NUMBER; - hash = (53 * hash) + internalGetBaseParams().hashCode(); - } - if (!internalGetServices().getMap().isEmpty()) { - hash = (37 * hash) + SERVICES_FIELD_NUMBER; - hash = (53 * hash) + internalGetServices().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + APPLICATION_FIELD_NUMBER; + hash = (53 * hash) + getApplication().hashCode(); + hash = (37 * hash) + REVISION_FIELD_NUMBER; + hash = (53 * hash) + getRevision().hashCode(); + hash = (37 * hash) + CLIENTVERSION_FIELD_NUMBER; + hash = (53 * hash) + getClientVersion().hashCode(); + if (!internalGetBaseParams().getMap().isEmpty()) { + hash = (37 * hash) + BASEPARAMS_FIELD_NUMBER; + hash = (53 * hash) + internalGetBaseParams().hashCode(); } - - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + if (!internalGetServices().getMap().isEmpty()) { + hash = (37 * hash) + SERVICES_FIELD_NUMBER; + hash = (53 * hash) + internalGetServices().hashCode(); } - - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.MetaRegister prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code MetaRegister} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:MetaRegister) + com.alipay.sofa.registry.common.model.client.pb.MetaRegisterOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaRegister_descriptor; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 4: + return internalGetBaseParams(); + case 5: + return internalGetServices(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField(int number) { + switch (number) { + case 4: + return internalGetMutableBaseParams(); + case 5: + return internalGetMutableServices(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaRegister_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.MetaRegister.class, + com.alipay.sofa.registry.common.model.client.pb.MetaRegister.Builder.class); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + // Construct using com.alipay.sofa.registry.common.model.client.pb.MetaRegister.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); - } + public Builder clear() { + super.clear(); + application_ = ""; - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); - } + revision_ = ""; - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); - } + clientVersion_ = ""; - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + internalGetMutableBaseParams().clear(); + internalGetMutableServices().clear(); + return this; } - public Builder newBuilderForType() { - return newBuilder(); + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaRegister_descriptor; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); + public com.alipay.sofa.registry.common.model.client.pb.MetaRegister + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.MetaRegister.getDefaultInstance(); } - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.MetaRegister prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + public com.alipay.sofa.registry.common.model.client.pb.MetaRegister build() { + com.alipay.sofa.registry.common.model.client.pb.MetaRegister result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + public com.alipay.sofa.registry.common.model.client.pb.MetaRegister buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.MetaRegister result = + new com.alipay.sofa.registry.common.model.client.pb.MetaRegister(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + result.application_ = application_; + result.revision_ = revision_; + result.clientVersion_ = clientVersion_; + result.baseParams_ = internalGetBaseParams(); + result.baseParams_.makeImmutable(); + result.services_ = internalGetServices(); + result.services_.makeImmutable(); + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + public Builder clone() { + return (Builder) super.clone(); } - /** - * Protobuf type {@code MetaRegister} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:MetaRegister) - com.alipay.sofa.registry.common.model.client.pb.MetaRegisterOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaRegister_descriptor; - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 4: - return internalGetBaseParams(); - case 5: - return internalGetServices(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMutableMapField(int number) { - switch (number) { - case 4: - return internalGetMutableBaseParams(); - case 5: - return internalGetMutableServices(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaRegister_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.MetaRegister.class, - com.alipay.sofa.registry.common.model.client.pb.MetaRegister.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.MetaRegister.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - application_ = ""; - - revision_ = ""; - - clientVersion_ = ""; - - internalGetMutableBaseParams().clear(); - internalGetMutableServices().clear(); - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaRegister_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaRegister getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.MetaRegister - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaRegister build() { - com.alipay.sofa.registry.common.model.client.pb.MetaRegister result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaRegister buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.MetaRegister result = new com.alipay.sofa.registry.common.model.client.pb.MetaRegister( - this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - result.application_ = application_; - result.revision_ = revision_; - result.clientVersion_ = clientVersion_; - result.baseParams_ = internalGetBaseParams(); - result.baseParams_.makeImmutable(); - result.services_ = internalGetServices(); - result.services_.makeImmutable(); - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.MetaRegister) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.MetaRegister) other); - } else { - super.mergeFrom(other); - return this; - } - } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); + } - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.MetaRegister other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.MetaRegister - .getDefaultInstance()) - return this; - if (!other.getApplication().isEmpty()) { - application_ = other.application_; - onChanged(); - } - if (!other.getRevision().isEmpty()) { - revision_ = other.revision_; - onChanged(); - } - if (!other.getClientVersion().isEmpty()) { - clientVersion_ = other.clientVersion_; - onChanged(); - } - internalGetMutableBaseParams().mergeFrom(other.internalGetBaseParams()); - internalGetMutableServices().mergeFrom(other.internalGetServices()); - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } - public final boolean isInitialized() { - return true; - } + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.MetaRegister parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.MetaRegister) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } - private int bitField0_; - - private java.lang.Object application_ = ""; - - /** - * string application = 1; - */ - public java.lang.String getApplication() { - java.lang.Object ref = application_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - application_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } - /** - * string application = 1; - */ - public com.google.protobuf.ByteString getApplicationBytes() { - java.lang.Object ref = application_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - application_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.MetaRegister) { + return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.MetaRegister) other); + } else { + super.mergeFrom(other); + return this; + } + } - /** - * string application = 1; - */ - public Builder setApplication(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.MetaRegister other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.MetaRegister.getDefaultInstance()) + return this; + if (!other.getApplication().isEmpty()) { + application_ = other.application_; + onChanged(); + } + if (!other.getRevision().isEmpty()) { + revision_ = other.revision_; + onChanged(); + } + if (!other.getClientVersion().isEmpty()) { + clientVersion_ = other.clientVersion_; + onChanged(); + } + internalGetMutableBaseParams().mergeFrom(other.internalGetBaseParams()); + internalGetMutableServices().mergeFrom(other.internalGetServices()); + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } - application_ = value; - onChanged(); - return this; - } + public final boolean isInitialized() { + return true; + } - /** - * string application = 1; - */ - public Builder clearApplication() { + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.MetaRegister parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.MetaRegister) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } - application_ = getDefaultInstance().getApplication(); - onChanged(); - return this; - } + private int bitField0_; - /** - * string application = 1; - */ - public Builder setApplicationBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + private java.lang.Object application_ = ""; - application_ = value; - onChanged(); - return this; - } + /** string application = 1; */ + public java.lang.String getApplication() { + java.lang.Object ref = application_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + application_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - private java.lang.Object revision_ = ""; - - /** - * string revision = 2; - */ - public java.lang.String getRevision() { - java.lang.Object ref = revision_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - revision_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** string application = 1; */ + public com.google.protobuf.ByteString getApplicationBytes() { + java.lang.Object ref = application_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + application_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string revision = 2; - */ - public com.google.protobuf.ByteString getRevisionBytes() { - java.lang.Object ref = revision_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - revision_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string application = 1; */ + public Builder setApplication(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - /** - * string revision = 2; - */ - public Builder setRevision(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + application_ = value; + onChanged(); + return this; + } - revision_ = value; - onChanged(); - return this; - } + /** string application = 1; */ + public Builder clearApplication() { - /** - * string revision = 2; - */ - public Builder clearRevision() { + application_ = getDefaultInstance().getApplication(); + onChanged(); + return this; + } - revision_ = getDefaultInstance().getRevision(); - onChanged(); - return this; - } + /** string application = 1; */ + public Builder setApplicationBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string revision = 2; - */ - public Builder setRevisionBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + application_ = value; + onChanged(); + return this; + } - revision_ = value; - onChanged(); - return this; - } + private java.lang.Object revision_ = ""; - private java.lang.Object clientVersion_ = ""; - - /** - * string clientVersion = 3; - */ - public java.lang.String getClientVersion() { - java.lang.Object ref = clientVersion_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - clientVersion_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** string revision = 2; */ + public java.lang.String getRevision() { + java.lang.Object ref = revision_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + revision_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - /** - * string clientVersion = 3; - */ - public com.google.protobuf.ByteString getClientVersionBytes() { - java.lang.Object ref = clientVersion_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - clientVersion_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string revision = 2; */ + public com.google.protobuf.ByteString getRevisionBytes() { + java.lang.Object ref = revision_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + revision_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string clientVersion = 3; - */ - public Builder setClientVersion(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + /** string revision = 2; */ + public Builder setRevision(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - clientVersion_ = value; - onChanged(); - return this; - } + revision_ = value; + onChanged(); + return this; + } - /** - * string clientVersion = 3; - */ - public Builder clearClientVersion() { + /** string revision = 2; */ + public Builder clearRevision() { - clientVersion_ = getDefaultInstance().getClientVersion(); - onChanged(); - return this; - } + revision_ = getDefaultInstance().getRevision(); + onChanged(); + return this; + } - /** - * string clientVersion = 3; - */ - public Builder setClientVersionBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string revision = 2; */ + public Builder setRevisionBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - clientVersion_ = value; - onChanged(); - return this; - } + revision_ = value; + onChanged(); + return this; + } - private com.google.protobuf.MapField baseParams_; + private java.lang.Object clientVersion_ = ""; - private com.google.protobuf.MapField internalGetBaseParams() { - if (baseParams_ == null) { - return com.google.protobuf.MapField - .emptyMapField(BaseParamsDefaultEntryHolder.defaultEntry); - } - return baseParams_; - } + /** string clientVersion = 3; */ + public java.lang.String getClientVersion() { + java.lang.Object ref = clientVersion_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + clientVersion_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - private com.google.protobuf.MapField internalGetMutableBaseParams() { - onChanged(); - ; - if (baseParams_ == null) { - baseParams_ = com.google.protobuf.MapField - .newMapField(BaseParamsDefaultEntryHolder.defaultEntry); - } - if (!baseParams_.isMutable()) { - baseParams_ = baseParams_.copy(); - } - return baseParams_; - } + /** string clientVersion = 3; */ + public com.google.protobuf.ByteString getClientVersionBytes() { + java.lang.Object ref = clientVersion_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + clientVersion_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - public int getBaseParamsCount() { - return internalGetBaseParams().getMap().size(); - } + /** string clientVersion = 3; */ + public Builder setClientVersion(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - /** - * map<string, .StringList> baseParams = 4; - */ + clientVersion_ = value; + onChanged(); + return this; + } - public boolean containsBaseParams(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetBaseParams().getMap().containsKey(key); - } + /** string clientVersion = 3; */ + public Builder clearClientVersion() { - /** - * Use {@link #getBaseParamsMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getBaseParams() { - return getBaseParamsMap(); - } + clientVersion_ = getDefaultInstance().getClientVersion(); + onChanged(); + return this; + } - /** - * map<string, .StringList> baseParams = 4; - */ + /** string clientVersion = 3; */ + public Builder setClientVersionBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - public java.util.Map getBaseParamsMap() { - return internalGetBaseParams().getMap(); - } + clientVersion_ = value; + onChanged(); + return this; + } - /** - * map<string, .StringList> baseParams = 4; - */ + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + baseParams_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + internalGetBaseParams() { + if (baseParams_ == null) { + return com.google.protobuf.MapField.emptyMapField( + BaseParamsDefaultEntryHolder.defaultEntry); + } + return baseParams_; + } - public com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetBaseParams() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + internalGetMutableBaseParams() { + onChanged(); + ; + if (baseParams_ == null) { + baseParams_ = + com.google.protobuf.MapField.newMapField(BaseParamsDefaultEntryHolder.defaultEntry); + } + if (!baseParams_.isMutable()) { + baseParams_ = baseParams_.copy(); + } + return baseParams_; + } - /** - * map<string, .StringList> baseParams = 4; - */ + public int getBaseParamsCount() { + return internalGetBaseParams().getMap().size(); + } - public com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetBaseParams() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } + /** map<string, .StringList> baseParams = 4; */ + public boolean containsBaseParams(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetBaseParams().getMap().containsKey(key); + } - public Builder clearBaseParams() { - internalGetMutableBaseParams().getMutableMap().clear(); - return this; - } + /** Use {@link #getBaseParamsMap()} instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + getBaseParams() { + return getBaseParamsMap(); + } - /** - * map<string, .StringList> baseParams = 4; - */ + /** map<string, .StringList> baseParams = 4; */ + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + getBaseParamsMap() { + return internalGetBaseParams().getMap(); + } - public Builder removeBaseParams(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableBaseParams().getMutableMap().remove(key); - return this; - } + /** map<string, .StringList> baseParams = 4; */ + public com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetBaseParams().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } - /** - * Use alternate mutation accessors instead. - */ - @java.lang.Deprecated - public java.util.Map getMutableBaseParams() { - return internalGetMutableBaseParams().getMutableMap(); - } + /** map<string, .StringList> baseParams = 4; */ + public com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetBaseParams().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } - /** - * map<string, .StringList> baseParams = 4; - */ - public Builder putBaseParams(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.StringList value) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - if (value == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableBaseParams().getMutableMap().put(key, value); - return this; - } + public Builder clearBaseParams() { + internalGetMutableBaseParams().getMutableMap().clear(); + return this; + } - /** - * map<string, .StringList> baseParams = 4; - */ + /** map<string, .StringList> baseParams = 4; */ + public Builder removeBaseParams(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableBaseParams().getMutableMap().remove(key); + return this; + } - public Builder putAllBaseParams(java.util.Map values) { - internalGetMutableBaseParams().getMutableMap().putAll(values); - return this; - } + /** Use alternate mutation accessors instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + getMutableBaseParams() { + return internalGetMutableBaseParams().getMutableMap(); + } - private com.google.protobuf.MapField services_; + /** map<string, .StringList> baseParams = 4; */ + public Builder putBaseParams( + java.lang.String key, com.alipay.sofa.registry.common.model.client.pb.StringList value) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + if (value == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableBaseParams().getMutableMap().put(key, value); + return this; + } - private com.google.protobuf.MapField internalGetServices() { - if (services_ == null) { - return com.google.protobuf.MapField - .emptyMapField(ServicesDefaultEntryHolder.defaultEntry); - } - return services_; - } + /** map<string, .StringList> baseParams = 4; */ + public Builder putAllBaseParams( + java.util.Map + values) { + internalGetMutableBaseParams().getMutableMap().putAll(values); + return this; + } - private com.google.protobuf.MapField internalGetMutableServices() { - onChanged(); - ; - if (services_ == null) { - services_ = com.google.protobuf.MapField - .newMapField(ServicesDefaultEntryHolder.defaultEntry); - } - if (!services_.isMutable()) { - services_ = services_.copy(); - } - return services_; - } + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + services_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + internalGetServices() { + if (services_ == null) { + return com.google.protobuf.MapField.emptyMapField(ServicesDefaultEntryHolder.defaultEntry); + } + return services_; + } - public int getServicesCount() { - return internalGetServices().getMap().size(); - } + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + internalGetMutableServices() { + onChanged(); + ; + if (services_ == null) { + services_ = + com.google.protobuf.MapField.newMapField(ServicesDefaultEntryHolder.defaultEntry); + } + if (!services_.isMutable()) { + services_ = services_.copy(); + } + return services_; + } - /** - * map<string, .MetaService> services = 5; - */ + public int getServicesCount() { + return internalGetServices().getMap().size(); + } - public boolean containsServices(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetServices().getMap().containsKey(key); - } + /** map<string, .MetaService> services = 5; */ + public boolean containsServices(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetServices().getMap().containsKey(key); + } - /** - * Use {@link #getServicesMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getServices() { - return getServicesMap(); - } + /** Use {@link #getServicesMap()} instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + getServices() { + return getServicesMap(); + } - /** - * map<string, .MetaService> services = 5; - */ + /** map<string, .MetaService> services = 5; */ + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + getServicesMap() { + return internalGetServices().getMap(); + } - public java.util.Map getServicesMap() { - return internalGetServices().getMap(); - } + /** map<string, .MetaService> services = 5; */ + public com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.MetaService defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetServices().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } - /** - * map<string, .MetaService> services = 5; - */ + /** map<string, .MetaService> services = 5; */ + public com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetServices().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } - public com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.MetaService defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetServices() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } + public Builder clearServices() { + internalGetMutableServices().getMutableMap().clear(); + return this; + } - /** - * map<string, .MetaService> services = 5; - */ + /** map<string, .MetaService> services = 5; */ + public Builder removeServices(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableServices().getMutableMap().remove(key); + return this; + } - public com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetServices() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } + /** Use alternate mutation accessors instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.MetaService> + getMutableServices() { + return internalGetMutableServices().getMutableMap(); + } - public Builder clearServices() { - internalGetMutableServices().getMutableMap().clear(); - return this; - } + /** map<string, .MetaService> services = 5; */ + public Builder putServices( + java.lang.String key, com.alipay.sofa.registry.common.model.client.pb.MetaService value) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + if (value == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableServices().getMutableMap().put(key, value); + return this; + } - /** - * map<string, .MetaService> services = 5; - */ + /** map<string, .MetaService> services = 5; */ + public Builder putAllServices( + java.util.Map + values) { + internalGetMutableServices().getMutableMap().putAll(values); + return this; + } - public Builder removeServices(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableServices().getMutableMap().remove(key); - return this; - } + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } - /** - * Use alternate mutation accessors instead. - */ - @java.lang.Deprecated - public java.util.Map getMutableServices() { - return internalGetMutableServices().getMutableMap(); - } + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - /** - * map<string, .MetaService> services = 5; - */ - public Builder putServices(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.MetaService value) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - if (value == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableServices().getMutableMap().put(key, value); - return this; - } + // @@protoc_insertion_point(builder_scope:MetaRegister) + } - /** - * map<string, .MetaService> services = 5; - */ + // @@protoc_insertion_point(class_scope:MetaRegister) + private static final com.alipay.sofa.registry.common.model.client.pb.MetaRegister + DEFAULT_INSTANCE; - public Builder putAllServices(java.util.Map values) { - internalGetMutableServices().getMutableMap().putAll(values); - return this; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.MetaRegister(); + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public MetaRegister parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new MetaRegister(input, extensionRegistry); } + }; - // @@protoc_insertion_point(builder_scope:MetaRegister) - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - // @@protoc_insertion_point(class_scope:MetaRegister) - private static final com.alipay.sofa.registry.common.model.client.pb.MetaRegister DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.MetaRegister(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.MetaRegister getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public MetaRegister parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new MetaRegister( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaRegister getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.MetaRegister getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaRegisterOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaRegisterOrBuilder.java index 86106b078..ad115cc8c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaRegisterOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaRegisterOrBuilder.java @@ -14,110 +14,76 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface MetaRegisterOrBuilder extends -// @@protoc_insertion_point(interface_extends:MetaRegister) - com.google.protobuf.MessageOrBuilder { - - /** - * string application = 1; - */ - java.lang.String getApplication(); - - /** - * string application = 1; - */ - com.google.protobuf.ByteString getApplicationBytes(); - - /** - * string revision = 2; - */ - java.lang.String getRevision(); - - /** - * string revision = 2; - */ - com.google.protobuf.ByteString getRevisionBytes(); - - /** - * string clientVersion = 3; - */ - java.lang.String getClientVersion(); - - /** - * string clientVersion = 3; - */ - com.google.protobuf.ByteString getClientVersionBytes(); - - /** - * map<string, .StringList> baseParams = 4; - */ - int getBaseParamsCount(); - - /** - * map<string, .StringList> baseParams = 4; - */ - boolean containsBaseParams(java.lang.String key); - - /** - * Use {@link #getBaseParamsMap()} instead. - */ - @java.lang.Deprecated - java.util.Map getBaseParams(); - - /** - * map<string, .StringList> baseParams = 4; - */ - java.util.Map getBaseParamsMap(); - - /** - * map<string, .StringList> baseParams = 4; - */ - - com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue); - - /** - * map<string, .StringList> baseParams = 4; - */ - - com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrThrow(java.lang.String key); - - /** - * map<string, .MetaService> services = 5; - */ - int getServicesCount(); - - /** - * map<string, .MetaService> services = 5; - */ - boolean containsServices(java.lang.String key); - - /** - * Use {@link #getServicesMap()} instead. - */ - @java.lang.Deprecated - java.util.Map getServices(); - - /** - * map<string, .MetaService> services = 5; - */ - java.util.Map getServicesMap(); - - /** - * map<string, .MetaService> services = 5; - */ - - com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.MetaService defaultValue); - - /** - * map<string, .MetaService> services = 5; - */ - - com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrThrow(java.lang.String key); +public interface MetaRegisterOrBuilder + extends + // @@protoc_insertion_point(interface_extends:MetaRegister) + com.google.protobuf.MessageOrBuilder { + + /** string application = 1; */ + java.lang.String getApplication(); + + /** string application = 1; */ + com.google.protobuf.ByteString getApplicationBytes(); + + /** string revision = 2; */ + java.lang.String getRevision(); + + /** string revision = 2; */ + com.google.protobuf.ByteString getRevisionBytes(); + + /** string clientVersion = 3; */ + java.lang.String getClientVersion(); + + /** string clientVersion = 3; */ + com.google.protobuf.ByteString getClientVersionBytes(); + + /** map<string, .StringList> baseParams = 4; */ + int getBaseParamsCount(); + + /** map<string, .StringList> baseParams = 4; */ + boolean containsBaseParams(java.lang.String key); + + /** Use {@link #getBaseParamsMap()} instead. */ + @java.lang.Deprecated + java.util.Map + getBaseParams(); + + /** map<string, .StringList> baseParams = 4; */ + java.util.Map + getBaseParamsMap(); + + /** map<string, .StringList> baseParams = 4; */ + com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue); + + /** map<string, .StringList> baseParams = 4; */ + com.alipay.sofa.registry.common.model.client.pb.StringList getBaseParamsOrThrow( + java.lang.String key); + + /** map<string, .MetaService> services = 5; */ + int getServicesCount(); + + /** map<string, .MetaService> services = 5; */ + boolean containsServices(java.lang.String key); + + /** Use {@link #getServicesMap()} instead. */ + @java.lang.Deprecated + java.util.Map + getServices(); + + /** map<string, .MetaService> services = 5; */ + java.util.Map + getServicesMap(); + + /** map<string, .MetaService> services = 5; */ + com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.MetaService defaultValue); + + /** map<string, .MetaService> services = 5; */ + com.alipay.sofa.registry.common.model.client.pb.MetaService getServicesOrThrow( + java.lang.String key); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaService.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaService.java index 188af850a..f4800555a 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaService.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaService.java @@ -14,804 +14,793 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code MetaService} - */ -public final class MetaService extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:MetaService) - MetaServiceOrBuilder { - private static final long serialVersionUID = 0L; - - // Use MetaService.newBuilder() to construct. - private MetaService(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private MetaService() { - id_ = ""; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } +/** Protobuf type {@code MetaService} */ +public final class MetaService extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:MetaService) + MetaServiceOrBuilder { + private static final long serialVersionUID = 0L; + + // Use MetaService.newBuilder() to construct. + private MetaService(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private MetaService() { + id_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private MetaService( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); - private MetaService(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - - id_ = s; - break; - } - case 26: { - if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { - params_ = com.google.protobuf.MapField - .newMapField(ParamsDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000002; - } - com.google.protobuf.MapEntry params__ = input - .readMessage(ParamsDefaultEntryHolder.defaultEntry.getParserForType(), - extensionRegistry); - params_.getMutableMap().put(params__.getKey(), params__.getValue()); - break; - } - } + id_ = s; + break; + } + case 26: + { + if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + params_ = + com.google.protobuf.MapField.newMapField(ParamsDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000002; + } + com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + params__ = + input.readMessage( + ParamsDefaultEntryHolder.defaultEntry.getParserForType(), + extensionRegistry); + params_.getMutableMap().put(params__.getKey(), params__.getValue()); + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaService_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 3: + return internalGetParams(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaService_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.MetaService.class, + com.alipay.sofa.registry.common.model.client.pb.MetaService.Builder.class); + } + + private int bitField0_; + public static final int ID_FIELD_NUMBER = 1; + private volatile java.lang.Object id_; + + /** string id = 1; */ + public java.lang.String getId() { + java.lang.Object ref = id_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + id_ = s; + return s; + } + } + + /** string id = 1; */ + public com.google.protobuf.ByteString getIdBytes() { + java.lang.Object ref = id_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + id_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int PARAMS_FIELD_NUMBER = 3; + + private static final class ParamsDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + defaultEntry = + com.google.protobuf.MapEntry + . + newDefaultInstance( + com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaService_ParamsEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.MESSAGE, + com.alipay.sofa.registry.common.model.client.pb.StringList + .getDefaultInstance()); + } + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + params_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + internalGetParams() { + if (params_ == null) { + return com.google.protobuf.MapField.emptyMapField(ParamsDefaultEntryHolder.defaultEntry); + } + return params_; + } + + public int getParamsCount() { + return internalGetParams().getMap().size(); + } + + /** map<string, .StringList> params = 3; */ + public boolean containsParams(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetParams().getMap().containsKey(key); + } + + /** Use {@link #getParamsMap()} instead. */ + @java.lang.Deprecated + public java.util.Map + getParams() { + return getParamsMap(); + } + + /** map<string, .StringList> params = 3; */ + public java.util.Map + getParamsMap() { + return internalGetParams().getMap(); + } + + /** map<string, .StringList> params = 3; */ + public com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetParams().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + + /** map<string, .StringList> params = 3; */ + public com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetParams().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_); + } + com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( + output, internalGetParams(), ParamsDefaultEntryHolder.defaultEntry, 3); + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!getIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_); + } + for (java.util.Map.Entry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + entry : internalGetParams().getMap().entrySet()) { + com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + params__ = + ParamsDefaultEntryHolder.defaultEntry + .newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, params__); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.MetaService)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.MetaService other = + (com.alipay.sofa.registry.common.model.client.pb.MetaService) obj; + + boolean result = true; + result = result && getId().equals(other.getId()); + result = result && internalGetParams().equals(other.internalGetParams()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + ID_FIELD_NUMBER; + hash = (53 * hash) + getId().hashCode(); + if (!internalGetParams().getMap().isEmpty()) { + hash = (37 * hash) + PARAMS_FIELD_NUMBER; + hash = (53 * hash) + internalGetParams().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.MetaService prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code MetaService} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:MetaService) + com.alipay.sofa.registry.common.model.client.pb.MetaServiceOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaService_descriptor; + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaService_descriptor; } - @SuppressWarnings({ "rawtypes" }) + @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 3: - return internalGetParams(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaService_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.MetaService.class, - com.alipay.sofa.registry.common.model.client.pb.MetaService.Builder.class); - } - - private int bitField0_; - public static final int ID_FIELD_NUMBER = 1; - private volatile java.lang.Object id_; - - /** - * string id = 1; - */ - public java.lang.String getId() { - java.lang.Object ref = id_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - id_ = s; - return s; - } - } - - /** - * string id = 1; - */ - public com.google.protobuf.ByteString getIdBytes() { - java.lang.Object ref = id_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - id_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + switch (number) { + case 3: + return internalGetParams(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - public static final int PARAMS_FIELD_NUMBER = 3; - - private static final class ParamsDefaultEntryHolder { - static final com.google.protobuf.MapEntry defaultEntry = com.google.protobuf.MapEntry - . newDefaultInstance( - com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaService_ParamsEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.MESSAGE, - com.alipay.sofa.registry.common.model.client.pb.StringList - .getDefaultInstance()); + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField(int number) { + switch (number) { + case 3: + return internalGetMutableParams(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - private com.google.protobuf.MapField params_; - - private com.google.protobuf.MapField internalGetParams() { - if (params_ == null) { - return com.google.protobuf.MapField - .emptyMapField(ParamsDefaultEntryHolder.defaultEntry); - } - return params_; + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaService_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.MetaService.class, + com.alipay.sofa.registry.common.model.client.pb.MetaService.Builder.class); } - public int getParamsCount() { - return internalGetParams().getMap().size(); + // Construct using com.alipay.sofa.registry.common.model.client.pb.MetaService.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - /** - * map<string, .StringList> params = 3; - */ - - public boolean containsParams(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetParams().getMap().containsKey(key); + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - /** - * Use {@link #getParamsMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getParams() { - return getParamsMap(); + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - /** - * map<string, .StringList> params = 3; - */ + public Builder clear() { + super.clear(); + id_ = ""; - public java.util.Map getParamsMap() { - return internalGetParams().getMap(); + internalGetMutableParams().clear(); + return this; } - /** - * map<string, .StringList> params = 3; - */ - - public com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetParams() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_MetaService_descriptor; } - /** - * map<string, .StringList> params = 3; - */ - - public com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetParams() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); + public com.alipay.sofa.registry.common.model.client.pb.MetaService getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.MetaService.getDefaultInstance(); } - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; + public com.alipay.sofa.registry.common.model.client.pb.MetaService build() { + com.alipay.sofa.registry.common.model.client.pb.MetaService result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (!getIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_); - } - com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(output, internalGetParams(), - ParamsDefaultEntryHolder.defaultEntry, 3); - unknownFields.writeTo(output); + public com.alipay.sofa.registry.common.model.client.pb.MetaService buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.MetaService result = + new com.alipay.sofa.registry.common.model.client.pb.MetaService(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + result.id_ = id_; + result.params_ = internalGetParams(); + result.params_.makeImmutable(); + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - if (!getIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_); - } - for (java.util.Map.Entry entry : internalGetParams() - .getMap().entrySet()) { - com.google.protobuf.MapEntry params__ = ParamsDefaultEntryHolder.defaultEntry - .newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build(); - size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, params__); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + public Builder clone() { + return (Builder) super.clone(); } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.MetaService)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.MetaService other = (com.alipay.sofa.registry.common.model.client.pb.MetaService) obj; - - boolean result = true; - result = result && getId().equals(other.getId()); - result = result && internalGetParams().equals(other.internalGetParams()); - result = result && unknownFields.equals(other.unknownFields); - return result; + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + ID_FIELD_NUMBER; - hash = (53 * hash) + getId().hashCode(); - if (!internalGetParams().getMap().isEmpty()) { - hash = (37 * hash) + PARAMS_FIELD_NUMBER; - hash = (53 * hash) + internalGetParams().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.MetaService) { + return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.MetaService) other); + } else { + super.mergeFrom(other); + return this; + } } - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.MetaService other) { + if (other == com.alipay.sofa.registry.common.model.client.pb.MetaService.getDefaultInstance()) + return this; + if (!other.getId().isEmpty()) { + id_ = other.id_; + onChanged(); + } + internalGetMutableParams().mergeFrom(other.internalGetParams()); + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public final boolean isInitialized() { + return true; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.MetaService parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.MetaService) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + private int bitField0_; - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); - } + private java.lang.Object id_ = ""; - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + /** string id = 1; */ + public java.lang.String getId() { + java.lang.Object ref = id_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + id_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string id = 1; */ + public com.google.protobuf.ByteString getIdBytes() { + java.lang.Object ref = id_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + id_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** string id = 1; */ + public Builder setId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + + id_ = value; + onChanged(); + return this; + } + + /** string id = 1; */ + public Builder clearId() { + + id_ = getDefaultInstance().getId(); + onChanged(); + return this; + } + + /** string id = 1; */ + public Builder setIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + id_ = value; + onChanged(); + return this; + } + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + params_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + internalGetParams() { + if (params_ == null) { + return com.google.protobuf.MapField.emptyMapField(ParamsDefaultEntryHolder.defaultEntry); + } + return params_; + } + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + internalGetMutableParams() { + onChanged(); + ; + if (params_ == null) { + params_ = com.google.protobuf.MapField.newMapField(ParamsDefaultEntryHolder.defaultEntry); + } + if (!params_.isMutable()) { + params_ = params_.copy(); + } + return params_; } - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public int getParamsCount() { + return internalGetParams().getMap().size(); } - public static com.alipay.sofa.registry.common.model.client.pb.MetaService parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + /** map<string, .StringList> params = 3; */ + public boolean containsParams(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetParams().getMap().containsKey(key); } - public Builder newBuilderForType() { - return newBuilder(); + /** Use {@link #getParamsMap()} instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + getParams() { + return getParamsMap(); + } + + /** map<string, .StringList> params = 3; */ + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + getParamsMap() { + return internalGetParams().getMap(); + } + + /** map<string, .StringList> params = 3; */ + public com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetParams().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + + /** map<string, .StringList> params = 3; */ + public com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetParams().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearParams() { + internalGetMutableParams().getMutableMap().clear(); + return this; + } + + /** map<string, .StringList> params = 3; */ + public Builder removeParams(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableParams().getMutableMap().remove(key); + return this; + } + + /** Use alternate mutation accessors instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.StringList> + getMutableParams() { + return internalGetMutableParams().getMutableMap(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); + /** map<string, .StringList> params = 3; */ + public Builder putParams( + java.lang.String key, com.alipay.sofa.registry.common.model.client.pb.StringList value) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + if (value == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableParams().getMutableMap().put(key, value); + return this; } - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.MetaService prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + /** map<string, .StringList> params = 3; */ + public Builder putAllParams( + java.util.Map + values) { + internalGetMutableParams().getMutableMap().putAll(values); + return this; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); } - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); } - /** - * Protobuf type {@code MetaService} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:MetaService) - com.alipay.sofa.registry.common.model.client.pb.MetaServiceOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaService_descriptor; - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 3: - return internalGetParams(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMutableMapField(int number) { - switch (number) { - case 3: - return internalGetMutableParams(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaService_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.MetaService.class, - com.alipay.sofa.registry.common.model.client.pb.MetaService.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.MetaService.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } + // @@protoc_insertion_point(builder_scope:MetaService) + } - public Builder clear() { - super.clear(); - id_ = ""; + // @@protoc_insertion_point(class_scope:MetaService) + private static final com.alipay.sofa.registry.common.model.client.pb.MetaService DEFAULT_INSTANCE; - internalGetMutableParams().clear(); - return this; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.MetaService(); + } - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_MetaService_descriptor; - } + public static com.alipay.sofa.registry.common.model.client.pb.MetaService getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public com.alipay.sofa.registry.common.model.client.pb.MetaService getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.MetaService.getDefaultInstance(); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public MetaService parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new MetaService(input, extensionRegistry); } + }; - public com.alipay.sofa.registry.common.model.client.pb.MetaService build() { - com.alipay.sofa.registry.common.model.client.pb.MetaService result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - public com.alipay.sofa.registry.common.model.client.pb.MetaService buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.MetaService result = new com.alipay.sofa.registry.common.model.client.pb.MetaService( - this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - result.id_ = id_; - result.params_ = internalGetParams(); - result.params_.makeImmutable(); - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.MetaService) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.MetaService) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.MetaService other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.MetaService - .getDefaultInstance()) - return this; - if (!other.getId().isEmpty()) { - id_ = other.id_; - onChanged(); - } - internalGetMutableParams().mergeFrom(other.internalGetParams()); - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.MetaService parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.MetaService) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private java.lang.Object id_ = ""; - - /** - * string id = 1; - */ - public java.lang.String getId() { - java.lang.Object ref = id_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - id_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } - - /** - * string id = 1; - */ - public com.google.protobuf.ByteString getIdBytes() { - java.lang.Object ref = id_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - id_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - /** - * string id = 1; - */ - public Builder setId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - - id_ = value; - onChanged(); - return this; - } - - /** - * string id = 1; - */ - public Builder clearId() { - - id_ = getDefaultInstance().getId(); - onChanged(); - return this; - } - - /** - * string id = 1; - */ - public Builder setIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - id_ = value; - onChanged(); - return this; - } - - private com.google.protobuf.MapField params_; - - private com.google.protobuf.MapField internalGetParams() { - if (params_ == null) { - return com.google.protobuf.MapField - .emptyMapField(ParamsDefaultEntryHolder.defaultEntry); - } - return params_; - } - - private com.google.protobuf.MapField internalGetMutableParams() { - onChanged(); - ; - if (params_ == null) { - params_ = com.google.protobuf.MapField - .newMapField(ParamsDefaultEntryHolder.defaultEntry); - } - if (!params_.isMutable()) { - params_ = params_.copy(); - } - return params_; - } - - public int getParamsCount() { - return internalGetParams().getMap().size(); - } - - /** - * map<string, .StringList> params = 3; - */ - - public boolean containsParams(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetParams().getMap().containsKey(key); - } - - /** - * Use {@link #getParamsMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getParams() { - return getParamsMap(); - } - - /** - * map<string, .StringList> params = 3; - */ - - public java.util.Map getParamsMap() { - return internalGetParams().getMap(); - } - - /** - * map<string, .StringList> params = 3; - */ - - public com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetParams() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - - /** - * map<string, .StringList> params = 3; - */ - - public com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetParams() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } - - public Builder clearParams() { - internalGetMutableParams().getMutableMap().clear(); - return this; - } - - /** - * map<string, .StringList> params = 3; - */ - - public Builder removeParams(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableParams().getMutableMap().remove(key); - return this; - } - - /** - * Use alternate mutation accessors instead. - */ - @java.lang.Deprecated - public java.util.Map getMutableParams() { - return internalGetMutableParams().getMutableMap(); - } - - /** - * map<string, .StringList> params = 3; - */ - public Builder putParams(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.StringList value) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - if (value == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableParams().getMutableMap().put(key, value); - return this; - } - - /** - * map<string, .StringList> params = 3; - */ - - public Builder putAllParams(java.util.Map values) { - internalGetMutableParams().getMutableMap().putAll(values); - return this; - } - - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } - - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - // @@protoc_insertion_point(builder_scope:MetaService) - } - - // @@protoc_insertion_point(class_scope:MetaService) - private static final com.alipay.sofa.registry.common.model.client.pb.MetaService DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.MetaService(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.MetaService getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public MetaService parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new MetaService( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public com.alipay.sofa.registry.common.model.client.pb.MetaService getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.MetaService getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaServiceOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaServiceOrBuilder.java index d4afd1b72..7e6f29086 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaServiceOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/MetaServiceOrBuilder.java @@ -14,56 +14,39 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface MetaServiceOrBuilder extends -// @@protoc_insertion_point(interface_extends:MetaService) - com.google.protobuf.MessageOrBuilder { - - /** - * string id = 1; - */ - java.lang.String getId(); - - /** - * string id = 1; - */ - com.google.protobuf.ByteString getIdBytes(); +public interface MetaServiceOrBuilder + extends + // @@protoc_insertion_point(interface_extends:MetaService) + com.google.protobuf.MessageOrBuilder { - /** - * map<string, .StringList> params = 3; - */ - int getParamsCount(); + /** string id = 1; */ + java.lang.String getId(); - /** - * map<string, .StringList> params = 3; - */ - boolean containsParams(java.lang.String key); + /** string id = 1; */ + com.google.protobuf.ByteString getIdBytes(); - /** - * Use {@link #getParamsMap()} instead. - */ - @java.lang.Deprecated - java.util.Map getParams(); + /** map<string, .StringList> params = 3; */ + int getParamsCount(); - /** - * map<string, .StringList> params = 3; - */ - java.util.Map getParamsMap(); + /** map<string, .StringList> params = 3; */ + boolean containsParams(java.lang.String key); - /** - * map<string, .StringList> params = 3; - */ + /** Use {@link #getParamsMap()} instead. */ + @java.lang.Deprecated + java.util.Map + getParams(); - com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue); + /** map<string, .StringList> params = 3; */ + java.util.Map + getParamsMap(); - /** - * map<string, .StringList> params = 3; - */ + /** map<string, .StringList> params = 3; */ + com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.StringList defaultValue); - com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrThrow(java.lang.String key); + /** map<string, .StringList> params = 3; */ + com.alipay.sofa.registry.common.model.client.pb.StringList getParamsOrThrow(java.lang.String key); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPb.java index f31848659..9e97946a6 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPb.java @@ -14,944 +14,954 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: PublisherRegisterPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code PublisherRegisterPb} - */ -public final class PublisherRegisterPb extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:PublisherRegisterPb) - PublisherRegisterPbOrBuilder { - private static final long serialVersionUID = 0L; - - // Use PublisherRegisterPb.newBuilder() to construct. - private PublisherRegisterPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private PublisherRegisterPb() { - dataList_ = java.util.Collections.emptyList(); - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; +/** Protobuf type {@code PublisherRegisterPb} */ +public final class PublisherRegisterPb extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:PublisherRegisterPb) + PublisherRegisterPbOrBuilder { + private static final long serialVersionUID = 0L; + + // Use PublisherRegisterPb.newBuilder() to construct. + private PublisherRegisterPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private PublisherRegisterPb() { + dataList_ = java.util.Collections.emptyList(); + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private PublisherRegisterPb( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: + { + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + dataList_ = + new java.util.ArrayList< + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb>(); + mutable_bitField0_ |= 0x00000001; + } + dataList_.add( + input.readMessage( + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.parser(), + extensionRegistry)); + break; + } + case 18: + { + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder subBuilder = + null; + if (baseRegister_ != null) { + subBuilder = baseRegister_.toBuilder(); + } + baseRegister_ = + input.readMessage( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.parser(), + extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(baseRegister_); + baseRegister_ = subBuilder.buildPartial(); + } + + break; + } + } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + dataList_ = java.util.Collections.unmodifiableList(dataList_); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOuterClass + .internal_static_PublisherRegisterPb_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOuterClass + .internal_static_PublisherRegisterPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb.class, + com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb.Builder.class); + } + + private int bitField0_; + public static final int DATALIST_FIELD_NUMBER = 1; + private java.util.List dataList_; + + /** repeated .DataBoxPb dataList = 1; */ + public java.util.List + getDataListList() { + return dataList_; + } + + /** repeated .DataBoxPb dataList = 1; */ + public java.util.List< + ? extends com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder> + getDataListOrBuilderList() { + return dataList_; + } + + /** repeated .DataBoxPb dataList = 1; */ + public int getDataListCount() { + return dataList_.size(); + } + + /** repeated .DataBoxPb dataList = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDataList(int index) { + return dataList_.get(index); + } + + /** repeated .DataBoxPb dataList = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataListOrBuilder( + int index) { + return dataList_.get(index); + } + + public static final int BASEREGISTER_FIELD_NUMBER = 2; + private com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb baseRegister_; + + /** .BaseRegisterPb baseRegister = 2; */ + public boolean hasBaseRegister() { + return baseRegister_ != null; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getBaseRegister() { + return baseRegister_ == null + ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.getDefaultInstance() + : baseRegister_; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder + getBaseRegisterOrBuilder() { + return getBaseRegister(); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + for (int i = 0; i < dataList_.size(); i++) { + output.writeMessage(1, dataList_.get(i)); + } + if (baseRegister_ != null) { + output.writeMessage(2, getBaseRegister()); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + for (int i = 0; i < dataList_.size(); i++) { + size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dataList_.get(i)); + } + if (baseRegister_ != null) { + size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getBaseRegister()); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb other = + (com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb) obj; + + boolean result = true; + result = result && getDataListList().equals(other.getDataListList()); + result = result && (hasBaseRegister() == other.hasBaseRegister()); + if (hasBaseRegister()) { + result = result && getBaseRegister().equals(other.getBaseRegister()); + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (getDataListCount() > 0) { + hash = (37 * hash) + DATALIST_FIELD_NUMBER; + hash = (53 * hash) + getDataListList().hashCode(); + } + if (hasBaseRegister()) { + hash = (37 * hash) + BASEREGISTER_FIELD_NUMBER; + hash = (53 * hash) + getBaseRegister().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code PublisherRegisterPb} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:PublisherRegisterPb) + com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOuterClass + .internal_static_PublisherRegisterPb_descriptor; } - private PublisherRegisterPb(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - dataList_ = new java.util.ArrayList(); - mutable_bitField0_ |= 0x00000001; - } - dataList_.add(input.readMessage( - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.parser(), - extensionRegistry)); - break; - } - case 18: { - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder subBuilder = null; - if (baseRegister_ != null) { - subBuilder = baseRegister_.toBuilder(); - } - baseRegister_ = input - .readMessage( - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .parser(), extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(baseRegister_); - baseRegister_ = subBuilder.buildPartial(); - } - - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - dataList_ = java.util.Collections.unmodifiableList(dataList_); - } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOuterClass + .internal_static_PublisherRegisterPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb.class, + com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb.Builder.class); } - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOuterClass.internal_static_PublisherRegisterPb_descriptor; + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOuterClass.internal_static_PublisherRegisterPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb.class, - com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb.Builder.class); + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - private int bitField0_; - public static final int DATALIST_FIELD_NUMBER = 1; - private java.util.List dataList_; - - /** - * repeated .DataBoxPb dataList = 1; - */ - public java.util.List getDataListList() { - return dataList_; + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { + getDataListFieldBuilder(); + } } - /** - * repeated .DataBoxPb dataList = 1; - */ - public java.util.List getDataListOrBuilderList() { - return dataList_; + public Builder clear() { + super.clear(); + if (dataListBuilder_ == null) { + dataList_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000001); + } else { + dataListBuilder_.clear(); + } + if (baseRegisterBuilder_ == null) { + baseRegister_ = null; + } else { + baseRegister_ = null; + baseRegisterBuilder_ = null; + } + return this; + } + + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOuterClass + .internal_static_PublisherRegisterPb_descriptor; + } + + public com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb + .getDefaultInstance(); + } + + public com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb build() { + com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + public com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb result = + new com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (dataListBuilder_ == null) { + if (((bitField0_ & 0x00000001) == 0x00000001)) { + dataList_ = java.util.Collections.unmodifiableList(dataList_); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.dataList_ = dataList_; + } else { + result.dataList_ = dataListBuilder_.build(); + } + if (baseRegisterBuilder_ == null) { + result.baseRegister_ = baseRegister_; + } else { + result.baseRegister_ = baseRegisterBuilder_.build(); + } + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } + + public Builder clone() { + return (Builder) super.clone(); + } + + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); + } + + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } + + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } + + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } + + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } + + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb + .getDefaultInstance()) return this; + if (dataListBuilder_ == null) { + if (!other.dataList_.isEmpty()) { + if (dataList_.isEmpty()) { + dataList_ = other.dataList_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureDataListIsMutable(); + dataList_.addAll(other.dataList_); + } + onChanged(); + } + } else { + if (!other.dataList_.isEmpty()) { + if (dataListBuilder_.isEmpty()) { + dataListBuilder_.dispose(); + dataListBuilder_ = null; + dataList_ = other.dataList_; + bitField0_ = (bitField0_ & ~0x00000001); + dataListBuilder_ = + com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders + ? getDataListFieldBuilder() + : null; + } else { + dataListBuilder_.addAllMessages(other.dataList_); + } + } + } + if (other.hasBaseRegister()) { + mergeBaseRegister(other.getBaseRegister()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - /** - * repeated .DataBoxPb dataList = 1; - */ + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private java.util.List dataList_ = + java.util.Collections.emptyList(); + + private void ensureDataListIsMutable() { + if (!((bitField0_ & 0x00000001) == 0x00000001)) { + dataList_ = + new java.util.ArrayList( + dataList_); + bitField0_ |= 0x00000001; + } + } + + private com.google.protobuf.RepeatedFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder> + dataListBuilder_; + + /** repeated .DataBoxPb dataList = 1; */ + public java.util.List + getDataListList() { + if (dataListBuilder_ == null) { + return java.util.Collections.unmodifiableList(dataList_); + } else { + return dataListBuilder_.getMessageList(); + } + } + + /** repeated .DataBoxPb dataList = 1; */ public int getDataListCount() { + if (dataListBuilder_ == null) { return dataList_.size(); + } else { + return dataListBuilder_.getCount(); + } } - /** - * repeated .DataBoxPb dataList = 1; - */ + /** repeated .DataBoxPb dataList = 1; */ public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDataList(int index) { + if (dataListBuilder_ == null) { return dataList_.get(index); - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataListOrBuilder(int index) { + } else { + return dataListBuilder_.getMessage(index); + } + } + + /** repeated .DataBoxPb dataList = 1; */ + public Builder setDataList( + int index, com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { + if (dataListBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureDataListIsMutable(); + dataList_.set(index, value); + onChanged(); + } else { + dataListBuilder_.setMessage(index, value); + } + return this; + } + + /** repeated .DataBoxPb dataList = 1; */ + public Builder setDataList( + int index, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { + if (dataListBuilder_ == null) { + ensureDataListIsMutable(); + dataList_.set(index, builderForValue.build()); + onChanged(); + } else { + dataListBuilder_.setMessage(index, builderForValue.build()); + } + return this; + } + + /** repeated .DataBoxPb dataList = 1; */ + public Builder addDataList(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { + if (dataListBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureDataListIsMutable(); + dataList_.add(value); + onChanged(); + } else { + dataListBuilder_.addMessage(value); + } + return this; + } + + /** repeated .DataBoxPb dataList = 1; */ + public Builder addDataList( + int index, com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { + if (dataListBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + ensureDataListIsMutable(); + dataList_.add(index, value); + onChanged(); + } else { + dataListBuilder_.addMessage(index, value); + } + return this; + } + + /** repeated .DataBoxPb dataList = 1; */ + public Builder addDataList( + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { + if (dataListBuilder_ == null) { + ensureDataListIsMutable(); + dataList_.add(builderForValue.build()); + onChanged(); + } else { + dataListBuilder_.addMessage(builderForValue.build()); + } + return this; + } + + /** repeated .DataBoxPb dataList = 1; */ + public Builder addDataList( + int index, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { + if (dataListBuilder_ == null) { + ensureDataListIsMutable(); + dataList_.add(index, builderForValue.build()); + onChanged(); + } else { + dataListBuilder_.addMessage(index, builderForValue.build()); + } + return this; + } + + /** repeated .DataBoxPb dataList = 1; */ + public Builder addAllDataList( + java.lang.Iterable + values) { + if (dataListBuilder_ == null) { + ensureDataListIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dataList_); + onChanged(); + } else { + dataListBuilder_.addAllMessages(values); + } + return this; + } + + /** repeated .DataBoxPb dataList = 1; */ + public Builder clearDataList() { + if (dataListBuilder_ == null) { + dataList_ = java.util.Collections.emptyList(); + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + } else { + dataListBuilder_.clear(); + } + return this; + } + + /** repeated .DataBoxPb dataList = 1; */ + public Builder removeDataList(int index) { + if (dataListBuilder_ == null) { + ensureDataListIsMutable(); + dataList_.remove(index); + onChanged(); + } else { + dataListBuilder_.remove(index); + } + return this; + } + + /** repeated .DataBoxPb dataList = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder getDataListBuilder( + int index) { + return getDataListFieldBuilder().getBuilder(index); + } + + /** repeated .DataBoxPb dataList = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataListOrBuilder( + int index) { + if (dataListBuilder_ == null) { return dataList_.get(index); - } - - public static final int BASEREGISTER_FIELD_NUMBER = 2; - private com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb baseRegister_; - - /** - * .BaseRegisterPb baseRegister = 2; - */ + } else { + return dataListBuilder_.getMessageOrBuilder(index); + } + } + + /** repeated .DataBoxPb dataList = 1; */ + public java.util.List< + ? extends com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder> + getDataListOrBuilderList() { + if (dataListBuilder_ != null) { + return dataListBuilder_.getMessageOrBuilderList(); + } else { + return java.util.Collections.unmodifiableList(dataList_); + } + } + + /** repeated .DataBoxPb dataList = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder addDataListBuilder() { + return getDataListFieldBuilder() + .addBuilder( + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance()); + } + + /** repeated .DataBoxPb dataList = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder addDataListBuilder( + int index) { + return getDataListFieldBuilder() + .addBuilder( + index, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance()); + } + + /** repeated .DataBoxPb dataList = 1; */ + public java.util.List + getDataListBuilderList() { + return getDataListFieldBuilder().getBuilderList(); + } + + private com.google.protobuf.RepeatedFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder> + getDataListFieldBuilder() { + if (dataListBuilder_ == null) { + dataListBuilder_ = + new com.google.protobuf.RepeatedFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder>( + dataList_, + ((bitField0_ & 0x00000001) == 0x00000001), + getParentForChildren(), + isClean()); + dataList_ = null; + } + return dataListBuilder_; + } + + private com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb baseRegister_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder> + baseRegisterBuilder_; + + /** .BaseRegisterPb baseRegister = 2; */ public boolean hasBaseRegister() { - return baseRegister_ != null; + return baseRegisterBuilder_ != null || baseRegister_ != null; } - /** - * .BaseRegisterPb baseRegister = 2; - */ + /** .BaseRegisterPb baseRegister = 2; */ public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getBaseRegister() { - return baseRegister_ == null ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .getDefaultInstance() : baseRegister_; - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder getBaseRegisterOrBuilder() { - return getBaseRegister(); - } - - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - for (int i = 0; i < dataList_.size(); i++) { - output.writeMessage(1, dataList_.get(i)); - } - if (baseRegister_ != null) { - output.writeMessage(2, getBaseRegister()); - } - unknownFields.writeTo(output); - } - - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - for (int i = 0; i < dataList_.size(); i++) { - size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, dataList_.get(i)); - } + if (baseRegisterBuilder_ == null) { + return baseRegister_ == null + ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.getDefaultInstance() + : baseRegister_; + } else { + return baseRegisterBuilder_.getMessage(); + } + } + + /** .BaseRegisterPb baseRegister = 2; */ + public Builder setBaseRegister( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb value) { + if (baseRegisterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + baseRegister_ = value; + onChanged(); + } else { + baseRegisterBuilder_.setMessage(value); + } + + return this; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public Builder setBaseRegister( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder builderForValue) { + if (baseRegisterBuilder_ == null) { + baseRegister_ = builderForValue.build(); + onChanged(); + } else { + baseRegisterBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public Builder mergeBaseRegister( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb value) { + if (baseRegisterBuilder_ == null) { if (baseRegister_ != null) { - size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getBaseRegister()); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb other = (com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb) obj; - - boolean result = true; - result = result && getDataListList().equals(other.getDataListList()); - result = result && (hasBaseRegister() == other.hasBaseRegister()); - if (hasBaseRegister()) { - result = result && getBaseRegister().equals(other.getBaseRegister()); - } - result = result && unknownFields.equals(other.unknownFields); - return result; - } - - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (getDataListCount() > 0) { - hash = (37 * hash) + DATALIST_FIELD_NUMBER; - hash = (53 * hash) + getDataListList().hashCode(); - } - if (hasBaseRegister()) { - hash = (37 * hash) + BASEREGISTER_FIELD_NUMBER; - hash = (53 * hash) + getBaseRegister().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } - - public Builder newBuilderForType() { - return newBuilder(); - } - - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } - - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - - /** - * Protobuf type {@code PublisherRegisterPb} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:PublisherRegisterPb) - com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOuterClass.internal_static_PublisherRegisterPb_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOuterClass.internal_static_PublisherRegisterPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb.class, - com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - getDataListFieldBuilder(); - } - } - - public Builder clear() { - super.clear(); - if (dataListBuilder_ == null) { - dataList_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000001); - } else { - dataListBuilder_.clear(); - } - if (baseRegisterBuilder_ == null) { - baseRegister_ = null; - } else { - baseRegister_ = null; - baseRegisterBuilder_ = null; - } - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPbOuterClass.internal_static_PublisherRegisterPb_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb build() { - com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb result = new com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb( - this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (dataListBuilder_ == null) { - if (((bitField0_ & 0x00000001) == 0x00000001)) { - dataList_ = java.util.Collections.unmodifiableList(dataList_); - bitField0_ = (bitField0_ & ~0x00000001); - } - result.dataList_ = dataList_; - } else { - result.dataList_ = dataListBuilder_.build(); - } - if (baseRegisterBuilder_ == null) { - result.baseRegister_ = baseRegister_; - } else { - result.baseRegister_ = baseRegisterBuilder_.build(); - } - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb - .getDefaultInstance()) - return this; - if (dataListBuilder_ == null) { - if (!other.dataList_.isEmpty()) { - if (dataList_.isEmpty()) { - dataList_ = other.dataList_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureDataListIsMutable(); - dataList_.addAll(other.dataList_); - } - onChanged(); - } - } else { - if (!other.dataList_.isEmpty()) { - if (dataListBuilder_.isEmpty()) { - dataListBuilder_.dispose(); - dataListBuilder_ = null; - dataList_ = other.dataList_; - bitField0_ = (bitField0_ & ~0x00000001); - dataListBuilder_ = com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders ? getDataListFieldBuilder() - : null; - } else { - dataListBuilder_.addAllMessages(other.dataList_); - } - } - } - if (other.hasBaseRegister()) { - mergeBaseRegister(other.getBaseRegister()); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private java.util.List dataList_ = java.util.Collections - .emptyList(); - - private void ensureDataListIsMutable() { - if (!((bitField0_ & 0x00000001) == 0x00000001)) { - dataList_ = new java.util.ArrayList( - dataList_); - bitField0_ |= 0x00000001; - } - } - - private com.google.protobuf.RepeatedFieldBuilderV3 dataListBuilder_; - - /** - * repeated .DataBoxPb dataList = 1; - */ - public java.util.List getDataListList() { - if (dataListBuilder_ == null) { - return java.util.Collections.unmodifiableList(dataList_); - } else { - return dataListBuilder_.getMessageList(); - } - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public int getDataListCount() { - if (dataListBuilder_ == null) { - return dataList_.size(); - } else { - return dataListBuilder_.getCount(); - } - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDataList(int index) { - if (dataListBuilder_ == null) { - return dataList_.get(index); - } else { - return dataListBuilder_.getMessage(index); - } - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public Builder setDataList(int index, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { - if (dataListBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensureDataListIsMutable(); - dataList_.set(index, value); - onChanged(); - } else { - dataListBuilder_.setMessage(index, value); - } - return this; - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public Builder setDataList(int index, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { - if (dataListBuilder_ == null) { - ensureDataListIsMutable(); - dataList_.set(index, builderForValue.build()); - onChanged(); - } else { - dataListBuilder_.setMessage(index, builderForValue.build()); - } - return this; - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public Builder addDataList(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { - if (dataListBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensureDataListIsMutable(); - dataList_.add(value); - onChanged(); - } else { - dataListBuilder_.addMessage(value); - } - return this; - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public Builder addDataList(int index, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { - if (dataListBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - ensureDataListIsMutable(); - dataList_.add(index, value); - onChanged(); - } else { - dataListBuilder_.addMessage(index, value); - } - return this; - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public Builder addDataList(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { - if (dataListBuilder_ == null) { - ensureDataListIsMutable(); - dataList_.add(builderForValue.build()); - onChanged(); - } else { - dataListBuilder_.addMessage(builderForValue.build()); - } - return this; - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public Builder addDataList(int index, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { - if (dataListBuilder_ == null) { - ensureDataListIsMutable(); - dataList_.add(index, builderForValue.build()); - onChanged(); - } else { - dataListBuilder_.addMessage(index, builderForValue.build()); - } - return this; - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public Builder addAllDataList(java.lang.Iterable values) { - if (dataListBuilder_ == null) { - ensureDataListIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll(values, dataList_); - onChanged(); - } else { - dataListBuilder_.addAllMessages(values); - } - return this; - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public Builder clearDataList() { - if (dataListBuilder_ == null) { - dataList_ = java.util.Collections.emptyList(); - bitField0_ = (bitField0_ & ~0x00000001); - onChanged(); - } else { - dataListBuilder_.clear(); - } - return this; - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public Builder removeDataList(int index) { - if (dataListBuilder_ == null) { - ensureDataListIsMutable(); - dataList_.remove(index); - onChanged(); - } else { - dataListBuilder_.remove(index); - } - return this; - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder getDataListBuilder(int index) { - return getDataListFieldBuilder().getBuilder(index); - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataListOrBuilder(int index) { - if (dataListBuilder_ == null) { - return dataList_.get(index); - } else { - return dataListBuilder_.getMessageOrBuilder(index); - } - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public java.util.List getDataListOrBuilderList() { - if (dataListBuilder_ != null) { - return dataListBuilder_.getMessageOrBuilderList(); - } else { - return java.util.Collections.unmodifiableList(dataList_); - } - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder addDataListBuilder() { - return getDataListFieldBuilder().addBuilder( - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance()); - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder addDataListBuilder(int index) { - return getDataListFieldBuilder().addBuilder(index, - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance()); - } - - /** - * repeated .DataBoxPb dataList = 1; - */ - public java.util.List getDataListBuilderList() { - return getDataListFieldBuilder().getBuilderList(); - } - - private com.google.protobuf.RepeatedFieldBuilderV3 getDataListFieldBuilder() { - if (dataListBuilder_ == null) { - dataListBuilder_ = new com.google.protobuf.RepeatedFieldBuilderV3( - dataList_, ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), - isClean()); - dataList_ = null; - } - return dataListBuilder_; - } - - private com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb baseRegister_ = null; - private com.google.protobuf.SingleFieldBuilderV3 baseRegisterBuilder_; - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public boolean hasBaseRegister() { - return baseRegisterBuilder_ != null || baseRegister_ != null; - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getBaseRegister() { - if (baseRegisterBuilder_ == null) { - return baseRegister_ == null ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .getDefaultInstance() : baseRegister_; - } else { - return baseRegisterBuilder_.getMessage(); - } - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public Builder setBaseRegister(com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb value) { - if (baseRegisterBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - baseRegister_ = value; - onChanged(); - } else { - baseRegisterBuilder_.setMessage(value); - } - - return this; - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public Builder setBaseRegister(com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder builderForValue) { - if (baseRegisterBuilder_ == null) { - baseRegister_ = builderForValue.build(); - onChanged(); - } else { - baseRegisterBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public Builder mergeBaseRegister(com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb value) { - if (baseRegisterBuilder_ == null) { - if (baseRegister_ != null) { - baseRegister_ = com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .newBuilder(baseRegister_).mergeFrom(value).buildPartial(); - } else { - baseRegister_ = value; - } - onChanged(); - } else { - baseRegisterBuilder_.mergeFrom(value); - } - - return this; - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public Builder clearBaseRegister() { - if (baseRegisterBuilder_ == null) { - baseRegister_ = null; - onChanged(); - } else { - baseRegister_ = null; - baseRegisterBuilder_ = null; - } - - return this; - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder getBaseRegisterBuilder() { - - onChanged(); - return getBaseRegisterFieldBuilder().getBuilder(); - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder getBaseRegisterOrBuilder() { - if (baseRegisterBuilder_ != null) { - return baseRegisterBuilder_.getMessageOrBuilder(); - } else { - return baseRegister_ == null ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .getDefaultInstance() : baseRegister_; - } - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - private com.google.protobuf.SingleFieldBuilderV3 getBaseRegisterFieldBuilder() { - if (baseRegisterBuilder_ == null) { - baseRegisterBuilder_ = new com.google.protobuf.SingleFieldBuilderV3( - getBaseRegister(), getParentForChildren(), isClean()); - baseRegister_ = null; - } - return baseRegisterBuilder_; - } - - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } - - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - // @@protoc_insertion_point(builder_scope:PublisherRegisterPb) - } - - // @@protoc_insertion_point(class_scope:PublisherRegisterPb) - private static final com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public PublisherRegisterPb parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new PublisherRegisterPb( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - + baseRegister_ = + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.newBuilder( + baseRegister_) + .mergeFrom(value) + .buildPartial(); + } else { + baseRegister_ = value; + } + onChanged(); + } else { + baseRegisterBuilder_.mergeFrom(value); + } + + return this; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public Builder clearBaseRegister() { + if (baseRegisterBuilder_ == null) { + baseRegister_ = null; + onChanged(); + } else { + baseRegister_ = null; + baseRegisterBuilder_ = null; + } + + return this; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder + getBaseRegisterBuilder() { + + onChanged(); + return getBaseRegisterFieldBuilder().getBuilder(); + } + + /** .BaseRegisterPb baseRegister = 2; */ + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder + getBaseRegisterOrBuilder() { + if (baseRegisterBuilder_ != null) { + return baseRegisterBuilder_.getMessageOrBuilder(); + } else { + return baseRegister_ == null + ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.getDefaultInstance() + : baseRegister_; + } + } + + /** .BaseRegisterPb baseRegister = 2; */ + private com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder> + getBaseRegisterFieldBuilder() { + if (baseRegisterBuilder_ == null) { + baseRegisterBuilder_ = + new com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder>( + getBaseRegister(), getParentForChildren(), isClean()); + baseRegister_ = null; + } + return baseRegisterBuilder_; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:PublisherRegisterPb) + } + + // @@protoc_insertion_point(class_scope:PublisherRegisterPb) + private static final com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb + DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb(); + } + + public static com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb + getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public PublisherRegisterPb parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new PublisherRegisterPb(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public com.alipay.sofa.registry.common.model.client.pb.PublisherRegisterPb + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPbOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPbOrBuilder.java index f7aca1c0c..c1bce2600 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPbOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPbOrBuilder.java @@ -14,52 +14,37 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: PublisherRegisterPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface PublisherRegisterPbOrBuilder extends -// @@protoc_insertion_point(interface_extends:PublisherRegisterPb) - com.google.protobuf.MessageOrBuilder { +public interface PublisherRegisterPbOrBuilder + extends + // @@protoc_insertion_point(interface_extends:PublisherRegisterPb) + com.google.protobuf.MessageOrBuilder { - /** - * repeated .DataBoxPb dataList = 1; - */ - java.util.List getDataListList(); + /** repeated .DataBoxPb dataList = 1; */ + java.util.List getDataListList(); - /** - * repeated .DataBoxPb dataList = 1; - */ - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDataList(int index); + /** repeated .DataBoxPb dataList = 1; */ + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDataList(int index); - /** - * repeated .DataBoxPb dataList = 1; - */ - int getDataListCount(); + /** repeated .DataBoxPb dataList = 1; */ + int getDataListCount(); - /** - * repeated .DataBoxPb dataList = 1; - */ - java.util.List getDataListOrBuilderList(); + /** repeated .DataBoxPb dataList = 1; */ + java.util.List + getDataListOrBuilderList(); - /** - * repeated .DataBoxPb dataList = 1; - */ - com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataListOrBuilder(int index); + /** repeated .DataBoxPb dataList = 1; */ + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataListOrBuilder( + int index); - /** - * .BaseRegisterPb baseRegister = 2; - */ - boolean hasBaseRegister(); + /** .BaseRegisterPb baseRegister = 2; */ + boolean hasBaseRegister(); - /** - * .BaseRegisterPb baseRegister = 2; - */ - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getBaseRegister(); + /** .BaseRegisterPb baseRegister = 2; */ + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getBaseRegister(); - /** - * .BaseRegisterPb baseRegister = 2; - */ - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder getBaseRegisterOrBuilder(); + /** .BaseRegisterPb baseRegister = 2; */ + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder + getBaseRegisterOrBuilder(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPbOuterClass.java index 1d14d4bd6..03e370213 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/PublisherRegisterPbOuterClass.java @@ -14,64 +14,62 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: PublisherRegisterPb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class PublisherRegisterPbOuterClass { - private PublisherRegisterPbOuterClass() { - } + private PublisherRegisterPbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor + internal_static_PublisherRegisterPb_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_PublisherRegisterPb_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_PublisherRegisterPb_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_PublisherRegisterPb_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\031PublisherRegisterPb.proto\032\017DataBoxPb.p" - + "roto\032\024BaseRegisterPb.proto\"Z\n\023PublisherR" - + "egisterPb\022\034\n\010dataList\030\001 \003(\0132\n.DataBoxPb\022" - + "%\n\014baseRegister\030\002 \001(\0132\017.BaseRegisterPbB7" - + "\n/com.alipay.sofa.registry.common.model." - + "client.pbP\001Z\002pbb\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom( - descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{ - com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass - .getDescriptor(), - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass - .getDescriptor(),}, assigner); - internal_static_PublisherRegisterPb_descriptor = getDescriptor() - .getMessageTypes().get(0); - internal_static_PublisherRegisterPb_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_PublisherRegisterPb_descriptor, - new java.lang.String[]{"DataList", "BaseRegister",}); - com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass - .getDescriptor(); - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass - .getDescriptor(); - } + static { + java.lang.String[] descriptorData = { + "\n\031PublisherRegisterPb.proto\032\017DataBoxPb.p" + + "roto\032\024BaseRegisterPb.proto\"Z\n\023PublisherR" + + "egisterPb\022\034\n\010dataList\030\001 \003(\0132\n.DataBoxPb\022" + + "%\n\014baseRegister\030\002 \001(\0132\017.BaseRegisterPbB7" + + "\n/com.alipay.sofa.registry.common.model." + + "client.pbP\001Z\002pbb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass.getDescriptor(), + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass.getDescriptor(), + }, + assigner); + internal_static_PublisherRegisterPb_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_PublisherRegisterPb_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_PublisherRegisterPb_descriptor, + new java.lang.String[] { + "DataList", "BaseRegister", + }); + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass.getDescriptor(); + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass.getDescriptor(); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPb.java index 2ca91c78d..fcdd07245 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPb.java @@ -14,1204 +14,1142 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: ReceivedConfigDataPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code ReceivedConfigDataPb} - */ -public final class ReceivedConfigDataPb extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:ReceivedConfigDataPb) - ReceivedConfigDataPbOrBuilder { - private static final long serialVersionUID = 0L; - - // Use ReceivedConfigDataPb.newBuilder() to construct. - private ReceivedConfigDataPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); +/** Protobuf type {@code ReceivedConfigDataPb} */ +public final class ReceivedConfigDataPb extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:ReceivedConfigDataPb) + ReceivedConfigDataPbOrBuilder { + private static final long serialVersionUID = 0L; + + // Use ReceivedConfigDataPb.newBuilder() to construct. + private ReceivedConfigDataPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private ReceivedConfigDataPb() { + dataId_ = ""; + group_ = ""; + instanceId_ = ""; + configuratorRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; + version_ = 0L; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private ReceivedConfigDataPb( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); - private ReceivedConfigDataPb() { - dataId_ = ""; - group_ = ""; - instanceId_ = ""; - configuratorRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; - version_ = 0L; - } + dataId_ = s; + break; + } + case 18: + { + java.lang.String s = input.readStringRequireUtf8(); - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } + group_ = s; + break; + } + case 26: + { + java.lang.String s = input.readStringRequireUtf8(); - private ReceivedConfigDataPb(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - - dataId_ = s; - break; - } - case 18: { - java.lang.String s = input.readStringRequireUtf8(); - - group_ = s; - break; - } - case 26: { - java.lang.String s = input.readStringRequireUtf8(); - - instanceId_ = s; - break; - } - case 34: { - java.lang.String s = input.readStringRequireUtf8(); - if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { - configuratorRegistIds_ = new com.google.protobuf.LazyStringArrayList(); - mutable_bitField0_ |= 0x00000008; - } - configuratorRegistIds_.add(s); - break; - } - case 42: { - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder subBuilder = null; - if (dataBox_ != null) { - subBuilder = dataBox_.toBuilder(); - } - dataBox_ = input.readMessage( - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.parser(), - extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(dataBox_); - dataBox_ = subBuilder.buildPartial(); - } - - break; - } - case 48: { - - version_ = input.readInt64(); - break; - } - } + instanceId_ = s; + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { - configuratorRegistIds_ = configuratorRegistIds_.getUnmodifiableView(); + case 34: + { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + configuratorRegistIds_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000008; + } + configuratorRegistIds_.add(s); + break; + } + case 42: + { + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder subBuilder = null; + if (dataBox_ != null) { + subBuilder = dataBox_.toBuilder(); + } + dataBox_ = + input.readMessage( + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.parser(), + extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(dataBox_); + dataBox_ = subBuilder.buildPartial(); + } + + break; + } + case 48: + { + version_ = input.readInt64(); + break; } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000008) == 0x00000008)) { + configuratorRegistIds_ = configuratorRegistIds_.getUnmodifiableView(); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); } - - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOuterClass.internal_static_ReceivedConfigDataPb_descriptor; + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOuterClass + .internal_static_ReceivedConfigDataPb_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOuterClass + .internal_static_ReceivedConfigDataPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb.class, + com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb.Builder.class); + } + + private int bitField0_; + public static final int DATAID_FIELD_NUMBER = 1; + private volatile java.lang.Object dataId_; + + /** string dataId = 1; */ + public java.lang.String getDataId() { + java.lang.Object ref = dataId_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + dataId_ = s; + return s; } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOuterClass.internal_static_ReceivedConfigDataPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb.class, - com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb.Builder.class); + } + + /** string dataId = 1; */ + public com.google.protobuf.ByteString getDataIdBytes() { + java.lang.Object ref = dataId_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + dataId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; } - - private int bitField0_; - public static final int DATAID_FIELD_NUMBER = 1; - private volatile java.lang.Object dataId_; - - /** - * string dataId = 1; - */ - public java.lang.String getDataId() { - java.lang.Object ref = dataId_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - dataId_ = s; - return s; - } + } + + public static final int GROUP_FIELD_NUMBER = 2; + private volatile java.lang.Object group_; + + /** string group = 2; */ + public java.lang.String getGroup() { + java.lang.Object ref = group_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + group_ = s; + return s; } - - /** - * string dataId = 1; - */ - public com.google.protobuf.ByteString getDataIdBytes() { - java.lang.Object ref = dataId_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - dataId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + } + + /** string group = 2; */ + public com.google.protobuf.ByteString getGroupBytes() { + java.lang.Object ref = group_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + group_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; } - - public static final int GROUP_FIELD_NUMBER = 2; - private volatile java.lang.Object group_; - - /** - * string group = 2; - */ - public java.lang.String getGroup() { - java.lang.Object ref = group_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - group_ = s; - return s; - } + } + + public static final int INSTANCEID_FIELD_NUMBER = 3; + private volatile java.lang.Object instanceId_; + + /** string instanceId = 3; */ + public java.lang.String getInstanceId() { + java.lang.Object ref = instanceId_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + instanceId_ = s; + return s; } - - /** - * string group = 2; - */ - public com.google.protobuf.ByteString getGroupBytes() { - java.lang.Object ref = group_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - group_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + } + + /** string instanceId = 3; */ + public com.google.protobuf.ByteString getInstanceIdBytes() { + java.lang.Object ref = instanceId_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + instanceId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; } - - public static final int INSTANCEID_FIELD_NUMBER = 3; - private volatile java.lang.Object instanceId_; - - /** - * string instanceId = 3; - */ - public java.lang.String getInstanceId() { - java.lang.Object ref = instanceId_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - instanceId_ = s; - return s; - } + } + + public static final int CONFIGURATORREGISTIDS_FIELD_NUMBER = 4; + private com.google.protobuf.LazyStringList configuratorRegistIds_; + + /** repeated string configuratorRegistIds = 4; */ + public com.google.protobuf.ProtocolStringList getConfiguratorRegistIdsList() { + return configuratorRegistIds_; + } + + /** repeated string configuratorRegistIds = 4; */ + public int getConfiguratorRegistIdsCount() { + return configuratorRegistIds_.size(); + } + + /** repeated string configuratorRegistIds = 4; */ + public java.lang.String getConfiguratorRegistIds(int index) { + return configuratorRegistIds_.get(index); + } + + /** repeated string configuratorRegistIds = 4; */ + public com.google.protobuf.ByteString getConfiguratorRegistIdsBytes(int index) { + return configuratorRegistIds_.getByteString(index); + } + + public static final int DATABOX_FIELD_NUMBER = 5; + private com.alipay.sofa.registry.common.model.client.pb.DataBoxPb dataBox_; + + /** .DataBoxPb dataBox = 5; */ + public boolean hasDataBox() { + return dataBox_ != null; + } + + /** .DataBoxPb dataBox = 5; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDataBox() { + return dataBox_ == null + ? com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance() + : dataBox_; + } + + /** .DataBoxPb dataBox = 5; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataBoxOrBuilder() { + return getDataBox(); + } + + public static final int VERSION_FIELD_NUMBER = 6; + private long version_; + + /** int64 version = 6; */ + public long getVersion() { + return version_; + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getDataIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, dataId_); } - - /** - * string instanceId = 3; - */ - public com.google.protobuf.ByteString getInstanceIdBytes() { - java.lang.Object ref = instanceId_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - instanceId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + if (!getGroupBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, group_); } - - public static final int CONFIGURATORREGISTIDS_FIELD_NUMBER = 4; - private com.google.protobuf.LazyStringList configuratorRegistIds_; - - /** - * repeated string configuratorRegistIds = 4; - */ - public com.google.protobuf.ProtocolStringList getConfiguratorRegistIdsList() { - return configuratorRegistIds_; + if (!getInstanceIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 3, instanceId_); } - - /** - * repeated string configuratorRegistIds = 4; - */ - public int getConfiguratorRegistIdsCount() { - return configuratorRegistIds_.size(); + for (int i = 0; i < configuratorRegistIds_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString( + output, 4, configuratorRegistIds_.getRaw(i)); } - - /** - * repeated string configuratorRegistIds = 4; - */ - public java.lang.String getConfiguratorRegistIds(int index) { - return configuratorRegistIds_.get(index); + if (dataBox_ != null) { + output.writeMessage(5, getDataBox()); } - - /** - * repeated string configuratorRegistIds = 4; - */ - public com.google.protobuf.ByteString getConfiguratorRegistIdsBytes(int index) { - return configuratorRegistIds_.getByteString(index); + if (version_ != 0L) { + output.writeInt64(6, version_); } + unknownFields.writeTo(output); + } - public static final int DATABOX_FIELD_NUMBER = 5; - private com.alipay.sofa.registry.common.model.client.pb.DataBoxPb dataBox_; + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; - /** - * .DataBoxPb dataBox = 5; - */ - public boolean hasDataBox() { - return dataBox_ != null; + size = 0; + if (!getDataIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, dataId_); } - - /** - * .DataBoxPb dataBox = 5; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDataBox() { - return dataBox_ == null ? com.alipay.sofa.registry.common.model.client.pb.DataBoxPb - .getDefaultInstance() : dataBox_; + if (!getGroupBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, group_); } - - /** - * .DataBoxPb dataBox = 5; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataBoxOrBuilder() { - return getDataBox(); + if (!getInstanceIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, instanceId_); } - - public static final int VERSION_FIELD_NUMBER = 6; - private long version_; - - /** - * int64 version = 6; - */ - public long getVersion() { - return version_; + { + int dataSize = 0; + for (int i = 0; i < configuratorRegistIds_.size(); i++) { + dataSize += computeStringSizeNoTag(configuratorRegistIds_.getRaw(i)); + } + size += dataSize; + size += 1 * getConfiguratorRegistIdsList().size(); } - - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; + if (dataBox_ != null) { + size += com.google.protobuf.CodedOutputStream.computeMessageSize(5, getDataBox()); } - - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (!getDataIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, dataId_); - } - if (!getGroupBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, group_); - } - if (!getInstanceIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 3, instanceId_); - } - for (int i = 0; i < configuratorRegistIds_.size(); i++) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 4, - configuratorRegistIds_.getRaw(i)); - } - if (dataBox_ != null) { - output.writeMessage(5, getDataBox()); - } - if (version_ != 0L) { - output.writeInt64(6, version_); - } - unknownFields.writeTo(output); + if (version_ != 0L) { + size += com.google.protobuf.CodedOutputStream.computeInt64Size(6, version_); } - - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - if (!getDataIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, dataId_); - } - if (!getGroupBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, group_); - } - if (!getInstanceIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, instanceId_); - } - { - int dataSize = 0; - for (int i = 0; i < configuratorRegistIds_.size(); i++) { - dataSize += computeStringSizeNoTag(configuratorRegistIds_.getRaw(i)); - } - size += dataSize; - size += 1 * getConfiguratorRegistIdsList().size(); - } - if (dataBox_ != null) { - size += com.google.protobuf.CodedOutputStream.computeMessageSize(5, getDataBox()); - } - if (version_ != 0L) { - size += com.google.protobuf.CodedOutputStream.computeInt64Size(6, version_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; } - - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb other = (com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb) obj; - - boolean result = true; - result = result && getDataId().equals(other.getDataId()); - result = result && getGroup().equals(other.getGroup()); - result = result && getInstanceId().equals(other.getInstanceId()); - result = result - && getConfiguratorRegistIdsList().equals(other.getConfiguratorRegistIdsList()); - result = result && (hasDataBox() == other.hasDataBox()); - if (hasDataBox()) { - result = result && getDataBox().equals(other.getDataBox()); - } - result = result && (getVersion() == other.getVersion()); - result = result && unknownFields.equals(other.unknownFields); - return result; + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb)) { + return super.equals(obj); } - - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + DATAID_FIELD_NUMBER; - hash = (53 * hash) + getDataId().hashCode(); - hash = (37 * hash) + GROUP_FIELD_NUMBER; - hash = (53 * hash) + getGroup().hashCode(); - hash = (37 * hash) + INSTANCEID_FIELD_NUMBER; - hash = (53 * hash) + getInstanceId().hashCode(); - if (getConfiguratorRegistIdsCount() > 0) { - hash = (37 * hash) + CONFIGURATORREGISTIDS_FIELD_NUMBER; - hash = (53 * hash) + getConfiguratorRegistIdsList().hashCode(); - } - if (hasDataBox()) { - hash = (37 * hash) + DATABOX_FIELD_NUMBER; - hash = (53 * hash) + getDataBox().hashCode(); - } - hash = (37 * hash) + VERSION_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getVersion()); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb other = + (com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb) obj; + + boolean result = true; + result = result && getDataId().equals(other.getDataId()); + result = result && getGroup().equals(other.getGroup()); + result = result && getInstanceId().equals(other.getInstanceId()); + result = result && getConfiguratorRegistIdsList().equals(other.getConfiguratorRegistIdsList()); + result = result && (hasDataBox() == other.hasDataBox()); + if (hasDataBox()) { + result = result && getDataBox().equals(other.getDataBox()); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + result = result && (getVersion() == other.getVersion()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + DATAID_FIELD_NUMBER; + hash = (53 * hash) + getDataId().hashCode(); + hash = (37 * hash) + GROUP_FIELD_NUMBER; + hash = (53 * hash) + getGroup().hashCode(); + hash = (37 * hash) + INSTANCEID_FIELD_NUMBER; + hash = (53 * hash) + getInstanceId().hashCode(); + if (getConfiguratorRegistIdsCount() > 0) { + hash = (37 * hash) + CONFIGURATORREGISTIDS_FIELD_NUMBER; + hash = (53 * hash) + getConfiguratorRegistIdsList().hashCode(); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + if (hasDataBox()) { + hash = (37 * hash) + DATABOX_FIELD_NUMBER; + hash = (53 * hash) + getDataBox().hashCode(); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + hash = (37 * hash) + VERSION_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getVersion()); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code ReceivedConfigDataPb} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:ReceivedConfigDataPb) + com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOuterClass + .internal_static_ReceivedConfigDataPb_descriptor; } - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOuterClass + .internal_static_ReceivedConfigDataPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb.class, + com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb.Builder.class); } - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); - } + public Builder clear() { + super.clear(); + dataId_ = ""; - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); - } + group_ = ""; - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); - } + instanceId_ = ""; - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + configuratorRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000008); + if (dataBoxBuilder_ == null) { + dataBox_ = null; + } else { + dataBox_ = null; + dataBoxBuilder_ = null; + } + version_ = 0L; - public Builder newBuilderForType() { - return newBuilder(); + return this; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOuterClass + .internal_static_ReceivedConfigDataPb_descriptor; } - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + public com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb + .getDefaultInstance(); } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + public com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb build() { + com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + public com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb result = + new com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + result.dataId_ = dataId_; + result.group_ = group_; + result.instanceId_ = instanceId_; + if (((bitField0_ & 0x00000008) == 0x00000008)) { + configuratorRegistIds_ = configuratorRegistIds_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000008); + } + result.configuratorRegistIds_ = configuratorRegistIds_; + if (dataBoxBuilder_ == null) { + result.dataBox_ = dataBox_; + } else { + result.dataBox_ = dataBoxBuilder_.build(); + } + result.version_ = version_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } - /** - * Protobuf type {@code ReceivedConfigDataPb} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:ReceivedConfigDataPb) - com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOuterClass.internal_static_ReceivedConfigDataPb_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOuterClass.internal_static_ReceivedConfigDataPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb.class, - com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - dataId_ = ""; - - group_ = ""; - - instanceId_ = ""; - - configuratorRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000008); - if (dataBoxBuilder_ == null) { - dataBox_ = null; - } else { - dataBox_ = null; - dataBoxBuilder_ = null; - } - version_ = 0L; - - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPbOuterClass.internal_static_ReceivedConfigDataPb_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb build() { - com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb result = new com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb( - this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - result.dataId_ = dataId_; - result.group_ = group_; - result.instanceId_ = instanceId_; - if (((bitField0_ & 0x00000008) == 0x00000008)) { - configuratorRegistIds_ = configuratorRegistIds_.getUnmodifiableView(); - bitField0_ = (bitField0_ & ~0x00000008); - } - result.configuratorRegistIds_ = configuratorRegistIds_; - if (dataBoxBuilder_ == null) { - result.dataBox_ = dataBox_; - } else { - result.dataBox_ = dataBoxBuilder_.build(); - } - result.version_ = version_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } + public Builder clone() { + return (Builder) super.clone(); + } - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); + } - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb) other); - } else { - super.mergeFrom(other); - return this; - } - } + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb - .getDefaultInstance()) - return this; - if (!other.getDataId().isEmpty()) { - dataId_ = other.dataId_; - onChanged(); - } - if (!other.getGroup().isEmpty()) { - group_ = other.group_; - onChanged(); - } - if (!other.getInstanceId().isEmpty()) { - instanceId_ = other.instanceId_; - onChanged(); - } - if (!other.configuratorRegistIds_.isEmpty()) { - if (configuratorRegistIds_.isEmpty()) { - configuratorRegistIds_ = other.configuratorRegistIds_; - bitField0_ = (bitField0_ & ~0x00000008); - } else { - ensureConfiguratorRegistIdsIsMutable(); - configuratorRegistIds_.addAll(other.configuratorRegistIds_); - } - onChanged(); - } - if (other.hasDataBox()) { - mergeDataBox(other.getDataBox()); - } - if (other.getVersion() != 0L) { - setVersion(other.getVersion()); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } - public final boolean isInitialized() { - return true; - } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb) other); + } else { + super.mergeFrom(other); + return this; + } + } - private int bitField0_; - - private java.lang.Object dataId_ = ""; - - /** - * string dataId = 1; - */ - public java.lang.String getDataId() { - java.lang.Object ref = dataId_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - dataId_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb + .getDefaultInstance()) return this; + if (!other.getDataId().isEmpty()) { + dataId_ = other.dataId_; + onChanged(); + } + if (!other.getGroup().isEmpty()) { + group_ = other.group_; + onChanged(); + } + if (!other.getInstanceId().isEmpty()) { + instanceId_ = other.instanceId_; + onChanged(); + } + if (!other.configuratorRegistIds_.isEmpty()) { + if (configuratorRegistIds_.isEmpty()) { + configuratorRegistIds_ = other.configuratorRegistIds_; + bitField0_ = (bitField0_ & ~0x00000008); + } else { + ensureConfiguratorRegistIdsIsMutable(); + configuratorRegistIds_.addAll(other.configuratorRegistIds_); + } + onChanged(); + } + if (other.hasDataBox()) { + mergeDataBox(other.getDataBox()); + } + if (other.getVersion() != 0L) { + setVersion(other.getVersion()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } - /** - * string dataId = 1; - */ - public com.google.protobuf.ByteString getDataIdBytes() { - java.lang.Object ref = dataId_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - dataId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + public final boolean isInitialized() { + return true; + } - /** - * string dataId = 1; - */ - public Builder setDataId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } - dataId_ = value; - onChanged(); - return this; - } + private int bitField0_; - /** - * string dataId = 1; - */ - public Builder clearDataId() { + private java.lang.Object dataId_ = ""; - dataId_ = getDefaultInstance().getDataId(); - onChanged(); - return this; - } + /** string dataId = 1; */ + public java.lang.String getDataId() { + java.lang.Object ref = dataId_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + dataId_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - /** - * string dataId = 1; - */ - public Builder setDataIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string dataId = 1; */ + public com.google.protobuf.ByteString getDataIdBytes() { + java.lang.Object ref = dataId_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + dataId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - dataId_ = value; - onChanged(); - return this; - } + /** string dataId = 1; */ + public Builder setDataId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - private java.lang.Object group_ = ""; - - /** - * string group = 2; - */ - public java.lang.String getGroup() { - java.lang.Object ref = group_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - group_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + dataId_ = value; + onChanged(); + return this; + } - /** - * string group = 2; - */ - public com.google.protobuf.ByteString getGroupBytes() { - java.lang.Object ref = group_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - group_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string dataId = 1; */ + public Builder clearDataId() { - /** - * string group = 2; - */ - public Builder setGroup(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + dataId_ = getDefaultInstance().getDataId(); + onChanged(); + return this; + } - group_ = value; - onChanged(); - return this; - } + /** string dataId = 1; */ + public Builder setDataIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string group = 2; - */ - public Builder clearGroup() { + dataId_ = value; + onChanged(); + return this; + } - group_ = getDefaultInstance().getGroup(); - onChanged(); - return this; - } + private java.lang.Object group_ = ""; - /** - * string group = 2; - */ - public Builder setGroupBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string group = 2; */ + public java.lang.String getGroup() { + java.lang.Object ref = group_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + group_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - group_ = value; - onChanged(); - return this; - } + /** string group = 2; */ + public com.google.protobuf.ByteString getGroupBytes() { + java.lang.Object ref = group_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + group_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - private java.lang.Object instanceId_ = ""; - - /** - * string instanceId = 3; - */ - public java.lang.String getInstanceId() { - java.lang.Object ref = instanceId_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - instanceId_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** string group = 2; */ + public Builder setGroup(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - /** - * string instanceId = 3; - */ - public com.google.protobuf.ByteString getInstanceIdBytes() { - java.lang.Object ref = instanceId_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - instanceId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + group_ = value; + onChanged(); + return this; + } - /** - * string instanceId = 3; - */ - public Builder setInstanceId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + /** string group = 2; */ + public Builder clearGroup() { - instanceId_ = value; - onChanged(); - return this; - } + group_ = getDefaultInstance().getGroup(); + onChanged(); + return this; + } - /** - * string instanceId = 3; - */ - public Builder clearInstanceId() { + /** string group = 2; */ + public Builder setGroupBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - instanceId_ = getDefaultInstance().getInstanceId(); - onChanged(); - return this; - } + group_ = value; + onChanged(); + return this; + } - /** - * string instanceId = 3; - */ - public Builder setInstanceIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + private java.lang.Object instanceId_ = ""; - instanceId_ = value; - onChanged(); - return this; - } + /** string instanceId = 3; */ + public java.lang.String getInstanceId() { + java.lang.Object ref = instanceId_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + instanceId_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - private com.google.protobuf.LazyStringList configuratorRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; + /** string instanceId = 3; */ + public com.google.protobuf.ByteString getInstanceIdBytes() { + java.lang.Object ref = instanceId_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + instanceId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - private void ensureConfiguratorRegistIdsIsMutable() { - if (!((bitField0_ & 0x00000008) == 0x00000008)) { - configuratorRegistIds_ = new com.google.protobuf.LazyStringArrayList( - configuratorRegistIds_); - bitField0_ |= 0x00000008; - } - } + /** string instanceId = 3; */ + public Builder setInstanceId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - /** - * repeated string configuratorRegistIds = 4; - */ - public com.google.protobuf.ProtocolStringList getConfiguratorRegistIdsList() { - return configuratorRegistIds_.getUnmodifiableView(); - } + instanceId_ = value; + onChanged(); + return this; + } - /** - * repeated string configuratorRegistIds = 4; - */ - public int getConfiguratorRegistIdsCount() { - return configuratorRegistIds_.size(); - } + /** string instanceId = 3; */ + public Builder clearInstanceId() { - /** - * repeated string configuratorRegistIds = 4; - */ - public java.lang.String getConfiguratorRegistIds(int index) { - return configuratorRegistIds_.get(index); - } + instanceId_ = getDefaultInstance().getInstanceId(); + onChanged(); + return this; + } - /** - * repeated string configuratorRegistIds = 4; - */ - public com.google.protobuf.ByteString getConfiguratorRegistIdsBytes(int index) { - return configuratorRegistIds_.getByteString(index); - } + /** string instanceId = 3; */ + public Builder setInstanceIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * repeated string configuratorRegistIds = 4; - */ - public Builder setConfiguratorRegistIds(int index, java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureConfiguratorRegistIdsIsMutable(); - configuratorRegistIds_.set(index, value); - onChanged(); - return this; - } + instanceId_ = value; + onChanged(); + return this; + } - /** - * repeated string configuratorRegistIds = 4; - */ - public Builder addConfiguratorRegistIds(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureConfiguratorRegistIdsIsMutable(); - configuratorRegistIds_.add(value); - onChanged(); - return this; - } + private com.google.protobuf.LazyStringList configuratorRegistIds_ = + com.google.protobuf.LazyStringArrayList.EMPTY; - /** - * repeated string configuratorRegistIds = 4; - */ - public Builder addAllConfiguratorRegistIds(java.lang.Iterable values) { - ensureConfiguratorRegistIdsIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll(values, configuratorRegistIds_); - onChanged(); - return this; - } + private void ensureConfiguratorRegistIdsIsMutable() { + if (!((bitField0_ & 0x00000008) == 0x00000008)) { + configuratorRegistIds_ = + new com.google.protobuf.LazyStringArrayList(configuratorRegistIds_); + bitField0_ |= 0x00000008; + } + } - /** - * repeated string configuratorRegistIds = 4; - */ - public Builder clearConfiguratorRegistIds() { - configuratorRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000008); - onChanged(); - return this; - } + /** repeated string configuratorRegistIds = 4; */ + public com.google.protobuf.ProtocolStringList getConfiguratorRegistIdsList() { + return configuratorRegistIds_.getUnmodifiableView(); + } - /** - * repeated string configuratorRegistIds = 4; - */ - public Builder addConfiguratorRegistIdsBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - ensureConfiguratorRegistIdsIsMutable(); - configuratorRegistIds_.add(value); - onChanged(); - return this; - } + /** repeated string configuratorRegistIds = 4; */ + public int getConfiguratorRegistIdsCount() { + return configuratorRegistIds_.size(); + } - private com.alipay.sofa.registry.common.model.client.pb.DataBoxPb dataBox_ = null; - private com.google.protobuf.SingleFieldBuilderV3 dataBoxBuilder_; + /** repeated string configuratorRegistIds = 4; */ + public java.lang.String getConfiguratorRegistIds(int index) { + return configuratorRegistIds_.get(index); + } - /** - * .DataBoxPb dataBox = 5; - */ - public boolean hasDataBox() { - return dataBoxBuilder_ != null || dataBox_ != null; - } + /** repeated string configuratorRegistIds = 4; */ + public com.google.protobuf.ByteString getConfiguratorRegistIdsBytes(int index) { + return configuratorRegistIds_.getByteString(index); + } - /** - * .DataBoxPb dataBox = 5; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDataBox() { - if (dataBoxBuilder_ == null) { - return dataBox_ == null ? com.alipay.sofa.registry.common.model.client.pb.DataBoxPb - .getDefaultInstance() : dataBox_; - } else { - return dataBoxBuilder_.getMessage(); - } - } + /** repeated string configuratorRegistIds = 4; */ + public Builder setConfiguratorRegistIds(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureConfiguratorRegistIdsIsMutable(); + configuratorRegistIds_.set(index, value); + onChanged(); + return this; + } - /** - * .DataBoxPb dataBox = 5; - */ - public Builder setDataBox(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { - if (dataBoxBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - dataBox_ = value; - onChanged(); - } else { - dataBoxBuilder_.setMessage(value); - } + /** repeated string configuratorRegistIds = 4; */ + public Builder addConfiguratorRegistIds(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureConfiguratorRegistIdsIsMutable(); + configuratorRegistIds_.add(value); + onChanged(); + return this; + } - return this; - } + /** repeated string configuratorRegistIds = 4; */ + public Builder addAllConfiguratorRegistIds(java.lang.Iterable values) { + ensureConfiguratorRegistIdsIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, configuratorRegistIds_); + onChanged(); + return this; + } - /** - * .DataBoxPb dataBox = 5; - */ - public Builder setDataBox(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { - if (dataBoxBuilder_ == null) { - dataBox_ = builderForValue.build(); - onChanged(); - } else { - dataBoxBuilder_.setMessage(builderForValue.build()); - } + /** repeated string configuratorRegistIds = 4; */ + public Builder clearConfiguratorRegistIds() { + configuratorRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000008); + onChanged(); + return this; + } - return this; - } + /** repeated string configuratorRegistIds = 4; */ + public Builder addConfiguratorRegistIdsBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureConfiguratorRegistIdsIsMutable(); + configuratorRegistIds_.add(value); + onChanged(); + return this; + } - /** - * .DataBoxPb dataBox = 5; - */ - public Builder mergeDataBox(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { - if (dataBoxBuilder_ == null) { - if (dataBox_ != null) { - dataBox_ = com.alipay.sofa.registry.common.model.client.pb.DataBoxPb - .newBuilder(dataBox_).mergeFrom(value).buildPartial(); - } else { - dataBox_ = value; - } - onChanged(); - } else { - dataBoxBuilder_.mergeFrom(value); - } + private com.alipay.sofa.registry.common.model.client.pb.DataBoxPb dataBox_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder> + dataBoxBuilder_; - return this; - } + /** .DataBoxPb dataBox = 5; */ + public boolean hasDataBox() { + return dataBoxBuilder_ != null || dataBox_ != null; + } - /** - * .DataBoxPb dataBox = 5; - */ - public Builder clearDataBox() { - if (dataBoxBuilder_ == null) { - dataBox_ = null; - onChanged(); - } else { - dataBox_ = null; - dataBoxBuilder_ = null; - } + /** .DataBoxPb dataBox = 5; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDataBox() { + if (dataBoxBuilder_ == null) { + return dataBox_ == null + ? com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance() + : dataBox_; + } else { + return dataBoxBuilder_.getMessage(); + } + } - return this; + /** .DataBoxPb dataBox = 5; */ + public Builder setDataBox(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { + if (dataBoxBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); } + dataBox_ = value; + onChanged(); + } else { + dataBoxBuilder_.setMessage(value); + } - /** - * .DataBoxPb dataBox = 5; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder getDataBoxBuilder() { - - onChanged(); - return getDataBoxFieldBuilder().getBuilder(); - } + return this; + } - /** - * .DataBoxPb dataBox = 5; - */ - public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataBoxOrBuilder() { - if (dataBoxBuilder_ != null) { - return dataBoxBuilder_.getMessageOrBuilder(); - } else { - return dataBox_ == null ? com.alipay.sofa.registry.common.model.client.pb.DataBoxPb - .getDefaultInstance() : dataBox_; - } - } + /** .DataBoxPb dataBox = 5; */ + public Builder setDataBox( + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder builderForValue) { + if (dataBoxBuilder_ == null) { + dataBox_ = builderForValue.build(); + onChanged(); + } else { + dataBoxBuilder_.setMessage(builderForValue.build()); + } + + return this; + } - /** - * .DataBoxPb dataBox = 5; - */ - private com.google.protobuf.SingleFieldBuilderV3 getDataBoxFieldBuilder() { - if (dataBoxBuilder_ == null) { - dataBoxBuilder_ = new com.google.protobuf.SingleFieldBuilderV3( - getDataBox(), getParentForChildren(), isClean()); - dataBox_ = null; - } - return dataBoxBuilder_; + /** .DataBoxPb dataBox = 5; */ + public Builder mergeDataBox(com.alipay.sofa.registry.common.model.client.pb.DataBoxPb value) { + if (dataBoxBuilder_ == null) { + if (dataBox_ != null) { + dataBox_ = + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.newBuilder(dataBox_) + .mergeFrom(value) + .buildPartial(); + } else { + dataBox_ = value; } + onChanged(); + } else { + dataBoxBuilder_.mergeFrom(value); + } - private long version_; - - /** - * int64 version = 6; - */ - public long getVersion() { - return version_; - } + return this; + } - /** - * int64 version = 6; - */ - public Builder setVersion(long value) { + /** .DataBoxPb dataBox = 5; */ + public Builder clearDataBox() { + if (dataBoxBuilder_ == null) { + dataBox_ = null; + onChanged(); + } else { + dataBox_ = null; + dataBoxBuilder_ = null; + } + + return this; + } - version_ = value; - onChanged(); - return this; - } + /** .DataBoxPb dataBox = 5; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder getDataBoxBuilder() { - /** - * int64 version = 6; - */ - public Builder clearVersion() { + onChanged(); + return getDataBoxFieldBuilder().getBuilder(); + } - version_ = 0L; - onChanged(); - return this; - } + /** .DataBoxPb dataBox = 5; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder + getDataBoxOrBuilder() { + if (dataBoxBuilder_ != null) { + return dataBoxBuilder_.getMessageOrBuilder(); + } else { + return dataBox_ == null + ? com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.getDefaultInstance() + : dataBox_; + } + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + /** .DataBoxPb dataBox = 5; */ + private com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder> + getDataBoxFieldBuilder() { + if (dataBoxBuilder_ == null) { + dataBoxBuilder_ = + new com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder>( + getDataBox(), getParentForChildren(), isClean()); + dataBox_ = null; + } + return dataBoxBuilder_; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } + private long version_; - // @@protoc_insertion_point(builder_scope:ReceivedConfigDataPb) + /** int64 version = 6; */ + public long getVersion() { + return version_; } - // @@protoc_insertion_point(class_scope:ReceivedConfigDataPb) - private static final com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb(); - } + /** int64 version = 6; */ + public Builder setVersion(long value) { - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb getDefaultInstance() { - return DEFAULT_INSTANCE; + version_ = value; + onChanged(); + return this; } - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public ReceivedConfigDataPb parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new ReceivedConfigDataPb( - input, - extensionRegistry); - } - }; + /** int64 version = 6; */ + public Builder clearVersion() { - public static com.google.protobuf.Parser parser() { - return PARSER; + version_ = 0L; + onChanged(); + return this; } - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); } - public com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb getDefaultInstanceForType() { - return DEFAULT_INSTANCE; + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); } + // @@protoc_insertion_point(builder_scope:ReceivedConfigDataPb) + } + + // @@protoc_insertion_point(class_scope:ReceivedConfigDataPb) + private static final com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb + DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb(); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb + getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public ReceivedConfigDataPb parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new ReceivedConfigDataPb(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public com.alipay.sofa.registry.common.model.client.pb.ReceivedConfigDataPb + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPbOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPbOrBuilder.java index 7f031381e..6c76620df 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPbOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPbOrBuilder.java @@ -14,82 +14,52 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: ReceivedConfigDataPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface ReceivedConfigDataPbOrBuilder extends -// @@protoc_insertion_point(interface_extends:ReceivedConfigDataPb) - com.google.protobuf.MessageOrBuilder { +public interface ReceivedConfigDataPbOrBuilder + extends + // @@protoc_insertion_point(interface_extends:ReceivedConfigDataPb) + com.google.protobuf.MessageOrBuilder { - /** - * string dataId = 1; - */ - java.lang.String getDataId(); + /** string dataId = 1; */ + java.lang.String getDataId(); - /** - * string dataId = 1; - */ - com.google.protobuf.ByteString getDataIdBytes(); + /** string dataId = 1; */ + com.google.protobuf.ByteString getDataIdBytes(); - /** - * string group = 2; - */ - java.lang.String getGroup(); + /** string group = 2; */ + java.lang.String getGroup(); - /** - * string group = 2; - */ - com.google.protobuf.ByteString getGroupBytes(); + /** string group = 2; */ + com.google.protobuf.ByteString getGroupBytes(); - /** - * string instanceId = 3; - */ - java.lang.String getInstanceId(); + /** string instanceId = 3; */ + java.lang.String getInstanceId(); - /** - * string instanceId = 3; - */ - com.google.protobuf.ByteString getInstanceIdBytes(); + /** string instanceId = 3; */ + com.google.protobuf.ByteString getInstanceIdBytes(); - /** - * repeated string configuratorRegistIds = 4; - */ - java.util.List getConfiguratorRegistIdsList(); + /** repeated string configuratorRegistIds = 4; */ + java.util.List getConfiguratorRegistIdsList(); - /** - * repeated string configuratorRegistIds = 4; - */ - int getConfiguratorRegistIdsCount(); + /** repeated string configuratorRegistIds = 4; */ + int getConfiguratorRegistIdsCount(); - /** - * repeated string configuratorRegistIds = 4; - */ - java.lang.String getConfiguratorRegistIds(int index); + /** repeated string configuratorRegistIds = 4; */ + java.lang.String getConfiguratorRegistIds(int index); - /** - * repeated string configuratorRegistIds = 4; - */ - com.google.protobuf.ByteString getConfiguratorRegistIdsBytes(int index); + /** repeated string configuratorRegistIds = 4; */ + com.google.protobuf.ByteString getConfiguratorRegistIdsBytes(int index); - /** - * .DataBoxPb dataBox = 5; - */ - boolean hasDataBox(); + /** .DataBoxPb dataBox = 5; */ + boolean hasDataBox(); - /** - * .DataBoxPb dataBox = 5; - */ - com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDataBox(); + /** .DataBoxPb dataBox = 5; */ + com.alipay.sofa.registry.common.model.client.pb.DataBoxPb getDataBox(); - /** - * .DataBoxPb dataBox = 5; - */ - com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataBoxOrBuilder(); + /** .DataBoxPb dataBox = 5; */ + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOrBuilder getDataBoxOrBuilder(); - /** - * int64 version = 6; - */ - long getVersion(); + /** int64 version = 6; */ + long getVersion(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPbOuterClass.java index db1b86249..8ddfa9d76 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedConfigDataPbOuterClass.java @@ -14,61 +14,61 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: ReceivedConfigDataPb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class ReceivedConfigDataPbOuterClass { - private ReceivedConfigDataPbOuterClass() { - } + private ReceivedConfigDataPbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor + internal_static_ReceivedConfigDataPb_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_ReceivedConfigDataPb_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_ReceivedConfigDataPb_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ReceivedConfigDataPb_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\032ReceivedConfigDataPb.proto\032\017DataBoxPb." - + "proto\"\226\001\n\024ReceivedConfigDataPb\022\016\n\006dataId" - + "\030\001 \001(\t\022\r\n\005group\030\002 \001(\t\022\022\n\ninstanceId\030\003 \001(" - + "\t\022\035\n\025configuratorRegistIds\030\004 \003(\t\022\033\n\007data" - + "Box\030\005 \001(\0132\n.DataBoxPb\022\017\n\007version\030\006 \001(\003B7" - + "\n/com.alipay.sofa.registry.common.model." - + "client.pbP\001Z\002pbb\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom( - descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass - .getDescriptor(),}, assigner); - internal_static_ReceivedConfigDataPb_descriptor = getDescriptor() - .getMessageTypes().get(0); - internal_static_ReceivedConfigDataPb_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_ReceivedConfigDataPb_descriptor, - new java.lang.String[]{"DataId", "Group", "InstanceId", - "ConfiguratorRegistIds", "DataBox", "Version",}); - com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass - .getDescriptor(); - } + static { + java.lang.String[] descriptorData = { + "\n\032ReceivedConfigDataPb.proto\032\017DataBoxPb." + + "proto\"\226\001\n\024ReceivedConfigDataPb\022\016\n\006dataId" + + "\030\001 \001(\t\022\r\n\005group\030\002 \001(\t\022\022\n\ninstanceId\030\003 \001(" + + "\t\022\035\n\025configuratorRegistIds\030\004 \003(\t\022\033\n\007data" + + "Box\030\005 \001(\0132\n.DataBoxPb\022\017\n\007version\030\006 \001(\003B7" + + "\n/com.alipay.sofa.registry.common.model." + + "client.pbP\001Z\002pbb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass.getDescriptor(), + }, + assigner); + internal_static_ReceivedConfigDataPb_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_ReceivedConfigDataPb_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_ReceivedConfigDataPb_descriptor, + new java.lang.String[] { + "DataId", "Group", "InstanceId", "ConfiguratorRegistIds", "DataBox", "Version", + }); + com.alipay.sofa.registry.common.model.client.pb.DataBoxPbOuterClass.getDescriptor(); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPb.java index 9dbe3d6aa..00bec1d49 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPb.java @@ -14,1665 +14,1563 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: ReceivedDataPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code ReceivedDataPb} - */ -public final class ReceivedDataPb extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:ReceivedDataPb) - ReceivedDataPbOrBuilder { - private static final long serialVersionUID = 0L; - - // Use ReceivedDataPb.newBuilder() to construct. - private ReceivedDataPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private ReceivedDataPb() { - dataId_ = ""; - group_ = ""; - instanceId_ = ""; - segment_ = ""; - scope_ = ""; - subscriberRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; - version_ = 0L; - localZone_ = ""; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } - - private ReceivedDataPb(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - - dataId_ = s; - break; - } - case 18: { - java.lang.String s = input.readStringRequireUtf8(); - - group_ = s; - break; - } - case 26: { - java.lang.String s = input.readStringRequireUtf8(); - - instanceId_ = s; - break; - } - case 34: { - java.lang.String s = input.readStringRequireUtf8(); - - segment_ = s; - break; - } - case 42: { - java.lang.String s = input.readStringRequireUtf8(); - - scope_ = s; - break; - } - case 50: { - java.lang.String s = input.readStringRequireUtf8(); - if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) { - subscriberRegistIds_ = new com.google.protobuf.LazyStringArrayList(); - mutable_bitField0_ |= 0x00000020; - } - subscriberRegistIds_.add(s); - break; - } - case 58: { - if (!((mutable_bitField0_ & 0x00000040) == 0x00000040)) { - data_ = com.google.protobuf.MapField - .newMapField(DataDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000040; - } - com.google.protobuf.MapEntry data__ = input - .readMessage(DataDefaultEntryHolder.defaultEntry.getParserForType(), - extensionRegistry); - data_.getMutableMap().put(data__.getKey(), data__.getValue()); - break; - } - case 64: { - - version_ = input.readInt64(); - break; - } - case 74: { - java.lang.String s = input.readStringRequireUtf8(); - - localZone_ = s; - break; - } - } +/** Protobuf type {@code ReceivedDataPb} */ +public final class ReceivedDataPb extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:ReceivedDataPb) + ReceivedDataPbOrBuilder { + private static final long serialVersionUID = 0L; + + // Use ReceivedDataPb.newBuilder() to construct. + private ReceivedDataPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private ReceivedDataPb() { + dataId_ = ""; + group_ = ""; + instanceId_ = ""; + segment_ = ""; + scope_ = ""; + subscriberRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; + version_ = 0L; + localZone_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private ReceivedDataPb( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) { - subscriberRegistIds_ = subscriberRegistIds_.getUnmodifiableView(); + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); + + dataId_ = s; + break; } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } + case 18: + { + java.lang.String s = input.readStringRequireUtf8(); - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass.internal_static_ReceivedDataPb_descriptor; - } + group_ = s; + break; + } + case 26: + { + java.lang.String s = input.readStringRequireUtf8(); - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 7: - return internalGetData(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } + instanceId_ = s; + break; + } + case 34: + { + java.lang.String s = input.readStringRequireUtf8(); - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass.internal_static_ReceivedDataPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.class, - com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.Builder.class); - } + segment_ = s; + break; + } + case 42: + { + java.lang.String s = input.readStringRequireUtf8(); - private int bitField0_; - public static final int DATAID_FIELD_NUMBER = 1; - private volatile java.lang.Object dataId_; + scope_ = s; + break; + } + case 50: + { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000020) == 0x00000020)) { + subscriberRegistIds_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000020; + } + subscriberRegistIds_.add(s); + break; + } + case 58: + { + if (!((mutable_bitField0_ & 0x00000040) == 0x00000040)) { + data_ = + com.google.protobuf.MapField.newMapField(DataDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000040; + } + com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + data__ = + input.readMessage( + DataDefaultEntryHolder.defaultEntry.getParserForType(), + extensionRegistry); + data_.getMutableMap().put(data__.getKey(), data__.getValue()); + break; + } + case 64: + { + version_ = input.readInt64(); + break; + } + case 74: + { + java.lang.String s = input.readStringRequireUtf8(); - /** - * string dataId = 1; - */ - public java.lang.String getDataId() { - java.lang.Object ref = dataId_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - dataId_ = s; - return s; + localZone_ = s; + break; + } } + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000020) == 0x00000020)) { + subscriberRegistIds_ = subscriberRegistIds_.getUnmodifiableView(); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); } - - /** - * string dataId = 1; - */ - public com.google.protobuf.ByteString getDataIdBytes() { - java.lang.Object ref = dataId_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - dataId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass + .internal_static_ReceivedDataPb_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 7: + return internalGetData(); + default: + throw new RuntimeException("Invalid map field number: " + number); } - - public static final int GROUP_FIELD_NUMBER = 2; - private volatile java.lang.Object group_; - - /** - * string group = 2; - */ - public java.lang.String getGroup() { - java.lang.Object ref = group_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - group_ = s; - return s; - } + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass + .internal_static_ReceivedDataPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.class, + com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.Builder.class); + } + + private int bitField0_; + public static final int DATAID_FIELD_NUMBER = 1; + private volatile java.lang.Object dataId_; + + /** string dataId = 1; */ + public java.lang.String getDataId() { + java.lang.Object ref = dataId_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + dataId_ = s; + return s; } - - /** - * string group = 2; - */ - public com.google.protobuf.ByteString getGroupBytes() { - java.lang.Object ref = group_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - group_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + } + + /** string dataId = 1; */ + public com.google.protobuf.ByteString getDataIdBytes() { + java.lang.Object ref = dataId_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + dataId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; } - - public static final int INSTANCEID_FIELD_NUMBER = 3; - private volatile java.lang.Object instanceId_; - - /** - * string instanceId = 3; - */ - public java.lang.String getInstanceId() { - java.lang.Object ref = instanceId_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - instanceId_ = s; - return s; - } + } + + public static final int GROUP_FIELD_NUMBER = 2; + private volatile java.lang.Object group_; + + /** string group = 2; */ + public java.lang.String getGroup() { + java.lang.Object ref = group_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + group_ = s; + return s; } - - /** - * string instanceId = 3; - */ - public com.google.protobuf.ByteString getInstanceIdBytes() { - java.lang.Object ref = instanceId_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - instanceId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + } + + /** string group = 2; */ + public com.google.protobuf.ByteString getGroupBytes() { + java.lang.Object ref = group_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + group_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; } - - public static final int SEGMENT_FIELD_NUMBER = 4; - private volatile java.lang.Object segment_; - - /** - * string segment = 4; - */ - public java.lang.String getSegment() { - java.lang.Object ref = segment_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - segment_ = s; - return s; - } - } - - /** - * string segment = 4; - */ - public com.google.protobuf.ByteString getSegmentBytes() { - java.lang.Object ref = segment_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - segment_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + } + + public static final int INSTANCEID_FIELD_NUMBER = 3; + private volatile java.lang.Object instanceId_; + + /** string instanceId = 3; */ + public java.lang.String getInstanceId() { + java.lang.Object ref = instanceId_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + instanceId_ = s; + return s; } - - public static final int SCOPE_FIELD_NUMBER = 5; - private volatile java.lang.Object scope_; - - /** - * string scope = 5; - */ - public java.lang.String getScope() { - java.lang.Object ref = scope_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - scope_ = s; - return s; - } + } + + /** string instanceId = 3; */ + public com.google.protobuf.ByteString getInstanceIdBytes() { + java.lang.Object ref = instanceId_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + instanceId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; } - - /** - * string scope = 5; - */ - public com.google.protobuf.ByteString getScopeBytes() { - java.lang.Object ref = scope_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - scope_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + } + + public static final int SEGMENT_FIELD_NUMBER = 4; + private volatile java.lang.Object segment_; + + /** string segment = 4; */ + public java.lang.String getSegment() { + java.lang.Object ref = segment_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + segment_ = s; + return s; } - - public static final int SUBSCRIBERREGISTIDS_FIELD_NUMBER = 6; - private com.google.protobuf.LazyStringList subscriberRegistIds_; - - /** - * repeated string subscriberRegistIds = 6; - */ - public com.google.protobuf.ProtocolStringList getSubscriberRegistIdsList() { - return subscriberRegistIds_; + } + + /** string segment = 4; */ + public com.google.protobuf.ByteString getSegmentBytes() { + java.lang.Object ref = segment_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + segment_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; } - - /** - * repeated string subscriberRegistIds = 6; - */ - public int getSubscriberRegistIdsCount() { - return subscriberRegistIds_.size(); + } + + public static final int SCOPE_FIELD_NUMBER = 5; + private volatile java.lang.Object scope_; + + /** string scope = 5; */ + public java.lang.String getScope() { + java.lang.Object ref = scope_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + scope_ = s; + return s; } - - /** - * repeated string subscriberRegistIds = 6; - */ - public java.lang.String getSubscriberRegistIds(int index) { - return subscriberRegistIds_.get(index); + } + + /** string scope = 5; */ + public com.google.protobuf.ByteString getScopeBytes() { + java.lang.Object ref = scope_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + scope_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; } - - /** - * repeated string subscriberRegistIds = 6; - */ - public com.google.protobuf.ByteString getSubscriberRegistIdsBytes(int index) { - return subscriberRegistIds_.getByteString(index); + } + + public static final int SUBSCRIBERREGISTIDS_FIELD_NUMBER = 6; + private com.google.protobuf.LazyStringList subscriberRegistIds_; + + /** repeated string subscriberRegistIds = 6; */ + public com.google.protobuf.ProtocolStringList getSubscriberRegistIdsList() { + return subscriberRegistIds_; + } + + /** repeated string subscriberRegistIds = 6; */ + public int getSubscriberRegistIdsCount() { + return subscriberRegistIds_.size(); + } + + /** repeated string subscriberRegistIds = 6; */ + public java.lang.String getSubscriberRegistIds(int index) { + return subscriberRegistIds_.get(index); + } + + /** repeated string subscriberRegistIds = 6; */ + public com.google.protobuf.ByteString getSubscriberRegistIdsBytes(int index) { + return subscriberRegistIds_.getByteString(index); + } + + public static final int DATA_FIELD_NUMBER = 7; + + private static final class DataDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + defaultEntry = + com.google.protobuf.MapEntry + . + newDefaultInstance( + com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass + .internal_static_ReceivedDataPb_DataEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.MESSAGE, + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb + .getDefaultInstance()); + } + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + data_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + internalGetData() { + if (data_ == null) { + return com.google.protobuf.MapField.emptyMapField(DataDefaultEntryHolder.defaultEntry); } + return data_; + } - public static final int DATA_FIELD_NUMBER = 7; + public int getDataCount() { + return internalGetData().getMap().size(); + } - private static final class DataDefaultEntryHolder { - static final com.google.protobuf.MapEntry defaultEntry = com.google.protobuf.MapEntry - . newDefaultInstance( - com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass.internal_static_ReceivedDataPb_DataEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.MESSAGE, - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb - .getDefaultInstance()); + /** map<string, .DataBoxesPb> data = 7; */ + public boolean containsData(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); } - - private com.google.protobuf.MapField data_; - - private com.google.protobuf.MapField internalGetData() { - if (data_ == null) { - return com.google.protobuf.MapField.emptyMapField(DataDefaultEntryHolder.defaultEntry); - } - return data_; + return internalGetData().getMap().containsKey(key); + } + + /** Use {@link #getDataMap()} instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + getData() { + return getDataMap(); + } + + /** map<string, .DataBoxesPb> data = 7; */ + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + getDataMap() { + return internalGetData().getMap(); + } + + /** map<string, .DataBoxesPb> data = 7; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); } - - public int getDataCount() { - return internalGetData().getMap().size(); + java.util.Map + map = internalGetData().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + + /** map<string, .DataBoxesPb> data = 7; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); } - - /** - * map<string, .DataBoxesPb> data = 7; - */ - - public boolean containsData(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetData().getMap().containsKey(key); + java.util.Map + map = internalGetData().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); } - - /** - * Use {@link #getDataMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getData() { - return getDataMap(); + return map.get(key); + } + + public static final int VERSION_FIELD_NUMBER = 8; + private long version_; + + /** int64 version = 8; */ + public long getVersion() { + return version_; + } + + public static final int LOCALZONE_FIELD_NUMBER = 9; + private volatile java.lang.Object localZone_; + + /** string localZone = 9; */ + public java.lang.String getLocalZone() { + java.lang.Object ref = localZone_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + localZone_ = s; + return s; } - - /** - * map<string, .DataBoxesPb> data = 7; - */ - - public java.util.Map getDataMap() { - return internalGetData().getMap(); + } + + /** string localZone = 9; */ + public com.google.protobuf.ByteString getLocalZoneBytes() { + java.lang.Object ref = localZone_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + localZone_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; } + } - /** - * map<string, .DataBoxesPb> data = 7; - */ + private byte memoizedIsInitialized = -1; - public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetData() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; - /** - * map<string, .DataBoxesPb> data = 7; - */ + memoizedIsInitialized = 1; + return true; + } - public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetData() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getDataIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, dataId_); } - - public static final int VERSION_FIELD_NUMBER = 8; - private long version_; - - /** - * int64 version = 8; - */ - public long getVersion() { - return version_; + if (!getGroupBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, group_); } - - public static final int LOCALZONE_FIELD_NUMBER = 9; - private volatile java.lang.Object localZone_; - - /** - * string localZone = 9; - */ - public java.lang.String getLocalZone() { - java.lang.Object ref = localZone_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - localZone_ = s; - return s; - } + if (!getInstanceIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 3, instanceId_); } - - /** - * string localZone = 9; - */ - public com.google.protobuf.ByteString getLocalZoneBytes() { - java.lang.Object ref = localZone_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - localZone_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + if (!getSegmentBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 4, segment_); } - - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; + if (!getScopeBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 5, scope_); } - - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (!getDataIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, dataId_); - } - if (!getGroupBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, group_); - } - if (!getInstanceIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 3, instanceId_); - } - if (!getSegmentBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 4, segment_); - } - if (!getScopeBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 5, scope_); - } - for (int i = 0; i < subscriberRegistIds_.size(); i++) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 6, - subscriberRegistIds_.getRaw(i)); - } - com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(output, internalGetData(), - DataDefaultEntryHolder.defaultEntry, 7); - if (version_ != 0L) { - output.writeInt64(8, version_); - } - if (!getLocalZoneBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 9, localZone_); - } - unknownFields.writeTo(output); + for (int i = 0; i < subscriberRegistIds_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 6, subscriberRegistIds_.getRaw(i)); + } + com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( + output, internalGetData(), DataDefaultEntryHolder.defaultEntry, 7); + if (version_ != 0L) { + output.writeInt64(8, version_); } + if (!getLocalZoneBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 9, localZone_); + } + unknownFields.writeTo(output); + } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; - size = 0; - if (!getDataIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, dataId_); - } - if (!getGroupBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, group_); - } - if (!getInstanceIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, instanceId_); - } - if (!getSegmentBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, segment_); - } - if (!getScopeBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, scope_); - } - { - int dataSize = 0; - for (int i = 0; i < subscriberRegistIds_.size(); i++) { - dataSize += computeStringSizeNoTag(subscriberRegistIds_.getRaw(i)); - } - size += dataSize; - size += 1 * getSubscriberRegistIdsList().size(); - } - for (java.util.Map.Entry entry : internalGetData() - .getMap().entrySet()) { - com.google.protobuf.MapEntry data__ = DataDefaultEntryHolder.defaultEntry - .newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build(); - size += com.google.protobuf.CodedOutputStream.computeMessageSize(7, data__); - } - if (version_ != 0L) { - size += com.google.protobuf.CodedOutputStream.computeInt64Size(8, version_); - } - if (!getLocalZoneBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(9, localZone_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + size = 0; + if (!getDataIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, dataId_); } - - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb other = (com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb) obj; - - boolean result = true; - result = result && getDataId().equals(other.getDataId()); - result = result && getGroup().equals(other.getGroup()); - result = result && getInstanceId().equals(other.getInstanceId()); - result = result && getSegment().equals(other.getSegment()); - result = result && getScope().equals(other.getScope()); - result = result && getSubscriberRegistIdsList().equals(other.getSubscriberRegistIdsList()); - result = result && internalGetData().equals(other.internalGetData()); - result = result && (getVersion() == other.getVersion()); - result = result && getLocalZone().equals(other.getLocalZone()); - result = result && unknownFields.equals(other.unknownFields); - return result; - } - - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + DATAID_FIELD_NUMBER; - hash = (53 * hash) + getDataId().hashCode(); - hash = (37 * hash) + GROUP_FIELD_NUMBER; - hash = (53 * hash) + getGroup().hashCode(); - hash = (37 * hash) + INSTANCEID_FIELD_NUMBER; - hash = (53 * hash) + getInstanceId().hashCode(); - hash = (37 * hash) + SEGMENT_FIELD_NUMBER; - hash = (53 * hash) + getSegment().hashCode(); - hash = (37 * hash) + SCOPE_FIELD_NUMBER; - hash = (53 * hash) + getScope().hashCode(); - if (getSubscriberRegistIdsCount() > 0) { - hash = (37 * hash) + SUBSCRIBERREGISTIDS_FIELD_NUMBER; - hash = (53 * hash) + getSubscriberRegistIdsList().hashCode(); - } - if (!internalGetData().getMap().isEmpty()) { - hash = (37 * hash) + DATA_FIELD_NUMBER; - hash = (53 * hash) + internalGetData().hashCode(); - } - hash = (37 * hash) + VERSION_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getVersion()); - hash = (37 * hash) + LOCALZONE_FIELD_NUMBER; - hash = (53 * hash) + getLocalZone().hashCode(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + if (!getGroupBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, group_); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + if (!getInstanceIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, instanceId_); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + if (!getSegmentBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, segment_); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + if (!getScopeBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, scope_); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + { + int dataSize = 0; + for (int i = 0; i < subscriberRegistIds_.size(); i++) { + dataSize += computeStringSizeNoTag(subscriberRegistIds_.getRaw(i)); + } + size += dataSize; + size += 1 * getSubscriberRegistIdsList().size(); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + for (java.util.Map.Entry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + entry : internalGetData().getMap().entrySet()) { + com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + data__ = + DataDefaultEntryHolder.defaultEntry + .newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream.computeMessageSize(7, data__); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + if (version_ != 0L) { + size += com.google.protobuf.CodedOutputStream.computeInt64Size(8, version_); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + if (!getLocalZoneBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(9, localZone_); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb)) { + return super.equals(obj); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb other = + (com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb) obj; + + boolean result = true; + result = result && getDataId().equals(other.getDataId()); + result = result && getGroup().equals(other.getGroup()); + result = result && getInstanceId().equals(other.getInstanceId()); + result = result && getSegment().equals(other.getSegment()); + result = result && getScope().equals(other.getScope()); + result = result && getSubscriberRegistIdsList().equals(other.getSubscriberRegistIdsList()); + result = result && internalGetData().equals(other.internalGetData()); + result = result && (getVersion() == other.getVersion()); + result = result && getLocalZone().equals(other.getLocalZone()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + DATAID_FIELD_NUMBER; + hash = (53 * hash) + getDataId().hashCode(); + hash = (37 * hash) + GROUP_FIELD_NUMBER; + hash = (53 * hash) + getGroup().hashCode(); + hash = (37 * hash) + INSTANCEID_FIELD_NUMBER; + hash = (53 * hash) + getInstanceId().hashCode(); + hash = (37 * hash) + SEGMENT_FIELD_NUMBER; + hash = (53 * hash) + getSegment().hashCode(); + hash = (37 * hash) + SCOPE_FIELD_NUMBER; + hash = (53 * hash) + getScope().hashCode(); + if (getSubscriberRegistIdsCount() > 0) { + hash = (37 * hash) + SUBSCRIBERREGISTIDS_FIELD_NUMBER; + hash = (53 * hash) + getSubscriberRegistIdsList().hashCode(); } - - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + if (!internalGetData().getMap().isEmpty()) { + hash = (37 * hash) + DATA_FIELD_NUMBER; + hash = (53 * hash) + internalGetData().hashCode(); } - - public Builder newBuilderForType() { - return newBuilder(); + hash = (37 * hash) + VERSION_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getVersion()); + hash = (37 * hash) + LOCALZONE_FIELD_NUMBER; + hash = (53 * hash) + getLocalZone().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code ReceivedDataPb} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:ReceivedDataPb) + com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOrBuilder { + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass + .internal_static_ReceivedDataPb_descriptor; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 7: + return internalGetData(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField(int number) { + switch (number) { + case 7: + return internalGetMutableData(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass + .internal_static_ReceivedDataPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.class, + com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.Builder.class); } - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + // Construct using com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - /** - * Protobuf type {@code ReceivedDataPb} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:ReceivedDataPb) - com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass.internal_static_ReceivedDataPb_descriptor; - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 7: - return internalGetData(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMutableMapField(int number) { - switch (number) { - case 7: - return internalGetMutableData(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass.internal_static_ReceivedDataPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.class, - com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - dataId_ = ""; - - group_ = ""; - - instanceId_ = ""; - - segment_ = ""; - - scope_ = ""; - - subscriberRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000020); - internalGetMutableData().clear(); - version_ = 0L; + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } - localZone_ = ""; + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} + } - return this; - } + public Builder clear() { + super.clear(); + dataId_ = ""; - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass.internal_static_ReceivedDataPb_descriptor; - } + group_ = ""; - public com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb - .getDefaultInstance(); - } + instanceId_ = ""; - public com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb build() { - com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } + segment_ = ""; - public com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb result = new com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb( - this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - result.dataId_ = dataId_; - result.group_ = group_; - result.instanceId_ = instanceId_; - result.segment_ = segment_; - result.scope_ = scope_; - if (((bitField0_ & 0x00000020) == 0x00000020)) { - subscriberRegistIds_ = subscriberRegistIds_.getUnmodifiableView(); - bitField0_ = (bitField0_ & ~0x00000020); - } - result.subscriberRegistIds_ = subscriberRegistIds_; - result.data_ = internalGetData(); - result.data_.makeImmutable(); - result.version_ = version_; - result.localZone_ = localZone_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } + scope_ = ""; - public Builder clone() { - return (Builder) super.clone(); - } + subscriberRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000020); + internalGetMutableData().clear(); + version_ = 0L; - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } + localZone_ = ""; - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } + return this; + } - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPbOuterClass + .internal_static_ReceivedDataPb_descriptor; + } - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } + public com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.getDefaultInstance(); + } - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } + public com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb build() { + com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb) other); - } else { - super.mergeFrom(other); - return this; - } - } + public com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb result = + new com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + result.dataId_ = dataId_; + result.group_ = group_; + result.instanceId_ = instanceId_; + result.segment_ = segment_; + result.scope_ = scope_; + if (((bitField0_ & 0x00000020) == 0x00000020)) { + subscriberRegistIds_ = subscriberRegistIds_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000020); + } + result.subscriberRegistIds_ = subscriberRegistIds_; + result.data_ = internalGetData(); + result.data_.makeImmutable(); + result.version_ = version_; + result.localZone_ = localZone_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; + } - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb - .getDefaultInstance()) - return this; - if (!other.getDataId().isEmpty()) { - dataId_ = other.dataId_; - onChanged(); - } - if (!other.getGroup().isEmpty()) { - group_ = other.group_; - onChanged(); - } - if (!other.getInstanceId().isEmpty()) { - instanceId_ = other.instanceId_; - onChanged(); - } - if (!other.getSegment().isEmpty()) { - segment_ = other.segment_; - onChanged(); - } - if (!other.getScope().isEmpty()) { - scope_ = other.scope_; - onChanged(); - } - if (!other.subscriberRegistIds_.isEmpty()) { - if (subscriberRegistIds_.isEmpty()) { - subscriberRegistIds_ = other.subscriberRegistIds_; - bitField0_ = (bitField0_ & ~0x00000020); - } else { - ensureSubscriberRegistIdsIsMutable(); - subscriberRegistIds_.addAll(other.subscriberRegistIds_); - } - onChanged(); - } - internalGetMutableData().mergeFrom(other.internalGetData()); - if (other.getVersion() != 0L) { - setVersion(other.getVersion()); - } - if (!other.getLocalZone().isEmpty()) { - localZone_ = other.localZone_; - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } + public Builder clone() { + return (Builder) super.clone(); + } - public final boolean isInitialized() { - return true; - } + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); + } - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); + } - private int bitField0_; - - private java.lang.Object dataId_ = ""; - - /** - * string dataId = 1; - */ - public java.lang.String getDataId() { - java.lang.Object ref = dataId_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - dataId_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } - /** - * string dataId = 1; - */ - public com.google.protobuf.ByteString getDataIdBytes() { - java.lang.Object ref = dataId_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - dataId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); + } - /** - * string dataId = 1; - */ - public Builder setDataId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } - dataId_ = value; - onChanged(); - return this; - } + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb) { + return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb) other); + } else { + super.mergeFrom(other); + return this; + } + } - /** - * string dataId = 1; - */ - public Builder clearDataId() { + public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb.getDefaultInstance()) + return this; + if (!other.getDataId().isEmpty()) { + dataId_ = other.dataId_; + onChanged(); + } + if (!other.getGroup().isEmpty()) { + group_ = other.group_; + onChanged(); + } + if (!other.getInstanceId().isEmpty()) { + instanceId_ = other.instanceId_; + onChanged(); + } + if (!other.getSegment().isEmpty()) { + segment_ = other.segment_; + onChanged(); + } + if (!other.getScope().isEmpty()) { + scope_ = other.scope_; + onChanged(); + } + if (!other.subscriberRegistIds_.isEmpty()) { + if (subscriberRegistIds_.isEmpty()) { + subscriberRegistIds_ = other.subscriberRegistIds_; + bitField0_ = (bitField0_ & ~0x00000020); + } else { + ensureSubscriberRegistIdsIsMutable(); + subscriberRegistIds_.addAll(other.subscriberRegistIds_); + } + onChanged(); + } + internalGetMutableData().mergeFrom(other.internalGetData()); + if (other.getVersion() != 0L) { + setVersion(other.getVersion()); + } + if (!other.getLocalZone().isEmpty()) { + localZone_ = other.localZone_; + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } - dataId_ = getDefaultInstance().getDataId(); - onChanged(); - return this; - } + public final boolean isInitialized() { + return true; + } - /** - * string dataId = 1; - */ - public Builder setDataIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } - dataId_ = value; - onChanged(); - return this; - } + private int bitField0_; - private java.lang.Object group_ = ""; - - /** - * string group = 2; - */ - public java.lang.String getGroup() { - java.lang.Object ref = group_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - group_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + private java.lang.Object dataId_ = ""; - /** - * string group = 2; - */ - public com.google.protobuf.ByteString getGroupBytes() { - java.lang.Object ref = group_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - group_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string dataId = 1; */ + public java.lang.String getDataId() { + java.lang.Object ref = dataId_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + dataId_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - /** - * string group = 2; - */ - public Builder setGroup(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + /** string dataId = 1; */ + public com.google.protobuf.ByteString getDataIdBytes() { + java.lang.Object ref = dataId_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + dataId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - group_ = value; - onChanged(); - return this; - } + /** string dataId = 1; */ + public Builder setDataId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - /** - * string group = 2; - */ - public Builder clearGroup() { + dataId_ = value; + onChanged(); + return this; + } - group_ = getDefaultInstance().getGroup(); - onChanged(); - return this; - } + /** string dataId = 1; */ + public Builder clearDataId() { - /** - * string group = 2; - */ - public Builder setGroupBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + dataId_ = getDefaultInstance().getDataId(); + onChanged(); + return this; + } - group_ = value; - onChanged(); - return this; - } + /** string dataId = 1; */ + public Builder setDataIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - private java.lang.Object instanceId_ = ""; - - /** - * string instanceId = 3; - */ - public java.lang.String getInstanceId() { - java.lang.Object ref = instanceId_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - instanceId_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + dataId_ = value; + onChanged(); + return this; + } - /** - * string instanceId = 3; - */ - public com.google.protobuf.ByteString getInstanceIdBytes() { - java.lang.Object ref = instanceId_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - instanceId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + private java.lang.Object group_ = ""; - /** - * string instanceId = 3; - */ - public Builder setInstanceId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + /** string group = 2; */ + public java.lang.String getGroup() { + java.lang.Object ref = group_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + group_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - instanceId_ = value; - onChanged(); - return this; - } + /** string group = 2; */ + public com.google.protobuf.ByteString getGroupBytes() { + java.lang.Object ref = group_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + group_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string instanceId = 3; - */ - public Builder clearInstanceId() { + /** string group = 2; */ + public Builder setGroup(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - instanceId_ = getDefaultInstance().getInstanceId(); - onChanged(); - return this; - } + group_ = value; + onChanged(); + return this; + } - /** - * string instanceId = 3; - */ - public Builder setInstanceIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string group = 2; */ + public Builder clearGroup() { - instanceId_ = value; - onChanged(); - return this; - } + group_ = getDefaultInstance().getGroup(); + onChanged(); + return this; + } - private java.lang.Object segment_ = ""; - - /** - * string segment = 4; - */ - public java.lang.String getSegment() { - java.lang.Object ref = segment_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - segment_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + /** string group = 2; */ + public Builder setGroupBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string segment = 4; - */ - public com.google.protobuf.ByteString getSegmentBytes() { - java.lang.Object ref = segment_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - segment_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + group_ = value; + onChanged(); + return this; + } - /** - * string segment = 4; - */ - public Builder setSegment(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + private java.lang.Object instanceId_ = ""; - segment_ = value; - onChanged(); - return this; - } + /** string instanceId = 3; */ + public java.lang.String getInstanceId() { + java.lang.Object ref = instanceId_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + instanceId_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - /** - * string segment = 4; - */ - public Builder clearSegment() { + /** string instanceId = 3; */ + public com.google.protobuf.ByteString getInstanceIdBytes() { + java.lang.Object ref = instanceId_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + instanceId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - segment_ = getDefaultInstance().getSegment(); - onChanged(); - return this; - } + /** string instanceId = 3; */ + public Builder setInstanceId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - /** - * string segment = 4; - */ - public Builder setSegmentBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + instanceId_ = value; + onChanged(); + return this; + } - segment_ = value; - onChanged(); - return this; - } + /** string instanceId = 3; */ + public Builder clearInstanceId() { - private java.lang.Object scope_ = ""; - - /** - * string scope = 5; - */ - public java.lang.String getScope() { - java.lang.Object ref = scope_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - scope_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + instanceId_ = getDefaultInstance().getInstanceId(); + onChanged(); + return this; + } - /** - * string scope = 5; - */ - public com.google.protobuf.ByteString getScopeBytes() { - java.lang.Object ref = scope_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - scope_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string instanceId = 3; */ + public Builder setInstanceIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string scope = 5; - */ - public Builder setScope(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + instanceId_ = value; + onChanged(); + return this; + } - scope_ = value; - onChanged(); - return this; - } + private java.lang.Object segment_ = ""; - /** - * string scope = 5; - */ - public Builder clearScope() { + /** string segment = 4; */ + public java.lang.String getSegment() { + java.lang.Object ref = segment_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + segment_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - scope_ = getDefaultInstance().getScope(); - onChanged(); - return this; - } + /** string segment = 4; */ + public com.google.protobuf.ByteString getSegmentBytes() { + java.lang.Object ref = segment_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + segment_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * string scope = 5; - */ - public Builder setScopeBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + /** string segment = 4; */ + public Builder setSegment(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - scope_ = value; - onChanged(); - return this; - } + segment_ = value; + onChanged(); + return this; + } - private com.google.protobuf.LazyStringList subscriberRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; + /** string segment = 4; */ + public Builder clearSegment() { - private void ensureSubscriberRegistIdsIsMutable() { - if (!((bitField0_ & 0x00000020) == 0x00000020)) { - subscriberRegistIds_ = new com.google.protobuf.LazyStringArrayList( - subscriberRegistIds_); - bitField0_ |= 0x00000020; - } - } + segment_ = getDefaultInstance().getSegment(); + onChanged(); + return this; + } - /** - * repeated string subscriberRegistIds = 6; - */ - public com.google.protobuf.ProtocolStringList getSubscriberRegistIdsList() { - return subscriberRegistIds_.getUnmodifiableView(); - } + /** string segment = 4; */ + public Builder setSegmentBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * repeated string subscriberRegistIds = 6; - */ - public int getSubscriberRegistIdsCount() { - return subscriberRegistIds_.size(); - } + segment_ = value; + onChanged(); + return this; + } - /** - * repeated string subscriberRegistIds = 6; - */ - public java.lang.String getSubscriberRegistIds(int index) { - return subscriberRegistIds_.get(index); - } + private java.lang.Object scope_ = ""; - /** - * repeated string subscriberRegistIds = 6; - */ - public com.google.protobuf.ByteString getSubscriberRegistIdsBytes(int index) { - return subscriberRegistIds_.getByteString(index); - } + /** string scope = 5; */ + public java.lang.String getScope() { + java.lang.Object ref = scope_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + scope_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - /** - * repeated string subscriberRegistIds = 6; - */ - public Builder setSubscriberRegistIds(int index, java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureSubscriberRegistIdsIsMutable(); - subscriberRegistIds_.set(index, value); - onChanged(); - return this; - } + /** string scope = 5; */ + public com.google.protobuf.ByteString getScopeBytes() { + java.lang.Object ref = scope_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + scope_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - /** - * repeated string subscriberRegistIds = 6; - */ - public Builder addSubscriberRegistIds(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureSubscriberRegistIdsIsMutable(); - subscriberRegistIds_.add(value); - onChanged(); - return this; - } + /** string scope = 5; */ + public Builder setScope(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - /** - * repeated string subscriberRegistIds = 6; - */ - public Builder addAllSubscriberRegistIds(java.lang.Iterable values) { - ensureSubscriberRegistIdsIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll(values, subscriberRegistIds_); - onChanged(); - return this; - } + scope_ = value; + onChanged(); + return this; + } - /** - * repeated string subscriberRegistIds = 6; - */ - public Builder clearSubscriberRegistIds() { - subscriberRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000020); - onChanged(); - return this; - } + /** string scope = 5; */ + public Builder clearScope() { - /** - * repeated string subscriberRegistIds = 6; - */ - public Builder addSubscriberRegistIdsBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - ensureSubscriberRegistIdsIsMutable(); - subscriberRegistIds_.add(value); - onChanged(); - return this; - } + scope_ = getDefaultInstance().getScope(); + onChanged(); + return this; + } - private com.google.protobuf.MapField data_; + /** string scope = 5; */ + public Builder setScopeBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - private com.google.protobuf.MapField internalGetData() { - if (data_ == null) { - return com.google.protobuf.MapField - .emptyMapField(DataDefaultEntryHolder.defaultEntry); - } - return data_; - } + scope_ = value; + onChanged(); + return this; + } - private com.google.protobuf.MapField internalGetMutableData() { - onChanged(); - ; - if (data_ == null) { - data_ = com.google.protobuf.MapField - .newMapField(DataDefaultEntryHolder.defaultEntry); - } - if (!data_.isMutable()) { - data_ = data_.copy(); - } - return data_; - } + private com.google.protobuf.LazyStringList subscriberRegistIds_ = + com.google.protobuf.LazyStringArrayList.EMPTY; - public int getDataCount() { - return internalGetData().getMap().size(); - } + private void ensureSubscriberRegistIdsIsMutable() { + if (!((bitField0_ & 0x00000020) == 0x00000020)) { + subscriberRegistIds_ = new com.google.protobuf.LazyStringArrayList(subscriberRegistIds_); + bitField0_ |= 0x00000020; + } + } - /** - * map<string, .DataBoxesPb> data = 7; - */ + /** repeated string subscriberRegistIds = 6; */ + public com.google.protobuf.ProtocolStringList getSubscriberRegistIdsList() { + return subscriberRegistIds_.getUnmodifiableView(); + } - public boolean containsData(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetData().getMap().containsKey(key); - } + /** repeated string subscriberRegistIds = 6; */ + public int getSubscriberRegistIdsCount() { + return subscriberRegistIds_.size(); + } - /** - * Use {@link #getDataMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getData() { - return getDataMap(); - } + /** repeated string subscriberRegistIds = 6; */ + public java.lang.String getSubscriberRegistIds(int index) { + return subscriberRegistIds_.get(index); + } - /** - * map<string, .DataBoxesPb> data = 7; - */ + /** repeated string subscriberRegistIds = 6; */ + public com.google.protobuf.ByteString getSubscriberRegistIdsBytes(int index) { + return subscriberRegistIds_.getByteString(index); + } - public java.util.Map getDataMap() { - return internalGetData().getMap(); - } + /** repeated string subscriberRegistIds = 6; */ + public Builder setSubscriberRegistIds(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureSubscriberRegistIdsIsMutable(); + subscriberRegistIds_.set(index, value); + onChanged(); + return this; + } - /** - * map<string, .DataBoxesPb> data = 7; - */ + /** repeated string subscriberRegistIds = 6; */ + public Builder addSubscriberRegistIds(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureSubscriberRegistIdsIsMutable(); + subscriberRegistIds_.add(value); + onChanged(); + return this; + } - public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetData() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } + /** repeated string subscriberRegistIds = 6; */ + public Builder addAllSubscriberRegistIds(java.lang.Iterable values) { + ensureSubscriberRegistIdsIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, subscriberRegistIds_); + onChanged(); + return this; + } - /** - * map<string, .DataBoxesPb> data = 7; - */ + /** repeated string subscriberRegistIds = 6; */ + public Builder clearSubscriberRegistIds() { + subscriberRegistIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000020); + onChanged(); + return this; + } - public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetData() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } + /** repeated string subscriberRegistIds = 6; */ + public Builder addSubscriberRegistIdsBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureSubscriberRegistIdsIsMutable(); + subscriberRegistIds_.add(value); + onChanged(); + return this; + } - public Builder clearData() { - internalGetMutableData().getMutableMap().clear(); - return this; - } + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + data_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + internalGetData() { + if (data_ == null) { + return com.google.protobuf.MapField.emptyMapField(DataDefaultEntryHolder.defaultEntry); + } + return data_; + } - /** - * map<string, .DataBoxesPb> data = 7; - */ + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + internalGetMutableData() { + onChanged(); + ; + if (data_ == null) { + data_ = com.google.protobuf.MapField.newMapField(DataDefaultEntryHolder.defaultEntry); + } + if (!data_.isMutable()) { + data_ = data_.copy(); + } + return data_; + } - public Builder removeData(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableData().getMutableMap().remove(key); - return this; - } + public int getDataCount() { + return internalGetData().getMap().size(); + } - /** - * Use alternate mutation accessors instead. - */ - @java.lang.Deprecated - public java.util.Map getMutableData() { - return internalGetMutableData().getMutableMap(); - } + /** map<string, .DataBoxesPb> data = 7; */ + public boolean containsData(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetData().getMap().containsKey(key); + } - /** - * map<string, .DataBoxesPb> data = 7; - */ - public Builder putData(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb value) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - if (value == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableData().getMutableMap().put(key, value); - return this; - } + /** Use {@link #getDataMap()} instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + getData() { + return getDataMap(); + } - /** - * map<string, .DataBoxesPb> data = 7; - */ + /** map<string, .DataBoxesPb> data = 7; */ + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + getDataMap() { + return internalGetData().getMap(); + } - public Builder putAllData(java.util.Map values) { - internalGetMutableData().getMutableMap().putAll(values); - return this; - } + /** map<string, .DataBoxesPb> data = 7; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetData().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } - private long version_; + /** map<string, .DataBoxesPb> data = 7; */ + public com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map + map = internalGetData().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } - /** - * int64 version = 8; - */ - public long getVersion() { - return version_; - } + public Builder clearData() { + internalGetMutableData().getMutableMap().clear(); + return this; + } - /** - * int64 version = 8; - */ - public Builder setVersion(long value) { + /** map<string, .DataBoxesPb> data = 7; */ + public Builder removeData(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableData().getMutableMap().remove(key); + return this; + } - version_ = value; - onChanged(); - return this; - } + /** Use alternate mutation accessors instead. */ + @java.lang.Deprecated + public java.util.Map< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb> + getMutableData() { + return internalGetMutableData().getMutableMap(); + } - /** - * int64 version = 8; - */ - public Builder clearVersion() { + /** map<string, .DataBoxesPb> data = 7; */ + public Builder putData( + java.lang.String key, com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb value) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + if (value == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableData().getMutableMap().put(key, value); + return this; + } - version_ = 0L; - onChanged(); - return this; - } + /** map<string, .DataBoxesPb> data = 7; */ + public Builder putAllData( + java.util.Map + values) { + internalGetMutableData().getMutableMap().putAll(values); + return this; + } - private java.lang.Object localZone_ = ""; - - /** - * string localZone = 9; - */ - public java.lang.String getLocalZone() { - java.lang.Object ref = localZone_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - localZone_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + private long version_; - /** - * string localZone = 9; - */ - public com.google.protobuf.ByteString getLocalZoneBytes() { - java.lang.Object ref = localZone_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - localZone_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** int64 version = 8; */ + public long getVersion() { + return version_; + } - /** - * string localZone = 9; - */ - public Builder setLocalZone(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + /** int64 version = 8; */ + public Builder setVersion(long value) { - localZone_ = value; - onChanged(); - return this; - } + version_ = value; + onChanged(); + return this; + } - /** - * string localZone = 9; - */ - public Builder clearLocalZone() { + /** int64 version = 8; */ + public Builder clearVersion() { - localZone_ = getDefaultInstance().getLocalZone(); - onChanged(); - return this; - } + version_ = 0L; + onChanged(); + return this; + } - /** - * string localZone = 9; - */ - public Builder setLocalZoneBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + private java.lang.Object localZone_ = ""; - localZone_ = value; - onChanged(); - return this; - } + /** string localZone = 9; */ + public java.lang.String getLocalZone() { + java.lang.Object ref = localZone_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + localZone_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + /** string localZone = 9; */ + public com.google.protobuf.ByteString getLocalZoneBytes() { + java.lang.Object ref = localZone_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + localZone_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } + /** string localZone = 9; */ + public Builder setLocalZone(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - // @@protoc_insertion_point(builder_scope:ReceivedDataPb) + localZone_ = value; + onChanged(); + return this; } - // @@protoc_insertion_point(class_scope:ReceivedDataPb) - private static final com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb(); - } + /** string localZone = 9; */ + public Builder clearLocalZone() { - public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb getDefaultInstance() { - return DEFAULT_INSTANCE; + localZone_ = getDefaultInstance().getLocalZone(); + onChanged(); + return this; } - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public ReceivedDataPb parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new ReceivedDataPb( - input, - extensionRegistry); - } - }; + /** string localZone = 9; */ + public Builder setLocalZoneBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - public static com.google.protobuf.Parser parser() { - return PARSER; + localZone_ = value; + onChanged(); + return this; } - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); } - public com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb getDefaultInstanceForType() { - return DEFAULT_INSTANCE; + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); } + // @@protoc_insertion_point(builder_scope:ReceivedDataPb) + } + + // @@protoc_insertion_point(class_scope:ReceivedDataPb) + private static final com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb + DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb(); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb + getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public ReceivedDataPb parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new ReceivedDataPb(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public com.alipay.sofa.registry.common.model.client.pb.ReceivedDataPb + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPbOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPbOrBuilder.java index d7fad1738..78f312fd5 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPbOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPbOrBuilder.java @@ -14,131 +14,84 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: ReceivedDataPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface ReceivedDataPbOrBuilder extends -// @@protoc_insertion_point(interface_extends:ReceivedDataPb) - com.google.protobuf.MessageOrBuilder { - - /** - * string dataId = 1; - */ - java.lang.String getDataId(); - - /** - * string dataId = 1; - */ - com.google.protobuf.ByteString getDataIdBytes(); - - /** - * string group = 2; - */ - java.lang.String getGroup(); - - /** - * string group = 2; - */ - com.google.protobuf.ByteString getGroupBytes(); - - /** - * string instanceId = 3; - */ - java.lang.String getInstanceId(); - - /** - * string instanceId = 3; - */ - com.google.protobuf.ByteString getInstanceIdBytes(); - - /** - * string segment = 4; - */ - java.lang.String getSegment(); - - /** - * string segment = 4; - */ - com.google.protobuf.ByteString getSegmentBytes(); - - /** - * string scope = 5; - */ - java.lang.String getScope(); - - /** - * string scope = 5; - */ - com.google.protobuf.ByteString getScopeBytes(); - - /** - * repeated string subscriberRegistIds = 6; - */ - java.util.List getSubscriberRegistIdsList(); - - /** - * repeated string subscriberRegistIds = 6; - */ - int getSubscriberRegistIdsCount(); - - /** - * repeated string subscriberRegistIds = 6; - */ - java.lang.String getSubscriberRegistIds(int index); - - /** - * repeated string subscriberRegistIds = 6; - */ - com.google.protobuf.ByteString getSubscriberRegistIdsBytes(int index); - - /** - * map<string, .DataBoxesPb> data = 7; - */ - int getDataCount(); - - /** - * map<string, .DataBoxesPb> data = 7; - */ - boolean containsData(java.lang.String key); - - /** - * Use {@link #getDataMap()} instead. - */ - @java.lang.Deprecated - java.util.Map getData(); - - /** - * map<string, .DataBoxesPb> data = 7; - */ - java.util.Map getDataMap(); - - /** - * map<string, .DataBoxesPb> data = 7; - */ - - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb defaultValue); - - /** - * map<string, .DataBoxesPb> data = 7; - */ - - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrThrow(java.lang.String key); - - /** - * int64 version = 8; - */ - long getVersion(); - - /** - * string localZone = 9; - */ - java.lang.String getLocalZone(); - - /** - * string localZone = 9; - */ - com.google.protobuf.ByteString getLocalZoneBytes(); +public interface ReceivedDataPbOrBuilder + extends + // @@protoc_insertion_point(interface_extends:ReceivedDataPb) + com.google.protobuf.MessageOrBuilder { + + /** string dataId = 1; */ + java.lang.String getDataId(); + + /** string dataId = 1; */ + com.google.protobuf.ByteString getDataIdBytes(); + + /** string group = 2; */ + java.lang.String getGroup(); + + /** string group = 2; */ + com.google.protobuf.ByteString getGroupBytes(); + + /** string instanceId = 3; */ + java.lang.String getInstanceId(); + + /** string instanceId = 3; */ + com.google.protobuf.ByteString getInstanceIdBytes(); + + /** string segment = 4; */ + java.lang.String getSegment(); + + /** string segment = 4; */ + com.google.protobuf.ByteString getSegmentBytes(); + + /** string scope = 5; */ + java.lang.String getScope(); + + /** string scope = 5; */ + com.google.protobuf.ByteString getScopeBytes(); + + /** repeated string subscriberRegistIds = 6; */ + java.util.List getSubscriberRegistIdsList(); + + /** repeated string subscriberRegistIds = 6; */ + int getSubscriberRegistIdsCount(); + + /** repeated string subscriberRegistIds = 6; */ + java.lang.String getSubscriberRegistIds(int index); + + /** repeated string subscriberRegistIds = 6; */ + com.google.protobuf.ByteString getSubscriberRegistIdsBytes(int index); + + /** map<string, .DataBoxesPb> data = 7; */ + int getDataCount(); + + /** map<string, .DataBoxesPb> data = 7; */ + boolean containsData(java.lang.String key); + + /** Use {@link #getDataMap()} instead. */ + @java.lang.Deprecated + java.util.Map + getData(); + + /** map<string, .DataBoxesPb> data = 7; */ + java.util.Map + getDataMap(); + + /** map<string, .DataBoxesPb> data = 7; */ + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb defaultValue); + + /** map<string, .DataBoxesPb> data = 7; */ + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb getDataOrThrow(java.lang.String key); + + /** int64 version = 8; */ + long getVersion(); + + /** string localZone = 9; */ + java.lang.String getLocalZone(); + + /** string localZone = 9; */ + com.google.protobuf.ByteString getLocalZoneBytes(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPbOuterClass.java index 2e6486878..d9a51e835 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ReceivedDataPbOuterClass.java @@ -14,72 +14,83 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: ReceivedDataPb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class ReceivedDataPbOuterClass { - private ReceivedDataPbOuterClass() { - } + private ReceivedDataPbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor internal_static_ReceivedDataPb_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_ReceivedDataPb_fieldAccessorTable; + static final com.google.protobuf.Descriptors.Descriptor + internal_static_ReceivedDataPb_DataEntry_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_ReceivedDataPb_DataEntry_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_ReceivedDataPb_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ReceivedDataPb_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_ReceivedDataPb_DataEntry_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ReceivedDataPb_DataEntry_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\024ReceivedDataPb.proto\032\021DataBoxesPb.prot" - + "o\"\210\002\n\016ReceivedDataPb\022\016\n\006dataId\030\001 \001(\t\022\r\n\005" - + "group\030\002 \001(\t\022\022\n\ninstanceId\030\003 \001(\t\022\017\n\007segme" - + "nt\030\004 \001(\t\022\r\n\005scope\030\005 \001(\t\022\033\n\023subscriberReg" - + "istIds\030\006 \003(\t\022\'\n\004data\030\007 \003(\0132\031.ReceivedDat" - + "aPb.DataEntry\022\017\n\007version\030\010 \001(\003\022\021\n\tlocalZ" - + "one\030\t \001(\t\0329\n\tDataEntry\022\013\n\003key\030\001 \001(\t\022\033\n\005v" - + "alue\030\002 \001(\0132\014.DataBoxesPb:\0028\001B7\n/com.alip" - + "ay.sofa.registry.common.model.client.pbP" - + "\001Z\002pbb\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom( - descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass - .getDescriptor(),}, assigner); - internal_static_ReceivedDataPb_descriptor = getDescriptor() - .getMessageTypes().get(0); - internal_static_ReceivedDataPb_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_ReceivedDataPb_descriptor, - new java.lang.String[]{"DataId", "Group", "InstanceId", - "Segment", "Scope", "SubscriberRegistIds", "Data", - "Version", "LocalZone",}); - internal_static_ReceivedDataPb_DataEntry_descriptor = internal_static_ReceivedDataPb_descriptor - .getNestedTypes().get(0); - internal_static_ReceivedDataPb_DataEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_ReceivedDataPb_DataEntry_descriptor, - new java.lang.String[]{"Key", "Value",}); - com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass - .getDescriptor(); - } + static { + java.lang.String[] descriptorData = { + "\n\024ReceivedDataPb.proto\032\021DataBoxesPb.prot" + + "o\"\210\002\n\016ReceivedDataPb\022\016\n\006dataId\030\001 \001(\t\022\r\n\005" + + "group\030\002 \001(\t\022\022\n\ninstanceId\030\003 \001(\t\022\017\n\007segme" + + "nt\030\004 \001(\t\022\r\n\005scope\030\005 \001(\t\022\033\n\023subscriberReg" + + "istIds\030\006 \003(\t\022\'\n\004data\030\007 \003(\0132\031.ReceivedDat" + + "aPb.DataEntry\022\017\n\007version\030\010 \001(\003\022\021\n\tlocalZ" + + "one\030\t \001(\t\0329\n\tDataEntry\022\013\n\003key\030\001 \001(\t\022\033\n\005v" + + "alue\030\002 \001(\0132\014.DataBoxesPb:\0028\001B7\n/com.alip" + + "ay.sofa.registry.common.model.client.pbP" + + "\001Z\002pbb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass.getDescriptor(), + }, + assigner); + internal_static_ReceivedDataPb_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_ReceivedDataPb_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_ReceivedDataPb_descriptor, + new java.lang.String[] { + "DataId", + "Group", + "InstanceId", + "Segment", + "Scope", + "SubscriberRegistIds", + "Data", + "Version", + "LocalZone", + }); + internal_static_ReceivedDataPb_DataEntry_descriptor = + internal_static_ReceivedDataPb_descriptor.getNestedTypes().get(0); + internal_static_ReceivedDataPb_DataEntry_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_ReceivedDataPb_DataEntry_descriptor, + new java.lang.String[] { + "Key", "Value", + }); + com.alipay.sofa.registry.common.model.client.pb.DataBoxesPbOuterClass.getDescriptor(); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePb.java index 540ef1915..6a76ac0ca 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePb.java @@ -14,828 +14,791 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: RegisterResponsePb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code RegisterResponsePb} - */ -public final class RegisterResponsePb extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:RegisterResponsePb) - RegisterResponsePbOrBuilder { - private static final long serialVersionUID = 0L; - - // Use RegisterResponsePb.newBuilder() to construct. - private RegisterResponsePb(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private RegisterResponsePb() { - success_ = false; - registId_ = ""; - version_ = 0L; - refused_ = false; - message_ = ""; - } +/** Protobuf type {@code RegisterResponsePb} */ +public final class RegisterResponsePb extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:RegisterResponsePb) + RegisterResponsePbOrBuilder { + private static final long serialVersionUID = 0L; + + // Use RegisterResponsePb.newBuilder() to construct. + private RegisterResponsePb(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private RegisterResponsePb() { + success_ = false; + registId_ = ""; + version_ = 0L; + refused_ = false; + message_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private RegisterResponsePb( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: + { + success_ = input.readBool(); + break; + } + case 18: + { + java.lang.String s = input.readStringRequireUtf8(); - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } + registId_ = s; + break; + } + case 24: + { + version_ = input.readInt64(); + break; + } + case 32: + { + refused_ = input.readBool(); + break; + } + case 42: + { + java.lang.String s = input.readStringRequireUtf8(); - private RegisterResponsePb(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 8: { - - success_ = input.readBool(); - break; - } - case 18: { - java.lang.String s = input.readStringRequireUtf8(); - - registId_ = s; - break; - } - case 24: { - - version_ = input.readInt64(); - break; - } - case 32: { - - refused_ = input.readBool(); - break; - } - case 42: { - java.lang.String s = input.readStringRequireUtf8(); - - message_ = s; - break; - } - } + message_ = s; + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOuterClass + .internal_static_RegisterResponsePb_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOuterClass + .internal_static_RegisterResponsePb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb.class, + com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb.Builder.class); + } + + public static final int SUCCESS_FIELD_NUMBER = 1; + private boolean success_; + + /** bool success = 1; */ + public boolean getSuccess() { + return success_; + } + + public static final int REGISTID_FIELD_NUMBER = 2; + private volatile java.lang.Object registId_; + + /** string registId = 2; */ + public java.lang.String getRegistId() { + java.lang.Object ref = registId_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + registId_ = s; + return s; + } + } + + /** string registId = 2; */ + public com.google.protobuf.ByteString getRegistIdBytes() { + java.lang.Object ref = registId_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + registId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int VERSION_FIELD_NUMBER = 3; + private long version_; + + /** int64 version = 3; */ + public long getVersion() { + return version_; + } + + public static final int REFUSED_FIELD_NUMBER = 4; + private boolean refused_; + + /** bool refused = 4; */ + public boolean getRefused() { + return refused_; + } + + public static final int MESSAGE_FIELD_NUMBER = 5; + private volatile java.lang.Object message_; + + /** string message = 5; */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + message_ = s; + return s; + } + } + + /** string message = 5; */ + public com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (success_ != false) { + output.writeBool(1, success_); + } + if (!getRegistIdBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, registId_); + } + if (version_ != 0L) { + output.writeInt64(3, version_); + } + if (refused_ != false) { + output.writeBool(4, refused_); + } + if (!getMessageBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 5, message_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (success_ != false) { + size += com.google.protobuf.CodedOutputStream.computeBoolSize(1, success_); + } + if (!getRegistIdBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, registId_); + } + if (version_ != 0L) { + size += com.google.protobuf.CodedOutputStream.computeInt64Size(3, version_); + } + if (refused_ != false) { + size += com.google.protobuf.CodedOutputStream.computeBoolSize(4, refused_); + } + if (!getMessageBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, message_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb other = + (com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb) obj; + + boolean result = true; + result = result && (getSuccess() == other.getSuccess()); + result = result && getRegistId().equals(other.getRegistId()); + result = result && (getVersion() == other.getVersion()); + result = result && (getRefused() == other.getRefused()); + result = result && getMessage().equals(other.getMessage()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + SUCCESS_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSuccess()); + hash = (37 * hash) + REGISTID_FIELD_NUMBER; + hash = (53 * hash) + getRegistId().hashCode(); + hash = (37 * hash) + VERSION_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getVersion()); + hash = (37 * hash) + REFUSED_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getRefused()); + hash = (37 * hash) + MESSAGE_FIELD_NUMBER; + hash = (53 * hash) + getMessage().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code RegisterResponsePb} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:RegisterResponsePb) + com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOuterClass.internal_static_RegisterResponsePb_descriptor; + return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOuterClass + .internal_static_RegisterResponsePb_descriptor; } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOuterClass.internal_static_RegisterResponsePb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb.class, - com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb.Builder.class); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOuterClass + .internal_static_RegisterResponsePb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb.class, + com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb.Builder.class); } - public static final int SUCCESS_FIELD_NUMBER = 1; - private boolean success_; - - /** - * bool success = 1; - */ - public boolean getSuccess() { - return success_; + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - public static final int REGISTID_FIELD_NUMBER = 2; - private volatile java.lang.Object registId_; - - /** - * string registId = 2; - */ - public java.lang.String getRegistId() { - java.lang.Object ref = registId_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - registId_ = s; - return s; - } + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - /** - * string registId = 2; - */ - public com.google.protobuf.ByteString getRegistIdBytes() { - java.lang.Object ref = registId_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - registId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - public static final int VERSION_FIELD_NUMBER = 3; - private long version_; + public Builder clear() { + super.clear(); + success_ = false; - /** - * int64 version = 3; - */ - public long getVersion() { - return version_; - } + registId_ = ""; - public static final int REFUSED_FIELD_NUMBER = 4; - private boolean refused_; + version_ = 0L; - /** - * bool refused = 4; - */ - public boolean getRefused() { - return refused_; - } + refused_ = false; - public static final int MESSAGE_FIELD_NUMBER = 5; - private volatile java.lang.Object message_; + message_ = ""; - /** - * string message = 5; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - message_ = s; - return s; - } + return this; } - /** - * string message = 5; - */ - public com.google.protobuf.ByteString getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOuterClass + .internal_static_RegisterResponsePb_descriptor; } - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; + public com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb + .getDefaultInstance(); } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (success_ != false) { - output.writeBool(1, success_); - } - if (!getRegistIdBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, registId_); - } - if (version_ != 0L) { - output.writeInt64(3, version_); - } - if (refused_ != false) { - output.writeBool(4, refused_); - } - if (!getMessageBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 5, message_); - } - unknownFields.writeTo(output); + public com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb build() { + com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - if (success_ != false) { - size += com.google.protobuf.CodedOutputStream.computeBoolSize(1, success_); - } - if (!getRegistIdBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, registId_); - } - if (version_ != 0L) { - size += com.google.protobuf.CodedOutputStream.computeInt64Size(3, version_); - } - if (refused_ != false) { - size += com.google.protobuf.CodedOutputStream.computeBoolSize(4, refused_); - } - if (!getMessageBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, message_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + public com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb result = + new com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb(this); + result.success_ = success_; + result.registId_ = registId_; + result.version_ = version_; + result.refused_ = refused_; + result.message_ = message_; + onBuilt(); + return result; } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb other = (com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb) obj; - - boolean result = true; - result = result && (getSuccess() == other.getSuccess()); - result = result && getRegistId().equals(other.getRegistId()); - result = result && (getVersion() == other.getVersion()); - result = result && (getRefused() == other.getRefused()); - result = result && getMessage().equals(other.getMessage()); - result = result && unknownFields.equals(other.unknownFields); - return result; - } - - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + SUCCESS_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSuccess()); - hash = (37 * hash) + REGISTID_FIELD_NUMBER; - hash = (53 * hash) + getRegistId().hashCode(); - hash = (37 * hash) + VERSION_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashLong(getVersion()); - hash = (37 * hash) + REFUSED_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getRefused()); - hash = (37 * hash) + MESSAGE_FIELD_NUMBER; - hash = (53 * hash) + getMessage().hashCode(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + public Builder clone() { + return (Builder) super.clone(); } - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb) other); + } else { + super.mergeFrom(other); + return this; + } } - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb + .getDefaultInstance()) return this; + if (other.getSuccess() != false) { + setSuccess(other.getSuccess()); + } + if (!other.getRegistId().isEmpty()) { + registId_ = other.registId_; + onChanged(); + } + if (other.getVersion() != 0L) { + setVersion(other.getVersion()); + } + if (other.getRefused() != false) { + setRefused(other.getRefused()); + } + if (!other.getMessage().isEmpty()) { + message_ = other.message_; + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public final boolean isInitialized() { + return true; } - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); - } + private boolean success_; - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + /** bool success = 1; */ + public boolean getSuccess() { + return success_; } - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + /** bool success = 1; */ + public Builder setSuccess(boolean value) { - public Builder newBuilderForType() { - return newBuilder(); + success_ = value; + onChanged(); + return this; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } + /** bool success = 1; */ + public Builder clearSuccess() { - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + success_ = false; + onChanged(); + return this; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } + private java.lang.Object registId_ = ""; - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + /** string registId = 2; */ + public java.lang.String getRegistId() { + java.lang.Object ref = registId_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + registId_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string registId = 2; */ + public com.google.protobuf.ByteString getRegistIdBytes() { + java.lang.Object ref = registId_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + registId_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - /** - * Protobuf type {@code RegisterResponsePb} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:RegisterResponsePb) - com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOuterClass.internal_static_RegisterResponsePb_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOuterClass.internal_static_RegisterResponsePb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb.class, - com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - success_ = false; - - registId_ = ""; - - version_ = 0L; - - refused_ = false; - - message_ = ""; - - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePbOuterClass.internal_static_RegisterResponsePb_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb build() { - com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb result = new com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb( - this); - result.success_ = success_; - result.registId_ = registId_; - result.version_ = version_; - result.refused_ = refused_; - result.message_ = message_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } + /** string registId = 2; */ + public Builder setRegistId(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb - .getDefaultInstance()) - return this; - if (other.getSuccess() != false) { - setSuccess(other.getSuccess()); - } - if (!other.getRegistId().isEmpty()) { - registId_ = other.registId_; - onChanged(); - } - if (other.getVersion() != 0L) { - setVersion(other.getVersion()); - } - if (other.getRefused() != false) { - setRefused(other.getRefused()); - } - if (!other.getMessage().isEmpty()) { - message_ = other.message_; - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private boolean success_; - - /** - * bool success = 1; - */ - public boolean getSuccess() { - return success_; - } - - /** - * bool success = 1; - */ - public Builder setSuccess(boolean value) { - - success_ = value; - onChanged(); - return this; - } - - /** - * bool success = 1; - */ - public Builder clearSuccess() { + registId_ = value; + onChanged(); + return this; + } - success_ = false; - onChanged(); - return this; - } + /** string registId = 2; */ + public Builder clearRegistId() { - private java.lang.Object registId_ = ""; - - /** - * string registId = 2; - */ - public java.lang.String getRegistId() { - java.lang.Object ref = registId_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - registId_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + registId_ = getDefaultInstance().getRegistId(); + onChanged(); + return this; + } - /** - * string registId = 2; - */ - public com.google.protobuf.ByteString getRegistIdBytes() { - java.lang.Object ref = registId_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - registId_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string registId = 2; */ + public Builder setRegistIdBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string registId = 2; - */ - public Builder setRegistId(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + registId_ = value; + onChanged(); + return this; + } - registId_ = value; - onChanged(); - return this; - } + private long version_; - /** - * string registId = 2; - */ - public Builder clearRegistId() { + /** int64 version = 3; */ + public long getVersion() { + return version_; + } - registId_ = getDefaultInstance().getRegistId(); - onChanged(); - return this; - } + /** int64 version = 3; */ + public Builder setVersion(long value) { - /** - * string registId = 2; - */ - public Builder setRegistIdBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + version_ = value; + onChanged(); + return this; + } - registId_ = value; - onChanged(); - return this; - } + /** int64 version = 3; */ + public Builder clearVersion() { - private long version_; + version_ = 0L; + onChanged(); + return this; + } - /** - * int64 version = 3; - */ - public long getVersion() { - return version_; - } + private boolean refused_; - /** - * int64 version = 3; - */ - public Builder setVersion(long value) { + /** bool refused = 4; */ + public boolean getRefused() { + return refused_; + } - version_ = value; - onChanged(); - return this; - } + /** bool refused = 4; */ + public Builder setRefused(boolean value) { - /** - * int64 version = 3; - */ - public Builder clearVersion() { + refused_ = value; + onChanged(); + return this; + } - version_ = 0L; - onChanged(); - return this; - } + /** bool refused = 4; */ + public Builder clearRefused() { - private boolean refused_; + refused_ = false; + onChanged(); + return this; + } - /** - * bool refused = 4; - */ - public boolean getRefused() { - return refused_; - } + private java.lang.Object message_ = ""; - /** - * bool refused = 4; - */ - public Builder setRefused(boolean value) { + /** string message = 5; */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + message_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string message = 5; */ + public com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - refused_ = value; - onChanged(); - return this; - } + /** string message = 5; */ + public Builder setMessage(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - /** - * bool refused = 4; - */ - public Builder clearRefused() { + message_ = value; + onChanged(); + return this; + } - refused_ = false; - onChanged(); - return this; - } + /** string message = 5; */ + public Builder clearMessage() { - private java.lang.Object message_ = ""; - - /** - * string message = 5; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - message_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + message_ = getDefaultInstance().getMessage(); + onChanged(); + return this; + } - /** - * string message = 5; - */ - public com.google.protobuf.ByteString getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string message = 5; */ + public Builder setMessageBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string message = 5; - */ - public Builder setMessage(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + message_ = value; + onChanged(); + return this; + } - message_ = value; - onChanged(); - return this; - } + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } - /** - * string message = 5; - */ - public Builder clearMessage() { + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - message_ = getDefaultInstance().getMessage(); - onChanged(); - return this; - } + // @@protoc_insertion_point(builder_scope:RegisterResponsePb) + } - /** - * string message = 5; - */ - public Builder setMessageBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + // @@protoc_insertion_point(class_scope:RegisterResponsePb) + private static final com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb + DEFAULT_INSTANCE; - message_ = value; - onChanged(); - return this; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb(); + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb + getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public RegisterResponsePb parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new RegisterResponsePb(input, extensionRegistry); } + }; - // @@protoc_insertion_point(builder_scope:RegisterResponsePb) - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - // @@protoc_insertion_point(class_scope:RegisterResponsePb) - private static final com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public RegisterResponsePb parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new RegisterResponsePb( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.RegisterResponsePb + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePbOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePbOrBuilder.java index 6fcbf355a..cb8d8ae8c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePbOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePbOrBuilder.java @@ -14,47 +14,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: RegisterResponsePb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface RegisterResponsePbOrBuilder extends -// @@protoc_insertion_point(interface_extends:RegisterResponsePb) - com.google.protobuf.MessageOrBuilder { - - /** - * bool success = 1; - */ - boolean getSuccess(); - - /** - * string registId = 2; - */ - java.lang.String getRegistId(); - - /** - * string registId = 2; - */ - com.google.protobuf.ByteString getRegistIdBytes(); - - /** - * int64 version = 3; - */ - long getVersion(); - - /** - * bool refused = 4; - */ - boolean getRefused(); - - /** - * string message = 5; - */ - java.lang.String getMessage(); - - /** - * string message = 5; - */ - com.google.protobuf.ByteString getMessageBytes(); +public interface RegisterResponsePbOrBuilder + extends + // @@protoc_insertion_point(interface_extends:RegisterResponsePb) + com.google.protobuf.MessageOrBuilder { + + /** bool success = 1; */ + boolean getSuccess(); + + /** string registId = 2; */ + java.lang.String getRegistId(); + + /** string registId = 2; */ + com.google.protobuf.ByteString getRegistIdBytes(); + + /** int64 version = 3; */ + long getVersion(); + + /** bool refused = 4; */ + boolean getRefused(); + + /** string message = 5; */ + java.lang.String getMessage(); + + /** string message = 5; */ + com.google.protobuf.ByteString getMessageBytes(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePbOuterClass.java index 5eb323655..c22e22042 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/RegisterResponsePbOuterClass.java @@ -14,56 +14,54 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: RegisterResponsePb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class RegisterResponsePbOuterClass { - private RegisterResponsePbOuterClass() { - } + private RegisterResponsePbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor + internal_static_RegisterResponsePb_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_RegisterResponsePb_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_RegisterResponsePb_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_RegisterResponsePb_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\030RegisterResponsePb.proto\"j\n\022RegisterRe" - + "sponsePb\022\017\n\007success\030\001 \001(\010\022\020\n\010registId\030\002 " - + "\001(\t\022\017\n\007version\030\003 \001(\003\022\017\n\007refused\030\004 \001(\010\022\017\n" - + "\007message\030\005 \001(\tB7\n/com.alipay.sofa.regist" - + "ry.common.model.client.pbP\001Z\002pbb\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{}, - assigner); - internal_static_RegisterResponsePb_descriptor = getDescriptor() - .getMessageTypes().get(0); - internal_static_RegisterResponsePb_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_RegisterResponsePb_descriptor, - new java.lang.String[]{"Success", "RegistId", "Version", - "Refused", "Message",}); - } + static { + java.lang.String[] descriptorData = { + "\n\030RegisterResponsePb.proto\"j\n\022RegisterRe" + + "sponsePb\022\017\n\007success\030\001 \001(\010\022\020\n\010registId\030\002 " + + "\001(\t\022\017\n\007version\030\003 \001(\003\022\017\n\007refused\030\004 \001(\010\022\017\n" + + "\007message\030\005 \001(\tB7\n/com.alipay.sofa.regist" + + "ry.common.model.client.pbP\001Z\002pbb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_RegisterResponsePb_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_RegisterResponsePb_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_RegisterResponsePb_descriptor, + new java.lang.String[] { + "Success", "RegistId", "Version", "Refused", "Message", + }); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPb.java index c9af7ee97..c8b9e1d3f 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPb.java @@ -14,582 +14,564 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: ResultPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code ResultPb} - */ -public final class ResultPb extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:ResultPb) - ResultPbOrBuilder { - private static final long serialVersionUID = 0L; - - // Use ResultPb.newBuilder() to construct. - private ResultPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private ResultPb() { - success_ = false; - message_ = ""; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } +/** Protobuf type {@code ResultPb} */ +public final class ResultPb extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:ResultPb) + ResultPbOrBuilder { + private static final long serialVersionUID = 0L; + + // Use ResultPb.newBuilder() to construct. + private ResultPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private ResultPb() { + success_ = false; + message_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private ResultPb( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 8: + { + success_ = input.readBool(); + break; + } + case 18: + { + java.lang.String s = input.readStringRequireUtf8(); - private ResultPb(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 8: { - - success_ = input.readBool(); - break; - } - case 18: { - java.lang.String s = input.readStringRequireUtf8(); - - message_ = s; - break; - } - } + message_ = s; + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass + .internal_static_ResultPb_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass + .internal_static_ResultPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.ResultPb.class, + com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder.class); + } + + public static final int SUCCESS_FIELD_NUMBER = 1; + private boolean success_; + + /** bool success = 1; */ + public boolean getSuccess() { + return success_; + } + + public static final int MESSAGE_FIELD_NUMBER = 2; + private volatile java.lang.Object message_; + + /** string message = 2; */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + message_ = s; + return s; + } + } + + /** string message = 2; */ + public com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (success_ != false) { + output.writeBool(1, success_); + } + if (!getMessageBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, message_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (success_ != false) { + size += com.google.protobuf.CodedOutputStream.computeBoolSize(1, success_); + } + if (!getMessageBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, message_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.ResultPb)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.ResultPb other = + (com.alipay.sofa.registry.common.model.client.pb.ResultPb) obj; + + boolean result = true; + result = result && (getSuccess() == other.getSuccess()); + result = result && getMessage().equals(other.getMessage()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + SUCCESS_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSuccess()); + hash = (37 * hash) + MESSAGE_FIELD_NUMBER; + hash = (53 * hash) + getMessage().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.ResultPb prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code ResultPb} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:ResultPb) + com.alipay.sofa.registry.common.model.client.pb.ResultPbOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass.internal_static_ResultPb_descriptor; + return com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass + .internal_static_ResultPb_descriptor; } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass.internal_static_ResultPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.ResultPb.class, - com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder.class); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass + .internal_static_ResultPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.ResultPb.class, + com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder.class); } - public static final int SUCCESS_FIELD_NUMBER = 1; - private boolean success_; - - /** - * bool success = 1; - */ - public boolean getSuccess() { - return success_; + // Construct using com.alipay.sofa.registry.common.model.client.pb.ResultPb.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - public static final int MESSAGE_FIELD_NUMBER = 2; - private volatile java.lang.Object message_; - - /** - * string message = 2; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - message_ = s; - return s; - } + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - /** - * string message = 2; - */ - public com.google.protobuf.ByteString getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - private byte memoizedIsInitialized = -1; + public Builder clear() { + super.clear(); + success_ = false; - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; + message_ = ""; - memoizedIsInitialized = 1; - return true; + return this; } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (success_ != false) { - output.writeBool(1, success_); - } - if (!getMessageBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, message_); - } - unknownFields.writeTo(output); + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass + .internal_static_ResultPb_descriptor; } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - if (success_ != false) { - size += com.google.protobuf.CodedOutputStream.computeBoolSize(1, success_); - } - if (!getMessageBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, message_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.ResultPb)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.ResultPb other = (com.alipay.sofa.registry.common.model.client.pb.ResultPb) obj; - - boolean result = true; - result = result && (getSuccess() == other.getSuccess()); - result = result && getMessage().equals(other.getMessage()); - result = result && unknownFields.equals(other.unknownFields); - return result; + public com.alipay.sofa.registry.common.model.client.pb.ResultPb getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.ResultPb.getDefaultInstance(); } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + SUCCESS_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSuccess()); - hash = (37 * hash) + MESSAGE_FIELD_NUMBER; - hash = (53 * hash) + getMessage().hashCode(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + public com.alipay.sofa.registry.common.model.client.pb.ResultPb build() { + com.alipay.sofa.registry.common.model.client.pb.ResultPb result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public com.alipay.sofa.registry.common.model.client.pb.ResultPb buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.ResultPb result = + new com.alipay.sofa.registry.common.model.client.pb.ResultPb(this); + result.success_ = success_; + result.message_ = message_; + onBuilt(); + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clone() { + return (Builder) super.clone(); } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.ResultPb) { + return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.ResultPb) other); + } else { + super.mergeFrom(other); + return this; + } } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.ResultPb other) { + if (other == com.alipay.sofa.registry.common.model.client.pb.ResultPb.getDefaultInstance()) + return this; + if (other.getSuccess() != false) { + setSuccess(other.getSuccess()); + } + if (!other.getMessage().isEmpty()) { + message_ = other.message_; + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + public final boolean isInitialized() { + return true; } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.ResultPb parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.ResultPb) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + private boolean success_; - public Builder newBuilderForType() { - return newBuilder(); + /** bool success = 1; */ + public boolean getSuccess() { + return success_; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } + /** bool success = 1; */ + public Builder setSuccess(boolean value) { - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.ResultPb prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + success_ = value; + onChanged(); + return this; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } + /** bool success = 1; */ + public Builder clearSuccess() { - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + success_ = false; + onChanged(); + return this; } - /** - * Protobuf type {@code ResultPb} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:ResultPb) - com.alipay.sofa.registry.common.model.client.pb.ResultPbOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass.internal_static_ResultPb_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass.internal_static_ResultPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.ResultPb.class, - com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.ResultPb.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - success_ = false; + private java.lang.Object message_ = ""; - message_ = ""; - - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass.internal_static_ResultPb_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.ResultPb getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.ResultPb.getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.ResultPb build() { - com.alipay.sofa.registry.common.model.client.pb.ResultPb result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.ResultPb buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.ResultPb result = new com.alipay.sofa.registry.common.model.client.pb.ResultPb( - this); - result.success_ = success_; - result.message_ = message_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.ResultPb) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.ResultPb) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.ResultPb other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.ResultPb - .getDefaultInstance()) - return this; - if (other.getSuccess() != false) { - setSuccess(other.getSuccess()); - } - if (!other.getMessage().isEmpty()) { - message_ = other.message_; - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.ResultPb parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.ResultPb) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private boolean success_; - - /** - * bool success = 1; - */ - public boolean getSuccess() { - return success_; - } - - /** - * bool success = 1; - */ - public Builder setSuccess(boolean value) { + /** string message = 2; */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + message_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string message = 2; */ + public com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - success_ = value; - onChanged(); - return this; - } + /** string message = 2; */ + public Builder setMessage(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - /** - * bool success = 1; - */ - public Builder clearSuccess() { + message_ = value; + onChanged(); + return this; + } - success_ = false; - onChanged(); - return this; - } + /** string message = 2; */ + public Builder clearMessage() { - private java.lang.Object message_ = ""; - - /** - * string message = 2; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - message_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + message_ = getDefaultInstance().getMessage(); + onChanged(); + return this; + } - /** - * string message = 2; - */ - public com.google.protobuf.ByteString getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string message = 2; */ + public Builder setMessageBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string message = 2; - */ - public Builder setMessage(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + message_ = value; + onChanged(); + return this; + } - message_ = value; - onChanged(); - return this; - } + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } - /** - * string message = 2; - */ - public Builder clearMessage() { + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - message_ = getDefaultInstance().getMessage(); - onChanged(); - return this; - } + // @@protoc_insertion_point(builder_scope:ResultPb) + } - /** - * string message = 2; - */ - public Builder setMessageBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + // @@protoc_insertion_point(class_scope:ResultPb) + private static final com.alipay.sofa.registry.common.model.client.pb.ResultPb DEFAULT_INSTANCE; - message_ = value; - onChanged(); - return this; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.ResultPb(); + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + public static com.alipay.sofa.registry.common.model.client.pb.ResultPb getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public ResultPb parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new ResultPb(input, extensionRegistry); } + }; - // @@protoc_insertion_point(builder_scope:ResultPb) - } - - // @@protoc_insertion_point(class_scope:ResultPb) - private static final com.alipay.sofa.registry.common.model.client.pb.ResultPb DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.ResultPb(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.ResultPb getDefaultInstance() { - return DEFAULT_INSTANCE; - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public ResultPb parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new ResultPb( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public com.alipay.sofa.registry.common.model.client.pb.ResultPb getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.ResultPb getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPbOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPbOrBuilder.java index f2354caff..dc2fe964a 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPbOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPbOrBuilder.java @@ -14,27 +14,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: ResultPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface ResultPbOrBuilder extends -// @@protoc_insertion_point(interface_extends:ResultPb) - com.google.protobuf.MessageOrBuilder { +public interface ResultPbOrBuilder + extends + // @@protoc_insertion_point(interface_extends:ResultPb) + com.google.protobuf.MessageOrBuilder { - /** - * bool success = 1; - */ - boolean getSuccess(); + /** bool success = 1; */ + boolean getSuccess(); - /** - * string message = 2; - */ - java.lang.String getMessage(); + /** string message = 2; */ + java.lang.String getMessage(); - /** - * string message = 2; - */ - com.google.protobuf.ByteString getMessageBytes(); + /** string message = 2; */ + com.google.protobuf.ByteString getMessageBytes(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPbOuterClass.java index 0490eff01..ca6ae781c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ResultPbOuterClass.java @@ -14,54 +14,52 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: ResultPb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class ResultPbOuterClass { - private ResultPbOuterClass() { - } + private ResultPbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor internal_static_ResultPb_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_ResultPb_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_ResultPb_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_ResultPb_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\016ResultPb.proto\",\n\010ResultPb\022\017\n\007success\030" - + "\001 \001(\010\022\017\n\007message\030\002 \001(\tB7\n/com.alipay.sof" - + "a.registry.common.model.client.pbP\001Z\002pbb" - + "\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{}, - assigner); - internal_static_ResultPb_descriptor = getDescriptor().getMessageTypes() - .get(0); - internal_static_ResultPb_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_ResultPb_descriptor, new java.lang.String[]{ - "Success", "Message",}); - } + static { + java.lang.String[] descriptorData = { + "\n\016ResultPb.proto\",\n\010ResultPb\022\017\n\007success\030" + + "\001 \001(\010\022\017\n\007message\030\002 \001(\tB7\n/com.alipay.sof" + + "a.registry.common.model.client.pbP\001Z\002pbb" + + "\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_ResultPb_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_ResultPb_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_ResultPb_descriptor, + new java.lang.String[] { + "Success", "Message", + }); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ScopeEnumPb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ScopeEnumPb.java index f388fe352..7dfcdbc0f 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ScopeEnumPb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ScopeEnumPb.java @@ -14,112 +14,95 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: ScopeEnumPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf enum {@code ScopeEnumPb} - */ +/** Protobuf enum {@code ScopeEnumPb} */ public enum ScopeEnumPb implements com.google.protobuf.ProtocolMessageEnum { - /** - * zone = 0; - */ - zone(0), - /** - * dataCenter = 1; - */ - dataCenter(1), - /** - * global = 2; - */ - global(2), UNRECOGNIZED(-1), ; - - /** - * zone = 0; - */ - public static final int zone_VALUE = 0; - /** - * dataCenter = 1; - */ - public static final int dataCenter_VALUE = 1; - /** - * global = 2; - */ - public static final int global_VALUE = 2; - - public final int getNumber() { - if (this == UNRECOGNIZED) { - throw new java.lang.IllegalArgumentException( - "Can't get the number of an unknown enum value."); - } - return value; + /** zone = 0; */ + zone(0), + /** dataCenter = 1; */ + dataCenter(1), + /** global = 2; */ + global(2), + UNRECOGNIZED(-1), + ; + + /** zone = 0; */ + public static final int zone_VALUE = 0; + /** dataCenter = 1; */ + public static final int dataCenter_VALUE = 1; + /** global = 2; */ + public static final int global_VALUE = 2; + + public final int getNumber() { + if (this == UNRECOGNIZED) { + throw new java.lang.IllegalArgumentException( + "Can't get the number of an unknown enum value."); } - - /** - * @deprecated Use {@link #forNumber(int)} instead. - */ - @java.lang.Deprecated - public static ScopeEnumPb valueOf(int value) { - return forNumber(value); + return value; + } + + /** @deprecated Use {@link #forNumber(int)} instead. */ + @java.lang.Deprecated + public static ScopeEnumPb valueOf(int value) { + return forNumber(value); + } + + public static ScopeEnumPb forNumber(int value) { + switch (value) { + case 0: + return zone; + case 1: + return dataCenter; + case 2: + return global; + default: + return null; } + } - public static ScopeEnumPb forNumber(int value) { - switch (value) { - case 0: - return zone; - case 1: - return dataCenter; - case 2: - return global; - default: - return null; + public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { + return internalValueMap; + } + + private static final com.google.protobuf.Internal.EnumLiteMap internalValueMap = + new com.google.protobuf.Internal.EnumLiteMap() { + public ScopeEnumPb findValueByNumber(int number) { + return ScopeEnumPb.forNumber(number); } - } + }; - public static com.google.protobuf.Internal.EnumLiteMap internalGetValueMap() { - return internalValueMap; - } + public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { + return getDescriptor().getValues().get(ordinal()); + } - private static final com.google.protobuf.Internal.EnumLiteMap internalValueMap = new com.google.protobuf.Internal.EnumLiteMap() { - public ScopeEnumPb findValueByNumber(int number) { - return ScopeEnumPb - .forNumber(number); - } - }; + public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { + return getDescriptor(); + } - public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { - return getDescriptor().getValues().get(ordinal()); - } + public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.ScopeEnumPbOuterClass.getDescriptor() + .getEnumTypes() + .get(0); + } - public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { - return getDescriptor(); - } + private static final ScopeEnumPb[] VALUES = values(); - public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.ScopeEnumPbOuterClass - .getDescriptor().getEnumTypes().get(0); + public static ScopeEnumPb valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { + if (desc.getType() != getDescriptor()) { + throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } - - private static final ScopeEnumPb[] VALUES = values(); - - public static ScopeEnumPb valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { - if (desc.getType() != getDescriptor()) { - throw new java.lang.IllegalArgumentException( - "EnumValueDescriptor is not for this type."); - } - if (desc.getIndex() == -1) { - return UNRECOGNIZED; - } - return VALUES[desc.getIndex()]; + if (desc.getIndex() == -1) { + return UNRECOGNIZED; } + return VALUES[desc.getIndex()]; + } - private final int value; + private final int value; - private ScopeEnumPb(int value) { - this.value = value; - } + private ScopeEnumPb(int value) { + this.value = value; + } - // @@protoc_insertion_point(enum_scope:ScopeEnumPb) + // @@protoc_insertion_point(enum_scope:ScopeEnumPb) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ScopeEnumPbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ScopeEnumPbOuterClass.java index 4c50f8ce0..66996f27f 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ScopeEnumPbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ScopeEnumPbOuterClass.java @@ -14,46 +14,41 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: ScopeEnumPb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class ScopeEnumPbOuterClass { - private ScopeEnumPbOuterClass() { - } + private ScopeEnumPbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\021ScopeEnumPb.proto*3\n\013ScopeEnumPb\022\010\n\004zo" - + "ne\020\000\022\016\n\ndataCenter\020\001\022\n\n\006global\020\002B7\n/com." - + "alipay.sofa.registry.common.model.client" - + ".pbP\001Z\002pbb\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{}, - assigner); - } + static { + java.lang.String[] descriptorData = { + "\n\021ScopeEnumPb.proto*3\n\013ScopeEnumPb\022\010\n\004zo" + + "ne\020\000\022\016\n\ndataCenter\020\001\022\n\n\006global\020\002B7\n/com." + + "alipay.sofa.registry.common.model.client" + + ".pbP\001Z\002pbb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingRequest.java index 471b13540..42b95d59c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingRequest.java @@ -14,576 +14,569 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code ServiceAppMappingRequest} - */ +/** Protobuf type {@code ServiceAppMappingRequest} */ public final class ServiceAppMappingRequest extends com.google.protobuf.GeneratedMessageV3 - implements - // @@protoc_insertion_point(message_implements:ServiceAppMappingRequest) - ServiceAppMappingRequestOrBuilder { - private static final long serialVersionUID = 0L; - - // Use ServiceAppMappingRequest.newBuilder() to construct. - private ServiceAppMappingRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private ServiceAppMappingRequest() { - serviceIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } - - private ServiceAppMappingRequest(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - serviceIds_ = new com.google.protobuf.LazyStringArrayList(); - mutable_bitField0_ |= 0x00000001; - } - serviceIds_.add(s); - break; - } - } + implements + // @@protoc_insertion_point(message_implements:ServiceAppMappingRequest) + ServiceAppMappingRequestOrBuilder { + private static final long serialVersionUID = 0L; + + // Use ServiceAppMappingRequest.newBuilder() to construct. + private ServiceAppMappingRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private ServiceAppMappingRequest() { + serviceIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private ServiceAppMappingRequest( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - serviceIds_ = serviceIds_.getUnmodifiableView(); + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + serviceIds_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000001; + } + serviceIds_.add(s); + break; } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + serviceIds_ = serviceIds_.getUnmodifiableView(); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_ServiceAppMappingRequest_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_ServiceAppMappingRequest_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest.class, + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest.Builder.class); + } + + public static final int SERVICEIDS_FIELD_NUMBER = 1; + private com.google.protobuf.LazyStringList serviceIds_; + + /** repeated string serviceIds = 1; */ + public com.google.protobuf.ProtocolStringList getServiceIdsList() { + return serviceIds_; + } + + /** repeated string serviceIds = 1; */ + public int getServiceIdsCount() { + return serviceIds_.size(); + } + + /** repeated string serviceIds = 1; */ + public java.lang.String getServiceIds(int index) { + return serviceIds_.get(index); + } + + /** repeated string serviceIds = 1; */ + public com.google.protobuf.ByteString getServiceIdsBytes(int index) { + return serviceIds_.getByteString(index); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + for (int i = 0; i < serviceIds_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, serviceIds_.getRaw(i)); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + { + int dataSize = 0; + for (int i = 0; i < serviceIds_.size(); i++) { + dataSize += computeStringSizeNoTag(serviceIds_.getRaw(i)); + } + size += dataSize; + size += 1 * getServiceIdsList().size(); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj + instanceof com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest other = + (com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest) obj; + + boolean result = true; + result = result && getServiceIdsList().equals(other.getServiceIdsList()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (getServiceIdsCount() > 0) { + hash = (37 * hash) + SERVICEIDS_FIELD_NUMBER; + hash = (53 * hash) + getServiceIdsList().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code ServiceAppMappingRequest} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:ServiceAppMappingRequest) + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequestOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_ServiceAppMappingRequest_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_ServiceAppMappingRequest_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest.class, - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest.Builder.class); - } - - public static final int SERVICEIDS_FIELD_NUMBER = 1; - private com.google.protobuf.LazyStringList serviceIds_; - - /** - * repeated string serviceIds = 1; - */ - public com.google.protobuf.ProtocolStringList getServiceIdsList() { - return serviceIds_; - } - - /** - * repeated string serviceIds = 1; - */ - public int getServiceIdsCount() { - return serviceIds_.size(); - } - - /** - * repeated string serviceIds = 1; - */ - public java.lang.String getServiceIds(int index) { - return serviceIds_.get(index); - } - - /** - * repeated string serviceIds = 1; - */ - public com.google.protobuf.ByteString getServiceIdsBytes(int index) { - return serviceIds_.getByteString(index); - } - - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; - } - - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - for (int i = 0; i < serviceIds_.size(); i++) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, serviceIds_.getRaw(i)); - } - unknownFields.writeTo(output); + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_ServiceAppMappingRequest_descriptor; } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - { - int dataSize = 0; - for (int i = 0; i < serviceIds_.size(); i++) { - dataSize += computeStringSizeNoTag(serviceIds_.getRaw(i)); - } - size += dataSize; - size += 1 * getServiceIdsList().size(); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_ServiceAppMappingRequest_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest.class, + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest.Builder + .class); } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest other = (com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest) obj; - - boolean result = true; - result = result && getServiceIdsList().equals(other.getServiceIdsList()); - result = result && unknownFields.equals(other.unknownFields); - return result; + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (getServiceIdsCount() > 0) { - hash = (37 * hash) + SERVICEIDS_FIELD_NUMBER; - hash = (53 * hash) + getServiceIdsList().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clear() { + super.clear(); + serviceIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_ServiceAppMappingRequest_descriptor; } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest + .getDefaultInstance(); } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest build() { + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest result = + buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest result = + new com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest(this); + int from_bitField0_ = bitField0_; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + serviceIds_ = serviceIds_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.serviceIds_ = serviceIds_; + onBuilt(); + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + public Builder clone() { + return (Builder) super.clone(); } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public Builder newBuilderForType() { - return newBuilder(); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other + instanceof com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest) other); + } else { + super.mergeFrom(other); + return this; + } } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest + .getDefaultInstance()) return this; + if (!other.serviceIds_.isEmpty()) { + if (serviceIds_.isEmpty()) { + serviceIds_ = other.serviceIds_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureServiceIdsIsMutable(); + serviceIds_.addAll(other.serviceIds_); + } + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + public final boolean isInitialized() { + return true; } - /** - * Protobuf type {@code ServiceAppMappingRequest} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:ServiceAppMappingRequest) - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequestOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_ServiceAppMappingRequest_descriptor; + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_ServiceAppMappingRequest_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest.class, - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - serviceIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_ServiceAppMappingRequest_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest build() { - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest result = new com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest( - this); - int from_bitField0_ = bitField0_; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - serviceIds_ = serviceIds_.getUnmodifiableView(); - bitField0_ = (bitField0_ & ~0x00000001); - } - result.serviceIds_ = serviceIds_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest - .getDefaultInstance()) - return this; - if (!other.serviceIds_.isEmpty()) { - if (serviceIds_.isEmpty()) { - serviceIds_ = other.serviceIds_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureServiceIdsIsMutable(); - serviceIds_.addAll(other.serviceIds_); - } - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private com.google.protobuf.LazyStringList serviceIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; - - private void ensureServiceIdsIsMutable() { - if (!((bitField0_ & 0x00000001) == 0x00000001)) { - serviceIds_ = new com.google.protobuf.LazyStringArrayList(serviceIds_); - bitField0_ |= 0x00000001; - } - } - - /** - * repeated string serviceIds = 1; - */ - public com.google.protobuf.ProtocolStringList getServiceIdsList() { - return serviceIds_.getUnmodifiableView(); - } - - /** - * repeated string serviceIds = 1; - */ - public int getServiceIdsCount() { - return serviceIds_.size(); - } - - /** - * repeated string serviceIds = 1; - */ - public java.lang.String getServiceIds(int index) { - return serviceIds_.get(index); - } - - /** - * repeated string serviceIds = 1; - */ - public com.google.protobuf.ByteString getServiceIdsBytes(int index) { - return serviceIds_.getByteString(index); - } - - /** - * repeated string serviceIds = 1; - */ - public Builder setServiceIds(int index, java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureServiceIdsIsMutable(); - serviceIds_.set(index, value); - onChanged(); - return this; - } - - /** - * repeated string serviceIds = 1; - */ - public Builder addServiceIds(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureServiceIdsIsMutable(); - serviceIds_.add(value); - onChanged(); - return this; - } - - /** - * repeated string serviceIds = 1; - */ - public Builder addAllServiceIds(java.lang.Iterable values) { - ensureServiceIdsIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll(values, serviceIds_); - onChanged(); - return this; - } - - /** - * repeated string serviceIds = 1; - */ - public Builder clearServiceIds() { - serviceIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - onChanged(); - return this; - } - - /** - * repeated string serviceIds = 1; - */ - public Builder addServiceIdsBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - ensureServiceIdsIsMutable(); - serviceIds_.add(value); - onChanged(); - return this; - } - - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } - - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - // @@protoc_insertion_point(builder_scope:ServiceAppMappingRequest) + } + return this; } - // @@protoc_insertion_point(class_scope:ServiceAppMappingRequest) - private static final com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest(); - } + private int bitField0_; - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest getDefaultInstance() { - return DEFAULT_INSTANCE; - } + private com.google.protobuf.LazyStringList serviceIds_ = + com.google.protobuf.LazyStringArrayList.EMPTY; - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public ServiceAppMappingRequest parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new ServiceAppMappingRequest( - input, - extensionRegistry); - } - }; + private void ensureServiceIdsIsMutable() { + if (!((bitField0_ & 0x00000001) == 0x00000001)) { + serviceIds_ = new com.google.protobuf.LazyStringArrayList(serviceIds_); + bitField0_ |= 0x00000001; + } + } - public static com.google.protobuf.Parser parser() { - return PARSER; + /** repeated string serviceIds = 1; */ + public com.google.protobuf.ProtocolStringList getServiceIdsList() { + return serviceIds_.getUnmodifiableView(); } - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; + /** repeated string serviceIds = 1; */ + public int getServiceIdsCount() { + return serviceIds_.size(); } - public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest getDefaultInstanceForType() { - return DEFAULT_INSTANCE; + /** repeated string serviceIds = 1; */ + public java.lang.String getServiceIds(int index) { + return serviceIds_.get(index); } + /** repeated string serviceIds = 1; */ + public com.google.protobuf.ByteString getServiceIdsBytes(int index) { + return serviceIds_.getByteString(index); + } + + /** repeated string serviceIds = 1; */ + public Builder setServiceIds(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureServiceIdsIsMutable(); + serviceIds_.set(index, value); + onChanged(); + return this; + } + + /** repeated string serviceIds = 1; */ + public Builder addServiceIds(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureServiceIdsIsMutable(); + serviceIds_.add(value); + onChanged(); + return this; + } + + /** repeated string serviceIds = 1; */ + public Builder addAllServiceIds(java.lang.Iterable values) { + ensureServiceIdsIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, serviceIds_); + onChanged(); + return this; + } + + /** repeated string serviceIds = 1; */ + public Builder clearServiceIds() { + serviceIds_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + return this; + } + + /** repeated string serviceIds = 1; */ + public Builder addServiceIdsBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureServiceIdsIsMutable(); + serviceIds_.add(value); + onChanged(); + return this; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:ServiceAppMappingRequest) + } + + // @@protoc_insertion_point(class_scope:ServiceAppMappingRequest) + private static final com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest + DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = + new com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest(); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest + getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public ServiceAppMappingRequest parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new ServiceAppMappingRequest(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingRequest + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingRequestOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingRequestOrBuilder.java index 15dd3066a..a7582b9d4 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingRequestOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingRequestOrBuilder.java @@ -14,32 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface ServiceAppMappingRequestOrBuilder extends -// @@protoc_insertion_point(interface_extends:ServiceAppMappingRequest) - com.google.protobuf.MessageOrBuilder { +public interface ServiceAppMappingRequestOrBuilder + extends + // @@protoc_insertion_point(interface_extends:ServiceAppMappingRequest) + com.google.protobuf.MessageOrBuilder { - /** - * repeated string serviceIds = 1; - */ - java.util.List getServiceIdsList(); + /** repeated string serviceIds = 1; */ + java.util.List getServiceIdsList(); - /** - * repeated string serviceIds = 1; - */ - int getServiceIdsCount(); + /** repeated string serviceIds = 1; */ + int getServiceIdsCount(); - /** - * repeated string serviceIds = 1; - */ - java.lang.String getServiceIds(int index); + /** repeated string serviceIds = 1; */ + java.lang.String getServiceIds(int index); - /** - * repeated string serviceIds = 1; - */ - com.google.protobuf.ByteString getServiceIdsBytes(int index); + /** repeated string serviceIds = 1; */ + com.google.protobuf.ByteString getServiceIdsBytes(int index); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingResponse.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingResponse.java index 0194d582b..ae45afd8d 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingResponse.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingResponse.java @@ -14,870 +14,870 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code ServiceAppMappingResponse} - */ +/** Protobuf type {@code ServiceAppMappingResponse} */ public final class ServiceAppMappingResponse extends com.google.protobuf.GeneratedMessageV3 - implements - // @@protoc_insertion_point(message_implements:ServiceAppMappingResponse) - ServiceAppMappingResponseOrBuilder { - private static final long serialVersionUID = 0L; - - // Use ServiceAppMappingResponse.newBuilder() to construct. - private ServiceAppMappingResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private ServiceAppMappingResponse() { - statusCode_ = 0; - message_ = ""; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } + implements + // @@protoc_insertion_point(message_implements:ServiceAppMappingResponse) + ServiceAppMappingResponseOrBuilder { + private static final long serialVersionUID = 0L; + + // Use ServiceAppMappingResponse.newBuilder() to construct. + private ServiceAppMappingResponse(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private ServiceAppMappingResponse() { + statusCode_ = 0; + message_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private ServiceAppMappingResponse( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: + { + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + serviceAppMapping_ = + com.google.protobuf.MapField.newMapField( + ServiceAppMappingDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000001; + } + com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.AppList> + serviceAppMapping__ = + input.readMessage( + ServiceAppMappingDefaultEntryHolder.defaultEntry.getParserForType(), + extensionRegistry); + serviceAppMapping_ + .getMutableMap() + .put(serviceAppMapping__.getKey(), serviceAppMapping__.getValue()); + break; + } + case 16: + { + statusCode_ = input.readInt32(); + break; + } + case 26: + { + java.lang.String s = input.readStringRequireUtf8(); - private ServiceAppMappingResponse(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - serviceAppMapping_ = com.google.protobuf.MapField - .newMapField(ServiceAppMappingDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000001; - } - com.google.protobuf.MapEntry serviceAppMapping__ = input - .readMessage( - ServiceAppMappingDefaultEntryHolder.defaultEntry.getParserForType(), - extensionRegistry); - serviceAppMapping_.getMutableMap().put(serviceAppMapping__.getKey(), - serviceAppMapping__.getValue()); - break; - } - case 16: { - - statusCode_ = input.readInt32(); - break; - } - case 26: { - java.lang.String s = input.readStringRequireUtf8(); - - message_ = s; - break; - } - } + message_ = s; + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_ServiceAppMappingResponse_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 1: + return internalGetServiceAppMapping(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_ServiceAppMappingResponse_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse.class, + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse.Builder + .class); + } + + private int bitField0_; + public static final int SERVICEAPPMAPPING_FIELD_NUMBER = 1; + + private static final class ServiceAppMappingDefaultEntryHolder { + static final com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.AppList> + defaultEntry = + com.google.protobuf.MapEntry + . + newDefaultInstance( + com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, + "", + com.google.protobuf.WireFormat.FieldType.MESSAGE, + com.alipay.sofa.registry.common.model.client.pb.AppList + .getDefaultInstance()); + } + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.AppList> + serviceAppMapping_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.AppList> + internalGetServiceAppMapping() { + if (serviceAppMapping_ == null) { + return com.google.protobuf.MapField.emptyMapField( + ServiceAppMappingDefaultEntryHolder.defaultEntry); + } + return serviceAppMapping_; + } + + public int getServiceAppMappingCount() { + return internalGetServiceAppMapping().getMap().size(); + } + + /** map<string, .AppList> serviceAppMapping = 1; */ + public boolean containsServiceAppMapping(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetServiceAppMapping().getMap().containsKey(key); + } + + /** Use {@link #getServiceAppMappingMap()} instead. */ + @java.lang.Deprecated + public java.util.Map + getServiceAppMapping() { + return getServiceAppMappingMap(); + } + + /** map<string, .AppList> serviceAppMapping = 1; */ + public java.util.Map + getServiceAppMappingMap() { + return internalGetServiceAppMapping().getMap(); + } + + /** map<string, .AppList> serviceAppMapping = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrDefault( + java.lang.String key, com.alipay.sofa.registry.common.model.client.pb.AppList defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map map = + internalGetServiceAppMapping().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + + /** map<string, .AppList> serviceAppMapping = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map map = + internalGetServiceAppMapping().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } + + public static final int STATUSCODE_FIELD_NUMBER = 2; + private int statusCode_; + + /** int32 statusCode = 2; */ + public int getStatusCode() { + return statusCode_; + } + + public static final int MESSAGE_FIELD_NUMBER = 3; + private volatile java.lang.Object message_; + + /** string message = 3; */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + message_ = s; + return s; + } + } + + /** string message = 3; */ + public com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + com.google.protobuf.GeneratedMessageV3.serializeStringMapTo( + output, + internalGetServiceAppMapping(), + ServiceAppMappingDefaultEntryHolder.defaultEntry, + 1); + if (statusCode_ != 0) { + output.writeInt32(2, statusCode_); + } + if (!getMessageBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 3, message_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + for (java.util.Map.Entry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.AppList> + entry : internalGetServiceAppMapping().getMap().entrySet()) { + com.google.protobuf.MapEntry< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.AppList> + serviceAppMapping__ = + ServiceAppMappingDefaultEntryHolder.defaultEntry + .newBuilderForType() + .setKey(entry.getKey()) + .setValue(entry.getValue()) + .build(); + size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, serviceAppMapping__); + } + if (statusCode_ != 0) { + size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, statusCode_); + } + if (!getMessageBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, message_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj + instanceof com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse other = + (com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse) obj; + + boolean result = true; + result = result && internalGetServiceAppMapping().equals(other.internalGetServiceAppMapping()); + result = result && (getStatusCode() == other.getStatusCode()); + result = result && getMessage().equals(other.getMessage()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (!internalGetServiceAppMapping().getMap().isEmpty()) { + hash = (37 * hash) + SERVICEAPPMAPPING_FIELD_NUMBER; + hash = (53 * hash) + internalGetServiceAppMapping().hashCode(); + } + hash = (37 * hash) + STATUSCODE_FIELD_NUMBER; + hash = (53 * hash) + getStatusCode(); + hash = (37 * hash) + MESSAGE_FIELD_NUMBER; + hash = (53 * hash) + getMessage().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code ServiceAppMappingResponse} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:ServiceAppMappingResponse) + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponseOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_ServiceAppMappingResponse_descriptor; + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_ServiceAppMappingResponse_descriptor; } - @SuppressWarnings({ "rawtypes" }) + @SuppressWarnings({"rawtypes"}) protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 1: - return internalGetServiceAppMapping(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } + switch (number) { + case 1: + return internalGetServiceAppMapping(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_ServiceAppMappingResponse_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse.class, - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse.Builder.class); + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField(int number) { + switch (number) { + case 1: + return internalGetMutableServiceAppMapping(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - private int bitField0_; - public static final int SERVICEAPPMAPPING_FIELD_NUMBER = 1; - - private static final class ServiceAppMappingDefaultEntryHolder { - static final com.google.protobuf.MapEntry defaultEntry = com.google.protobuf.MapEntry - . newDefaultInstance( - com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_ServiceAppMappingResponse_ServiceAppMappingEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.MESSAGE, - com.alipay.sofa.registry.common.model.client.pb.AppList - .getDefaultInstance()); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_ServiceAppMappingResponse_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse.class, + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse.Builder + .class); } - private com.google.protobuf.MapField serviceAppMapping_; - - private com.google.protobuf.MapField internalGetServiceAppMapping() { - if (serviceAppMapping_ == null) { - return com.google.protobuf.MapField - .emptyMapField(ServiceAppMappingDefaultEntryHolder.defaultEntry); - } - return serviceAppMapping_; + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - public int getServiceAppMappingCount() { - return internalGetServiceAppMapping().getMap().size(); + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - - public boolean containsServiceAppMapping(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetServiceAppMapping().getMap().containsKey(key); + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - /** - * Use {@link #getServiceAppMappingMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getServiceAppMapping() { - return getServiceAppMappingMap(); - } + public Builder clear() { + super.clear(); + internalGetMutableServiceAppMapping().clear(); + statusCode_ = 0; - /** - * map<string, .AppList> serviceAppMapping = 1; - */ + message_ = ""; - public java.util.Map getServiceAppMappingMap() { - return internalGetServiceAppMapping().getMap(); + return this; } - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - - public com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.AppList defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetServiceAppMapping() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_ServiceAppMappingResponse_descriptor; } - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - - public com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetServiceAppMapping() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); + public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse + .getDefaultInstance(); } - public static final int STATUSCODE_FIELD_NUMBER = 2; - private int statusCode_; - - /** - * int32 statusCode = 2; - */ - public int getStatusCode() { - return statusCode_; + public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse build() { + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse result = + buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public static final int MESSAGE_FIELD_NUMBER = 3; - private volatile java.lang.Object message_; - - /** - * string message = 3; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - message_ = s; - return s; - } + public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse + buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse result = + new com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + result.serviceAppMapping_ = internalGetServiceAppMapping(); + result.serviceAppMapping_.makeImmutable(); + result.statusCode_ = statusCode_; + result.message_ = message_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } - /** - * string message = 3; - */ - public com.google.protobuf.ByteString getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + public Builder clone() { + return (Builder) super.clone(); } - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - com.google.protobuf.GeneratedMessageV3.serializeStringMapTo(output, - internalGetServiceAppMapping(), ServiceAppMappingDefaultEntryHolder.defaultEntry, 1); - if (statusCode_ != 0) { - output.writeInt32(2, statusCode_); - } - if (!getMessageBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 3, message_); - } - unknownFields.writeTo(output); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - for (java.util.Map.Entry entry : internalGetServiceAppMapping() - .getMap().entrySet()) { - com.google.protobuf.MapEntry serviceAppMapping__ = ServiceAppMappingDefaultEntryHolder.defaultEntry - .newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build(); - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(1, serviceAppMapping__); - } - if (statusCode_ != 0) { - size += com.google.protobuf.CodedOutputStream.computeInt32Size(2, statusCode_); - } - if (!getMessageBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, message_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse other = (com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse) obj; - - boolean result = true; - result = result - && internalGetServiceAppMapping().equals(other.internalGetServiceAppMapping()); - result = result && (getStatusCode() == other.getStatusCode()); - result = result && getMessage().equals(other.getMessage()); - result = result && unknownFields.equals(other.unknownFields); - return result; + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (!internalGetServiceAppMapping().getMap().isEmpty()) { - hash = (37 * hash) + SERVICEAPPMAPPING_FIELD_NUMBER; - hash = (53 * hash) + internalGetServiceAppMapping().hashCode(); - } - hash = (37 * hash) + STATUSCODE_FIELD_NUMBER; - hash = (53 * hash) + getStatusCode(); - hash = (37 * hash) + MESSAGE_FIELD_NUMBER; - hash = (53 * hash) + getMessage().hashCode(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other + instanceof com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse) other); + } else { + super.mergeFrom(other); + return this; + } } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse + .getDefaultInstance()) return this; + internalGetMutableServiceAppMapping().mergeFrom(other.internalGetServiceAppMapping()); + if (other.getStatusCode() != 0) { + setStatusCode(other.getStatusCode()); + } + if (!other.getMessage().isEmpty()) { + message_ = other.message_; + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parsedMessage = + null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.AppList> + serviceAppMapping_; + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.AppList> + internalGetServiceAppMapping() { + if (serviceAppMapping_ == null) { + return com.google.protobuf.MapField.emptyMapField( + ServiceAppMappingDefaultEntryHolder.defaultEntry); + } + return serviceAppMapping_; + } + + private com.google.protobuf.MapField< + java.lang.String, com.alipay.sofa.registry.common.model.client.pb.AppList> + internalGetMutableServiceAppMapping() { + onChanged(); + ; + if (serviceAppMapping_ == null) { + serviceAppMapping_ = + com.google.protobuf.MapField.newMapField( + ServiceAppMappingDefaultEntryHolder.defaultEntry); + } + if (!serviceAppMapping_.isMutable()) { + serviceAppMapping_ = serviceAppMapping_.copy(); + } + return serviceAppMapping_; } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public int getServiceAppMappingCount() { + return internalGetServiceAppMapping().getMap().size(); } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + /** map<string, .AppList> serviceAppMapping = 1; */ + public boolean containsServiceAppMapping(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + return internalGetServiceAppMapping().getMap().containsKey(key); } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + /** Use {@link #getServiceAppMappingMap()} instead. */ + @java.lang.Deprecated + public java.util.Map + getServiceAppMapping() { + return getServiceAppMappingMap(); + } + + /** map<string, .AppList> serviceAppMapping = 1; */ + public java.util.Map + getServiceAppMappingMap() { + return internalGetServiceAppMapping().getMap(); + } + + /** map<string, .AppList> serviceAppMapping = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrDefault( + java.lang.String key, + com.alipay.sofa.registry.common.model.client.pb.AppList defaultValue) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map map = + internalGetServiceAppMapping().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + + /** map<string, .AppList> serviceAppMapping = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrThrow( + java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + java.util.Map map = + internalGetServiceAppMapping().getMap(); + if (!map.containsKey(key)) { + throw new java.lang.IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearServiceAppMapping() { + internalGetMutableServiceAppMapping().getMutableMap().clear(); + return this; + } + + /** map<string, .AppList> serviceAppMapping = 1; */ + public Builder removeServiceAppMapping(java.lang.String key) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableServiceAppMapping().getMutableMap().remove(key); + return this; + } + + /** Use alternate mutation accessors instead. */ + @java.lang.Deprecated + public java.util.Map + getMutableServiceAppMapping() { + return internalGetMutableServiceAppMapping().getMutableMap(); } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + /** map<string, .AppList> serviceAppMapping = 1; */ + public Builder putServiceAppMapping( + java.lang.String key, com.alipay.sofa.registry.common.model.client.pb.AppList value) { + if (key == null) { + throw new java.lang.NullPointerException(); + } + if (value == null) { + throw new java.lang.NullPointerException(); + } + internalGetMutableServiceAppMapping().getMutableMap().put(key, value); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + /** map<string, .AppList> serviceAppMapping = 1; */ + public Builder putAllServiceAppMapping( + java.util.Map + values) { + internalGetMutableServiceAppMapping().getMutableMap().putAll(values); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); - } + private int statusCode_; - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + /** int32 statusCode = 2; */ + public int getStatusCode() { + return statusCode_; } - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + /** int32 statusCode = 2; */ + public Builder setStatusCode(int value) { - public Builder newBuilderForType() { - return newBuilder(); + statusCode_ = value; + onChanged(); + return this; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } + /** int32 statusCode = 2; */ + public Builder clearStatusCode() { - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + statusCode_ = 0; + onChanged(); + return this; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } + private java.lang.Object message_ = ""; - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + /** string message = 3; */ + public java.lang.String getMessage() { + java.lang.Object ref = message_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + message_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string message = 3; */ + public com.google.protobuf.ByteString getMessageBytes() { + java.lang.Object ref = message_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + message_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - /** - * Protobuf type {@code ServiceAppMappingResponse} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:ServiceAppMappingResponse) - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponseOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_ServiceAppMappingResponse_descriptor; - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMapField(int number) { - switch (number) { - case 1: - return internalGetServiceAppMapping(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - @SuppressWarnings({ "rawtypes" }) - protected com.google.protobuf.MapField internalGetMutableMapField(int number) { - switch (number) { - case 1: - return internalGetMutableServiceAppMapping(); - default: - throw new RuntimeException("Invalid map field number: " + number); - } - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_ServiceAppMappingResponse_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse.class, - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - internalGetMutableServiceAppMapping().clear(); - statusCode_ = 0; - - message_ = ""; - - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_ServiceAppMappingResponse_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse build() { - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse result = new com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse( - this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - result.serviceAppMapping_ = internalGetServiceAppMapping(); - result.serviceAppMapping_.makeImmutable(); - result.statusCode_ = statusCode_; - result.message_ = message_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse - .getDefaultInstance()) - return this; - internalGetMutableServiceAppMapping().mergeFrom(other.internalGetServiceAppMapping()); - if (other.getStatusCode() != 0) { - setStatusCode(other.getStatusCode()); - } - if (!other.getMessage().isEmpty()) { - message_ = other.message_; - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private com.google.protobuf.MapField serviceAppMapping_; - - private com.google.protobuf.MapField internalGetServiceAppMapping() { - if (serviceAppMapping_ == null) { - return com.google.protobuf.MapField - .emptyMapField(ServiceAppMappingDefaultEntryHolder.defaultEntry); - } - return serviceAppMapping_; - } - - private com.google.protobuf.MapField internalGetMutableServiceAppMapping() { - onChanged(); - ; - if (serviceAppMapping_ == null) { - serviceAppMapping_ = com.google.protobuf.MapField - .newMapField(ServiceAppMappingDefaultEntryHolder.defaultEntry); - } - if (!serviceAppMapping_.isMutable()) { - serviceAppMapping_ = serviceAppMapping_.copy(); - } - return serviceAppMapping_; - } - - public int getServiceAppMappingCount() { - return internalGetServiceAppMapping().getMap().size(); - } - - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - - public boolean containsServiceAppMapping(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - return internalGetServiceAppMapping().getMap().containsKey(key); - } - - /** - * Use {@link #getServiceAppMappingMap()} instead. - */ - @java.lang.Deprecated - public java.util.Map getServiceAppMapping() { - return getServiceAppMappingMap(); - } - - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - - public java.util.Map getServiceAppMappingMap() { - return internalGetServiceAppMapping().getMap(); - } - - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - - public com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.AppList defaultValue) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetServiceAppMapping() - .getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - - public com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrThrow(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - java.util.Map map = internalGetServiceAppMapping() - .getMap(); - if (!map.containsKey(key)) { - throw new java.lang.IllegalArgumentException(); - } - return map.get(key); - } + /** string message = 3; */ + public Builder setMessage(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - public Builder clearServiceAppMapping() { - internalGetMutableServiceAppMapping().getMutableMap().clear(); - return this; - } - - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - - public Builder removeServiceAppMapping(java.lang.String key) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableServiceAppMapping().getMutableMap().remove(key); - return this; - } - - /** - * Use alternate mutation accessors instead. - */ - @java.lang.Deprecated - public java.util.Map getMutableServiceAppMapping() { - return internalGetMutableServiceAppMapping().getMutableMap(); - } - - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - public Builder putServiceAppMapping(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.AppList value) { - if (key == null) { - throw new java.lang.NullPointerException(); - } - if (value == null) { - throw new java.lang.NullPointerException(); - } - internalGetMutableServiceAppMapping().getMutableMap().put(key, value); - return this; - } - - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - - public Builder putAllServiceAppMapping(java.util.Map values) { - internalGetMutableServiceAppMapping().getMutableMap().putAll(values); - return this; - } - - private int statusCode_; - - /** - * int32 statusCode = 2; - */ - public int getStatusCode() { - return statusCode_; - } - - /** - * int32 statusCode = 2; - */ - public Builder setStatusCode(int value) { - - statusCode_ = value; - onChanged(); - return this; - } - - /** - * int32 statusCode = 2; - */ - public Builder clearStatusCode() { + message_ = value; + onChanged(); + return this; + } - statusCode_ = 0; - onChanged(); - return this; - } + /** string message = 3; */ + public Builder clearMessage() { - private java.lang.Object message_ = ""; - - /** - * string message = 3; - */ - public java.lang.String getMessage() { - java.lang.Object ref = message_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - message_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + message_ = getDefaultInstance().getMessage(); + onChanged(); + return this; + } - /** - * string message = 3; - */ - public com.google.protobuf.ByteString getMessageBytes() { - java.lang.Object ref = message_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - message_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string message = 3; */ + public Builder setMessageBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string message = 3; - */ - public Builder setMessage(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + message_ = value; + onChanged(); + return this; + } - message_ = value; - onChanged(); - return this; - } + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } - /** - * string message = 3; - */ - public Builder clearMessage() { + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - message_ = getDefaultInstance().getMessage(); - onChanged(); - return this; - } + // @@protoc_insertion_point(builder_scope:ServiceAppMappingResponse) + } - /** - * string message = 3; - */ - public Builder setMessageBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + // @@protoc_insertion_point(class_scope:ServiceAppMappingResponse) + private static final com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse + DEFAULT_INSTANCE; - message_ = value; - onChanged(); - return this; - } + static { + DEFAULT_INSTANCE = + new com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse(); + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse + getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public ServiceAppMappingResponse parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new ServiceAppMappingResponse(input, extensionRegistry); } + }; - // @@protoc_insertion_point(builder_scope:ServiceAppMappingResponse) - } - - // @@protoc_insertion_point(class_scope:ServiceAppMappingResponse) - private static final com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public ServiceAppMappingResponse parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new ServiceAppMappingResponse( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.ServiceAppMappingResponse + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingResponseOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingResponseOrBuilder.java index 304783bb7..c839326a0 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingResponseOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/ServiceAppMappingResponseOrBuilder.java @@ -14,61 +14,42 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface ServiceAppMappingResponseOrBuilder extends -// @@protoc_insertion_point(interface_extends:ServiceAppMappingResponse) - com.google.protobuf.MessageOrBuilder { - - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - int getServiceAppMappingCount(); - - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - boolean containsServiceAppMapping(java.lang.String key); +public interface ServiceAppMappingResponseOrBuilder + extends + // @@protoc_insertion_point(interface_extends:ServiceAppMappingResponse) + com.google.protobuf.MessageOrBuilder { - /** - * Use {@link #getServiceAppMappingMap()} instead. - */ - @java.lang.Deprecated - java.util.Map getServiceAppMapping(); + /** map<string, .AppList> serviceAppMapping = 1; */ + int getServiceAppMappingCount(); - /** - * map<string, .AppList> serviceAppMapping = 1; - */ - java.util.Map getServiceAppMappingMap(); + /** map<string, .AppList> serviceAppMapping = 1; */ + boolean containsServiceAppMapping(java.lang.String key); - /** - * map<string, .AppList> serviceAppMapping = 1; - */ + /** Use {@link #getServiceAppMappingMap()} instead. */ + @java.lang.Deprecated + java.util.Map + getServiceAppMapping(); - com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrDefault(java.lang.String key, - com.alipay.sofa.registry.common.model.client.pb.AppList defaultValue); + /** map<string, .AppList> serviceAppMapping = 1; */ + java.util.Map + getServiceAppMappingMap(); - /** - * map<string, .AppList> serviceAppMapping = 1; - */ + /** map<string, .AppList> serviceAppMapping = 1; */ + com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrDefault( + java.lang.String key, com.alipay.sofa.registry.common.model.client.pb.AppList defaultValue); - com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrThrow(java.lang.String key); + /** map<string, .AppList> serviceAppMapping = 1; */ + com.alipay.sofa.registry.common.model.client.pb.AppList getServiceAppMappingOrThrow( + java.lang.String key); - /** - * int32 statusCode = 2; - */ - int getStatusCode(); + /** int32 statusCode = 2; */ + int getStatusCode(); - /** - * string message = 3; - */ - java.lang.String getMessage(); + /** string message = 3; */ + java.lang.String getMessage(); - /** - * string message = 3; - */ - com.google.protobuf.ByteString getMessageBytes(); + /** string message = 3; */ + com.google.protobuf.ByteString getMessageBytes(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/StringList.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/StringList.java index 2f7f3bba2..50313847b 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/StringList.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/StringList.java @@ -14,574 +14,553 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code StringList} - */ -public final class StringList extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:StringList) - StringListOrBuilder { - private static final long serialVersionUID = 0L; - - // Use StringList.newBuilder() to construct. - private StringList(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private StringList() { - values_ = com.google.protobuf.LazyStringArrayList.EMPTY; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } - - private StringList(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - values_ = new com.google.protobuf.LazyStringArrayList(); - mutable_bitField0_ |= 0x00000001; - } - values_.add(s); - break; - } - } +/** Protobuf type {@code StringList} */ +public final class StringList extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:StringList) + StringListOrBuilder { + private static final long serialVersionUID = 0L; + + // Use StringList.newBuilder() to construct. + private StringList(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private StringList() { + values_ = com.google.protobuf.LazyStringArrayList.EMPTY; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private StringList( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { - values_ = values_.getUnmodifiableView(); + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + values_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000001; + } + values_.add(s); + break; } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { + values_ = values_.getUnmodifiableView(); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_StringList_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_StringList_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.StringList.class, + com.alipay.sofa.registry.common.model.client.pb.StringList.Builder.class); + } + + public static final int VALUES_FIELD_NUMBER = 1; + private com.google.protobuf.LazyStringList values_; + + /** repeated string values = 1; */ + public com.google.protobuf.ProtocolStringList getValuesList() { + return values_; + } + + /** repeated string values = 1; */ + public int getValuesCount() { + return values_.size(); + } + + /** repeated string values = 1; */ + public java.lang.String getValues(int index) { + return values_.get(index); + } + + /** repeated string values = 1; */ + public com.google.protobuf.ByteString getValuesBytes(int index) { + return values_.getByteString(index); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + for (int i = 0; i < values_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, values_.getRaw(i)); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + { + int dataSize = 0; + for (int i = 0; i < values_.size(); i++) { + dataSize += computeStringSizeNoTag(values_.getRaw(i)); + } + size += dataSize; + size += 1 * getValuesList().size(); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.StringList)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.StringList other = + (com.alipay.sofa.registry.common.model.client.pb.StringList) obj; + + boolean result = true; + result = result && getValuesList().equals(other.getValuesList()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (getValuesCount() > 0) { + hash = (37 * hash) + VALUES_FIELD_NUMBER; + hash = (53 * hash) + getValuesList().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom(byte[] data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseDelimitedFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.StringList prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code StringList} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:StringList) + com.alipay.sofa.registry.common.model.client.pb.StringListOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_StringList_descriptor; + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_StringList_descriptor; } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_StringList_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.StringList.class, - com.alipay.sofa.registry.common.model.client.pb.StringList.Builder.class); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_StringList_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.StringList.class, + com.alipay.sofa.registry.common.model.client.pb.StringList.Builder.class); } - public static final int VALUES_FIELD_NUMBER = 1; - private com.google.protobuf.LazyStringList values_; - - /** - * repeated string values = 1; - */ - public com.google.protobuf.ProtocolStringList getValuesList() { - return values_; + // Construct using com.alipay.sofa.registry.common.model.client.pb.StringList.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - /** - * repeated string values = 1; - */ - public int getValuesCount() { - return values_.size(); + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - /** - * repeated string values = 1; - */ - public java.lang.String getValues(int index) { - return values_.get(index); + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - /** - * repeated string values = 1; - */ - public com.google.protobuf.ByteString getValuesBytes(int index) { - return values_.getByteString(index); + public Builder clear() { + super.clear(); + values_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + return this; } - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb + .internal_static_StringList_descriptor; } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - for (int i = 0; i < values_.size(); i++) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, values_.getRaw(i)); - } - unknownFields.writeTo(output); + public com.alipay.sofa.registry.common.model.client.pb.StringList getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.StringList.getDefaultInstance(); } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - { - int dataSize = 0; - for (int i = 0; i < values_.size(); i++) { - dataSize += computeStringSizeNoTag(values_.getRaw(i)); - } - size += dataSize; - size += 1 * getValuesList().size(); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + public com.alipay.sofa.registry.common.model.client.pb.StringList build() { + com.alipay.sofa.registry.common.model.client.pb.StringList result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.StringList)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.StringList other = (com.alipay.sofa.registry.common.model.client.pb.StringList) obj; - - boolean result = true; - result = result && getValuesList().equals(other.getValuesList()); - result = result && unknownFields.equals(other.unknownFields); - return result; + public com.alipay.sofa.registry.common.model.client.pb.StringList buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.StringList result = + new com.alipay.sofa.registry.common.model.client.pb.StringList(this); + int from_bitField0_ = bitField0_; + if (((bitField0_ & 0x00000001) == 0x00000001)) { + values_ = values_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000001); + } + result.values_ = values_; + onBuilt(); + return result; } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (getValuesCount() > 0) { - hash = (37 * hash) + VALUES_FIELD_NUMBER; - hash = (53 * hash) + getValuesList().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + public Builder clone() { + return (Builder) super.clone(); } - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.StringList) { + return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.StringList) other); + } else { + super.mergeFrom(other); + return this; + } } - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.StringList other) { + if (other == com.alipay.sofa.registry.common.model.client.pb.StringList.getDefaultInstance()) + return this; + if (!other.values_.isEmpty()) { + if (values_.isEmpty()) { + values_ = other.values_; + bitField0_ = (bitField0_ & ~0x00000001); + } else { + ensureValuesIsMutable(); + values_.addAll(other.values_); + } + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public final boolean isInitialized() { + return true; } - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.StringList parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.StringList) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); - } + private int bitField0_; - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); - } + private com.google.protobuf.LazyStringList values_ = + com.google.protobuf.LazyStringArrayList.EMPTY; - public static com.alipay.sofa.registry.common.model.client.pb.StringList parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + private void ensureValuesIsMutable() { + if (!((bitField0_ & 0x00000001) == 0x00000001)) { + values_ = new com.google.protobuf.LazyStringArrayList(values_); + bitField0_ |= 0x00000001; + } } - public Builder newBuilderForType() { - return newBuilder(); + /** repeated string values = 1; */ + public com.google.protobuf.ProtocolStringList getValuesList() { + return values_.getUnmodifiableView(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); + /** repeated string values = 1; */ + public int getValuesCount() { + return values_.size(); } - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.StringList prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + /** repeated string values = 1; */ + public java.lang.String getValues(int index) { + return values_.get(index); } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + /** repeated string values = 1; */ + public com.google.protobuf.ByteString getValuesBytes(int index) { + return values_.getByteString(index); } - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + /** repeated string values = 1; */ + public Builder setValues(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureValuesIsMutable(); + values_.set(index, value); + onChanged(); + return this; } - /** - * Protobuf type {@code StringList} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:StringList) - com.alipay.sofa.registry.common.model.client.pb.StringListOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_StringList_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_StringList_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.StringList.class, - com.alipay.sofa.registry.common.model.client.pb.StringList.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.StringList.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - values_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.AppDiscoveryMetaPb.internal_static_StringList_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.StringList getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.StringList.getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.StringList build() { - com.alipay.sofa.registry.common.model.client.pb.StringList result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.StringList buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.StringList result = new com.alipay.sofa.registry.common.model.client.pb.StringList( - this); - int from_bitField0_ = bitField0_; - if (((bitField0_ & 0x00000001) == 0x00000001)) { - values_ = values_.getUnmodifiableView(); - bitField0_ = (bitField0_ & ~0x00000001); - } - result.values_ = values_; - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.StringList) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.StringList) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.StringList other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.StringList - .getDefaultInstance()) - return this; - if (!other.values_.isEmpty()) { - if (values_.isEmpty()) { - values_ = other.values_; - bitField0_ = (bitField0_ & ~0x00000001); - } else { - ensureValuesIsMutable(); - values_.addAll(other.values_); - } - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.StringList parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.StringList) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private com.google.protobuf.LazyStringList values_ = com.google.protobuf.LazyStringArrayList.EMPTY; - - private void ensureValuesIsMutable() { - if (!((bitField0_ & 0x00000001) == 0x00000001)) { - values_ = new com.google.protobuf.LazyStringArrayList(values_); - bitField0_ |= 0x00000001; - } - } - - /** - * repeated string values = 1; - */ - public com.google.protobuf.ProtocolStringList getValuesList() { - return values_.getUnmodifiableView(); - } + /** repeated string values = 1; */ + public Builder addValues(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureValuesIsMutable(); + values_.add(value); + onChanged(); + return this; + } - /** - * repeated string values = 1; - */ - public int getValuesCount() { - return values_.size(); - } + /** repeated string values = 1; */ + public Builder addAllValues(java.lang.Iterable values) { + ensureValuesIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, values_); + onChanged(); + return this; + } - /** - * repeated string values = 1; - */ - public java.lang.String getValues(int index) { - return values_.get(index); - } + /** repeated string values = 1; */ + public Builder clearValues() { + values_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000001); + onChanged(); + return this; + } - /** - * repeated string values = 1; - */ - public com.google.protobuf.ByteString getValuesBytes(int index) { - return values_.getByteString(index); - } + /** repeated string values = 1; */ + public Builder addValuesBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureValuesIsMutable(); + values_.add(value); + onChanged(); + return this; + } - /** - * repeated string values = 1; - */ - public Builder setValues(int index, java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureValuesIsMutable(); - values_.set(index, value); - onChanged(); - return this; - } + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } - /** - * repeated string values = 1; - */ - public Builder addValues(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureValuesIsMutable(); - values_.add(value); - onChanged(); - return this; - } + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - /** - * repeated string values = 1; - */ - public Builder addAllValues(java.lang.Iterable values) { - ensureValuesIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll(values, values_); - onChanged(); - return this; - } + // @@protoc_insertion_point(builder_scope:StringList) + } - /** - * repeated string values = 1; - */ - public Builder clearValues() { - values_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000001); - onChanged(); - return this; - } + // @@protoc_insertion_point(class_scope:StringList) + private static final com.alipay.sofa.registry.common.model.client.pb.StringList DEFAULT_INSTANCE; - /** - * repeated string values = 1; - */ - public Builder addValuesBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - ensureValuesIsMutable(); - values_.add(value); - onChanged(); - return this; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.StringList(); + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + public static com.alipay.sofa.registry.common.model.client.pb.StringList getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public StringList parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new StringList(input, extensionRegistry); } + }; - // @@protoc_insertion_point(builder_scope:StringList) - } - - // @@protoc_insertion_point(class_scope:StringList) - private static final com.alipay.sofa.registry.common.model.client.pb.StringList DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.StringList(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.StringList getDefaultInstance() { - return DEFAULT_INSTANCE; - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public StringList parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new StringList( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public com.alipay.sofa.registry.common.model.client.pb.StringList getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.StringList getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/StringListOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/StringListOrBuilder.java index d9f8260bf..c2ba86069 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/StringListOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/StringListOrBuilder.java @@ -14,32 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: AppDiscoveryMetaPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface StringListOrBuilder extends -// @@protoc_insertion_point(interface_extends:StringList) - com.google.protobuf.MessageOrBuilder { +public interface StringListOrBuilder + extends + // @@protoc_insertion_point(interface_extends:StringList) + com.google.protobuf.MessageOrBuilder { - /** - * repeated string values = 1; - */ - java.util.List getValuesList(); + /** repeated string values = 1; */ + java.util.List getValuesList(); - /** - * repeated string values = 1; - */ - int getValuesCount(); + /** repeated string values = 1; */ + int getValuesCount(); - /** - * repeated string values = 1; - */ - java.lang.String getValues(int index); + /** repeated string values = 1; */ + java.lang.String getValues(int index); - /** - * repeated string values = 1; - */ - com.google.protobuf.ByteString getValuesBytes(int index); + /** repeated string values = 1; */ + com.google.protobuf.ByteString getValuesBytes(int index); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPb.java index f1dda707b..314855181 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPb.java @@ -14,712 +14,714 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: SubscriberRegisterPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code SubscriberRegisterPb} - */ -public final class SubscriberRegisterPb extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:SubscriberRegisterPb) - SubscriberRegisterPbOrBuilder { - private static final long serialVersionUID = 0L; - - // Use SubscriberRegisterPb.newBuilder() to construct. - private SubscriberRegisterPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private SubscriberRegisterPb() { - scope_ = ""; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } +/** Protobuf type {@code SubscriberRegisterPb} */ +public final class SubscriberRegisterPb extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:SubscriberRegisterPb) + SubscriberRegisterPbOrBuilder { + private static final long serialVersionUID = 0L; + + // Use SubscriberRegisterPb.newBuilder() to construct. + private SubscriberRegisterPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private SubscriberRegisterPb() { + scope_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private SubscriberRegisterPb( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); - private SubscriberRegisterPb(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - - scope_ = s; - break; - } - case 18: { - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder subBuilder = null; - if (baseRegister_ != null) { - subBuilder = baseRegister_.toBuilder(); - } - baseRegister_ = input - .readMessage( - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .parser(), extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(baseRegister_); - baseRegister_ = subBuilder.buildPartial(); - } - - break; - } - } + scope_ = s; + break; + } + case 18: + { + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder subBuilder = + null; + if (baseRegister_ != null) { + subBuilder = baseRegister_.toBuilder(); + } + baseRegister_ = + input.readMessage( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.parser(), + extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(baseRegister_); + baseRegister_ = subBuilder.buildPartial(); + } + + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOuterClass + .internal_static_SubscriberRegisterPb_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOuterClass + .internal_static_SubscriberRegisterPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb.class, + com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb.Builder.class); + } + + public static final int SCOPE_FIELD_NUMBER = 1; + private volatile java.lang.Object scope_; + + /** string scope = 1; */ + public java.lang.String getScope() { + java.lang.Object ref = scope_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + scope_ = s; + return s; + } + } + + /** string scope = 1; */ + public com.google.protobuf.ByteString getScopeBytes() { + java.lang.Object ref = scope_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + scope_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int BASEREGISTER_FIELD_NUMBER = 2; + private com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb baseRegister_; + + /** .BaseRegisterPb baseRegister = 2; */ + public boolean hasBaseRegister() { + return baseRegister_ != null; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getBaseRegister() { + return baseRegister_ == null + ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.getDefaultInstance() + : baseRegister_; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder + getBaseRegisterOrBuilder() { + return getBaseRegister(); + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getScopeBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, scope_); + } + if (baseRegister_ != null) { + output.writeMessage(2, getBaseRegister()); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!getScopeBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, scope_); + } + if (baseRegister_ != null) { + size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getBaseRegister()); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb other = + (com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb) obj; + + boolean result = true; + result = result && getScope().equals(other.getScope()); + result = result && (hasBaseRegister() == other.hasBaseRegister()); + if (hasBaseRegister()) { + result = result && getBaseRegister().equals(other.getBaseRegister()); + } + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + SCOPE_FIELD_NUMBER; + hash = (53 * hash) + getScope().hashCode(); + if (hasBaseRegister()) { + hash = (37 * hash) + BASEREGISTER_FIELD_NUMBER; + hash = (53 * hash) + getBaseRegister().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code SubscriberRegisterPb} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:SubscriberRegisterPb) + com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOuterClass.internal_static_SubscriberRegisterPb_descriptor; + return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOuterClass + .internal_static_SubscriberRegisterPb_descriptor; } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOuterClass.internal_static_SubscriberRegisterPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb.class, - com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb.Builder.class); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOuterClass + .internal_static_SubscriberRegisterPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb.class, + com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb.Builder.class); } - public static final int SCOPE_FIELD_NUMBER = 1; - private volatile java.lang.Object scope_; - - /** - * string scope = 1; - */ - public java.lang.String getScope() { - java.lang.Object ref = scope_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - scope_ = s; - return s; - } + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - /** - * string scope = 1; - */ - public com.google.protobuf.ByteString getScopeBytes() { - java.lang.Object ref = scope_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - scope_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - public static final int BASEREGISTER_FIELD_NUMBER = 2; - private com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb baseRegister_; - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public boolean hasBaseRegister() { - return baseRegister_ != null; + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - /** - * .BaseRegisterPb baseRegister = 2; - */ - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getBaseRegister() { - return baseRegister_ == null ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .getDefaultInstance() : baseRegister_; - } + public Builder clear() { + super.clear(); + scope_ = ""; - /** - * .BaseRegisterPb baseRegister = 2; - */ - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder getBaseRegisterOrBuilder() { - return getBaseRegister(); + if (baseRegisterBuilder_ == null) { + baseRegister_ = null; + } else { + baseRegister_ = null; + baseRegisterBuilder_ = null; + } + return this; } - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; - - memoizedIsInitialized = 1; - return true; + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOuterClass + .internal_static_SubscriberRegisterPb_descriptor; } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (!getScopeBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, scope_); - } - if (baseRegister_ != null) { - output.writeMessage(2, getBaseRegister()); - } - unknownFields.writeTo(output); + public com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb + .getDefaultInstance(); } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - if (!getScopeBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, scope_); - } - if (baseRegister_ != null) { - size += com.google.protobuf.CodedOutputStream.computeMessageSize(2, getBaseRegister()); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + public com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb build() { + com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb other = (com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb) obj; - - boolean result = true; - result = result && getScope().equals(other.getScope()); - result = result && (hasBaseRegister() == other.hasBaseRegister()); - if (hasBaseRegister()) { - result = result && getBaseRegister().equals(other.getBaseRegister()); - } - result = result && unknownFields.equals(other.unknownFields); - return result; + public com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb result = + new com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb(this); + result.scope_ = scope_; + if (baseRegisterBuilder_ == null) { + result.baseRegister_ = baseRegister_; + } else { + result.baseRegister_ = baseRegisterBuilder_.build(); + } + onBuilt(); + return result; } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + SCOPE_FIELD_NUMBER; - hash = (53 * hash) + getScope().hashCode(); - if (hasBaseRegister()) { - hash = (37 * hash) + BASEREGISTER_FIELD_NUMBER; - hash = (53 * hash) + getBaseRegister().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + public Builder clone() { + return (Builder) super.clone(); } - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb) other); + } else { + super.mergeFrom(other); + return this; + } } - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb + .getDefaultInstance()) return this; + if (!other.getScope().isEmpty()) { + scope_ = other.scope_; + onChanged(); + } + if (other.hasBaseRegister()) { + mergeBaseRegister(other.getBaseRegister()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public final boolean isInitialized() { + return true; } - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); - } + private java.lang.Object scope_ = ""; - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + /** string scope = 1; */ + public java.lang.String getScope() { + java.lang.Object ref = scope_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + scope_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string scope = 1; */ + public com.google.protobuf.ByteString getScopeBytes() { + java.lang.Object ref = scope_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + scope_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + /** string scope = 1; */ + public Builder setScope(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - public Builder newBuilderForType() { - return newBuilder(); + scope_ = value; + onChanged(); + return this; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } + /** string scope = 1; */ + public Builder clearScope() { - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + scope_ = getDefaultInstance().getScope(); + onChanged(); + return this; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } + /** string scope = 1; */ + public Builder setScopeBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + scope_ = value; + onChanged(); + return this; } - /** - * Protobuf type {@code SubscriberRegisterPb} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:SubscriberRegisterPb) - com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOuterClass.internal_static_SubscriberRegisterPb_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOuterClass.internal_static_SubscriberRegisterPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb.class, - com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - scope_ = ""; - - if (baseRegisterBuilder_ == null) { - baseRegister_ = null; - } else { - baseRegister_ = null; - baseRegisterBuilder_ = null; - } - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPbOuterClass.internal_static_SubscriberRegisterPb_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb build() { - com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb result = new com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb( - this); - result.scope_ = scope_; - if (baseRegisterBuilder_ == null) { - result.baseRegister_ = baseRegister_; - } else { - result.baseRegister_ = baseRegisterBuilder_.build(); - } - onBuilt(); - return result; - } - - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } + private com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb baseRegister_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder> + baseRegisterBuilder_; - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb - .getDefaultInstance()) - return this; - if (!other.getScope().isEmpty()) { - scope_ = other.scope_; - onChanged(); - } - if (other.hasBaseRegister()) { - mergeBaseRegister(other.getBaseRegister()); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private java.lang.Object scope_ = ""; - - /** - * string scope = 1; - */ - public java.lang.String getScope() { - java.lang.Object ref = scope_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - scope_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } - - /** - * string scope = 1; - */ - public com.google.protobuf.ByteString getScopeBytes() { - java.lang.Object ref = scope_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - scope_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - /** - * string scope = 1; - */ - public Builder setScope(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - - scope_ = value; - onChanged(); - return this; - } - - /** - * string scope = 1; - */ - public Builder clearScope() { - - scope_ = getDefaultInstance().getScope(); - onChanged(); - return this; - } - - /** - * string scope = 1; - */ - public Builder setScopeBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - scope_ = value; - onChanged(); - return this; - } - - private com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb baseRegister_ = null; - private com.google.protobuf.SingleFieldBuilderV3 baseRegisterBuilder_; - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public boolean hasBaseRegister() { - return baseRegisterBuilder_ != null || baseRegister_ != null; - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getBaseRegister() { - if (baseRegisterBuilder_ == null) { - return baseRegister_ == null ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .getDefaultInstance() : baseRegister_; - } else { - return baseRegisterBuilder_.getMessage(); - } - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public Builder setBaseRegister(com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb value) { - if (baseRegisterBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - baseRegister_ = value; - onChanged(); - } else { - baseRegisterBuilder_.setMessage(value); - } - - return this; - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public Builder setBaseRegister(com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder builderForValue) { - if (baseRegisterBuilder_ == null) { - baseRegister_ = builderForValue.build(); - onChanged(); - } else { - baseRegisterBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public Builder mergeBaseRegister(com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb value) { - if (baseRegisterBuilder_ == null) { - if (baseRegister_ != null) { - baseRegister_ = com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .newBuilder(baseRegister_).mergeFrom(value).buildPartial(); - } else { - baseRegister_ = value; - } - onChanged(); - } else { - baseRegisterBuilder_.mergeFrom(value); - } - - return this; - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public Builder clearBaseRegister() { - if (baseRegisterBuilder_ == null) { - baseRegister_ = null; - onChanged(); - } else { - baseRegister_ = null; - baseRegisterBuilder_ = null; - } - - return this; - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder getBaseRegisterBuilder() { - - onChanged(); - return getBaseRegisterFieldBuilder().getBuilder(); - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder getBaseRegisterOrBuilder() { - if (baseRegisterBuilder_ != null) { - return baseRegisterBuilder_.getMessageOrBuilder(); - } else { - return baseRegister_ == null ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb - .getDefaultInstance() : baseRegister_; - } - } - - /** - * .BaseRegisterPb baseRegister = 2; - */ - private com.google.protobuf.SingleFieldBuilderV3 getBaseRegisterFieldBuilder() { - if (baseRegisterBuilder_ == null) { - baseRegisterBuilder_ = new com.google.protobuf.SingleFieldBuilderV3( - getBaseRegister(), getParentForChildren(), isClean()); - baseRegister_ = null; - } - return baseRegisterBuilder_; - } - - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } - - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - // @@protoc_insertion_point(builder_scope:SubscriberRegisterPb) - } - - // @@protoc_insertion_point(class_scope:SubscriberRegisterPb) - private static final com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public SubscriberRegisterPb parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new SubscriberRegisterPb( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; + /** .BaseRegisterPb baseRegister = 2; */ + public boolean hasBaseRegister() { + return baseRegisterBuilder_ != null || baseRegister_ != null; } - public com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + /** .BaseRegisterPb baseRegister = 2; */ + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getBaseRegister() { + if (baseRegisterBuilder_ == null) { + return baseRegister_ == null + ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.getDefaultInstance() + : baseRegister_; + } else { + return baseRegisterBuilder_.getMessage(); + } + } + + /** .BaseRegisterPb baseRegister = 2; */ + public Builder setBaseRegister( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb value) { + if (baseRegisterBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + baseRegister_ = value; + onChanged(); + } else { + baseRegisterBuilder_.setMessage(value); + } + + return this; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public Builder setBaseRegister( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder builderForValue) { + if (baseRegisterBuilder_ == null) { + baseRegister_ = builderForValue.build(); + onChanged(); + } else { + baseRegisterBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public Builder mergeBaseRegister( + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb value) { + if (baseRegisterBuilder_ == null) { + if (baseRegister_ != null) { + baseRegister_ = + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.newBuilder( + baseRegister_) + .mergeFrom(value) + .buildPartial(); + } else { + baseRegister_ = value; + } + onChanged(); + } else { + baseRegisterBuilder_.mergeFrom(value); + } + return this; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public Builder clearBaseRegister() { + if (baseRegisterBuilder_ == null) { + baseRegister_ = null; + onChanged(); + } else { + baseRegister_ = null; + baseRegisterBuilder_ = null; + } + + return this; + } + + /** .BaseRegisterPb baseRegister = 2; */ + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder + getBaseRegisterBuilder() { + + onChanged(); + return getBaseRegisterFieldBuilder().getBuilder(); + } + + /** .BaseRegisterPb baseRegister = 2; */ + public com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder + getBaseRegisterOrBuilder() { + if (baseRegisterBuilder_ != null) { + return baseRegisterBuilder_.getMessageOrBuilder(); + } else { + return baseRegister_ == null + ? com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.getDefaultInstance() + : baseRegister_; + } + } + + /** .BaseRegisterPb baseRegister = 2; */ + private com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder> + getBaseRegisterFieldBuilder() { + if (baseRegisterBuilder_ == null) { + baseRegisterBuilder_ = + new com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder>( + getBaseRegister(), getParentForChildren(), isClean()); + baseRegister_ = null; + } + return baseRegisterBuilder_; + } + + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } + + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:SubscriberRegisterPb) + } + + // @@protoc_insertion_point(class_scope:SubscriberRegisterPb) + private static final com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb + DEFAULT_INSTANCE; + + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb(); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb + getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public SubscriberRegisterPb parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new SubscriberRegisterPb(input, extensionRegistry); + } + }; + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + public com.alipay.sofa.registry.common.model.client.pb.SubscriberRegisterPb + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPbOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPbOrBuilder.java index c854b4d48..f753a6837 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPbOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPbOrBuilder.java @@ -14,37 +14,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: SubscriberRegisterPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface SubscriberRegisterPbOrBuilder extends -// @@protoc_insertion_point(interface_extends:SubscriberRegisterPb) - com.google.protobuf.MessageOrBuilder { +public interface SubscriberRegisterPbOrBuilder + extends + // @@protoc_insertion_point(interface_extends:SubscriberRegisterPb) + com.google.protobuf.MessageOrBuilder { - /** - * string scope = 1; - */ - java.lang.String getScope(); + /** string scope = 1; */ + java.lang.String getScope(); - /** - * string scope = 1; - */ - com.google.protobuf.ByteString getScopeBytes(); + /** string scope = 1; */ + com.google.protobuf.ByteString getScopeBytes(); - /** - * .BaseRegisterPb baseRegister = 2; - */ - boolean hasBaseRegister(); + /** .BaseRegisterPb baseRegister = 2; */ + boolean hasBaseRegister(); - /** - * .BaseRegisterPb baseRegister = 2; - */ - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getBaseRegister(); + /** .BaseRegisterPb baseRegister = 2; */ + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPb getBaseRegister(); - /** - * .BaseRegisterPb baseRegister = 2; - */ - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder getBaseRegisterOrBuilder(); + /** .BaseRegisterPb baseRegister = 2; */ + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOrBuilder + getBaseRegisterOrBuilder(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPbOuterClass.java index 5431d8b82..e0cdb9369 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SubscriberRegisterPbOuterClass.java @@ -14,58 +14,59 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: SubscriberRegisterPb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class SubscriberRegisterPbOuterClass { - private SubscriberRegisterPbOuterClass() { - } + private SubscriberRegisterPbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor + internal_static_SubscriberRegisterPb_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_SubscriberRegisterPb_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_SubscriberRegisterPb_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_SubscriberRegisterPb_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\032SubscriberRegisterPb.proto\032\024BaseRegist" - + "erPb.proto\"L\n\024SubscriberRegisterPb\022\r\n\005sc" - + "ope\030\001 \001(\t\022%\n\014baseRegister\030\002 \001(\0132\017.BaseRe" - + "gisterPbB7\n/com.alipay.sofa.registry.com" - + "mon.model.client.pbP\001Z\002pbb\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom( - descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass - .getDescriptor(),}, assigner); - internal_static_SubscriberRegisterPb_descriptor = getDescriptor() - .getMessageTypes().get(0); - internal_static_SubscriberRegisterPb_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_SubscriberRegisterPb_descriptor, - new java.lang.String[]{"Scope", "BaseRegister",}); - com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass - .getDescriptor(); - } + static { + java.lang.String[] descriptorData = { + "\n\032SubscriberRegisterPb.proto\032\024BaseRegist" + + "erPb.proto\"L\n\024SubscriberRegisterPb\022\r\n\005sc" + + "ope\030\001 \001(\t\022%\n\014baseRegister\030\002 \001(\0132\017.BaseRe" + + "gisterPbB7\n/com.alipay.sofa.registry.com" + + "mon.model.client.pbP\001Z\002pbb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass.getDescriptor(), + }, + assigner); + internal_static_SubscriberRegisterPb_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_SubscriberRegisterPb_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_SubscriberRegisterPb_descriptor, + new java.lang.String[] { + "Scope", "BaseRegister", + }); + com.alipay.sofa.registry.common.model.client.pb.BaseRegisterPbOuterClass.getDescriptor(); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPb.java index e2bb8926b..549e1b154 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPb.java @@ -14,648 +14,635 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: SyncConfigRequestPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code SyncConfigRequestPb} - */ -public final class SyncConfigRequestPb extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:SyncConfigRequestPb) - SyncConfigRequestPbOrBuilder { - private static final long serialVersionUID = 0L; - - // Use SyncConfigRequestPb.newBuilder() to construct. - private SyncConfigRequestPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private SyncConfigRequestPb() { - dataCenter_ = ""; - zone_ = ""; - } +/** Protobuf type {@code SyncConfigRequestPb} */ +public final class SyncConfigRequestPb extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:SyncConfigRequestPb) + SyncConfigRequestPbOrBuilder { + private static final long serialVersionUID = 0L; + + // Use SyncConfigRequestPb.newBuilder() to construct. + private SyncConfigRequestPb(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private SyncConfigRequestPb() { + dataCenter_ = ""; + zone_ = ""; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private SyncConfigRequestPb( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: + { + java.lang.String s = input.readStringRequireUtf8(); - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } + dataCenter_ = s; + break; + } + case 18: + { + java.lang.String s = input.readStringRequireUtf8(); - private SyncConfigRequestPb(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - java.lang.String s = input.readStringRequireUtf8(); - - dataCenter_ = s; - break; - } - case 18: { - java.lang.String s = input.readStringRequireUtf8(); - - zone_ = s; - break; - } - } + zone_ = s; + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOuterClass + .internal_static_SyncConfigRequestPb_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOuterClass + .internal_static_SyncConfigRequestPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb.class, + com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb.Builder.class); + } + + public static final int DATACENTER_FIELD_NUMBER = 1; + private volatile java.lang.Object dataCenter_; + + /** string dataCenter = 1; */ + public java.lang.String getDataCenter() { + java.lang.Object ref = dataCenter_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + dataCenter_ = s; + return s; + } + } + + /** string dataCenter = 1; */ + public com.google.protobuf.ByteString getDataCenterBytes() { + java.lang.Object ref = dataCenter_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + dataCenter_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + public static final int ZONE_FIELD_NUMBER = 2; + private volatile java.lang.Object zone_; + + /** string zone = 2; */ + public java.lang.String getZone() { + java.lang.Object ref = zone_; + if (ref instanceof java.lang.String) { + return (java.lang.String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + zone_ = s; + return s; + } + } + + /** string zone = 2; */ + public com.google.protobuf.ByteString getZoneBytes() { + java.lang.Object ref = zone_; + if (ref instanceof java.lang.String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + zone_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getDataCenterBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, dataCenter_); + } + if (!getZoneBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, zone_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (!getDataCenterBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, dataCenter_); + } + if (!getZoneBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, zone_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb other = + (com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb) obj; + + boolean result = true; + result = result && getDataCenter().equals(other.getDataCenter()); + result = result && getZone().equals(other.getZone()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + DATACENTER_FIELD_NUMBER; + hash = (53 * hash) + getDataCenter().hashCode(); + hash = (37 * hash) + ZONE_FIELD_NUMBER; + hash = (53 * hash) + getZone().hashCode(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code SyncConfigRequestPb} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:SyncConfigRequestPb) + com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOuterClass.internal_static_SyncConfigRequestPb_descriptor; + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOuterClass + .internal_static_SyncConfigRequestPb_descriptor; } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOuterClass.internal_static_SyncConfigRequestPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb.class, - com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb.Builder.class); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOuterClass + .internal_static_SyncConfigRequestPb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb.class, + com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb.Builder.class); } - public static final int DATACENTER_FIELD_NUMBER = 1; - private volatile java.lang.Object dataCenter_; - - /** - * string dataCenter = 1; - */ - public java.lang.String getDataCenter() { - java.lang.Object ref = dataCenter_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - dataCenter_ = s; - return s; - } + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - /** - * string dataCenter = 1; - */ - public com.google.protobuf.ByteString getDataCenterBytes() { - java.lang.Object ref = dataCenter_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - dataCenter_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - public static final int ZONE_FIELD_NUMBER = 2; - private volatile java.lang.Object zone_; - - /** - * string zone = 2; - */ - public java.lang.String getZone() { - java.lang.Object ref = zone_; - if (ref instanceof java.lang.String) { - return (java.lang.String) ref; - } else { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - zone_ = s; - return s; - } - } - - /** - * string zone = 2; - */ - public com.google.protobuf.ByteString getZoneBytes() { - java.lang.Object ref = zone_; - if (ref instanceof java.lang.String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - zone_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; + public Builder clear() { + super.clear(); + dataCenter_ = ""; - memoizedIsInitialized = 1; - return true; - } + zone_ = ""; - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (!getDataCenterBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, dataCenter_); - } - if (!getZoneBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, zone_); - } - unknownFields.writeTo(output); + return this; } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; - - size = 0; - if (!getDataCenterBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, dataCenter_); - } - if (!getZoneBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, zone_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOuterClass + .internal_static_SyncConfigRequestPb_descriptor; } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb other = (com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb) obj; - - boolean result = true; - result = result && getDataCenter().equals(other.getDataCenter()); - result = result && getZone().equals(other.getZone()); - result = result && unknownFields.equals(other.unknownFields); - return result; + public com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb + .getDefaultInstance(); } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + DATACENTER_FIELD_NUMBER; - hash = (53 * hash) + getDataCenter().hashCode(); - hash = (37 * hash) + ZONE_FIELD_NUMBER; - hash = (53 * hash) + getZone().hashCode(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + public com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb build() { + com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb result = + new com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb(this); + result.dataCenter_ = dataCenter_; + result.zone_ = zone_; + onBuilt(); + return result; } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clone() { + return (Builder) super.clone(); } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb) other); + } else { + super.mergeFrom(other); + return this; + } } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb + .getDefaultInstance()) return this; + if (!other.getDataCenter().isEmpty()) { + dataCenter_ = other.dataCenter_; + onChanged(); + } + if (!other.getZone().isEmpty()) { + zone_ = other.zone_; + onChanged(); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + public final boolean isInitialized() { + return true; } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + private java.lang.Object dataCenter_ = ""; - public Builder newBuilderForType() { - return newBuilder(); + /** string dataCenter = 1; */ + public java.lang.String getDataCenter() { + java.lang.Object ref = dataCenter_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + dataCenter_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string dataCenter = 1; */ + public com.google.protobuf.ByteString getDataCenterBytes() { + java.lang.Object ref = dataCenter_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + dataCenter_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } + /** string dataCenter = 1; */ + public Builder setDataCenter(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + dataCenter_ = value; + onChanged(); + return this; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); - } + /** string dataCenter = 1; */ + public Builder clearDataCenter() { - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + dataCenter_ = getDefaultInstance().getDataCenter(); + onChanged(); + return this; } - /** - * Protobuf type {@code SyncConfigRequestPb} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:SyncConfigRequestPb) - com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOuterClass.internal_static_SyncConfigRequestPb_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOuterClass.internal_static_SyncConfigRequestPb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb.class, - com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - dataCenter_ = ""; - - zone_ = ""; - - return this; - } - - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPbOuterClass.internal_static_SyncConfigRequestPb_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb - .getDefaultInstance(); - } - - public com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb build() { - com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - public com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb result = new com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb( - this); - result.dataCenter_ = dataCenter_; - result.zone_ = zone_; - onBuilt(); - return result; - } + /** string dataCenter = 1; */ + public Builder setDataCenterBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - public Builder clone() { - return (Builder) super.clone(); - } - - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb) other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb - .getDefaultInstance()) - return this; - if (!other.getDataCenter().isEmpty()) { - dataCenter_ = other.dataCenter_; - onChanged(); - } - if (!other.getZone().isEmpty()) { - zone_ = other.zone_; - onChanged(); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private java.lang.Object dataCenter_ = ""; - - /** - * string dataCenter = 1; - */ - public java.lang.String getDataCenter() { - java.lang.Object ref = dataCenter_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - dataCenter_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } - - /** - * string dataCenter = 1; - */ - public com.google.protobuf.ByteString getDataCenterBytes() { - java.lang.Object ref = dataCenter_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - dataCenter_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - /** - * string dataCenter = 1; - */ - public Builder setDataCenter(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + dataCenter_ = value; + onChanged(); + return this; + } - dataCenter_ = value; - onChanged(); - return this; - } + private java.lang.Object zone_ = ""; - /** - * string dataCenter = 1; - */ - public Builder clearDataCenter() { + /** string zone = 2; */ + public java.lang.String getZone() { + java.lang.Object ref = zone_; + if (!(ref instanceof java.lang.String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + java.lang.String s = bs.toStringUtf8(); + zone_ = s; + return s; + } else { + return (java.lang.String) ref; + } + } + + /** string zone = 2; */ + public com.google.protobuf.ByteString getZoneBytes() { + java.lang.Object ref = zone_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = + com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); + zone_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } - dataCenter_ = getDefaultInstance().getDataCenter(); - onChanged(); - return this; - } + /** string zone = 2; */ + public Builder setZone(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } - /** - * string dataCenter = 1; - */ - public Builder setDataCenterBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + zone_ = value; + onChanged(); + return this; + } - dataCenter_ = value; - onChanged(); - return this; - } + /** string zone = 2; */ + public Builder clearZone() { - private java.lang.Object zone_ = ""; - - /** - * string zone = 2; - */ - public java.lang.String getZone() { - java.lang.Object ref = zone_; - if (!(ref instanceof java.lang.String)) { - com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; - java.lang.String s = bs.toStringUtf8(); - zone_ = s; - return s; - } else { - return (java.lang.String) ref; - } - } + zone_ = getDefaultInstance().getZone(); + onChanged(); + return this; + } - /** - * string zone = 2; - */ - public com.google.protobuf.ByteString getZoneBytes() { - java.lang.Object ref = zone_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = com.google.protobuf.ByteString - .copyFromUtf8((java.lang.String) ref); - zone_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } + /** string zone = 2; */ + public Builder setZoneBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); - /** - * string zone = 2; - */ - public Builder setZone(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } + zone_ = value; + onChanged(); + return this; + } - zone_ = value; - onChanged(); - return this; - } + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); + } - /** - * string zone = 2; - */ - public Builder clearZone() { + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } - zone_ = getDefaultInstance().getZone(); - onChanged(); - return this; - } + // @@protoc_insertion_point(builder_scope:SyncConfigRequestPb) + } - /** - * string zone = 2; - */ - public Builder setZoneBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); + // @@protoc_insertion_point(class_scope:SyncConfigRequestPb) + private static final com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb + DEFAULT_INSTANCE; - zone_ = value; - onChanged(); - return this; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb(); + } - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb + getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public SyncConfigRequestPb parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new SyncConfigRequestPb(input, extensionRegistry); } + }; - // @@protoc_insertion_point(builder_scope:SyncConfigRequestPb) - } - - // @@protoc_insertion_point(class_scope:SyncConfigRequestPb) - private static final com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public SyncConfigRequestPb parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new SyncConfigRequestPb( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - public com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.SyncConfigRequestPb + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPbOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPbOrBuilder.java index 90533b602..224a471a1 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPbOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPbOrBuilder.java @@ -14,32 +14,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: SyncConfigRequestPb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface SyncConfigRequestPbOrBuilder extends -// @@protoc_insertion_point(interface_extends:SyncConfigRequestPb) - com.google.protobuf.MessageOrBuilder { +public interface SyncConfigRequestPbOrBuilder + extends + // @@protoc_insertion_point(interface_extends:SyncConfigRequestPb) + com.google.protobuf.MessageOrBuilder { - /** - * string dataCenter = 1; - */ - java.lang.String getDataCenter(); + /** string dataCenter = 1; */ + java.lang.String getDataCenter(); - /** - * string dataCenter = 1; - */ - com.google.protobuf.ByteString getDataCenterBytes(); + /** string dataCenter = 1; */ + com.google.protobuf.ByteString getDataCenterBytes(); - /** - * string zone = 2; - */ - java.lang.String getZone(); + /** string zone = 2; */ + java.lang.String getZone(); - /** - * string zone = 2; - */ - com.google.protobuf.ByteString getZoneBytes(); + /** string zone = 2; */ + com.google.protobuf.ByteString getZoneBytes(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPbOuterClass.java index 066709fbf..3a594515a 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigRequestPbOuterClass.java @@ -14,54 +14,53 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: SyncConfigRequestPb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class SyncConfigRequestPbOuterClass { - private SyncConfigRequestPbOuterClass() { - } + private SyncConfigRequestPbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor + internal_static_SyncConfigRequestPb_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_SyncConfigRequestPb_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_SyncConfigRequestPb_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_SyncConfigRequestPb_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\031SyncConfigRequestPb.proto\"7\n\023SyncConfi" - + "gRequestPb\022\022\n\ndataCenter\030\001 \001(\t\022\014\n\004zone\030\002" - + " \001(\tB7\n/com.alipay.sofa.registry.common." - + "model.client.pbP\001Z\002pbb\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{}, - assigner); - internal_static_SyncConfigRequestPb_descriptor = getDescriptor() - .getMessageTypes().get(0); - internal_static_SyncConfigRequestPb_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_SyncConfigRequestPb_descriptor, - new java.lang.String[]{"DataCenter", "Zone",}); - } + static { + java.lang.String[] descriptorData = { + "\n\031SyncConfigRequestPb.proto\"7\n\023SyncConfi" + + "gRequestPb\022\022\n\ndataCenter\030\001 \001(\t\022\014\n\004zone\030\002" + + " \001(\tB7\n/com.alipay.sofa.registry.common." + + "model.client.pbP\001Z\002pbb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}, assigner); + internal_static_SyncConfigRequestPb_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_SyncConfigRequestPb_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_SyncConfigRequestPb_descriptor, + new java.lang.String[] { + "DataCenter", "Zone", + }); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePb.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePb.java index dbcce0360..7e8cf5001 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePb.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePb.java @@ -14,827 +14,803 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: SyncConfigResponsePb.proto - package com.alipay.sofa.registry.common.model.client.pb; -/** - * Protobuf type {@code SyncConfigResponsePb} - */ -public final class SyncConfigResponsePb extends com.google.protobuf.GeneratedMessageV3 implements -// @@protoc_insertion_point(message_implements:SyncConfigResponsePb) - SyncConfigResponsePbOrBuilder { - private static final long serialVersionUID = 0L; - - // Use SyncConfigResponsePb.newBuilder() to construct. - private SyncConfigResponsePb(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - - private SyncConfigResponsePb() { - availableSegments_ = com.google.protobuf.LazyStringArrayList.EMPTY; - retryInterval_ = 0; - } - - @java.lang.Override - public final com.google.protobuf.UnknownFieldSet getUnknownFields() { - return this.unknownFields; - } - - private SyncConfigResponsePb(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new java.lang.NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet - .newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - default: { - if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { - done = true; - } - break; - } - case 10: { - com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder subBuilder = null; - if (result_ != null) { - subBuilder = result_.toBuilder(); - } - result_ = input.readMessage( - com.alipay.sofa.registry.common.model.client.pb.ResultPb.parser(), - extensionRegistry); - if (subBuilder != null) { - subBuilder.mergeFrom(result_); - result_ = subBuilder.buildPartial(); - } - - break; - } - case 18: { - java.lang.String s = input.readStringRequireUtf8(); - if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { - availableSegments_ = new com.google.protobuf.LazyStringArrayList(); - mutable_bitField0_ |= 0x00000002; - } - availableSegments_.add(s); - break; - } - case 24: { - - retryInterval_ = input.readInt32(); - break; - } - } +/** Protobuf type {@code SyncConfigResponsePb} */ +public final class SyncConfigResponsePb extends com.google.protobuf.GeneratedMessageV3 + implements + // @@protoc_insertion_point(message_implements:SyncConfigResponsePb) + SyncConfigResponsePbOrBuilder { + private static final long serialVersionUID = 0L; + + // Use SyncConfigResponsePb.newBuilder() to construct. + private SyncConfigResponsePb(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private SyncConfigResponsePb() { + availableSegments_ = com.google.protobuf.LazyStringArrayList.EMPTY; + retryInterval_ = 0; + } + + @java.lang.Override + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; + } + + private SyncConfigResponsePb( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new java.lang.NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = + com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + default: + { + if (!parseUnknownFieldProto3(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + case 10: + { + com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder subBuilder = null; + if (result_ != null) { + subBuilder = result_.toBuilder(); + } + result_ = + input.readMessage( + com.alipay.sofa.registry.common.model.client.pb.ResultPb.parser(), + extensionRegistry); + if (subBuilder != null) { + subBuilder.mergeFrom(result_); + result_ = subBuilder.buildPartial(); + } + + break; + } + case 18: + { + java.lang.String s = input.readStringRequireUtf8(); + if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + availableSegments_ = new com.google.protobuf.LazyStringArrayList(); + mutable_bitField0_ |= 0x00000002; + } + availableSegments_.add(s); + break; } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException(e) - .setUnfinishedMessage(this); - } finally { - if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { - availableSegments_ = availableSegments_.getUnmodifiableView(); + case 24: + { + retryInterval_ = input.readInt32(); + break; } - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); } - } - + } + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { + availableSegments_ = availableSegments_.getUnmodifiableView(); + } + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOuterClass + .internal_static_SyncConfigResponsePb_descriptor; + } + + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOuterClass + .internal_static_SyncConfigResponsePb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb.class, + com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb.Builder.class); + } + + private int bitField0_; + public static final int RESULT_FIELD_NUMBER = 1; + private com.alipay.sofa.registry.common.model.client.pb.ResultPb result_; + + /** .ResultPb result = 1; */ + public boolean hasResult() { + return result_ != null; + } + + /** .ResultPb result = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.ResultPb getResult() { + return result_ == null + ? com.alipay.sofa.registry.common.model.client.pb.ResultPb.getDefaultInstance() + : result_; + } + + /** .ResultPb result = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.ResultPbOrBuilder getResultOrBuilder() { + return getResult(); + } + + public static final int AVAILABLESEGMENTS_FIELD_NUMBER = 2; + private com.google.protobuf.LazyStringList availableSegments_; + + /** repeated string availableSegments = 2; */ + public com.google.protobuf.ProtocolStringList getAvailableSegmentsList() { + return availableSegments_; + } + + /** repeated string availableSegments = 2; */ + public int getAvailableSegmentsCount() { + return availableSegments_.size(); + } + + /** repeated string availableSegments = 2; */ + public java.lang.String getAvailableSegments(int index) { + return availableSegments_.get(index); + } + + /** repeated string availableSegments = 2; */ + public com.google.protobuf.ByteString getAvailableSegmentsBytes(int index) { + return availableSegments_.getByteString(index); + } + + public static final int RETRYINTERVAL_FIELD_NUMBER = 3; + private int retryInterval_; + + /** int32 retryInterval = 3; */ + public int getRetryInterval() { + return retryInterval_; + } + + private byte memoizedIsInitialized = -1; + + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) return true; + if (isInitialized == 0) return false; + + memoizedIsInitialized = 1; + return true; + } + + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (result_ != null) { + output.writeMessage(1, getResult()); + } + for (int i = 0; i < availableSegments_.size(); i++) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, availableSegments_.getRaw(i)); + } + if (retryInterval_ != 0) { + output.writeInt32(3, retryInterval_); + } + unknownFields.writeTo(output); + } + + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) return size; + + size = 0; + if (result_ != null) { + size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getResult()); + } + { + int dataSize = 0; + for (int i = 0; i < availableSegments_.size(); i++) { + dataSize += computeStringSizeNoTag(availableSegments_.getRaw(i)); + } + size += dataSize; + size += 1 * getAvailableSegmentsList().size(); + } + if (retryInterval_ != 0) { + size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, retryInterval_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; + } + + @java.lang.Override + public boolean equals(final java.lang.Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb)) { + return super.equals(obj); + } + com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb other = + (com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb) obj; + + boolean result = true; + result = result && (hasResult() == other.hasResult()); + if (hasResult()) { + result = result && getResult().equals(other.getResult()); + } + result = result && getAvailableSegmentsList().equals(other.getAvailableSegmentsList()); + result = result && (getRetryInterval() == other.getRetryInterval()); + result = result && unknownFields.equals(other.unknownFields); + return result; + } + + @java.lang.Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + if (hasResult()) { + hash = (37 * hash) + RESULT_FIELD_NUMBER; + hash = (53 * hash) + getResult().hashCode(); + } + if (getAvailableSegmentsCount() > 0) { + hash = (37 * hash) + AVAILABLESEGMENTS_FIELD_NUMBER; + hash = (53 * hash) + getAvailableSegmentsList().hashCode(); + } + hash = (37 * hash) + RETRYINTERVAL_FIELD_NUMBER; + hash = (53 * hash) + getRetryInterval(); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom( + java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom( + java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom( + com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom( + com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom( + byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom( + byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom( + java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb + parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb + parseDelimitedFrom( + java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( + PARSER, input, extensionRegistry); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom( + com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException( + PARSER, input, extensionRegistry); + } + + public Builder newBuilderForType() { + return newBuilder(); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder( + com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + } + + @java.lang.Override + protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; + } + + /** Protobuf type {@code SyncConfigResponsePb} */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder + implements + // @@protoc_insertion_point(builder_implements:SyncConfigResponsePb) + com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOuterClass.internal_static_SyncConfigResponsePb_descriptor; + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOuterClass + .internal_static_SyncConfigResponsePb_descriptor; } - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOuterClass.internal_static_SyncConfigResponsePb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb.class, - com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb.Builder.class); + protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internalGetFieldAccessorTable() { + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOuterClass + .internal_static_SyncConfigResponsePb_fieldAccessorTable + .ensureFieldAccessorsInitialized( + com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb.class, + com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb.Builder.class); } - private int bitField0_; - public static final int RESULT_FIELD_NUMBER = 1; - private com.alipay.sofa.registry.common.model.client.pb.ResultPb result_; - - /** - * .ResultPb result = 1; - */ - public boolean hasResult() { - return result_ != null; + // Construct using + // com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); } - /** - * .ResultPb result = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.ResultPb getResult() { - return result_ == null ? com.alipay.sofa.registry.common.model.client.pb.ResultPb - .getDefaultInstance() : result_; + private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); } - /** - * .ResultPb result = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.ResultPbOrBuilder getResultOrBuilder() { - return getResult(); + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } - public static final int AVAILABLESEGMENTS_FIELD_NUMBER = 2; - private com.google.protobuf.LazyStringList availableSegments_; + public Builder clear() { + super.clear(); + if (resultBuilder_ == null) { + result_ = null; + } else { + result_ = null; + resultBuilder_ = null; + } + availableSegments_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000002); + retryInterval_ = 0; - /** - * repeated string availableSegments = 2; - */ - public com.google.protobuf.ProtocolStringList getAvailableSegmentsList() { - return availableSegments_; + return this; } - /** - * repeated string availableSegments = 2; - */ - public int getAvailableSegmentsCount() { - return availableSegments_.size(); + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOuterClass + .internal_static_SyncConfigResponsePb_descriptor; } - /** - * repeated string availableSegments = 2; - */ - public java.lang.String getAvailableSegments(int index) { - return availableSegments_.get(index); + public com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb + getDefaultInstanceForType() { + return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb + .getDefaultInstance(); } - /** - * repeated string availableSegments = 2; - */ - public com.google.protobuf.ByteString getAvailableSegmentsBytes(int index) { - return availableSegments_.getByteString(index); + public com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb build() { + com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; } - public static final int RETRYINTERVAL_FIELD_NUMBER = 3; - private int retryInterval_; - - /** - * int32 retryInterval = 3; - */ - public int getRetryInterval() { - return retryInterval_; + public com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb buildPartial() { + com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb result = + new com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb(this); + int from_bitField0_ = bitField0_; + int to_bitField0_ = 0; + if (resultBuilder_ == null) { + result.result_ = result_; + } else { + result.result_ = resultBuilder_.build(); + } + if (((bitField0_ & 0x00000002) == 0x00000002)) { + availableSegments_ = availableSegments_.getUnmodifiableView(); + bitField0_ = (bitField0_ & ~0x00000002); + } + result.availableSegments_ = availableSegments_; + result.retryInterval_ = retryInterval_; + result.bitField0_ = to_bitField0_; + onBuilt(); + return result; } - private byte memoizedIsInitialized = -1; - - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) - return true; - if (isInitialized == 0) - return false; + public Builder clone() { + return (Builder) super.clone(); + } - memoizedIsInitialized = 1; - return true; + public Builder setField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.setField(field, value); } - public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { - if (result_ != null) { - output.writeMessage(1, getResult()); - } - for (int i = 0; i < availableSegments_.size(); i++) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, - availableSegments_.getRaw(i)); - } - if (retryInterval_ != 0) { - output.writeInt32(3, retryInterval_); - } - unknownFields.writeTo(output); + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return (Builder) super.clearField(field); } - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) - return size; + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return (Builder) super.clearOneof(oneof); + } - size = 0; - if (result_ != null) { - size += com.google.protobuf.CodedOutputStream.computeMessageSize(1, getResult()); - } - { - int dataSize = 0; - for (int i = 0; i < availableSegments_.size(); i++) { - dataSize += computeStringSizeNoTag(availableSegments_.getRaw(i)); - } - size += dataSize; - size += 1 * getAvailableSegmentsList().size(); - } - if (retryInterval_ != 0) { - size += com.google.protobuf.CodedOutputStream.computeInt32Size(3, retryInterval_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; + public Builder setRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { + return (Builder) super.setRepeatedField(field, index, value); } - @java.lang.Override - public boolean equals(final java.lang.Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb)) { - return super.equals(obj); - } - com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb other = (com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb) obj; + public Builder addRepeatedField( + com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { + return (Builder) super.addRepeatedField(field, value); + } - boolean result = true; - result = result && (hasResult() == other.hasResult()); - if (hasResult()) { - result = result && getResult().equals(other.getResult()); - } - result = result && getAvailableSegmentsList().equals(other.getAvailableSegmentsList()); - result = result && (getRetryInterval() == other.getRetryInterval()); - result = result && unknownFields.equals(other.unknownFields); - return result; + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb) { + return mergeFrom( + (com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb) other); + } else { + super.mergeFrom(other); + return this; + } } - @java.lang.Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - if (hasResult()) { - hash = (37 * hash) + RESULT_FIELD_NUMBER; - hash = (53 * hash) + getResult().hashCode(); + public Builder mergeFrom( + com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb other) { + if (other + == com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb + .getDefaultInstance()) return this; + if (other.hasResult()) { + mergeResult(other.getResult()); + } + if (!other.availableSegments_.isEmpty()) { + if (availableSegments_.isEmpty()) { + availableSegments_ = other.availableSegments_; + bitField0_ = (bitField0_ & ~0x00000002); + } else { + ensureAvailableSegmentsIsMutable(); + availableSegments_.addAll(other.availableSegments_); } - if (getAvailableSegmentsCount() > 0) { - hash = (37 * hash) + AVAILABLESEGMENTS_FIELD_NUMBER; - hash = (53 * hash) + getAvailableSegmentsList().hashCode(); - } - hash = (37 * hash) + RETRYINTERVAL_FIELD_NUMBER; - hash = (53 * hash) + getRetryInterval(); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; + onChanged(); + } + if (other.getRetryInterval() != 0) { + setRetryInterval(other.getRetryInterval()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom(java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + public final boolean isInitialized() { + return true; + } + + public Builder mergeFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = + (com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb) + e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + private int bitField0_; + + private com.alipay.sofa.registry.common.model.client.pb.ResultPb result_ = null; + private com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.ResultPb, + com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.ResultPbOrBuilder> + resultBuilder_; + + /** .ResultPb result = 1; */ + public boolean hasResult() { + return resultBuilder_ != null || result_ != null; } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom(java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } + /** .ResultPb result = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.ResultPb getResult() { + if (resultBuilder_ == null) { + return result_ == null + ? com.alipay.sofa.registry.common.model.client.pb.ResultPb.getDefaultInstance() + : result_; + } else { + return resultBuilder_.getMessage(); + } + } + + /** .ResultPb result = 1; */ + public Builder setResult(com.alipay.sofa.registry.common.model.client.pb.ResultPb value) { + if (resultBuilder_ == null) { + if (value == null) { + throw new NullPointerException(); + } + result_ = value; + onChanged(); + } else { + resultBuilder_.setMessage(value); + } + + return this; + } + + /** .ResultPb result = 1; */ + public Builder setResult( + com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder builderForValue) { + if (resultBuilder_ == null) { + result_ = builderForValue.build(); + onChanged(); + } else { + resultBuilder_.setMessage(builderForValue.build()); + } + + return this; + } + + /** .ResultPb result = 1; */ + public Builder mergeResult(com.alipay.sofa.registry.common.model.client.pb.ResultPb value) { + if (resultBuilder_ == null) { + if (result_ != null) { + result_ = + com.alipay.sofa.registry.common.model.client.pb.ResultPb.newBuilder(result_) + .mergeFrom(value) + .buildPartial(); + } else { + result_ = value; + } + onChanged(); + } else { + resultBuilder_.mergeFrom(value); + } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom(com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom(com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } + /** .ResultPb result = 1; */ + public Builder clearResult() { + if (resultBuilder_ == null) { + result_ = null; + onChanged(); + } else { + result_ = null; + resultBuilder_ = null; + } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); + return this; } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom(byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } + /** .ResultPb result = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder getResultBuilder() { - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + onChanged(); + return getResultFieldBuilder().getBuilder(); } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); + /** .ResultPb result = 1; */ + public com.alipay.sofa.registry.common.model.client.pb.ResultPbOrBuilder getResultOrBuilder() { + if (resultBuilder_ != null) { + return resultBuilder_.getMessageOrBuilder(); + } else { + return result_ == null + ? com.alipay.sofa.registry.common.model.client.pb.ResultPb.getDefaultInstance() + : result_; + } + } + + /** .ResultPb result = 1; */ + private com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.ResultPb, + com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.ResultPbOrBuilder> + getResultFieldBuilder() { + if (resultBuilder_ == null) { + resultBuilder_ = + new com.google.protobuf.SingleFieldBuilderV3< + com.alipay.sofa.registry.common.model.client.pb.ResultPb, + com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder, + com.alipay.sofa.registry.common.model.client.pb.ResultPbOrBuilder>( + getResult(), getParentForChildren(), isClean()); + result_ = null; + } + return resultBuilder_; + } + + private com.google.protobuf.LazyStringList availableSegments_ = + com.google.protobuf.LazyStringArrayList.EMPTY; + + private void ensureAvailableSegmentsIsMutable() { + if (!((bitField0_ & 0x00000002) == 0x00000002)) { + availableSegments_ = new com.google.protobuf.LazyStringArrayList(availableSegments_); + bitField0_ |= 0x00000002; + } + } + + /** repeated string availableSegments = 2; */ + public com.google.protobuf.ProtocolStringList getAvailableSegmentsList() { + return availableSegments_.getUnmodifiableView(); } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + /** repeated string availableSegments = 2; */ + public int getAvailableSegmentsCount() { + return availableSegments_.size(); } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseDelimitedFrom(java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, - extensionRegistry); + /** repeated string availableSegments = 2; */ + public java.lang.String getAvailableSegments(int index) { + return availableSegments_.get(index); } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom(com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + /** repeated string availableSegments = 2; */ + public com.google.protobuf.ByteString getAvailableSegmentsBytes(int index) { + return availableSegments_.getByteString(index); + } + + /** repeated string availableSegments = 2; */ + public Builder setAvailableSegments(int index, java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureAvailableSegmentsIsMutable(); + availableSegments_.set(index, value); + onChanged(); + return this; + } + + /** repeated string availableSegments = 2; */ + public Builder addAvailableSegments(java.lang.String value) { + if (value == null) { + throw new NullPointerException(); + } + ensureAvailableSegmentsIsMutable(); + availableSegments_.add(value); + onChanged(); + return this; + } + + /** repeated string availableSegments = 2; */ + public Builder addAllAvailableSegments(java.lang.Iterable values) { + ensureAvailableSegmentsIsMutable(); + com.google.protobuf.AbstractMessageLite.Builder.addAll(values, availableSegments_); + onChanged(); + return this; + } + + /** repeated string availableSegments = 2; */ + public Builder clearAvailableSegments() { + availableSegments_ = com.google.protobuf.LazyStringArrayList.EMPTY; + bitField0_ = (bitField0_ & ~0x00000002); + onChanged(); + return this; + } + + /** repeated string availableSegments = 2; */ + public Builder addAvailableSegmentsBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + ensureAvailableSegmentsIsMutable(); + availableSegments_.add(value); + onChanged(); + return this; + } + + private int retryInterval_; + + /** int32 retryInterval = 3; */ + public int getRetryInterval() { + return retryInterval_; } - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parseFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, - extensionRegistry); - } + /** int32 retryInterval = 3; */ + public Builder setRetryInterval(int value) { - public Builder newBuilderForType() { - return newBuilder(); + retryInterval_ = value; + onChanged(); + return this; } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } + /** int32 retryInterval = 3; */ + public Builder clearRetryInterval() { - public static Builder newBuilder(com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + retryInterval_ = 0; + onChanged(); + return this; } - public Builder toBuilder() { - return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFieldsProto3(unknownFields); } - @java.lang.Override - protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; + public final Builder mergeUnknownFields( + final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); } - /** - * Protobuf type {@code SyncConfigResponsePb} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder - implements - // @@protoc_insertion_point(builder_implements:SyncConfigResponsePb) - com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOuterClass.internal_static_SyncConfigResponsePb_descriptor; - } - - protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOuterClass.internal_static_SyncConfigResponsePb_fieldAccessorTable - .ensureFieldAccessorsInitialized( - com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb.class, - com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb.Builder.class); - } - - // Construct using com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { - } - } - - public Builder clear() { - super.clear(); - if (resultBuilder_ == null) { - result_ = null; - } else { - result_ = null; - resultBuilder_ = null; - } - availableSegments_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000002); - retryInterval_ = 0; - - return this; - } + // @@protoc_insertion_point(builder_scope:SyncConfigResponsePb) + } - public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePbOuterClass.internal_static_SyncConfigResponsePb_descriptor; - } - - public com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb getDefaultInstanceForType() { - return com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb - .getDefaultInstance(); - } + // @@protoc_insertion_point(class_scope:SyncConfigResponsePb) + private static final com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb + DEFAULT_INSTANCE; - public com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb build() { - com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } + static { + DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb(); + } - public com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb buildPartial() { - com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb result = new com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb( - this); - int from_bitField0_ = bitField0_; - int to_bitField0_ = 0; - if (resultBuilder_ == null) { - result.result_ = result_; - } else { - result.result_ = resultBuilder_.build(); - } - if (((bitField0_ & 0x00000002) == 0x00000002)) { - availableSegments_ = availableSegments_.getUnmodifiableView(); - bitField0_ = (bitField0_ & ~0x00000002); - } - result.availableSegments_ = availableSegments_; - result.retryInterval_ = retryInterval_; - result.bitField0_ = to_bitField0_; - onBuilt(); - return result; - } + public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb + getDefaultInstance() { + return DEFAULT_INSTANCE; + } - public Builder clone() { - return (Builder) super.clone(); + private static final com.google.protobuf.Parser PARSER = + new com.google.protobuf.AbstractParser() { + public SyncConfigResponsePb parsePartialFrom( + com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new SyncConfigResponsePb(input, extensionRegistry); } + }; - public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.setField(field, value); - } - - public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { - return (Builder) super.clearField(field); - } - - public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return (Builder) super.clearOneof(oneof); - } - - public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - int index, java.lang.Object value) { - return (Builder) super.setRepeatedField(field, index, value); - } - - public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, - java.lang.Object value) { - return (Builder) super.addRepeatedField(field, value); - } - - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb) { - return mergeFrom((com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb) other); - } else { - super.mergeFrom(other); - return this; - } - } + public static com.google.protobuf.Parser parser() { + return PARSER; + } - public Builder mergeFrom(com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb other) { - if (other == com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb - .getDefaultInstance()) - return this; - if (other.hasResult()) { - mergeResult(other.getResult()); - } - if (!other.availableSegments_.isEmpty()) { - if (availableSegments_.isEmpty()) { - availableSegments_ = other.availableSegments_; - bitField0_ = (bitField0_ & ~0x00000002); - } else { - ensureAvailableSegmentsIsMutable(); - availableSegments_.addAll(other.availableSegments_); - } - onChanged(); - } - if (other.getRetryInterval() != 0) { - setRetryInterval(other.getRetryInterval()); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; - } - - public final boolean isInitialized() { - return true; - } - - public Builder mergeFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb) e - .getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - - private int bitField0_; - - private com.alipay.sofa.registry.common.model.client.pb.ResultPb result_ = null; - private com.google.protobuf.SingleFieldBuilderV3 resultBuilder_; - - /** - * .ResultPb result = 1; - */ - public boolean hasResult() { - return resultBuilder_ != null || result_ != null; - } - - /** - * .ResultPb result = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.ResultPb getResult() { - if (resultBuilder_ == null) { - return result_ == null ? com.alipay.sofa.registry.common.model.client.pb.ResultPb - .getDefaultInstance() : result_; - } else { - return resultBuilder_.getMessage(); - } - } - - /** - * .ResultPb result = 1; - */ - public Builder setResult(com.alipay.sofa.registry.common.model.client.pb.ResultPb value) { - if (resultBuilder_ == null) { - if (value == null) { - throw new NullPointerException(); - } - result_ = value; - onChanged(); - } else { - resultBuilder_.setMessage(value); - } - - return this; - } - - /** - * .ResultPb result = 1; - */ - public Builder setResult(com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder builderForValue) { - if (resultBuilder_ == null) { - result_ = builderForValue.build(); - onChanged(); - } else { - resultBuilder_.setMessage(builderForValue.build()); - } - - return this; - } - - /** - * .ResultPb result = 1; - */ - public Builder mergeResult(com.alipay.sofa.registry.common.model.client.pb.ResultPb value) { - if (resultBuilder_ == null) { - if (result_ != null) { - result_ = com.alipay.sofa.registry.common.model.client.pb.ResultPb - .newBuilder(result_).mergeFrom(value).buildPartial(); - } else { - result_ = value; - } - onChanged(); - } else { - resultBuilder_.mergeFrom(value); - } - - return this; - } - - /** - * .ResultPb result = 1; - */ - public Builder clearResult() { - if (resultBuilder_ == null) { - result_ = null; - onChanged(); - } else { - result_ = null; - resultBuilder_ = null; - } - - return this; - } - - /** - * .ResultPb result = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.ResultPb.Builder getResultBuilder() { - - onChanged(); - return getResultFieldBuilder().getBuilder(); - } - - /** - * .ResultPb result = 1; - */ - public com.alipay.sofa.registry.common.model.client.pb.ResultPbOrBuilder getResultOrBuilder() { - if (resultBuilder_ != null) { - return resultBuilder_.getMessageOrBuilder(); - } else { - return result_ == null ? com.alipay.sofa.registry.common.model.client.pb.ResultPb - .getDefaultInstance() : result_; - } - } - - /** - * .ResultPb result = 1; - */ - private com.google.protobuf.SingleFieldBuilderV3 getResultFieldBuilder() { - if (resultBuilder_ == null) { - resultBuilder_ = new com.google.protobuf.SingleFieldBuilderV3( - getResult(), getParentForChildren(), isClean()); - result_ = null; - } - return resultBuilder_; - } - - private com.google.protobuf.LazyStringList availableSegments_ = com.google.protobuf.LazyStringArrayList.EMPTY; - - private void ensureAvailableSegmentsIsMutable() { - if (!((bitField0_ & 0x00000002) == 0x00000002)) { - availableSegments_ = new com.google.protobuf.LazyStringArrayList(availableSegments_); - bitField0_ |= 0x00000002; - } - } - - /** - * repeated string availableSegments = 2; - */ - public com.google.protobuf.ProtocolStringList getAvailableSegmentsList() { - return availableSegments_.getUnmodifiableView(); - } - - /** - * repeated string availableSegments = 2; - */ - public int getAvailableSegmentsCount() { - return availableSegments_.size(); - } - - /** - * repeated string availableSegments = 2; - */ - public java.lang.String getAvailableSegments(int index) { - return availableSegments_.get(index); - } - - /** - * repeated string availableSegments = 2; - */ - public com.google.protobuf.ByteString getAvailableSegmentsBytes(int index) { - return availableSegments_.getByteString(index); - } - - /** - * repeated string availableSegments = 2; - */ - public Builder setAvailableSegments(int index, java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureAvailableSegmentsIsMutable(); - availableSegments_.set(index, value); - onChanged(); - return this; - } - - /** - * repeated string availableSegments = 2; - */ - public Builder addAvailableSegments(java.lang.String value) { - if (value == null) { - throw new NullPointerException(); - } - ensureAvailableSegmentsIsMutable(); - availableSegments_.add(value); - onChanged(); - return this; - } - - /** - * repeated string availableSegments = 2; - */ - public Builder addAllAvailableSegments(java.lang.Iterable values) { - ensureAvailableSegmentsIsMutable(); - com.google.protobuf.AbstractMessageLite.Builder.addAll(values, availableSegments_); - onChanged(); - return this; - } - - /** - * repeated string availableSegments = 2; - */ - public Builder clearAvailableSegments() { - availableSegments_ = com.google.protobuf.LazyStringArrayList.EMPTY; - bitField0_ = (bitField0_ & ~0x00000002); - onChanged(); - return this; - } - - /** - * repeated string availableSegments = 2; - */ - public Builder addAvailableSegmentsBytes(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - ensureAvailableSegmentsIsMutable(); - availableSegments_.add(value); - onChanged(); - return this; - } - - private int retryInterval_; - - /** - * int32 retryInterval = 3; - */ - public int getRetryInterval() { - return retryInterval_; - } - - /** - * int32 retryInterval = 3; - */ - public Builder setRetryInterval(int value) { - - retryInterval_ = value; - onChanged(); - return this; - } - - /** - * int32 retryInterval = 3; - */ - public Builder clearRetryInterval() { - - retryInterval_ = 0; - onChanged(); - return this; - } - - public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFieldsProto3(unknownFields); - } - - public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); - } - - // @@protoc_insertion_point(builder_scope:SyncConfigResponsePb) - } - - // @@protoc_insertion_point(class_scope:SyncConfigResponsePb) - private static final com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb(); - } - - public static com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { - public SyncConfigResponsePb parsePartialFrom(com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new SyncConfigResponsePb( - input, - extensionRegistry); - } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @java.lang.Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - public com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } + @java.lang.Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + public com.alipay.sofa.registry.common.model.client.pb.SyncConfigResponsePb + getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePbOrBuilder.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePbOrBuilder.java index e31ce58e5..ad1877a7a 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePbOrBuilder.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePbOrBuilder.java @@ -14,52 +14,34 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: SyncConfigResponsePb.proto - package com.alipay.sofa.registry.common.model.client.pb; -public interface SyncConfigResponsePbOrBuilder extends -// @@protoc_insertion_point(interface_extends:SyncConfigResponsePb) - com.google.protobuf.MessageOrBuilder { +public interface SyncConfigResponsePbOrBuilder + extends + // @@protoc_insertion_point(interface_extends:SyncConfigResponsePb) + com.google.protobuf.MessageOrBuilder { - /** - * .ResultPb result = 1; - */ - boolean hasResult(); + /** .ResultPb result = 1; */ + boolean hasResult(); - /** - * .ResultPb result = 1; - */ - com.alipay.sofa.registry.common.model.client.pb.ResultPb getResult(); + /** .ResultPb result = 1; */ + com.alipay.sofa.registry.common.model.client.pb.ResultPb getResult(); - /** - * .ResultPb result = 1; - */ - com.alipay.sofa.registry.common.model.client.pb.ResultPbOrBuilder getResultOrBuilder(); + /** .ResultPb result = 1; */ + com.alipay.sofa.registry.common.model.client.pb.ResultPbOrBuilder getResultOrBuilder(); - /** - * repeated string availableSegments = 2; - */ - java.util.List getAvailableSegmentsList(); + /** repeated string availableSegments = 2; */ + java.util.List getAvailableSegmentsList(); - /** - * repeated string availableSegments = 2; - */ - int getAvailableSegmentsCount(); + /** repeated string availableSegments = 2; */ + int getAvailableSegmentsCount(); - /** - * repeated string availableSegments = 2; - */ - java.lang.String getAvailableSegments(int index); + /** repeated string availableSegments = 2; */ + java.lang.String getAvailableSegments(int index); - /** - * repeated string availableSegments = 2; - */ - com.google.protobuf.ByteString getAvailableSegmentsBytes(int index); + /** repeated string availableSegments = 2; */ + com.google.protobuf.ByteString getAvailableSegmentsBytes(int index); - /** - * int32 retryInterval = 3; - */ - int getRetryInterval(); + /** int32 retryInterval = 3; */ + int getRetryInterval(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePbOuterClass.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePbOuterClass.java index d5e57fd46..83b8422de 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePbOuterClass.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/client/pb/SyncConfigResponsePbOuterClass.java @@ -14,60 +14,60 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -// Generated by the protocol buffer compiler. DO NOT EDIT! -// source: SyncConfigResponsePb.proto - package com.alipay.sofa.registry.common.model.client.pb; public final class SyncConfigResponsePbOuterClass { - private SyncConfigResponsePbOuterClass() { - } + private SyncConfigResponsePbOuterClass() {} + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); - } + static final com.google.protobuf.Descriptors.Descriptor + internal_static_SyncConfigResponsePb_descriptor; + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable + internal_static_SyncConfigResponsePb_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor internal_static_SyncConfigResponsePb_descriptor; - static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_SyncConfigResponsePb_fieldAccessorTable; + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } - public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { - return descriptor; - } + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - private static com.google.protobuf.Descriptors.FileDescriptor descriptor; - static { - java.lang.String[] descriptorData = {"\n\032SyncConfigResponsePb.proto\032\016ResultPb.p" - + "roto\"c\n\024SyncConfigResponsePb\022\031\n\006result\030\001" - + " \001(\0132\t.ResultPb\022\031\n\021availableSegments\030\002 \003" - + "(\t\022\025\n\rretryInterval\030\003 \001(\005B7\n/com.alipay." - + "sofa.registry.common.model.client.pbP\001Z\002" - + "pbb\006proto3"}; - com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { - public com.google.protobuf.ExtensionRegistry assignDescriptors( - com.google.protobuf.Descriptors.FileDescriptor root) { - descriptor = root; - return null; - } - }; - com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom( - descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[]{com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass - .getDescriptor(),}, assigner); - internal_static_SyncConfigResponsePb_descriptor = getDescriptor() - .getMessageTypes().get(0); - internal_static_SyncConfigResponsePb_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_SyncConfigResponsePb_descriptor, - new java.lang.String[]{"Result", "AvailableSegments", - "RetryInterval",}); - com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass - .getDescriptor(); - } + static { + java.lang.String[] descriptorData = { + "\n\032SyncConfigResponsePb.proto\032\016ResultPb.p" + + "roto\"c\n\024SyncConfigResponsePb\022\031\n\006result\030\001" + + " \001(\0132\t.ResultPb\022\031\n\021availableSegments\030\002 \003" + + "(\t\022\025\n\rretryInterval\030\003 \001(\005B7\n/com.alipay." + + "sofa.registry.common.model.client.pbP\001Z\002" + + "pbb\006proto3" + }; + com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = + new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { + public com.google.protobuf.ExtensionRegistry assignDescriptors( + com.google.protobuf.Descriptors.FileDescriptor root) { + descriptor = root; + return null; + } + }; + com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom( + descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] { + com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass.getDescriptor(), + }, + assigner); + internal_static_SyncConfigResponsePb_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_SyncConfigResponsePb_fieldAccessorTable = + new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_SyncConfigResponsePb_descriptor, + new java.lang.String[] { + "Result", "AvailableSegments", "RetryInterval", + }); + com.alipay.sofa.registry.common.model.client.pb.ResultPbOuterClass.getDescriptor(); + } - // @@protoc_insertion_point(outer_class_scope) + // @@protoc_insertion_point(outer_class_scope) } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/console/PersistenceData.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/console/PersistenceData.java index 75ae50f11..d7d7820e4 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/console/PersistenceData.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/console/PersistenceData.java @@ -19,116 +19,128 @@ import java.io.Serializable; /** - * * @author shangyu.wh * @version $Id: PersistenceData.java, v 0.1 2018-04-18 11:20 shangyu.wh Exp $ */ public class PersistenceData implements Serializable { - private String dataId; - - private String group; - - private String instanceId; - - private Long version; - - private String data; - - /** - * Getter method for property version. - * - * @return property value of version - */ - public Long getVersion() { - return version; - } - - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * Getter method for property data. - * - * @return property value of data - */ - public String getData() { - return data; - } - - /** - * Setter method for property data. - * - * @param data value to be assigned to property data - */ - public void setData(String data) { - this.data = data; - } - - /** - * Getter method for property dataId. - * - * @return property value of dataId - */ - public String getDataId() { - return dataId; - } - - /** - * Setter method for property dataId. - * - * @param dataId value to be assigned to property dataId - */ - public void setDataId(String dataId) { - this.dataId = dataId; - } - - /** - * Getter method for property group. - * - * @return property value of group - */ - public String getGroup() { - return group; - } - - /** - * Setter method for property group. - * - * @param group value to be assigned to property group - */ - public void setGroup(String group) { - this.group = group; - } - - /** - * Getter method for property instanceId. - * - * @return property value of instanceId - */ - public String getInstanceId() { - return instanceId; - } - - /** - * Setter method for property instanceId. - * - * @param instanceId value to be assigned to property instanceId - */ - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; - } - - @Override - public String toString() { - return "PersistenceData{" + "dataId='" + dataId + '\'' + ", group='" + group + '\'' - + ", instanceId='" + instanceId + '\'' + ", version=" + version + ", data='" + data - + '\'' + '}'; - } -} \ No newline at end of file + private String dataId; + + private String group; + + private String instanceId; + + private Long version; + + private String data; + + /** + * Getter method for property version. + * + * @return property value of version + */ + public Long getVersion() { + return version; + } + + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * Getter method for property data. + * + * @return property value of data + */ + public String getData() { + return data; + } + + /** + * Setter method for property data. + * + * @param data value to be assigned to property data + */ + public void setData(String data) { + this.data = data; + } + + /** + * Getter method for property dataId. + * + * @return property value of dataId + */ + public String getDataId() { + return dataId; + } + + /** + * Setter method for property dataId. + * + * @param dataId value to be assigned to property dataId + */ + public void setDataId(String dataId) { + this.dataId = dataId; + } + + /** + * Getter method for property group. + * + * @return property value of group + */ + public String getGroup() { + return group; + } + + /** + * Setter method for property group. + * + * @param group value to be assigned to property group + */ + public void setGroup(String group) { + this.group = group; + } + + /** + * Getter method for property instanceId. + * + * @return property value of instanceId + */ + public String getInstanceId() { + return instanceId; + } + + /** + * Setter method for property instanceId. + * + * @param instanceId value to be assigned to property instanceId + */ + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + @Override + public String toString() { + return "PersistenceData{" + + "dataId='" + + dataId + + '\'' + + ", group='" + + group + + '\'' + + ", instanceId='" + + instanceId + + '\'' + + ", version=" + + version + + ", data='" + + data + + '\'' + + '}'; + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/constants/ValueConstants.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/constants/ValueConstants.java index 4c91c8735..360f2ee0c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/constants/ValueConstants.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/constants/ValueConstants.java @@ -22,66 +22,55 @@ */ public class ValueConstants { - /** - * connectId: sourceAddress_targetAddress - */ - public static final String CONNECT_ID_SPLIT = "_"; + /** connectId: sourceAddress_targetAddress */ + public static final String CONNECT_ID_SPLIT = "_"; - /** - * The constant DEFAULT_GROUP. - */ - public static final String DEFAULT_GROUP = "DEFAULT_GROUP"; + /** The constant DEFAULT_GROUP. */ + public static final String DEFAULT_GROUP = "DEFAULT_GROUP"; - /** - * The constant DEFAULT_ZONE. - */ - public static final String DEFAULT_ZONE = "DEFAULT_ZONE"; + /** The constant DEFAULT_ZONE. */ + public static final String DEFAULT_ZONE = "DEFAULT_ZONE"; - public static final String DEFAULT_INSTANCE_ID = "DEFAULT_INSTANCE_ID"; + public static final String DEFAULT_INSTANCE_ID = "DEFAULT_INSTANCE_ID"; - /** - * The constant DEFAULT_DATA_CENTER. - */ - public static final String DEFAULT_DATA_CENTER = "DefaultDataCenter"; + /** The constant DEFAULT_DATA_CENTER. */ + public static final String DEFAULT_DATA_CENTER = "DefaultDataCenter"; - public static final long DEFAULT_NO_DATUM_VERSION = 1L; + public static final long DEFAULT_NO_DATUM_VERSION = 1L; - private static final Integer SYSTEM_RAFT_PORT = Integer - .getInteger("RAFT_SERVER_PORT"); + private static final Integer SYSTEM_RAFT_PORT = Integer.getInteger("RAFT_SERVER_PORT"); - public static final int RAFT_SERVER_PORT = SYSTEM_RAFT_PORT != null - ? SYSTEM_RAFT_PORT - : 9614; + public static final int RAFT_SERVER_PORT = SYSTEM_RAFT_PORT != null ? SYSTEM_RAFT_PORT : 9614; - public static final int CROSS_DC_META_SYNC_INTERVAL_MILLI = Integer - .getInteger("CROSS_DC_META_SYNC_INTERVAL_MILLI", 60 * 1000); + public static final int CROSS_DC_META_SYNC_INTERVAL_MILLI = + Integer.getInteger("CROSS_DC_META_SYNC_INTERVAL_MILLI", 60 * 1000); - private static final String SYSTEM_RAFT_GROUP = System - .getProperty("RAFT_SERVER_GROUP"); + private static final String SYSTEM_RAFT_GROUP = System.getProperty("RAFT_SERVER_GROUP"); - public static final String RAFT_SERVER_GROUP = SYSTEM_RAFT_GROUP != null - ? SYSTEM_RAFT_GROUP - : "RegistryGroup"; + public static final String RAFT_SERVER_GROUP = + SYSTEM_RAFT_GROUP != null ? SYSTEM_RAFT_GROUP : "RegistryGroup"; - public static final String STOP_PUSH_DATA_SWITCH_DATA_ID = "session.stop.push.data.switch#@#9600#@#CONFIG"; + public static final String STOP_PUSH_DATA_SWITCH_DATA_ID = + "session.stop.push.data.switch#@#9600#@#CONFIG"; - public static final String BLACK_LIST_DATA_ID = "session.blacklist.data#@#9600#@#CONFIG"; + public static final String BLACK_LIST_DATA_ID = "session.blacklist.data#@#9600#@#CONFIG"; - public static final String DATA_DATUM_SYNC_SESSION_INTERVAL_SEC = "data.datum.sync.session.interval.sec#@#9600#@#CONFIG"; + public static final String DATA_DATUM_SYNC_SESSION_INTERVAL_SEC = + "data.datum.sync.session.interval.sec#@#9600#@#CONFIG"; - public static final String DATA_SESSION_LEASE_SEC = "data.session.lease.sec#@#9600#@#CONFIG"; + public static final String DATA_SESSION_LEASE_SEC = "data.session.lease.sec#@#9600#@#CONFIG"; - public static final String DISABLE_DATA_ID_CASE_SENSITIVE_SWITCH = "disable.dataId.case.sensitive"; - /** - * switch for dataId sensitive is disable or not, default value is false - * which means dataId is case sensitive - */ - public static final boolean DISABLE_DATA_ID_CASE_SENSITIVE = Boolean - .parseBoolean(System - .getProperty(DISABLE_DATA_ID_CASE_SENSITIVE_SWITCH)); + public static final String DISABLE_DATA_ID_CASE_SENSITIVE_SWITCH = + "disable.dataId.case.sensitive"; + /** + * switch for dataId sensitive is disable or not, default value is false which means dataId is + * case sensitive + */ + public static final boolean DISABLE_DATA_ID_CASE_SENSITIVE = + Boolean.parseBoolean(System.getProperty(DISABLE_DATA_ID_CASE_SENSITIVE_SWITCH)); - // response status code - public static final int METADATA_STATUS_PROCESS_SUCCESS = 200; - public static final int METADATA_STATUS_DATA_NOT_FOUND = 404; - public static final int METADATA_STATUS_PROCESS_ERROR = 500; + // response status code + public static final int METADATA_STATUS_PROCESS_SUCCESS = 200; + public static final int METADATA_STATUS_DATA_NOT_FOUND = 404; + public static final int METADATA_STATUS_PROCESS_ERROR = 500; } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/AbstractSlotRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/AbstractSlotRequest.java index b21ab858c..6a7060cf3 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/AbstractSlotRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/AbstractSlotRequest.java @@ -17,62 +17,59 @@ package com.alipay.sofa.registry.common.model.dataserver; import com.alipay.sofa.registry.common.model.ProcessId; - import java.io.Serializable; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-04 16:44 yuzhi.lyz Exp $ */ public abstract class AbstractSlotRequest implements Serializable { - protected final ProcessId sessionProcessId; - private final int slotId; - protected long slotTableEpoch; - protected long slotLeaderEpoch; + protected final ProcessId sessionProcessId; + private final int slotId; + protected long slotTableEpoch; + protected long slotLeaderEpoch; - protected AbstractSlotRequest(int slotId, ProcessId sessionProcessId) { - this.slotId = slotId; - this.sessionProcessId = sessionProcessId; - } + protected AbstractSlotRequest(int slotId, ProcessId sessionProcessId) { + this.slotId = slotId; + this.sessionProcessId = sessionProcessId; + } - /** - * Getter method for property sessionProcessId. - * - * @return property value of sessionProcessId - */ - public ProcessId getSessionProcessId() { - return sessionProcessId; - } + /** + * Getter method for property sessionProcessId. + * + * @return property value of sessionProcessId + */ + public ProcessId getSessionProcessId() { + return sessionProcessId; + } - /** - * Getter method for property slotTableEpoch. - * - * @return property value of slotTableEpoch - */ - public long getSlotTableEpoch() { - return slotTableEpoch; - } + /** + * Getter method for property slotTableEpoch. + * + * @return property value of slotTableEpoch + */ + public long getSlotTableEpoch() { + return slotTableEpoch; + } - /** - * Setter method for property slotTableEpoch. - * - * @param slotTableEpoch - * value to be assigned to property slotTableEpoch - */ - public void setSlotTableEpoch(long slotTableEpoch) { - this.slotTableEpoch = slotTableEpoch; - } + /** + * Setter method for property slotTableEpoch. + * + * @param slotTableEpoch value to be assigned to property slotTableEpoch + */ + public void setSlotTableEpoch(long slotTableEpoch) { + this.slotTableEpoch = slotTableEpoch; + } - public long getSlotLeaderEpoch() { - return slotLeaderEpoch; - } + public long getSlotLeaderEpoch() { + return slotLeaderEpoch; + } - public void setSlotLeaderEpoch(long slotLeaderEpoch) { - this.slotLeaderEpoch = slotLeaderEpoch; - } + public void setSlotLeaderEpoch(long slotLeaderEpoch) { + this.slotLeaderEpoch = slotLeaderEpoch; + } - public int getSlotId() { - return slotId; - } + public int getSlotId() { + return slotId; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/BatchRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/BatchRequest.java index 0de499fd5..548773eb3 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/BatchRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/BatchRequest.java @@ -19,24 +19,27 @@ import com.alipay.sofa.registry.common.model.ProcessId; import com.alipay.sofa.registry.util.StringFormatter; import com.google.common.collect.Lists; - import java.util.List; public class BatchRequest extends AbstractSlotRequest { - private final List request; + private final List request; - public BatchRequest(ProcessId sessionProcessId, int slotId, List request) { - super(slotId, sessionProcessId); - this.request = Lists.newArrayList(request); - } + public BatchRequest(ProcessId sessionProcessId, int slotId, List request) { + super(slotId, sessionProcessId); + this.request = Lists.newArrayList(request); + } - public List getRequest() { - return request; - } + public List getRequest() { + return request; + } - @Override - public String toString() { - return StringFormatter.format("Batch:{},{},{},{}", getSlotId(), request.size(), - getSlotLeaderEpoch(), getSlotTableEpoch()); - } + @Override + public String toString() { + return StringFormatter.format( + "Batch:{},{},{},{}", + getSlotId(), + request.size(), + getSlotLeaderEpoch(), + getSlotTableEpoch()); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/ClientOffPublisher.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/ClientOffPublisher.java index 8d878b7bb..723bb5994 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/ClientOffPublisher.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/ClientOffPublisher.java @@ -17,11 +17,9 @@ package com.alipay.sofa.registry.common.model.dataserver; import com.alipay.sofa.registry.common.model.ConnectId; -import com.alipay.sofa.registry.common.model.ProcessId; import com.alipay.sofa.registry.common.model.RegisterVersion; import com.alipay.sofa.registry.common.model.store.Publisher; import com.google.common.collect.Maps; - import java.io.Serializable; import java.util.*; @@ -32,36 +30,40 @@ * @version $Id: ClientOffPublisher.java, v 0.1 2017-12-01 15:48 qian.lqlq Exp $ */ public final class ClientOffPublisher implements Serializable { - private static final long serialVersionUID = -3547806571058756207L; + private static final long serialVersionUID = -3547806571058756207L; - private final ConnectId connectId; - private final Map> publisherMap = Maps.newHashMap(); + private final ConnectId connectId; + private final Map> publisherMap = Maps.newHashMap(); - public ClientOffPublisher(ConnectId connectId) { - this.connectId = connectId; - } + public ClientOffPublisher(ConnectId connectId) { + this.connectId = connectId; + } - public void addPublisher(Publisher publisher) { - Map publishers = publisherMap.computeIfAbsent( - publisher.getDataInfoId(), k -> Maps.newHashMap()); - publishers.put(publisher.getRegisterId(), publisher.registerVersion()); - } + public void addPublisher(Publisher publisher) { + Map publishers = + publisherMap.computeIfAbsent(publisher.getDataInfoId(), k -> Maps.newHashMap()); + publishers.put(publisher.getRegisterId(), publisher.registerVersion()); + } - public ConnectId getConnectId() { - return connectId; - } + public ConnectId getConnectId() { + return connectId; + } - public Map> getPublisherMap() { - return publisherMap; - } + public Map> getPublisherMap() { + return publisherMap; + } - public boolean isEmpty() { - return publisherMap.isEmpty(); - } + public boolean isEmpty() { + return publisherMap.isEmpty(); + } - @Override - public String toString() { - return "ClientOffPublisher{" + "connectId=" + connectId + ", publisherMap=" + publisherMap - + '}'; - } + @Override + public String toString() { + return "ClientOffPublisher{" + + "connectId=" + + connectId + + ", publisherMap=" + + publisherMap + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/Datum.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/Datum.java index 04529d232..4e7df528f 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/Datum.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/Datum.java @@ -16,14 +16,13 @@ */ package com.alipay.sofa.registry.common.model.dataserver; -import java.io.Serializable; -import java.util.Collections; -import java.util.Map; - import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.common.model.store.WordCache; import com.alipay.sofa.registry.util.DatumVersionUtil; import com.google.common.collect.Maps; +import java.io.Serializable; +import java.util.Collections; +import java.util.Map; /** * datum store in dataserver @@ -33,222 +32,226 @@ */ public class Datum implements Serializable { - private static final long serialVersionUID = 5307489721610438103L; - - private String dataInfoId; - - private String dataCenter; - - private String dataId; - - private String instanceId; - - private String group; - //key=registerId - private final Map pubMap = Maps.newHashMap(); - - private long version; - - /** - * constructor - */ - public Datum() { - } - - /** - * constructor - * @param dataInfoId - * @param dataCenter - */ - public Datum(String dataInfoId, String dataCenter) { - this.dataInfoId = WordCache.getWordCache(dataInfoId); - this.dataCenter = WordCache.getWordCache(dataCenter); - updateVersion(); - } - - /** - * constructor - * @param publisher - * @param dataCenter - */ - public Datum(Publisher publisher, String dataCenter) { - this(publisher.getDataInfoId(), dataCenter); - this.dataId = publisher.getDataId(); - this.instanceId = publisher.getInstanceId(); - this.group = publisher.getGroup(); - addPublisher(publisher); - } - - /** - * constructor - * @param publisher - * @param dataCenter - * @param version - */ - public Datum(Publisher publisher, String dataCenter, long version) { - this.dataInfoId = publisher.getDataInfoId(); - this.dataCenter = WordCache.getWordCache(dataCenter); - this.version = version; - this.dataId = publisher.getDataId(); - this.instanceId = publisher.getInstanceId(); - this.group = publisher.getGroup(); - addPublisher(publisher); - } - - public void updateVersion() { - this.version = DatumVersionUtil.nextId(); - } - - /** - * Getter method for property dataInfoId. - * - * @return property value of dataInfoId - */ - public String getDataInfoId() { - return dataInfoId; - } - - /** - * Setter method for property dataInfoId. - * - * @param dataInfoId value to be assigned to property dataInfoId - */ - public void setDataInfoId(String dataInfoId) { - this.dataInfoId = WordCache.getWordCache(dataInfoId); + private static final long serialVersionUID = 5307489721610438103L; + + private String dataInfoId; + + private String dataCenter; + + private String dataId; + + private String instanceId; + + private String group; + // key=registerId + private final Map pubMap = Maps.newHashMap(); + + private long version; + + /** constructor */ + public Datum() {} + + /** + * constructor + * + * @param dataInfoId + * @param dataCenter + */ + public Datum(String dataInfoId, String dataCenter) { + this.dataInfoId = WordCache.getWordCache(dataInfoId); + this.dataCenter = WordCache.getWordCache(dataCenter); + updateVersion(); + } + + /** + * constructor + * + * @param publisher + * @param dataCenter + */ + public Datum(Publisher publisher, String dataCenter) { + this(publisher.getDataInfoId(), dataCenter); + this.dataId = publisher.getDataId(); + this.instanceId = publisher.getInstanceId(); + this.group = publisher.getGroup(); + addPublisher(publisher); + } + + /** + * constructor + * + * @param publisher + * @param dataCenter + * @param version + */ + public Datum(Publisher publisher, String dataCenter, long version) { + this.dataInfoId = publisher.getDataInfoId(); + this.dataCenter = WordCache.getWordCache(dataCenter); + this.version = version; + this.dataId = publisher.getDataId(); + this.instanceId = publisher.getInstanceId(); + this.group = publisher.getGroup(); + addPublisher(publisher); + } + + public void updateVersion() { + this.version = DatumVersionUtil.nextId(); + } + + /** + * Getter method for property dataInfoId. + * + * @return property value of dataInfoId + */ + public String getDataInfoId() { + return dataInfoId; + } + + /** + * Setter method for property dataInfoId. + * + * @param dataInfoId value to be assigned to property dataInfoId + */ + public void setDataInfoId(String dataInfoId) { + this.dataInfoId = WordCache.getWordCache(dataInfoId); + } + + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * Setter method for property dataCenter. + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = WordCache.getWordCache(dataCenter); + } + + /** + * Getter method for property dataId. + * + * @return property value of dataId + */ + public String getDataId() { + return dataId; + } + + /** + * Setter method for property dataId. + * + * @param dataId value to be assigned to property dataId + */ + public void setDataId(String dataId) { + this.dataId = WordCache.getWordCache(dataId); + } + + /** + * Getter method for property instanceId. + * + * @return property value of instanceId + */ + public String getInstanceId() { + return instanceId; + } + + /** + * Setter method for property instanceId. + * + * @param instanceId value to be assigned to property instanceId + */ + public void setInstanceId(String instanceId) { + this.instanceId = WordCache.getWordCache(instanceId); + } + + /** + * Getter method for property group. + * + * @return property value of group + */ + public String getGroup() { + return group; + } + + /** + * Setter method for property group. + * + * @param group value to be assigned to property group + */ + public void setGroup(String group) { + this.group = WordCache.getWordCache(group); + } + + /** + * Getter method for property version. + * + * @return property value of version + */ + public long getVersion() { + return version; + } + + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(long version) { + this.version = version; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(128); + sb.append("Datum={") + .append(dataInfoId) + .append(", dataCenter=") + .append(dataCenter) + .append(", size=") + .append(publisherSize()) + .append(", ver=") + .append(version) + .append('}'); + return sb.toString(); + } + + public synchronized boolean addPublisher(Publisher publisher) { + Publisher existing = pubMap.computeIfAbsent(publisher.getRegisterId(), k -> publisher); + if (existing == publisher) { + return true; } - - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } - - /** - * Setter method for property dataCenter. - * - * @param dataCenter value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = WordCache.getWordCache(dataCenter); - } - - /** - * Getter method for property dataId. - * - * @return property value of dataId - */ - public String getDataId() { - return dataId; - } - - /** - * Setter method for property dataId. - * - * @param dataId value to be assigned to property dataId - */ - public void setDataId(String dataId) { - this.dataId = WordCache.getWordCache(dataId); - } - - /** - * Getter method for property instanceId. - * - * @return property value of instanceId - */ - public String getInstanceId() { - return instanceId; - } - - /** - * Setter method for property instanceId. - * - * @param instanceId value to be assigned to property instanceId - */ - public void setInstanceId(String instanceId) { - this.instanceId = WordCache.getWordCache(instanceId); - } - - /** - * Getter method for property group. - * - * @return property value of group - */ - public String getGroup() { - return group; + if (!existing.registerVersion().orderThan(publisher.registerVersion())) { + return false; } + pubMap.put(publisher.getRegisterId(), publisher); + return true; + } - /** - * Setter method for property group. - * - * @param group value to be assigned to property group - */ - public void setGroup(String group) { - this.group = WordCache.getWordCache(group); - } - - /** - * Getter method for property version. - * - * @return property value of version - */ - public long getVersion() { - return version; - } + public synchronized int publisherSize() { + return pubMap.size(); + } - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(long version) { - this.version = version; + public synchronized void addPublishers(Map publisherMap) { + if (publisherMap != null) { + publisherMap.values().forEach(p -> addPublisher(p)); } + } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(128); - sb.append("Datum={").append(dataInfoId).append(", dataCenter=").append(dataCenter) - .append(", size=").append(publisherSize()).append(", ver=").append(version).append('}'); - return sb.toString(); - } + public synchronized Map getPubMap() { + return Collections.unmodifiableMap(Maps.newHashMap(pubMap)); + } - public synchronized boolean addPublisher(Publisher publisher) { - Publisher existing = pubMap.computeIfAbsent(publisher.getRegisterId(), k -> publisher); - if (existing == publisher) { - return true; - } - if (!existing.registerVersion().orderThan(publisher.registerVersion())) { - return false; - } - pubMap.put(publisher.getRegisterId(), publisher); - return true; + /** should not call that, just for json serde */ + public synchronized void setPubMap(Map pubMap) { + this.pubMap.clear(); + if (pubMap != null) { + this.pubMap.putAll(pubMap); } - - public synchronized int publisherSize() { - return pubMap.size(); - } - - public synchronized void addPublishers(Map publisherMap) { - if (publisherMap != null) { - publisherMap.values().forEach(p->addPublisher(p)); - } - } - - public synchronized Map getPubMap() { - return Collections.unmodifiableMap(Maps.newHashMap(pubMap)); - } - - /** - * should not call that, just for json serde - */ - public synchronized void setPubMap(Map pubMap) { - this.pubMap.clear(); - if (pubMap != null) { - this.pubMap.putAll(pubMap); - } - } - + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumDigest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumDigest.java index a7a41f6b0..3fcd3fda6 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumDigest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumDigest.java @@ -20,41 +20,46 @@ import java.util.Objects; public final class DatumDigest implements Serializable { - private final long publisherIdSign; - private final long publisherVerSign; - private final long publisherTimestampSign; - private final int publisherNum; + private final long publisherIdSign; + private final long publisherVerSign; + private final long publisherTimestampSign; + private final int publisherNum; - public DatumDigest(int publisherNum, long publisherIdSign, long publisherVerSign, - long publisherTimestampSign) { - this.publisherNum = publisherNum; - this.publisherIdSign = publisherIdSign; - this.publisherVerSign = publisherVerSign; - this.publisherTimestampSign = publisherTimestampSign; - } + public DatumDigest( + int publisherNum, long publisherIdSign, long publisherVerSign, long publisherTimestampSign) { + this.publisherNum = publisherNum; + this.publisherIdSign = publisherIdSign; + this.publisherVerSign = publisherVerSign; + this.publisherTimestampSign = publisherTimestampSign; + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - DatumDigest that = (DatumDigest) o; - return publisherNum == that.publisherNum && publisherIdSign == that.publisherIdSign - && publisherVerSign == that.publisherVerSign - && publisherTimestampSign == that.publisherTimestampSign; - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DatumDigest that = (DatumDigest) o; + return publisherNum == that.publisherNum + && publisherIdSign == that.publisherIdSign + && publisherVerSign == that.publisherVerSign + && publisherTimestampSign == that.publisherTimestampSign; + } - @Override - public int hashCode() { - return Objects - .hash(publisherNum, publisherIdSign, publisherVerSign, publisherTimestampSign); - } + @Override + public int hashCode() { + return Objects.hash(publisherNum, publisherIdSign, publisherVerSign, publisherTimestampSign); + } - @Override - public String toString() { - return "DatumDigest{" + "publisherNum=" + publisherNum + ", publisherIdSign=" - + publisherIdSign + ", publisherVerSign=" + publisherVerSign - + ", publisherTimestampSign=" + publisherTimestampSign + '}'; - } + @Override + public String toString() { + return "DatumDigest{" + + "publisherNum=" + + publisherNum + + ", publisherIdSign=" + + publisherIdSign + + ", publisherVerSign=" + + publisherVerSign + + ", publisherTimestampSign=" + + publisherTimestampSign + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumSummary.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumSummary.java index e02c48da3..94fa2b55d 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumSummary.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumSummary.java @@ -19,89 +19,86 @@ import com.alipay.sofa.registry.common.model.RegisterVersion; import com.alipay.sofa.registry.common.model.store.Publisher; import com.google.common.collect.Maps; - import java.io.Serializable; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.Map; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-05 14:27 yuzhi.lyz Exp $ */ public class DatumSummary implements Serializable { - private final String dataInfoId; - private final Map publisherVersions; + private final String dataInfoId; + private final Map publisherVersions; - public DatumSummary(String dataInfoId, - Map publisherVersions) { - this.dataInfoId = dataInfoId; - this.publisherVersions = Collections.unmodifiableMap(publisherVersions); - } - - public DatumSummary(String dataInfoId) { - this.dataInfoId = dataInfoId; - this.publisherVersions = Collections.emptyMap(); - } + public DatumSummary( + String dataInfoId, Map publisherVersions) { + this.dataInfoId = dataInfoId; + this.publisherVersions = Collections.unmodifiableMap(publisherVersions); + } - public static DatumSummary of(String dataInfoId, Map publisherMap) { - Map versionMap = Maps.newHashMapWithExpectedSize(publisherMap - .size()); - for (Map.Entry e : publisherMap.entrySet()) { - versionMap.put(e.getKey(), e.getValue().registerVersion()); - } - return new DatumSummary(dataInfoId, versionMap); - } + public DatumSummary(String dataInfoId) { + this.dataInfoId = dataInfoId; + this.publisherVersions = Collections.emptyMap(); + } - /** - * Getter method for property dataInfoId. - * @return property value of dataInfoId - */ - public String getDataInfoId() { - return dataInfoId; + public static DatumSummary of(String dataInfoId, Map publisherMap) { + Map versionMap = Maps.newHashMapWithExpectedSize(publisherMap.size()); + for (Map.Entry e : publisherMap.entrySet()) { + versionMap.put(e.getKey(), e.getValue().registerVersion()); } + return new DatumSummary(dataInfoId, versionMap); + } - /** - * Getter method for property publisherVersions. - * @return property value of publisherVersions - */ - public Map getPublisherVersions() { - return publisherVersions; - } + /** + * Getter method for property dataInfoId. + * + * @return property value of dataInfoId + */ + public String getDataInfoId() { + return dataInfoId; + } - public Map getPublisherVersions(Collection registerIds) { - Map m = Maps.newHashMapWithExpectedSize(registerIds.size()); - for (String registerId : registerIds) { - RegisterVersion v = publisherVersions.get(registerId); - if (v == null) { - throw new IllegalArgumentException("not contains registerId:" + registerId); - } - m.put(registerId, v); - } - return m; - } + /** + * Getter method for property publisherVersions. + * + * @return property value of publisherVersions + */ + public Map getPublisherVersions() { + return publisherVersions; + } - public boolean isEmpty() { - return publisherVersions.isEmpty(); + public Map getPublisherVersions(Collection registerIds) { + Map m = Maps.newHashMapWithExpectedSize(registerIds.size()); + for (String registerId : registerIds) { + RegisterVersion v = publisherVersions.get(registerId); + if (v == null) { + throw new IllegalArgumentException("not contains registerId:" + registerId); + } + m.put(registerId, v); } + return m; + } - public int size() { - return publisherVersions.size(); - } + public boolean isEmpty() { + return publisherVersions.isEmpty(); + } - public static int countPublisherSize(Collection summaries) { - int count = 0; - for (DatumSummary summary : summaries) { - count += summary.size(); - } - return count; - } + public int size() { + return publisherVersions.size(); + } - @Override - public String toString() { - return String.format("Summary={%s=%d}", dataInfoId, size()); + public static int countPublisherSize(Collection summaries) { + int count = 0; + for (DatumSummary summary : summaries) { + count += summary.size(); } + return count; + } + @Override + public String toString() { + return String.format("Summary={%s=%d}", dataInfoId, size()); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumVersion.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumVersion.java index ebb1338d0..d2ff0944c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumVersion.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/DatumVersion.java @@ -24,42 +24,40 @@ */ public final class DatumVersion implements Serializable { - private final long value; - - public DatumVersion(long v) { - this.value = v; - } - - /** - * Getter method for property value. - * - * @return property value of value - */ - public long getValue() { - return value; - } - - @Override - public String toString() { - return Long.valueOf(value).toString(); - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - DatumVersion that = (DatumVersion) o; - return value == that.value; - } - - @Override - public int hashCode() { - return Long.valueOf(value).hashCode(); - } - - public static DatumVersion of(long v) { - return new DatumVersion(v); - } + private final long value; + + public DatumVersion(long v) { + this.value = v; + } + + /** + * Getter method for property value. + * + * @return property value of value + */ + public long getValue() { + return value; + } + + @Override + public String toString() { + return Long.valueOf(value).toString(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DatumVersion that = (DatumVersion) o; + return value == that.value; + } + + @Override + public int hashCode() { + return Long.valueOf(value).hashCode(); + } + + public static DatumVersion of(long v) { + return new DatumVersion(v); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/GetDataRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/GetDataRequest.java index d2fe6c5af..7ae6cf88e 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/GetDataRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/GetDataRequest.java @@ -27,43 +27,46 @@ */ public class GetDataRequest extends AbstractSlotRequest { - private static final long serialVersionUID = 8133437572926931258L; + private static final long serialVersionUID = 8133437572926931258L; - private final String dataInfoId; + private final String dataInfoId; - /** - * if datacenter is null, means all datacenters - */ - private final String dataCenter; + /** if datacenter is null, means all datacenters */ + private final String dataCenter; - public GetDataRequest(ProcessId sessionProcessId, String dataInfoId, String dataCenter, - int slotId) { - super(slotId, sessionProcessId); - this.dataInfoId = dataInfoId; - this.dataCenter = dataCenter; - } + public GetDataRequest( + ProcessId sessionProcessId, String dataInfoId, String dataCenter, int slotId) { + super(slotId, sessionProcessId); + this.dataInfoId = dataInfoId; + this.dataCenter = dataCenter; + } - /** - * Getter method for property dataInfoId. - * - * @return property value of dataInfoId - */ - public String getDataInfoId() { - return dataInfoId; - } + /** + * Getter method for property dataInfoId. + * + * @return property value of dataInfoId + */ + public String getDataInfoId() { + return dataInfoId; + } - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } - @Override - public String toString() { - return StringFormatter.format("GetData:{},{},{},{},{}", dataInfoId, dataCenter, - getSlotId(), getSlotLeaderEpoch(), getSlotTableEpoch()); - } + @Override + public String toString() { + return StringFormatter.format( + "GetData:{},{},{},{},{}", + dataInfoId, + dataCenter, + getSlotId(), + getSlotLeaderEpoch(), + getSlotTableEpoch()); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/GetDataVersionRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/GetDataVersionRequest.java index 5d939f27b..c092cc57c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/GetDataVersionRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/GetDataVersionRequest.java @@ -18,12 +18,8 @@ import com.alipay.sofa.registry.common.model.ProcessId; import com.alipay.sofa.registry.util.StringFormatter; -import com.google.common.collect.Lists; import com.google.common.collect.Maps; - -import java.io.Serializable; import java.util.Collections; -import java.util.List; import java.util.Map; /** @@ -34,33 +30,39 @@ */ public class GetDataVersionRequest extends AbstractSlotRequest { - private static final long serialVersionUID = 8942977145684175886L; + private static final long serialVersionUID = 8942977145684175886L; - private final String dataCenter; - // dataInfoId:max(push.version) - private final Map interests; + private final String dataCenter; + // dataInfoId:max(push.version) + private final Map interests; - /** - * constructor - */ - public GetDataVersionRequest(String dataCenter, ProcessId sessionProcessId, int slotId, - Map interests) { - super(slotId, sessionProcessId); - this.dataCenter = dataCenter; - this.interests = Collections.unmodifiableMap(Maps.newHashMap(interests)); - } + /** constructor */ + public GetDataVersionRequest( + String dataCenter, + ProcessId sessionProcessId, + int slotId, + Map interests) { + super(slotId, sessionProcessId); + this.dataCenter = dataCenter; + this.interests = Collections.unmodifiableMap(Maps.newHashMap(interests)); + } - public Map getInterests() { - return interests; - } + public Map getInterests() { + return interests; + } - public String getDataCenter() { - return dataCenter; - } + public String getDataCenter() { + return dataCenter; + } - @Override - public String toString() { - return StringFormatter.format("GetDataVer:{},{},{},{},interests={}", getSlotId(), - dataCenter, getSlotLeaderEpoch(), getSlotTableEpoch(), interests.size()); - } -} \ No newline at end of file + @Override + public String toString() { + return StringFormatter.format( + "GetDataVer:{},{},{},{},interests={}", + getSlotId(), + dataCenter, + getSlotLeaderEpoch(), + getSlotTableEpoch(), + interests.size()); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/CheckRevisionsRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/CheckRevisionsRequest.java index fa097604e..9464b0617 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/CheckRevisionsRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/CheckRevisionsRequest.java @@ -19,9 +19,9 @@ import java.io.Serializable; public class CheckRevisionsRequest implements Serializable { - public String keysDigest; + public String keysDigest; - public CheckRevisionsRequest(String keysDigest) { - this.keysDigest = keysDigest; - } + public CheckRevisionsRequest(String keysDigest) { + this.keysDigest = keysDigest; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ConfigureLoadbalanceRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ConfigureLoadbalanceRequest.java index a480c11ff..9832b289f 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ConfigureLoadbalanceRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ConfigureLoadbalanceRequest.java @@ -17,25 +17,23 @@ package com.alipay.sofa.registry.common.model.metaserver; import java.io.Serializable; -import java.util.Map; /** * @author xiangxu * @version : LoadbalanceConfig.java, v 0.1 2020年05月29日 10:19 上午 xiangxu Exp $ */ public class ConfigureLoadbalanceRequest implements Serializable { - private int maxConnections; + private int maxConnections; - public ConfigureLoadbalanceRequest(int maxConnections) { - this.maxConnections = maxConnections; - } + public ConfigureLoadbalanceRequest(int maxConnections) { + this.maxConnections = maxConnections; + } - public int getMaxConnections() { - return maxConnections; - } + public int getMaxConnections() { + return maxConnections; + } - public void setMaxConnections(int maxConnections) { - this.maxConnections = maxConnections; - } - -} \ No newline at end of file + public void setMaxConnections(int maxConnections) { + this.maxConnections = maxConnections; + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/DataCenterNodes.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/DataCenterNodes.java index 525ec2e65..9da966f3b 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/DataCenterNodes.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/DataCenterNodes.java @@ -19,113 +19,112 @@ import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.Node.NodeType; import com.google.common.collect.Maps; - import java.io.Serializable; import java.util.List; import java.util.Map; /** - * * @author shangyu.wh * @version $Id: DataCenterNodes.java, v 0.1 2018-02-12 11:06 shangyu.wh Exp $ */ public class DataCenterNodes implements Serializable { - private final NodeType nodeType; - - private Long version; - - private String dataCenterId; - - private Map nodes; - - /** - * constructor - * @param nodeType - * @param version - * @param dataCenterId - */ - public DataCenterNodes(NodeType nodeType, Long version, String dataCenterId) { - this.nodeType = nodeType; - this.version = version; - this.dataCenterId = dataCenterId; - } - - public static DataCenterNodes transferFrom(long epoch, String dc, List nodes) { - if(nodes == null || nodes.isEmpty()) { - return new DataCenterNodes<>(null, epoch, dc); - } - NodeType type = nodes.get(0).getNodeType(); - Map nodeMap = Maps.newHashMap(); - nodes.forEach(node->nodeMap.put(node.getNodeUrl().getIpAddress(), node)); - DataCenterNodes result = new DataCenterNodes(type, epoch, dc); - result.setNodes(nodeMap); - return result; - } - - /** - * Getter method for property version. - * - * @return property value of version - */ - public Long getVersion() { - return version; - } + private final NodeType nodeType; - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(Long version) { - this.version = version; - } + private Long version; - /** - * Getter method for property dataCenterId. - * - * @return property value of dataCenterId - */ - public String getDataCenterId() { - return dataCenterId; - } + private String dataCenterId; - /** - * Setter method for property dataCenterId. - * - * @param dataCenterId value to be assigned to property dataCenterId - */ - public void setDataCenterId(String dataCenterId) { - this.dataCenterId = dataCenterId; - } + private Map nodes; - /** - * Getter method for property nodes. - * - * @return property value of nodes - */ - public Map getNodes() { - return nodes; - } - - /** - * Setter method for property nodes. - * - * @param nodes value to be assigned to property nodes - */ - public void setNodes(Map nodes) { - this.nodes = nodes; - } + /** + * constructor + * + * @param nodeType + * @param version + * @param dataCenterId + */ + public DataCenterNodes(NodeType nodeType, Long version, String dataCenterId) { + this.nodeType = nodeType; + this.version = version; + this.dataCenterId = dataCenterId; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("DataCenterNodes{"); - sb.append("nodeType=").append(nodeType); - sb.append(", version=").append(version); - sb.append(", dataCenterId='").append(dataCenterId).append('\''); - sb.append(", nodes=").append(nodes); - sb.append('}'); - return sb.toString(); + public static DataCenterNodes transferFrom( + long epoch, String dc, List nodes) { + if (nodes == null || nodes.isEmpty()) { + return new DataCenterNodes<>(null, epoch, dc); } - -} \ No newline at end of file + NodeType type = nodes.get(0).getNodeType(); + Map nodeMap = Maps.newHashMap(); + nodes.forEach(node -> nodeMap.put(node.getNodeUrl().getIpAddress(), node)); + DataCenterNodes result = new DataCenterNodes(type, epoch, dc); + result.setNodes(nodeMap); + return result; + } + + /** + * Getter method for property version. + * + * @return property value of version + */ + public Long getVersion() { + return version; + } + + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * Getter method for property dataCenterId. + * + * @return property value of dataCenterId + */ + public String getDataCenterId() { + return dataCenterId; + } + + /** + * Setter method for property dataCenterId. + * + * @param dataCenterId value to be assigned to property dataCenterId + */ + public void setDataCenterId(String dataCenterId) { + this.dataCenterId = dataCenterId; + } + + /** + * Getter method for property nodes. + * + * @return property value of nodes + */ + public Map getNodes() { + return nodes; + } + + /** + * Setter method for property nodes. + * + * @param nodes value to be assigned to property nodes + */ + public void setNodes(Map nodes) { + this.nodes = nodes; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("DataCenterNodes{"); + sb.append("nodeType=").append(nodeType); + sb.append(", version=").append(version); + sb.append(", dataCenterId='").append(dataCenterId).append('\''); + sb.append(", nodes=").append(nodes); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/DataOperator.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/DataOperator.java index e8b984932..4ae94f3fd 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/DataOperator.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/DataOperator.java @@ -17,10 +17,12 @@ package com.alipay.sofa.registry.common.model.metaserver; /** - * * @author shangyu.wh * @version $Id: DataOperator.java, v 0.1 2018-04-17 21:03 shangyu.wh Exp $ */ public enum DataOperator { - ADD, REMOVE, UPDATE, QUERY -} \ No newline at end of file + ADD, + REMOVE, + UPDATE, + QUERY +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/FetchProvideDataRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/FetchProvideDataRequest.java index 86de06583..9d2ce9011 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/FetchProvideDataRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/FetchProvideDataRequest.java @@ -19,36 +19,36 @@ import java.io.Serializable; /** - * * @author shangyu.wh * @version $Id: FetchProvideDataRequest.java, v 0.1 2018-04-17 21:19 shangyu.wh Exp $ */ public class FetchProvideDataRequest implements Serializable { - private final String dataInfoId; + private final String dataInfoId; - /** - * construtor - * @param dataInfoId - */ - public FetchProvideDataRequest(String dataInfoId) { - this.dataInfoId = dataInfoId; - } + /** + * construtor + * + * @param dataInfoId + */ + public FetchProvideDataRequest(String dataInfoId) { + this.dataInfoId = dataInfoId; + } - /** - * Getter method for property dataInfoId. - * - * @return property value of dataInfoId - */ - public String getDataInfoId() { - return dataInfoId; - } + /** + * Getter method for property dataInfoId. + * + * @return property value of dataInfoId + */ + public String getDataInfoId() { + return dataInfoId; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("FetchProvideDataRequest{"); - sb.append("dataInfoId='").append(dataInfoId).append('\''); - sb.append('}'); - return sb.toString(); - } -} \ No newline at end of file + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("FetchProvideDataRequest{"); + sb.append("dataInfoId='").append(dataInfoId).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/FetchRevisionsRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/FetchRevisionsRequest.java index a3d2713c0..0d0b83d77 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/FetchRevisionsRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/FetchRevisionsRequest.java @@ -20,9 +20,9 @@ import java.util.List; public class FetchRevisionsRequest implements Serializable { - public List keys; + public List keys; - public FetchRevisionsRequest(List keys) { - this.keys = keys; - } + public FetchRevisionsRequest(List keys) { + this.keys = keys; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetLoadbalanceMetricsRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetLoadbalanceMetricsRequest.java index 34af0395b..569de1ded 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetLoadbalanceMetricsRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetLoadbalanceMetricsRequest.java @@ -20,8 +20,6 @@ /** * @author xiangxu - * @version : SessionLoadbalanceMetrics.java, v 0.1 2020年05月27日 11:13 上午 xiangxu - * Exp $ + * @version : SessionLoadbalanceMetrics.java, v 0.1 2020年05月27日 11:13 上午 xiangxu Exp $ */ -public class GetLoadbalanceMetricsRequest implements Serializable { -} \ No newline at end of file +public class GetLoadbalanceMetricsRequest implements Serializable {} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetSlotTableRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetSlotTableRequest.java index 57a0f9b7c..06227e0e3 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetSlotTableRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetSlotTableRequest.java @@ -19,67 +19,77 @@ import java.io.Serializable; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-11 11:16 yuzhi.lyz Exp $ */ public class GetSlotTableRequest implements Serializable { - private static final long serialVersionUID = 2478663577413212315L; - private long epochOfNode; - // session node not care the followers - private boolean ignoredFollowers; - // data node only care self, if not set, get all - private String targetDataNode; + private static final long serialVersionUID = 2478663577413212315L; + private long epochOfNode; + // session node not care the followers + private boolean ignoredFollowers; + // data node only care self, if not set, get all + private String targetDataNode; - public GetSlotTableRequest(long epochOfNode, String targetDataNode, boolean ignoredFollowers) { - this.epochOfNode = epochOfNode; - this.targetDataNode = targetDataNode; - this.ignoredFollowers = ignoredFollowers; - } + public GetSlotTableRequest(long epochOfNode, String targetDataNode, boolean ignoredFollowers) { + this.epochOfNode = epochOfNode; + this.targetDataNode = targetDataNode; + this.ignoredFollowers = ignoredFollowers; + } - /** - * Getter method for property epochOfNode. - * @return property value of epochOfNode - */ - public long getEpochOfNode() { - return epochOfNode; - } + /** + * Getter method for property epochOfNode. + * + * @return property value of epochOfNode + */ + public long getEpochOfNode() { + return epochOfNode; + } - /** - * Setter method for property epochOfNode. - * @param epochOfNode value to be assigned to property epochOfNode - */ - public void setEpochOfNode(long epochOfNode) { - this.epochOfNode = epochOfNode; - } + /** + * Setter method for property epochOfNode. + * + * @param epochOfNode value to be assigned to property epochOfNode + */ + public void setEpochOfNode(long epochOfNode) { + this.epochOfNode = epochOfNode; + } - /** - * Getter method for property targetDataNode. - * @return property value of targetDataNode - */ - public String getTargetDataNode() { - return targetDataNode; - } + /** + * Getter method for property targetDataNode. + * + * @return property value of targetDataNode + */ + public String getTargetDataNode() { + return targetDataNode; + } - /** - * Setter method for property targetDataNode. - * @param targetDataNode value to be assigned to property targetDataNode - */ - public void setTargetDataNode(String targetDataNode) { - this.targetDataNode = targetDataNode; - } + /** + * Setter method for property targetDataNode. + * + * @param targetDataNode value to be assigned to property targetDataNode + */ + public void setTargetDataNode(String targetDataNode) { + this.targetDataNode = targetDataNode; + } - public boolean isIgnoredFollowers() { - return ignoredFollowers; - } + public boolean isIgnoredFollowers() { + return ignoredFollowers; + } - public void setIgnoredFollowers(boolean v) { - this.ignoredFollowers = v; - } + public void setIgnoredFollowers(boolean v) { + this.ignoredFollowers = v; + } - @Override - public String toString() { - return "GetSlotTableRequest{" + "epochOfNode=" + epochOfNode + ", ignoredFollowers=" - + ignoredFollowers + ", targetDataNode='" + targetDataNode + '\'' + '}'; - } + @Override + public String toString() { + return "GetSlotTableRequest{" + + "epochOfNode=" + + epochOfNode + + ", ignoredFollowers=" + + ignoredFollowers + + ", targetDataNode='" + + targetDataNode + + '\'' + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetSlotTableResult.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetSlotTableResult.java index 3980ae57c..38ecddab7 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetSlotTableResult.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/GetSlotTableResult.java @@ -17,57 +17,59 @@ package com.alipay.sofa.registry.common.model.metaserver; import com.alipay.sofa.registry.common.model.slot.DataNodeSlot; - import java.util.List; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-11 13:48 yuzhi.lyz Exp $ */ public class GetSlotTableResult { - private long epoch; - private List slots; + private long epoch; + private List slots; - public GetSlotTableResult(long epoch, List slots) { - this.epoch = epoch; - this.slots = slots; - } + public GetSlotTableResult(long epoch, List slots) { + this.epoch = epoch; + this.slots = slots; + } - /** - * Getter method for property epoch. - * @return property value of epoch - */ - public long getEpoch() { - return epoch; - } + /** + * Getter method for property epoch. + * + * @return property value of epoch + */ + public long getEpoch() { + return epoch; + } - /** - * Setter method for property epoch. - * @param epoch value to be assigned to property epoch - */ - public void setEpoch(long epoch) { - this.epoch = epoch; - } + /** + * Setter method for property epoch. + * + * @param epoch value to be assigned to property epoch + */ + public void setEpoch(long epoch) { + this.epoch = epoch; + } - /** - * Getter method for property slots. - * @return property value of slots - */ - public List getSlots() { - return slots; - } + /** + * Getter method for property slots. + * + * @return property value of slots + */ + public List getSlots() { + return slots; + } - /** - * Setter method for property slots. - * @param slots value to be assigned to property slots - */ - public void setSlots(List slots) { - this.slots = slots; - } + /** + * Setter method for property slots. + * + * @param slots value to be assigned to property slots + */ + public void setSlots(List slots) { + this.slots = slots; + } - @Override - public String toString() { - return "GetSlotTableResult{" + "epoch=" + epoch + ", slots=" + slots + '}'; - } + @Override + public String toString() { + return "GetSlotTableResult{" + "epoch=" + epoch + ", slots=" + slots + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/Lease.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/Lease.java index aba75778c..62bc7ec36 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/Lease.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/Lease.java @@ -22,143 +22,147 @@ /** * heartbeat info for node + * * @author shangyu.wh * @version $Id: Renewer.java, v 0.1 2018-01-16 17:10 shangyu.wh Exp $ */ public class Lease implements Serializable { - public static final String LEASE_DURATION = "lease.duration"; - public static final int DEFAULT_DURATION_SECS = Integer.getInteger(LEASE_DURATION, 30); - - private T renewal; - - private long beginTimestamp; - - private volatile long lastUpdateTimestamp; - - private long duration; - - /** - * constructor - * @param renewal - * @param durationSECS - */ - public Lease(T renewal, long durationSECS) { - this.renewal = renewal; - this.beginTimestamp = System.currentTimeMillis(); - this.lastUpdateTimestamp = beginTimestamp; - this.duration = durationSECS * 1000; - } - - /** - * Constructor. - * - * @param renewal the renewal - * @param duration the duration - * @param unit the unit - */ - public Lease(T renewal, long duration, TimeUnit unit) { - this(renewal, unit.toSeconds(duration)); - } - - /** - * verify expired or not - * @return - */ - public boolean isExpired() { - return System.currentTimeMillis() > lastUpdateTimestamp + duration; - } - - /** - * refresh lastUpdateTimestamp - */ - public void renew() { - lastUpdateTimestamp = System.currentTimeMillis(); - } - - /** - * refresh lastUpdateTimestamp by durationSECS - * @param durationSECS - */ - public void renew(long durationSECS) { - lastUpdateTimestamp = System.currentTimeMillis(); - duration = durationSECS * 1000; - } - - /** - * Getter method for property renewal. - * - * @return property value of renewal - */ - public T getRenewal() { - return renewal; - } - - /** - * Setter method for property renewal. - * - * @param renewal value to be assigned to property renewal - */ - public void setRenewal(T renewal) { - this.renewal = renewal; - } - - /** - * Getter method for property beginTimestamp. - * - * @return property value of beginTimestamp - */ - public long getBeginTimestamp() { - return beginTimestamp; - } - - /** - * Getter method for property lastUpdateTimestamp. - * - * @return property value of lastUpdateTimestamp - */ - public long getLastUpdateTimestamp() { - return lastUpdateTimestamp; - } - - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "Lease{" + - "renewal=" + renewal + - ", beginTimestamp=" + beginTimestamp + - ", lastUpdateTimestamp=" + lastUpdateTimestamp + - ", duration=" + duration + - '}'; - } - - /** - * Equals boolean. - * - * @param o the o - * @return the boolean - */ - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - Lease lease = (Lease) o; - return beginTimestamp == lease.beginTimestamp && renewal.equals(lease.renewal); - } - - /** - * Hash code int. - * - * @return the int - */ - @Override - public int hashCode() { - return Objects.hash(renewal, beginTimestamp); - } -} \ No newline at end of file + public static final String LEASE_DURATION = "lease.duration"; + public static final int DEFAULT_DURATION_SECS = Integer.getInteger(LEASE_DURATION, 30); + + private T renewal; + + private long beginTimestamp; + + private volatile long lastUpdateTimestamp; + + private long duration; + + /** + * constructor + * + * @param renewal + * @param durationSECS + */ + public Lease(T renewal, long durationSECS) { + this.renewal = renewal; + this.beginTimestamp = System.currentTimeMillis(); + this.lastUpdateTimestamp = beginTimestamp; + this.duration = durationSECS * 1000; + } + + /** + * Constructor. + * + * @param renewal the renewal + * @param duration the duration + * @param unit the unit + */ + public Lease(T renewal, long duration, TimeUnit unit) { + this(renewal, unit.toSeconds(duration)); + } + + /** + * verify expired or not + * + * @return + */ + public boolean isExpired() { + return System.currentTimeMillis() > lastUpdateTimestamp + duration; + } + + /** refresh lastUpdateTimestamp */ + public void renew() { + lastUpdateTimestamp = System.currentTimeMillis(); + } + + /** + * refresh lastUpdateTimestamp by durationSECS + * + * @param durationSECS + */ + public void renew(long durationSECS) { + lastUpdateTimestamp = System.currentTimeMillis(); + duration = durationSECS * 1000; + } + + /** + * Getter method for property renewal. + * + * @return property value of renewal + */ + public T getRenewal() { + return renewal; + } + + /** + * Setter method for property renewal. + * + * @param renewal value to be assigned to property renewal + */ + public void setRenewal(T renewal) { + this.renewal = renewal; + } + + /** + * Getter method for property beginTimestamp. + * + * @return property value of beginTimestamp + */ + public long getBeginTimestamp() { + return beginTimestamp; + } + + /** + * Getter method for property lastUpdateTimestamp. + * + * @return property value of lastUpdateTimestamp + */ + public long getLastUpdateTimestamp() { + return lastUpdateTimestamp; + } + + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "Lease{" + + "renewal=" + + renewal + + ", beginTimestamp=" + + beginTimestamp + + ", lastUpdateTimestamp=" + + lastUpdateTimestamp + + ", duration=" + + duration + + '}'; + } + + /** + * Equals boolean. + * + * @param o the o + * @return the boolean + */ + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + Lease lease = (Lease) o; + return beginTimestamp == lease.beginTimestamp && renewal.equals(lease.renewal); + } + + /** + * Hash code int. + * + * @return the int + */ + @Override + public int hashCode() { + return Objects.hash(renewal, beginTimestamp); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/LoadbalanceMetrics.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/LoadbalanceMetrics.java index 342b73c0a..59c3f23fa 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/LoadbalanceMetrics.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/LoadbalanceMetrics.java @@ -23,16 +23,15 @@ * @version : LoadbalanceMetrics.java, v 0.1 2020年05月27日 2:29 下午 xiangxu Exp $ */ public class LoadbalanceMetrics implements Serializable { - private int connectionCount; + private int connectionCount; - public LoadbalanceMetrics() { - } + public LoadbalanceMetrics() {} - public int getConnectionCount() { - return connectionCount; - } + public int getConnectionCount() { + return connectionCount; + } - public void setConnectionCount(int connectionCount) { - this.connectionCount = connectionCount; - } -} \ No newline at end of file + public void setConnectionCount(int connectionCount) { + this.connectionCount = connectionCount; + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/NodeChangeResult.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/NodeChangeResult.java index dd9e9c4c2..7dbd2d685 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/NodeChangeResult.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/NodeChangeResult.java @@ -18,126 +18,125 @@ import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.Node.NodeType; - import java.io.Serializable; import java.util.Map; /** - * * @author shangyu.wh * @version $Id: NodeChangeRequest.java, v 0.1 2018-01-11 16:55 shangyu.wh Exp $ */ public class NodeChangeResult implements Serializable { - private final NodeType nodeType; - - private Map> nodes; - - private Long version; - - private Map dataCenterListVersions; - - /** local dataCenter id */ - private String localDataCenter; - - /** - * constructor - * @param nodeType - */ - public NodeChangeResult(NodeType nodeType) { - this.nodeType = nodeType; - } - - /** - * Getter method for property nodeType. - * - * @return property value of nodeType - */ - public NodeType getNodeType() { - return nodeType; - } - - /** - * Getter method for property nodes. - * - * @return property value of nodes - */ - public Map> getNodes() { - return nodes; - } - - /** - * Setter method for property nodes. - * - * @param nodes value to be assigned to property nodes - */ - public void setNodes(Map> nodes) { - this.nodes = nodes; - } - - /** - * Getter method for property localDataCenter. - * - * @return property value of localDataCenter - */ - public String getLocalDataCenter() { - return localDataCenter; - } - - /** - * Setter method for property localDataCenter. - * - * @param localDataCenter value to be assigned to property localDataCenter - */ - public void setLocalDataCenter(String localDataCenter) { - this.localDataCenter = localDataCenter; - } - - /** - * Getter method for property version. - * - * @return property value of version - */ - public Long getVersion() { - return version; - } - - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * Getter method for property dataCenterListVersions. - * - * @return property value of dataCenterListVersions - */ - public Map getDataCenterListVersions() { - return dataCenterListVersions; - } - - /** - * Setter method for property dataCenterListVersions. - * - * @param dataCenterListVersions value to be assigned to property dataCenterListVersions - */ - public void setDataCenterListVersions(Map dataCenterListVersions) { - this.dataCenterListVersions = dataCenterListVersions; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("NodeChangeResult{"); - sb.append("nodeType=").append(nodeType); - sb.append(", nodes=").append(nodes); - sb.append(", version=").append(version); - sb.append(", dataCenterListVersions=").append(dataCenterListVersions); - sb.append(", localDataCenter='").append(localDataCenter).append('\''); - sb.append('}'); - return sb.toString(); - } -} \ No newline at end of file + private final NodeType nodeType; + + private Map> nodes; + + private Long version; + + private Map dataCenterListVersions; + + /** local dataCenter id */ + private String localDataCenter; + + /** + * constructor + * + * @param nodeType + */ + public NodeChangeResult(NodeType nodeType) { + this.nodeType = nodeType; + } + + /** + * Getter method for property nodeType. + * + * @return property value of nodeType + */ + public NodeType getNodeType() { + return nodeType; + } + + /** + * Getter method for property nodes. + * + * @return property value of nodes + */ + public Map> getNodes() { + return nodes; + } + + /** + * Setter method for property nodes. + * + * @param nodes value to be assigned to property nodes + */ + public void setNodes(Map> nodes) { + this.nodes = nodes; + } + + /** + * Getter method for property localDataCenter. + * + * @return property value of localDataCenter + */ + public String getLocalDataCenter() { + return localDataCenter; + } + + /** + * Setter method for property localDataCenter. + * + * @param localDataCenter value to be assigned to property localDataCenter + */ + public void setLocalDataCenter(String localDataCenter) { + this.localDataCenter = localDataCenter; + } + + /** + * Getter method for property version. + * + * @return property value of version + */ + public Long getVersion() { + return version; + } + + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * Getter method for property dataCenterListVersions. + * + * @return property value of dataCenterListVersions + */ + public Map getDataCenterListVersions() { + return dataCenterListVersions; + } + + /** + * Setter method for property dataCenterListVersions. + * + * @param dataCenterListVersions value to be assigned to property dataCenterListVersions + */ + public void setDataCenterListVersions(Map dataCenterListVersions) { + this.dataCenterListVersions = dataCenterListVersions; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("NodeChangeResult{"); + sb.append("nodeType=").append(nodeType); + sb.append(", nodes=").append(nodes); + sb.append(", version=").append(version); + sb.append(", dataCenterListVersions=").append(dataCenterListVersions); + sb.append(", localDataCenter='").append(localDataCenter).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ProvideData.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ProvideData.java index c4ce7839d..6ff88c04b 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ProvideData.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ProvideData.java @@ -17,113 +17,111 @@ package com.alipay.sofa.registry.common.model.metaserver; import com.alipay.sofa.registry.common.model.ServerDataBox; - import java.io.Serializable; /** - * * @author shangyu.wh * @version $Id: ProvideData.java, v 0.1 2018-04-17 20:13 shangyu.wh Exp $ */ public class ProvideData implements Serializable { - private ServerDataBox provideData; - - private String dataInfoId; - - private Long version; - - /** - * construtor - * @param provideData - * @param dataInfoId - * @param version - */ - public ProvideData(ServerDataBox provideData, String dataInfoId, Long version) { - this.provideData = provideData; - this.dataInfoId = dataInfoId; - this.version = version; - } - - /** - * Getter method for property provideData. - * - * @return property value of provideData - */ - public ServerDataBox getProvideData() { - return provideData; - } - - /** - * Setter method for property provideData. - * - * @param provideData value to be assigned to property provideData - */ - public void setProvideData(ServerDataBox provideData) { - this.provideData = provideData; - } - - /** - * Getter method for property dataInfoId. - * - * @return property value of dataInfoId - */ - public String getDataInfoId() { - return dataInfoId; - } - - /** - * Setter method for property dataInfoId. - * - * @param dataInfoId value to be assigned to property dataInfoId - */ - public void setDataInfoId(String dataInfoId) { - this.dataInfoId = dataInfoId; + private ServerDataBox provideData; + + private String dataInfoId; + + private Long version; + + /** + * construtor + * + * @param provideData + * @param dataInfoId + * @param version + */ + public ProvideData(ServerDataBox provideData, String dataInfoId, Long version) { + this.provideData = provideData; + this.dataInfoId = dataInfoId; + this.version = version; + } + + /** + * Getter method for property provideData. + * + * @return property value of provideData + */ + public ServerDataBox getProvideData() { + return provideData; + } + + /** + * Setter method for property provideData. + * + * @param provideData value to be assigned to property provideData + */ + public void setProvideData(ServerDataBox provideData) { + this.provideData = provideData; + } + + /** + * Getter method for property dataInfoId. + * + * @return property value of dataInfoId + */ + public String getDataInfoId() { + return dataInfoId; + } + + /** + * Setter method for property dataInfoId. + * + * @param dataInfoId value to be assigned to property dataInfoId + */ + public void setDataInfoId(String dataInfoId) { + this.dataInfoId = dataInfoId; + } + + /** + * Getter method for property version. + * + * @return property value of version + */ + public Long getVersion() { + return version; + } + + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(Long version) { + this.version = version; + } + + public static String toString(ProvideData provideData) { + if (provideData == null || provideData.getProvideData() == null) { + return null; } - - /** - * Getter method for property version. - * - * @return property value of version - */ - public Long getVersion() { - return version; - } - - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(Long version) { - this.version = version; - } - - public static String toString(ProvideData provideData) { - if (provideData == null || provideData.getProvideData() == null) { - return null; - } - return (String) provideData.getProvideData().getObject(); - } - - public static Boolean toBool(ProvideData provideData) { - String obj = ProvideData.toString(provideData); - return obj != null ? Boolean.parseBoolean(obj) : null; - } - - public static Integer toInteger(ProvideData provideData) { - String obj = ProvideData.toString(provideData); - return obj != null ? Integer.valueOf(obj) : null; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ProvideData{"); - sb.append("provideData=").append(provideData); - sb.append(", dataInfoId='").append(dataInfoId).append('\''); - sb.append(", version=").append(version); - sb.append('}'); - return sb.toString(); - } - -} \ No newline at end of file + return (String) provideData.getProvideData().getObject(); + } + + public static Boolean toBool(ProvideData provideData) { + String obj = ProvideData.toString(provideData); + return obj != null ? Boolean.parseBoolean(obj) : null; + } + + public static Integer toInteger(ProvideData provideData) { + String obj = ProvideData.toString(provideData); + return obj != null ? Integer.valueOf(obj) : null; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ProvideData{"); + sb.append("provideData=").append(provideData); + sb.append(", dataInfoId='").append(dataInfoId).append('\''); + sb.append(", version=").append(version); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ProvideDataChangeEvent.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ProvideDataChangeEvent.java index 48d027380..ce4ef81e8 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ProvideDataChangeEvent.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ProvideDataChangeEvent.java @@ -16,125 +16,124 @@ */ package com.alipay.sofa.registry.common.model.metaserver; -import java.io.Serializable; -import java.util.Set; - import com.alipay.sofa.registry.common.model.Node.NodeType; import com.google.common.collect.Sets; +import java.io.Serializable; +import java.util.Set; /** - * * @author shangyu.wh * @version $Id: NotifyProvideDataChange.java, v 0.1 2018-04-18 15:18 shangyu.wh Exp $ */ public class ProvideDataChangeEvent implements Serializable { - private String dataInfoId; - - private Long version; - - private DataOperator dataOperator; - - private Set nodeTypes; - - /** - * constructor - * @param dataInfoId - * @param version - * @param dataOperator - */ - public ProvideDataChangeEvent(String dataInfoId, Long version, DataOperator dataOperator) { - this(dataInfoId, version, dataOperator, Sets.newHashSet(NodeType.SESSION)); - } - - public ProvideDataChangeEvent(String dataInfoId, Long version, DataOperator dataOperator, - Set nodeTypes) { - this.dataInfoId = dataInfoId; - this.version = version; - this.dataOperator = dataOperator; - this.nodeTypes = nodeTypes; - } - - /** - * Getter method for property dataInfoId. - * - * @return property value of dataInfoId - */ - public String getDataInfoId() { - return dataInfoId; - } - - /** - * Setter method for property dataInfoId. - * - * @param dataInfoId value to be assigned to property dataInfoId - */ - public void setDataInfoId(String dataInfoId) { - this.dataInfoId = dataInfoId; - } - - /** - * Getter method for property version. - * - * @return property value of version - */ - public Long getVersion() { - return version; - } - - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(Long version) { - this.version = version; - } - - /** - * Getter method for property dataOperator. - * - * @return property value of dataOperator - */ - public DataOperator getDataOperator() { - return dataOperator; - } - - /** - * Setter method for property dataOperator. - * - * @param dataOperator value to be assigned to property dataOperator - */ - public void setDataOperator(DataOperator dataOperator) { - this.dataOperator = dataOperator; - } - - /** - * Getter method for property nodeType. - * - * @return property value of nodeType - */ - public Set getNodeTypes() { - return nodeTypes; - } - - /** - * Setter method for property nodeType. - * - * @param nodeTypes value to be assigned to property nodeType - */ - public void setNodeTypes(Set nodeTypes) { - this.nodeTypes = nodeTypes; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("NotifyProvideDataChange{"); - sb.append("dataInfoId='").append(dataInfoId).append('\''); - sb.append(", version=").append(version); - sb.append(", dataOperator=").append(dataOperator); - sb.append(", nodeTypes=").append(nodeTypes); - sb.append('}'); - return sb.toString(); - } -} \ No newline at end of file + private String dataInfoId; + + private Long version; + + private DataOperator dataOperator; + + private Set nodeTypes; + + /** + * constructor + * + * @param dataInfoId + * @param version + * @param dataOperator + */ + public ProvideDataChangeEvent(String dataInfoId, Long version, DataOperator dataOperator) { + this(dataInfoId, version, dataOperator, Sets.newHashSet(NodeType.SESSION)); + } + + public ProvideDataChangeEvent( + String dataInfoId, Long version, DataOperator dataOperator, Set nodeTypes) { + this.dataInfoId = dataInfoId; + this.version = version; + this.dataOperator = dataOperator; + this.nodeTypes = nodeTypes; + } + + /** + * Getter method for property dataInfoId. + * + * @return property value of dataInfoId + */ + public String getDataInfoId() { + return dataInfoId; + } + + /** + * Setter method for property dataInfoId. + * + * @param dataInfoId value to be assigned to property dataInfoId + */ + public void setDataInfoId(String dataInfoId) { + this.dataInfoId = dataInfoId; + } + + /** + * Getter method for property version. + * + * @return property value of version + */ + public Long getVersion() { + return version; + } + + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * Getter method for property dataOperator. + * + * @return property value of dataOperator + */ + public DataOperator getDataOperator() { + return dataOperator; + } + + /** + * Setter method for property dataOperator. + * + * @param dataOperator value to be assigned to property dataOperator + */ + public void setDataOperator(DataOperator dataOperator) { + this.dataOperator = dataOperator; + } + + /** + * Getter method for property nodeType. + * + * @return property value of nodeType + */ + public Set getNodeTypes() { + return nodeTypes; + } + + /** + * Setter method for property nodeType. + * + * @param nodeTypes value to be assigned to property nodeType + */ + public void setNodeTypes(Set nodeTypes) { + this.nodeTypes = nodeTypes; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("NotifyProvideDataChange{"); + sb.append("dataInfoId='").append(dataInfoId).append('\''); + sb.append(", version=").append(version); + sb.append(", dataOperator=").append(dataOperator); + sb.append(", nodeTypes=").append(nodeTypes); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/SlotTableChangeEvent.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/SlotTableChangeEvent.java index 88ed2fc69..32e343de0 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/SlotTableChangeEvent.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/SlotTableChangeEvent.java @@ -19,25 +19,23 @@ import java.io.Serializable; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-02 17:30 yuzhi.lyz Exp $ - * */ public final class SlotTableChangeEvent implements Serializable { - private final long slotTableEpoch; + private final long slotTableEpoch; - public SlotTableChangeEvent(long slotTableEpoch) { - this.slotTableEpoch = slotTableEpoch; - } + public SlotTableChangeEvent(long slotTableEpoch) { + this.slotTableEpoch = slotTableEpoch; + } - public long getSlotTableEpoch() { - return slotTableEpoch; - } + public long getSlotTableEpoch() { + return slotTableEpoch; + } - @Override - public String toString() { - return "SlotTableChangeEvent{" + "slotTableEpoch=" + slotTableEpoch + '}'; - } + @Override + public String toString() { + return "SlotTableChangeEvent{" + "slotTableEpoch=" + slotTableEpoch + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/cluster/Cluster.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/cluster/Cluster.java index c5f802c58..edc04669d 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/cluster/Cluster.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/cluster/Cluster.java @@ -20,22 +20,21 @@ /** * @author chen.zhu - *

- * Mar 09, 2021 + *

Mar 09, 2021 */ public interface Cluster { - /** - * Epoch long. - * - * @return the long - */ - long getEpoch(); + /** + * Epoch long. + * + * @return the long + */ + long getEpoch(); - /** - * Gets get cluster members. - * - * @return the get cluster members - */ - List getClusterMembers(); + /** + * Gets get cluster members. + * + * @return the get cluster members + */ + List getClusterMembers(); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/cluster/VersionedList.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/cluster/VersionedList.java index 81fbc76db..2057686d5 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/cluster/VersionedList.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/cluster/VersionedList.java @@ -22,29 +22,28 @@ /** * @author chen.zhu - *

- * Mar 09, 2021 + *

Mar 09, 2021 */ public class VersionedList implements Cluster, Serializable { - public final static VersionedList EMPTY = new VersionedList(-1L, Collections.EMPTY_LIST); + public static final VersionedList EMPTY = new VersionedList(-1L, Collections.EMPTY_LIST); - private final long epoch; + private final long epoch; - private final List members; + private final List members; - public VersionedList(long epoch, List members) { - this.epoch = epoch; - this.members = members; - } + public VersionedList(long epoch, List members) { + this.epoch = epoch; + this.members = members; + } - @Override - public long getEpoch() { - return epoch; - } + @Override + public long getEpoch() { + return epoch; + } - @Override - public List getClusterMembers() { - return members; - } + @Override + public List getClusterMembers() { + return members; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/BaseHeartBeatResponse.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/BaseHeartBeatResponse.java index 3a7f3656b..5169fc580 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/BaseHeartBeatResponse.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/BaseHeartBeatResponse.java @@ -20,78 +20,80 @@ import com.alipay.sofa.registry.common.model.metaserver.nodes.MetaNode; import com.alipay.sofa.registry.common.model.metaserver.nodes.SessionNode; import com.alipay.sofa.registry.common.model.slot.SlotTable; -import com.google.common.collect.Maps; import com.google.common.collect.Sets; - import java.io.Serializable; import java.util.*; /** * @author chen.zhu - *

- * Nov 27, 2020 + *

Nov 27, 2020 */ public class BaseHeartBeatResponse implements Serializable { - private final SlotTable slotTable; - - private final VersionedList metaNodes; - - private final VersionedList sessionNodes; - - private final String metaLeader; - - private final long metaLeaderEpoch; - - public BaseHeartBeatResponse(VersionedList metaNodes, SlotTable slotTable, - String metaLeader, long metaLeaderEpoch) { - this(metaNodes, slotTable, VersionedList.EMPTY, metaLeader, metaLeaderEpoch); - } - - public BaseHeartBeatResponse(VersionedList metaNodes, SlotTable slotTable, - VersionedList sessionNodes, String metaLeader, long metaLeaderEpoch) { - this.slotTable = slotTable; - this.metaNodes = metaNodes; - this.sessionNodes = sessionNodes; - this.metaLeader = metaLeader; - this.metaLeaderEpoch = metaLeaderEpoch; - } - - public SlotTable getSlotTable() { - return slotTable; - } - - - public List getMetaNodes() { - return metaNodes.getClusterMembers(); - } - - public String getMetaLeader() { - return metaLeader; - } - - public long getMetaLeaderEpoch() { - return metaLeaderEpoch; - } - - - public Map getSessionNodesMap() { - final Map m = new HashMap<>(sessionNodes.getClusterMembers().size()); - sessionNodes.getClusterMembers().forEach(s -> m.put(s.getIp(), s)); - return m; - } - - public Set getDataCentersFromMetaNodes() { - Set dcs = Sets.newHashSet(); - metaNodes.getClusterMembers().forEach(m -> dcs.add(m.getDataCenter())); - return dcs; - } - - public long getSessionServerEpoch() { - return sessionNodes.getEpoch(); - } - - public long getMetaServerEpoch() { - return metaNodes.getEpoch(); - } + private final SlotTable slotTable; + + private final VersionedList metaNodes; + + private final VersionedList sessionNodes; + + private final String metaLeader; + + private final long metaLeaderEpoch; + + public BaseHeartBeatResponse( + VersionedList metaNodes, + SlotTable slotTable, + String metaLeader, + long metaLeaderEpoch) { + this(metaNodes, slotTable, VersionedList.EMPTY, metaLeader, metaLeaderEpoch); + } + + public BaseHeartBeatResponse( + VersionedList metaNodes, + SlotTable slotTable, + VersionedList sessionNodes, + String metaLeader, + long metaLeaderEpoch) { + this.slotTable = slotTable; + this.metaNodes = metaNodes; + this.sessionNodes = sessionNodes; + this.metaLeader = metaLeader; + this.metaLeaderEpoch = metaLeaderEpoch; + } + + public SlotTable getSlotTable() { + return slotTable; + } + + public List getMetaNodes() { + return metaNodes.getClusterMembers(); + } + + public String getMetaLeader() { + return metaLeader; + } + + public long getMetaLeaderEpoch() { + return metaLeaderEpoch; + } + + public Map getSessionNodesMap() { + final Map m = new HashMap<>(sessionNodes.getClusterMembers().size()); + sessionNodes.getClusterMembers().forEach(s -> m.put(s.getIp(), s)); + return m; + } + + public Set getDataCentersFromMetaNodes() { + Set dcs = Sets.newHashSet(); + metaNodes.getClusterMembers().forEach(m -> dcs.add(m.getDataCenter())); + return dcs; + } + + public long getSessionServerEpoch() { + return sessionNodes.getEpoch(); + } + + public long getMetaServerEpoch() { + return metaNodes.getEpoch(); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/DataHeartBeatResponse.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/DataHeartBeatResponse.java index 89183147a..2d69a749f 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/DataHeartBeatResponse.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/DataHeartBeatResponse.java @@ -21,22 +21,26 @@ import com.alipay.sofa.registry.common.model.metaserver.nodes.SessionNode; import com.alipay.sofa.registry.common.model.slot.SlotTable; -import java.util.List; - /** * @author chen.zhu - *

- * Nov 27, 2020 + *

Nov 27, 2020 */ public class DataHeartBeatResponse extends BaseHeartBeatResponse { + public DataHeartBeatResponse( + VersionedList metaNodes, + SlotTable slotTable, + String metaLeader, + long metaLeaderEpoch) { + super(metaNodes, slotTable, metaLeader, metaLeaderEpoch); + } - public DataHeartBeatResponse(VersionedList metaNodes, SlotTable slotTable, String metaLeader, long metaLeaderEpoch) { - super(metaNodes, slotTable, metaLeader, metaLeaderEpoch); - } - - public DataHeartBeatResponse(VersionedList metaNodes, SlotTable slotTable, VersionedList sessionNodes, - String metaLeader, long metaLeaderEpoch) { - super(metaNodes, slotTable, sessionNodes, metaLeader, metaLeaderEpoch); - } + public DataHeartBeatResponse( + VersionedList metaNodes, + SlotTable slotTable, + VersionedList sessionNodes, + String metaLeader, + long metaLeaderEpoch) { + super(metaNodes, slotTable, sessionNodes, metaLeader, metaLeaderEpoch); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/HeartbeatRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/HeartbeatRequest.java index d20d03394..c370d8419 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/HeartbeatRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/HeartbeatRequest.java @@ -18,173 +18,178 @@ import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.slot.BaseSlotStatus; -import com.alipay.sofa.registry.common.model.slot.DataNodeSlot; import com.alipay.sofa.registry.common.model.slot.SlotConfig; import com.alipay.sofa.registry.common.model.slot.SlotTable; - import java.io.Serializable; import java.util.Collections; import java.util.List; /** - * * @author shangyu.wh * @version $Id: RenewNodesRequest.java, v 0.1 2018-03-30 19:51 shangyu.wh Exp $ */ public class HeartbeatRequest implements Serializable { - private int duration; - - private final T node; - - private final long slotTableEpoch; - - private final String dataCenter; - - private final long timestamp; - - private final SlotConfig.SlotBasicInfo slotBasicInfo; - - private final List slotStatuses; - - private SlotTable slotTable; - - /** - * constructor - * @param node - * @param slotTableEpoch - */ - public HeartbeatRequest(T node, long slotTableEpoch, String dataCenter, long timestamp, - SlotConfig.SlotBasicInfo slotBasicInfo) { - this.node = node; - this.slotTableEpoch = slotTableEpoch; - this.dataCenter = dataCenter; - this.timestamp = timestamp; - this.slotBasicInfo = slotBasicInfo; - this.slotStatuses = Collections.EMPTY_LIST; - } - - /** - * constructor - * @param node - * @param slotTableEpoch - */ - public HeartbeatRequest(T node, long slotTableEpoch, String dataCenter, long timestamp, - SlotConfig.SlotBasicInfo slotBasicInfo, - final List slotStatuses) { - this.node = node; - this.slotTableEpoch = slotTableEpoch; - this.dataCenter = dataCenter; - this.timestamp = timestamp; - this.slotBasicInfo = slotBasicInfo; - this.slotStatuses = slotStatuses; - } - - /** - * Getter method for property duration. - * - * @return property value of duration - */ - public int getDuration() { - return duration; - } - - /** - * Setter method for property duration. - * - * @param duration value to be assigned to property duration - */ - public void setDuration(int duration) { - this.duration = duration; - } - - /** - * Getter method for property node. - * - * @return property value of node - */ - public T getNode() { - return node; - } - - /** - * Gets get data center. - * - * @return the get data center - */ - public String getDataCenter() { - return dataCenter; - } - - /** - * Gets get timestamp. - * - * @return the get timestamp - */ - public long getTimestamp() { - return timestamp; - } - - /** - * Gets get slot basic info. - * - * @return the get slot basic info - */ - public SlotConfig.SlotBasicInfo getSlotBasicInfo() { - return slotBasicInfo; - } - - /** - * Gets get slot table epoch. - * - * @return the get slot table epoch - */ - public long getSlotTableEpoch() { - return slotTableEpoch; - } - - /** - * Gets get slot status. - * - * @return the get slot status - */ - public List getSlotStatus() { - return slotStatuses; - } - - - /** - * Gets get slot table. - * - * @return the get slot table - */ - public SlotTable getSlotTable() { - return slotTable; - } - - - /** - * Sets set slot table. - * - * @param slotTable the slot table - * @return the set slot table - */ - public HeartbeatRequest setSlotTable(SlotTable slotTable) { - this.slotTable = slotTable; - return this; - } - - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("RenewNodesRequest{"); - sb.append("duration=").append(duration); - sb.append(", node=").append(node); - sb.append('}'); - return sb.toString(); - } -} \ No newline at end of file + private int duration; + + private final T node; + + private final long slotTableEpoch; + + private final String dataCenter; + + private final long timestamp; + + private final SlotConfig.SlotBasicInfo slotBasicInfo; + + private final List slotStatuses; + + private SlotTable slotTable; + + /** + * constructor + * + * @param node + * @param slotTableEpoch + */ + public HeartbeatRequest( + T node, + long slotTableEpoch, + String dataCenter, + long timestamp, + SlotConfig.SlotBasicInfo slotBasicInfo) { + this.node = node; + this.slotTableEpoch = slotTableEpoch; + this.dataCenter = dataCenter; + this.timestamp = timestamp; + this.slotBasicInfo = slotBasicInfo; + this.slotStatuses = Collections.EMPTY_LIST; + } + + /** + * constructor + * + * @param node + * @param slotTableEpoch + */ + public HeartbeatRequest( + T node, + long slotTableEpoch, + String dataCenter, + long timestamp, + SlotConfig.SlotBasicInfo slotBasicInfo, + final List slotStatuses) { + this.node = node; + this.slotTableEpoch = slotTableEpoch; + this.dataCenter = dataCenter; + this.timestamp = timestamp; + this.slotBasicInfo = slotBasicInfo; + this.slotStatuses = slotStatuses; + } + + /** + * Getter method for property duration. + * + * @return property value of duration + */ + public int getDuration() { + return duration; + } + + /** + * Setter method for property duration. + * + * @param duration value to be assigned to property duration + */ + public void setDuration(int duration) { + this.duration = duration; + } + + /** + * Getter method for property node. + * + * @return property value of node + */ + public T getNode() { + return node; + } + + /** + * Gets get data center. + * + * @return the get data center + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * Gets get timestamp. + * + * @return the get timestamp + */ + public long getTimestamp() { + return timestamp; + } + + /** + * Gets get slot basic info. + * + * @return the get slot basic info + */ + public SlotConfig.SlotBasicInfo getSlotBasicInfo() { + return slotBasicInfo; + } + + /** + * Gets get slot table epoch. + * + * @return the get slot table epoch + */ + public long getSlotTableEpoch() { + return slotTableEpoch; + } + + /** + * Gets get slot status. + * + * @return the get slot status + */ + public List getSlotStatus() { + return slotStatuses; + } + + /** + * Gets get slot table. + * + * @return the get slot table + */ + public SlotTable getSlotTable() { + return slotTable; + } + + /** + * Sets set slot table. + * + * @param slotTable the slot table + * @return the set slot table + */ + public HeartbeatRequest setSlotTable(SlotTable slotTable) { + this.slotTable = slotTable; + return this; + } + + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("RenewNodesRequest{"); + sb.append("duration=").append(duration); + sb.append(", node=").append(node); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/SessionHeartBeatResponse.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/SessionHeartBeatResponse.java index 31db6afb3..3e7f1fb39 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/SessionHeartBeatResponse.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/inter/heartbeat/SessionHeartBeatResponse.java @@ -21,17 +21,18 @@ import com.alipay.sofa.registry.common.model.metaserver.nodes.SessionNode; import com.alipay.sofa.registry.common.model.slot.SlotTable; -import java.util.List; - /** * @author chen.zhu - *

- * Nov 27, 2020 + *

Nov 27, 2020 */ public class SessionHeartBeatResponse extends BaseHeartBeatResponse { - public SessionHeartBeatResponse(VersionedList metaNodes, SlotTable slotTable, - VersionedList sessionNodes, String metaLeader, long metaLeaderEpoch) { - super(metaNodes, slotTable, sessionNodes, metaLeader, metaLeaderEpoch); - } + public SessionHeartBeatResponse( + VersionedList metaNodes, + SlotTable slotTable, + VersionedList sessionNodes, + String metaLeader, + long metaLeaderEpoch) { + super(metaNodes, slotTable, sessionNodes, metaLeader, metaLeaderEpoch); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/DataNode.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/DataNode.java index 26f586186..dffb8922e 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/DataNode.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/DataNode.java @@ -20,161 +20,164 @@ import com.alipay.sofa.registry.common.model.store.URL; /** - * * @author shangyu.wh * @version $Id: DataNode.java, v 0.1 2018-01-18 18:06 shangyu.wh Exp $ */ public class DataNode implements Node { - private final URL nodeUrl; - - private final String nodeName; - - private final String dataCenter; - - private String regionId; - - private long registrationTimestamp; - - /** - * constructor - * @param nodeUrl - * @param dataCenter - */ - public DataNode(URL nodeUrl, String dataCenter) { - this.nodeUrl = nodeUrl; - this.nodeName = nodeUrl.getIpAddress(); - this.dataCenter = dataCenter; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof DataNode)) { - return false; - } - - DataNode that = (DataNode) o; - - if (nodeName != null ? !nodeName.equals(that.nodeName) : that.nodeName != null) { - return false; - } + private final URL nodeUrl; - if (dataCenter != null ? !dataCenter.equals(that.dataCenter) : that.dataCenter != null) { - return false; - } + private final String nodeName; - if (regionId != null ? !regionId.equals(that.regionId) : that.regionId != null) { - return false; - } + private final String dataCenter; - if (registrationTimestamp != that.registrationTimestamp) { - return false; - } + private String regionId; - return nodeUrl != null ? (nodeUrl.getAddressString() != null ? nodeUrl.getAddressString() - .equals(that.nodeUrl.getAddressString()) : that.nodeUrl.getAddressString() != null) - : that.nodeUrl != null; - } - - /** - * Hash code int. - * - * @return the int - */ - @Override - public int hashCode() { - int result = nodeName != null ? nodeName.hashCode() : 0; - result = 31 * result + (dataCenter != null ? dataCenter.hashCode() : 0); - result = 31 * result + (regionId != null ? regionId.hashCode() : 0); - result = 31 * result + (int) (registrationTimestamp ^ (registrationTimestamp >>> 32)); - result = 31 - * result - + (nodeUrl != null ? (nodeUrl.getAddressString() != null ? nodeUrl - .getAddressString().hashCode() : 0) : 0); - return result; - } - - @Override - public NodeType getNodeType() { - return NodeType.DATA; - } + private long registrationTimestamp; - @Override - public URL getNodeUrl() { - return nodeUrl; - } + /** + * constructor + * + * @param nodeUrl + * @param dataCenter + */ + public DataNode(URL nodeUrl, String dataCenter) { + this.nodeUrl = nodeUrl; + this.nodeName = nodeUrl.getIpAddress(); + this.dataCenter = dataCenter; + } - /** - * get ip address for nodeUrl - * @return - */ - public String getIp() { - return nodeUrl == null ? "" : nodeUrl.getIpAddress(); + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - /** - * Getter method for property nodeName. - * - * @return property value of nodeName - */ - public String getNodeName() { - return nodeName; + if (!(o instanceof DataNode)) { + return false; } - /** - * Getter method for property regionId. - * - * @return property value of regionId - */ - public String getRegionId() { - return regionId; - } - - /** - * Setter method for property regionId. - * - * @param regionId value to be assigned to property regionId - */ - public void setRegionId(String regionId) { - this.regionId = regionId; - } + DataNode that = (DataNode) o; - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; + if (nodeName != null ? !nodeName.equals(that.nodeName) : that.nodeName != null) { + return false; } - /** - * Getter method for property registrationTimestamp. - * - * @return property value of registrationTimestamp - */ - public long getRegistrationTimestamp() { - return registrationTimestamp; + if (dataCenter != null ? !dataCenter.equals(that.dataCenter) : that.dataCenter != null) { + return false; } - /** - * Setter method for property registrationTimestamp. - * - * @param registrationTimestamp value to be assigned to property registrationTimestamp - */ - public void setRegistrationTimestamp(long registrationTimestamp) { - this.registrationTimestamp = registrationTimestamp; + if (regionId != null ? !regionId.equals(that.regionId) : that.regionId != null) { + return false; } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("DataNode{"); - sb.append("ip=").append(getIp()); - sb.append('}'); - return sb.toString(); + if (registrationTimestamp != that.registrationTimestamp) { + return false; } -} \ No newline at end of file + return nodeUrl != null + ? (nodeUrl.getAddressString() != null + ? nodeUrl.getAddressString().equals(that.nodeUrl.getAddressString()) + : that.nodeUrl.getAddressString() != null) + : that.nodeUrl != null; + } + + /** + * Hash code int. + * + * @return the int + */ + @Override + public int hashCode() { + int result = nodeName != null ? nodeName.hashCode() : 0; + result = 31 * result + (dataCenter != null ? dataCenter.hashCode() : 0); + result = 31 * result + (regionId != null ? regionId.hashCode() : 0); + result = 31 * result + (int) (registrationTimestamp ^ (registrationTimestamp >>> 32)); + result = + 31 * result + + (nodeUrl != null + ? (nodeUrl.getAddressString() != null ? nodeUrl.getAddressString().hashCode() : 0) + : 0); + return result; + } + + @Override + public NodeType getNodeType() { + return NodeType.DATA; + } + + @Override + public URL getNodeUrl() { + return nodeUrl; + } + + /** + * get ip address for nodeUrl + * + * @return + */ + public String getIp() { + return nodeUrl == null ? "" : nodeUrl.getIpAddress(); + } + + /** + * Getter method for property nodeName. + * + * @return property value of nodeName + */ + public String getNodeName() { + return nodeName; + } + + /** + * Getter method for property regionId. + * + * @return property value of regionId + */ + public String getRegionId() { + return regionId; + } + + /** + * Setter method for property regionId. + * + * @param regionId value to be assigned to property regionId + */ + public void setRegionId(String regionId) { + this.regionId = regionId; + } + + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * Getter method for property registrationTimestamp. + * + * @return property value of registrationTimestamp + */ + public long getRegistrationTimestamp() { + return registrationTimestamp; + } + + /** + * Setter method for property registrationTimestamp. + * + * @param registrationTimestamp value to be assigned to property registrationTimestamp + */ + public void setRegistrationTimestamp(long registrationTimestamp) { + this.registrationTimestamp = registrationTimestamp; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("DataNode{"); + sb.append("ip=").append(getIp()); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/MetaNode.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/MetaNode.java index 128fc18a3..e161041ac 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/MetaNode.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/MetaNode.java @@ -18,123 +18,121 @@ import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.store.URL; - import java.util.Objects; /** - * * @author shangyu.wh * @version $Id: MetaNode.java, v 0.1 2018-03-02 16:42 shangyu.wh Exp $ */ public class MetaNode implements Node { - private final NodeType nodeType = NodeType.META; - - private final URL nodeUrl; - - private final String dataCenter; - - private String name; - - private String regionId; - - /** - * constructor - * @param nodeUrl - * @param dataCenter - */ - public MetaNode(URL nodeUrl, String dataCenter) { - this.nodeUrl = nodeUrl; - this.name = getIp(); - this.dataCenter = dataCenter; - } - - @Override - public NodeType getNodeType() { - return nodeType; - } - - @Override - public URL getNodeUrl() { - return nodeUrl; - } - - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } - - /** - * get ip address from nodeUrl - * @return - */ - public String getIp() { - return nodeUrl == null ? "" : nodeUrl.getIpAddress(); - } - - /** - * Getter method for property name. - * - * @return property value of name - */ - public String getName() { - return name; - } - - /** - * Setter method for property name. - * - * @param name value to be assigned to property name - */ - public void setName(String name) { - this.name = name; - } - - /** - * Getter method for property regionId. - * - * @return property value of regionId - */ - public String getRegionId() { - return regionId; - } - - /** - * Setter method for property regionId. - * - * @param regionId value to be assigned to property regionId - */ - public void setRegionId(String regionId) { - this.regionId = regionId; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("MetaNode{"); - sb.append("ip=").append(getIp()); - sb.append('}'); - return sb.toString(); - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - MetaNode metaNode = (MetaNode) o; - return nodeType == metaNode.nodeType && nodeUrl.equals(metaNode.nodeUrl) - && Objects.equals(dataCenter, metaNode.dataCenter) - && Objects.equals(name, metaNode.name); - } - - @Override - public int hashCode() { - return Objects.hash(nodeType, nodeUrl, dataCenter, name); - } - -} \ No newline at end of file + private final NodeType nodeType = NodeType.META; + + private final URL nodeUrl; + + private final String dataCenter; + + private String name; + + private String regionId; + + /** + * constructor + * + * @param nodeUrl + * @param dataCenter + */ + public MetaNode(URL nodeUrl, String dataCenter) { + this.nodeUrl = nodeUrl; + this.name = getIp(); + this.dataCenter = dataCenter; + } + + @Override + public NodeType getNodeType() { + return nodeType; + } + + @Override + public URL getNodeUrl() { + return nodeUrl; + } + + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * get ip address from nodeUrl + * + * @return + */ + public String getIp() { + return nodeUrl == null ? "" : nodeUrl.getIpAddress(); + } + + /** + * Getter method for property name. + * + * @return property value of name + */ + public String getName() { + return name; + } + + /** + * Setter method for property name. + * + * @param name value to be assigned to property name + */ + public void setName(String name) { + this.name = name; + } + + /** + * Getter method for property regionId. + * + * @return property value of regionId + */ + public String getRegionId() { + return regionId; + } + + /** + * Setter method for property regionId. + * + * @param regionId value to be assigned to property regionId + */ + public void setRegionId(String regionId) { + this.regionId = regionId; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("MetaNode{"); + sb.append("ip=").append(getIp()); + sb.append('}'); + return sb.toString(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MetaNode metaNode = (MetaNode) o; + return nodeType == metaNode.nodeType + && nodeUrl.equals(metaNode.nodeUrl) + && Objects.equals(dataCenter, metaNode.dataCenter) + && Objects.equals(name, metaNode.name); + } + + @Override + public int hashCode() { + return Objects.hash(nodeType, nodeUrl, dataCenter, name); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/SessionNode.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/SessionNode.java index 189ea93d3..4396e74cf 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/SessionNode.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/nodes/SessionNode.java @@ -18,152 +18,154 @@ import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.ProcessId; -import com.alipay.sofa.registry.common.model.metaserver.ProvideData; import com.alipay.sofa.registry.common.model.store.URL; /** - * * @author shangyu.wh * @version $Id: SessionNodeRegister.java, v 0.1 2018-01-11 16:32 shangyu.wh Exp $ */ public class SessionNode implements Node { - private URL nodeUrl; - - private String regionId; - - private String name; - - private ProcessId processId; - - /** - * constructor - * @param nodeUrl - * @param regionId - */ - public SessionNode(URL nodeUrl, String regionId) { - this.nodeUrl = nodeUrl; - this.regionId = regionId; - } - - @Override - public NodeType getNodeType() { - return NodeType.SESSION; + private URL nodeUrl; + + private String regionId; + + private String name; + + private ProcessId processId; + + /** + * constructor + * + * @param nodeUrl + * @param regionId + */ + public SessionNode(URL nodeUrl, String regionId) { + this.nodeUrl = nodeUrl; + this.regionId = regionId; + } + + @Override + public NodeType getNodeType() { + return NodeType.SESSION; + } + + @Override + public URL getNodeUrl() { + return nodeUrl; + } + + /** + * get ip address from nodeUrl + * + * @return + */ + public String getIp() { + return nodeUrl == null ? "" : nodeUrl.getIpAddress(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - @Override - public URL getNodeUrl() { - return nodeUrl; + if (!(o instanceof SessionNode)) { + return false; } - /** - * get ip address from nodeUrl - * @return - */ - public String getIp() { - return nodeUrl == null ? "" : nodeUrl.getIpAddress(); - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof SessionNode)) { - return false; - } - - SessionNode that = (SessionNode) o; - - if (name != null ? !name.equals(that.name) : that.name != null) { - return false; - } - - if (regionId != null ? !regionId.equals(that.regionId) : that.regionId != null) { - return false; - } - - return nodeUrl != null ? (nodeUrl.getAddressString() != null ? nodeUrl.getAddressString() - .equals(that.nodeUrl.getAddressString()) : that.nodeUrl.getAddressString() != null) - : that.nodeUrl != null; - } - - public ProcessId getProcessId() { - return processId; - } - - public SessionNode setProcessId(ProcessId processId) { - this.processId = processId; - return this; - } - - /** - * Hash code int. - * - * @return the int - */ - @Override - public int hashCode() { - int result = name != null ? name.hashCode() : 0; - result = 31 * result + (regionId != null ? regionId.hashCode() : 0); - result = 31 - * result - + (nodeUrl != null ? (nodeUrl.getAddressString() != null ? nodeUrl - .getAddressString().hashCode() : 0) : 0); - return result; - } - - /** - * Setter method for property nodeUrl. - * - * @param nodeUrl value to be assigned to property nodeUrl - */ - public void setNodeUrl(URL nodeUrl) { - this.nodeUrl = nodeUrl; - } - - /** - * Getter method for property regionId. - * - * @return property value of regionId - */ - public String getRegionId() { - return regionId; - } - - /** - * Setter method for property regionId. - * - * @param regionId value to be assigned to property regionId - */ - public void setRegionId(String regionId) { - this.regionId = regionId; - } - - /** - * Getter method for property name. - * - * @return property value of name - */ - public String getName() { - return name; - } + SessionNode that = (SessionNode) o; - /** - * Setter method for property name. - * - * @param name value to be assigned to property name - */ - public void setName(String name) { - this.name = name; + if (name != null ? !name.equals(that.name) : that.name != null) { + return false; } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("SessionNode{"); - sb.append("ip=").append(getIp()); - sb.append('}'); - return sb.toString(); + if (regionId != null ? !regionId.equals(that.regionId) : that.regionId != null) { + return false; } -} \ No newline at end of file + return nodeUrl != null + ? (nodeUrl.getAddressString() != null + ? nodeUrl.getAddressString().equals(that.nodeUrl.getAddressString()) + : that.nodeUrl.getAddressString() != null) + : that.nodeUrl != null; + } + + public ProcessId getProcessId() { + return processId; + } + + public SessionNode setProcessId(ProcessId processId) { + this.processId = processId; + return this; + } + + /** + * Hash code int. + * + * @return the int + */ + @Override + public int hashCode() { + int result = name != null ? name.hashCode() : 0; + result = 31 * result + (regionId != null ? regionId.hashCode() : 0); + result = + 31 * result + + (nodeUrl != null + ? (nodeUrl.getAddressString() != null ? nodeUrl.getAddressString().hashCode() : 0) + : 0); + return result; + } + + /** + * Setter method for property nodeUrl. + * + * @param nodeUrl value to be assigned to property nodeUrl + */ + public void setNodeUrl(URL nodeUrl) { + this.nodeUrl = nodeUrl; + } + + /** + * Getter method for property regionId. + * + * @return property value of regionId + */ + public String getRegionId() { + return regionId; + } + + /** + * Setter method for property regionId. + * + * @param regionId value to be assigned to property regionId + */ + public void setRegionId(String regionId) { + this.regionId = regionId; + } + + /** + * Getter method for property name. + * + * @return property value of name + */ + public String getName() { + return name; + } + + /** + * Setter method for property name. + * + * @param name value to be assigned to property name + */ + public void setName(String name) { + this.name = name; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("SessionNode{"); + sb.append("ip=").append(getIp()); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/rpc/NodeClusterViewRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/rpc/NodeClusterViewRequest.java index bab8a3d7f..4a126807e 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/rpc/NodeClusterViewRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/rpc/NodeClusterViewRequest.java @@ -17,66 +17,63 @@ package com.alipay.sofa.registry.common.model.metaserver.rpc; import com.alipay.sofa.registry.common.model.Node.NodeType; - import java.io.Serializable; /** - * * @author shangyu.wh * @version $Id: GetChangeListRequest.java, v 0.1 2018-02-12 11:02 shangyu.wh Exp $ */ public class NodeClusterViewRequest implements Serializable { - private final NodeType nodeType; + private final NodeType nodeType; - /** - * get list data dataCenter - */ - private String dataCenterId; + /** get list data dataCenter */ + private String dataCenterId; - /** - * constructor - * @param nodeType - * @param dataCenterId - */ - public NodeClusterViewRequest(NodeType nodeType, String dataCenterId) { - this.nodeType = nodeType; - this.dataCenterId = dataCenterId; - } + /** + * constructor + * + * @param nodeType + * @param dataCenterId + */ + public NodeClusterViewRequest(NodeType nodeType, String dataCenterId) { + this.nodeType = nodeType; + this.dataCenterId = dataCenterId; + } - /** - * Getter method for property dataCenterId. - * - * @return property value of dataCenterId - */ - public String getDataCenterId() { - return dataCenterId; - } + /** + * Getter method for property dataCenterId. + * + * @return property value of dataCenterId + */ + public String getDataCenterId() { + return dataCenterId; + } - /** - * Setter method for property dataCenterId. - * - * @param dataCenterId value to be assigned to property dataCenterId - */ - public void setDataCenterId(String dataCenterId) { - this.dataCenterId = dataCenterId; - } + /** + * Setter method for property dataCenterId. + * + * @param dataCenterId value to be assigned to property dataCenterId + */ + public void setDataCenterId(String dataCenterId) { + this.dataCenterId = dataCenterId; + } - /** - * Getter method for property nodeType. - * - * @return property value of nodeType - */ - public NodeType getNodeType() { - return nodeType; - } + /** + * Getter method for property nodeType. + * + * @return property value of nodeType + */ + public NodeType getNodeType() { + return nodeType; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("GetChangeListRequest{"); - sb.append("nodeType=").append(nodeType); - sb.append(", dataCenterId='").append(dataCenterId).append('\''); - sb.append('}'); - return sb.toString(); - } -} \ No newline at end of file + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("GetChangeListRequest{"); + sb.append("nodeType=").append(nodeType); + sb.append(", dataCenterId='").append(dataCenterId).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/CancelAddressRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/CancelAddressRequest.java index ec27e96aa..84db1882a 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/CancelAddressRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/CancelAddressRequest.java @@ -17,51 +17,50 @@ package com.alipay.sofa.registry.common.model.sessionserver; import com.alipay.sofa.registry.common.model.ConnectId; - import java.io.Serializable; import java.util.List; /** * The type Cancel address request. + * * @author shangyu.wh * @version $Id : CancelAddressRequest.java, v 0.1 2017-12-22 17:04 shangyu.wh Exp $ */ public class CancelAddressRequest implements Serializable { - private static final long serialVersionUID = -4398310292728124256L; + private static final long serialVersionUID = -4398310292728124256L; - private List connectIds; + private List connectIds; - public CancelAddressRequest() { - } + public CancelAddressRequest() {} - /** - * Constructor. - * - * @param connectIds the connect ids - */ - public CancelAddressRequest(List connectIds) { - this.connectIds = connectIds; - } + /** + * Constructor. + * + * @param connectIds the connect ids + */ + public CancelAddressRequest(List connectIds) { + this.connectIds = connectIds; + } - /** - * Getter method for property connectIds. - * - * @return property value of connectIds - */ - public List getConnectIds() { - return connectIds; - } + /** + * Getter method for property connectIds. + * + * @return property value of connectIds + */ + public List getConnectIds() { + return connectIds; + } - public void setConnectIds(List connectIds) { - this.connectIds = connectIds; - } + public void setConnectIds(List connectIds) { + this.connectIds = connectIds; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("CancelAddressRequest{"); - sb.append("connectIds=").append(connectIds); - sb.append('}'); - return sb.toString(); - } -} \ No newline at end of file + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("CancelAddressRequest{"); + sb.append("connectIds=").append(connectIds); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/DataChangeRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/DataChangeRequest.java index e0f6b60fa..f9206ac48 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/DataChangeRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/DataChangeRequest.java @@ -17,9 +17,6 @@ package com.alipay.sofa.registry.common.model.sessionserver; import com.alipay.sofa.registry.common.model.dataserver.DatumVersion; -import com.alipay.sofa.registry.common.model.store.WordCache; -import com.google.common.collect.Maps; - import java.io.Serializable; import java.util.*; @@ -31,28 +28,33 @@ */ public class DataChangeRequest implements Serializable { - private static final long serialVersionUID = -7674982522990222894L; + private static final long serialVersionUID = -7674982522990222894L; - private final Map dataInfoIds; + private final Map dataInfoIds; - private final String dataCenter; + private final String dataCenter; - public DataChangeRequest(String dataCenter, Map dataInfoIds) { - this.dataCenter = dataCenter; - this.dataInfoIds = dataInfoIds; - } + public DataChangeRequest(String dataCenter, Map dataInfoIds) { + this.dataCenter = dataCenter; + this.dataInfoIds = dataInfoIds; + } - public Map getDataInfoIds() { - return Collections.unmodifiableMap(dataInfoIds); - } + public Map getDataInfoIds() { + return Collections.unmodifiableMap(dataInfoIds); + } - public String getDataCenter() { - return dataCenter; - } + public String getDataCenter() { + return dataCenter; + } - @Override - public String toString() { - return "DataChangeRequest{" + "dataInfoIds=" + dataInfoIds + ", dataCenter='" + dataCenter - + '\'' + '}'; - } + @Override + public String toString() { + return "DataChangeRequest{" + + "dataInfoIds=" + + dataInfoIds + + ", dataCenter='" + + dataCenter + + '\'' + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/DataPushRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/DataPushRequest.java index 53eaf69ce..c6bd71211 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/DataPushRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/sessionserver/DataPushRequest.java @@ -17,53 +17,51 @@ package com.alipay.sofa.registry.common.model.sessionserver; import com.alipay.sofa.registry.common.model.dataserver.Datum; - import java.io.Serializable; /** - * * @author shangyu.wh * @version $Id: DataPushRequest.java, v 0.1 2018-08-29 18:11 shangyu.wh Exp $ */ public class DataPushRequest implements Serializable { - private Datum datum; - - /** - * constructor - * @param datum - */ - public DataPushRequest(Datum datum) { - this.datum = datum; - } + private Datum datum; - /** - * Getter method for property datum. - * - * @return property value of datum - */ - public Datum getDatum() { - return datum; - } + /** + * constructor + * + * @param datum + */ + public DataPushRequest(Datum datum) { + this.datum = datum; + } - /** - * Setter method for property datum. - * - * @param datum value to be assigned to property datum - */ - public void setDatum(Datum datum) { - this.datum = datum; - } + /** + * Getter method for property datum. + * + * @return property value of datum + */ + public Datum getDatum() { + return datum; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("DataPushRequest{"); - sb.append("dataInfoId=").append(datum.getDataInfoId()); - sb.append(", dataCenter=").append(datum.getDataCenter()); - sb.append(", version=").append(datum.getVersion()); - sb.append(", pubsize=").append(datum.publisherSize()); - sb.append('}'); - return sb.toString(); - } + /** + * Setter method for property datum. + * + * @param datum value to be assigned to property datum + */ + public void setDatum(Datum datum) { + this.datum = datum; + } -} \ No newline at end of file + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("DataPushRequest{"); + sb.append("dataInfoId=").append(datum.getDataInfoId()); + sb.append(", dataCenter=").append(datum.getDataCenter()); + sb.append(", version=").append(datum.getVersion()); + sb.append(", pubsize=").append(datum.publisherSize()); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/BaseSlotStatus.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/BaseSlotStatus.java index e65654b0d..317185d65 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/BaseSlotStatus.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/BaseSlotStatus.java @@ -20,85 +20,96 @@ /** * @author chen.zhu - *

- * Feb 24, 2021 + *

Feb 24, 2021 */ public class BaseSlotStatus implements Serializable { - protected final int slotId; + protected final int slotId; - protected final long slotLeaderEpoch; + protected final long slotLeaderEpoch; - protected final Slot.Role role; + protected final Slot.Role role; - protected final String server; + protected final String server; - /** - * Constructor. - * @param slotId the slot id - * @param slotLeaderEpoch the slot leader epoch - * @param role the role - * @param server - */ - public BaseSlotStatus(int slotId, long slotLeaderEpoch, Slot.Role role, String server) { - this.slotId = slotId; - this.slotLeaderEpoch = slotLeaderEpoch; - this.role = role; - this.server = server; - } + /** + * Constructor. + * + * @param slotId the slot id + * @param slotLeaderEpoch the slot leader epoch + * @param role the role + * @param server + */ + public BaseSlotStatus(int slotId, long slotLeaderEpoch, Slot.Role role, String server) { + this.slotId = slotId; + this.slotLeaderEpoch = slotLeaderEpoch; + this.role = role; + this.server = server; + } - /** - * Gets get slot id. - * - * @return the get slot id - */ - public int getSlotId() { - return slotId; - } + /** + * Gets get slot id. + * + * @return the get slot id + */ + public int getSlotId() { + return slotId; + } - /** - * Gets get slot leader epoch. - * - * @return the get slot leader epoch - */ - public long getSlotLeaderEpoch() { - return slotLeaderEpoch; - } + /** + * Gets get slot leader epoch. + * + * @return the get slot leader epoch + */ + public long getSlotLeaderEpoch() { + return slotLeaderEpoch; + } - /** - * Gets get role. - * - * @return the get role - */ - public Slot.Role getRole() { - return role; - } + /** + * Gets get role. + * + * @return the get role + */ + public Slot.Role getRole() { + return role; + } + + /** + * Gets get data server. + * + * @return the get data server + */ + public String getServer() { + return server; + } + + public enum LeaderStatus { + INIT, + HEALTHY, + UNHEALTHY; /** - * Gets get data server. + * Is healthy boolean. * - * @return the get data server + * @return the boolean */ - public String getServer() { - return server; + public boolean isHealthy() { + return this == HEALTHY; } + } - public enum LeaderStatus { - INIT, HEALTHY, UNHEALTHY; - - /** - * Is healthy boolean. - * - * @return the boolean - */ - public boolean isHealthy() { - return this == HEALTHY; - } - } - - @Override - public String toString() { - return "BaseSlotStatus{" + "slotId=" + slotId + ", slotLeaderEpoch=" + slotLeaderEpoch - + ", role=" + role + ", server='" + server + '\'' + '}'; - } + @Override + public String toString() { + return "BaseSlotStatus{" + + "slotId=" + + slotId + + ", slotLeaderEpoch=" + + slotLeaderEpoch + + ", role=" + + role + + ", server='" + + server + + '\'' + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataNodeSlot.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataNodeSlot.java index 88af3a87e..6f69c4df6 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataNodeSlot.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataNodeSlot.java @@ -18,141 +18,148 @@ import com.google.common.collect.Lists; import com.google.common.collect.Sets; - import java.io.Serializable; import java.util.*; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-03 11:27 yuzhi.lyz Exp $ */ public final class DataNodeSlot implements Serializable { - private static final long serialVersionUID = -4418378966762753298L; - private final String dataNode; - private final Set leaders = Sets.newTreeSet(); - private final Set followers = Sets.newTreeSet(); - - /** - * Constructor. - * - * @param dataNode the data node - */ - public DataNodeSlot(String dataNode) { - this.dataNode = dataNode; - } - - /** - * Fork data node slot. - * - * @param ignoreFollowers the ignore followers - * @return the data node slot - */ - public DataNodeSlot fork(boolean ignoreFollowers) { - DataNodeSlot clone = new DataNodeSlot(dataNode); - clone.leaders.addAll(leaders); - if (!ignoreFollowers) { - clone.followers.addAll(followers); - } - return clone; - } - - public DataNodeSlot addLeader(int slotId) { - leaders.add(slotId); - return this; - } - - public DataNodeSlot addLeader(Collection slotIds) { - leaders.addAll(slotIds); - return this; - } - - public DataNodeSlot removeLeader(int slotId) { - leaders.remove(slotId); - return this; - } - - public DataNodeSlot addFollower(int slotId) { - followers.add(slotId); - return this; - } - - public DataNodeSlot addFollower(Collection slotIds) { - followers.addAll(slotIds); - return this; - } - - public DataNodeSlot removeFollower(int slotId) { - followers.remove(slotId); - return this; - } - - public boolean containsLeader(int slotId) { - return leaders.contains(slotId); - } - - public boolean containsFollower(int slotId) { - return followers.contains(slotId); - } - - /** - * Getter method for property dataNode. - * @return property value of dataNode - */ - public String getDataNode() { - return dataNode; - } - - /** - * Getter method for property leaders. - * @return property value of leaders - */ - public Set getLeaders() { - return Collections.unmodifiableSet(leaders); - } - - /** - * Getter method for property followers. - * @return property value of followers - */ - public Set getFollowers() { - return Collections.unmodifiableSet(followers); - } - - /** - * Total slot num int. - * - * @return the int - */ - public int totalSlotNum() { - return leaders.size() + followers.size(); - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - DataNodeSlot that = (DataNodeSlot) o; - return Objects.equals(dataNode, that.dataNode) && Objects.equals(leaders, that.leaders) - && Objects.equals(followers, that.followers); - } - - @Override - public int hashCode() { - return Objects.hash(dataNode, leaders, followers); - } - - @Override - public String toString() { - return "DataNodeSlot{" + "dataNode='" + dataNode + '\'' + ", leaders=" + leaders - + ", followers=" + followers + '}'; - } - - public static List collectDataNodes(Collection dataNodeSlots) { - Set ret = Sets.newLinkedHashSet(); - dataNodeSlots.forEach(d -> ret.add(d.dataNode)); - return Lists.newArrayList(ret); - } + private static final long serialVersionUID = -4418378966762753298L; + private final String dataNode; + private final Set leaders = Sets.newTreeSet(); + private final Set followers = Sets.newTreeSet(); + + /** + * Constructor. + * + * @param dataNode the data node + */ + public DataNodeSlot(String dataNode) { + this.dataNode = dataNode; + } + + /** + * Fork data node slot. + * + * @param ignoreFollowers the ignore followers + * @return the data node slot + */ + public DataNodeSlot fork(boolean ignoreFollowers) { + DataNodeSlot clone = new DataNodeSlot(dataNode); + clone.leaders.addAll(leaders); + if (!ignoreFollowers) { + clone.followers.addAll(followers); + } + return clone; + } + + public DataNodeSlot addLeader(int slotId) { + leaders.add(slotId); + return this; + } + + public DataNodeSlot addLeader(Collection slotIds) { + leaders.addAll(slotIds); + return this; + } + + public DataNodeSlot removeLeader(int slotId) { + leaders.remove(slotId); + return this; + } + + public DataNodeSlot addFollower(int slotId) { + followers.add(slotId); + return this; + } + + public DataNodeSlot addFollower(Collection slotIds) { + followers.addAll(slotIds); + return this; + } + + public DataNodeSlot removeFollower(int slotId) { + followers.remove(slotId); + return this; + } + + public boolean containsLeader(int slotId) { + return leaders.contains(slotId); + } + + public boolean containsFollower(int slotId) { + return followers.contains(slotId); + } + + /** + * Getter method for property dataNode. + * + * @return property value of dataNode + */ + public String getDataNode() { + return dataNode; + } + + /** + * Getter method for property leaders. + * + * @return property value of leaders + */ + public Set getLeaders() { + return Collections.unmodifiableSet(leaders); + } + + /** + * Getter method for property followers. + * + * @return property value of followers + */ + public Set getFollowers() { + return Collections.unmodifiableSet(followers); + } + + /** + * Total slot num int. + * + * @return the int + */ + public int totalSlotNum() { + return leaders.size() + followers.size(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DataNodeSlot that = (DataNodeSlot) o; + return Objects.equals(dataNode, that.dataNode) + && Objects.equals(leaders, that.leaders) + && Objects.equals(followers, that.followers); + } + + @Override + public int hashCode() { + return Objects.hash(dataNode, leaders, followers); + } + + @Override + public String toString() { + return "DataNodeSlot{" + + "dataNode='" + + dataNode + + '\'' + + ", leaders=" + + leaders + + ", followers=" + + followers + + '}'; + } + + public static List collectDataNodes(Collection dataNodeSlots) { + Set ret = Sets.newLinkedHashSet(); + dataNodeSlots.forEach(d -> ret.add(d.dataNode)); + return Lists.newArrayList(ret); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffDigestRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffDigestRequest.java index 6505fa9bc..ea8af803d 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffDigestRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffDigestRequest.java @@ -17,53 +17,58 @@ package com.alipay.sofa.registry.common.model.slot; import com.alipay.sofa.registry.common.model.dataserver.DatumDigest; - import java.io.Serializable; import java.util.Collections; import java.util.Map; -import java.util.Set; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-05 14:24 yuzhi.lyz Exp $ */ public class DataSlotDiffDigestRequest implements Serializable { - private final long slotTableEpoch; - // all dataInfoIds, diff by digest - private final Map datumDigest; - private final int slotId; + private final long slotTableEpoch; + // all dataInfoIds, diff by digest + private final Map datumDigest; + private final int slotId; - public DataSlotDiffDigestRequest(long slotTableEpoch, int slotId, - Map datumDigest) { - this.slotTableEpoch = slotTableEpoch; - this.slotId = slotId; - this.datumDigest = datumDigest; - } + public DataSlotDiffDigestRequest( + long slotTableEpoch, int slotId, Map datumDigest) { + this.slotTableEpoch = slotTableEpoch; + this.slotId = slotId; + this.datumDigest = datumDigest; + } - /** - * Getter method for property slotId. - * @return property value of slotId - */ - public int getSlotId() { - return slotId; - } + /** + * Getter method for property slotId. + * + * @return property value of slotId + */ + public int getSlotId() { + return slotId; + } - /** - * Getter method for property slotTableEpoch. - * @return property value of slotTableEpoch - */ - public long getSlotTableEpoch() { - return slotTableEpoch; - } + /** + * Getter method for property slotTableEpoch. + * + * @return property value of slotTableEpoch + */ + public long getSlotTableEpoch() { + return slotTableEpoch; + } - public Map getDatumDigest() { - return Collections.unmodifiableMap(datumDigest); - } + public Map getDatumDigest() { + return Collections.unmodifiableMap(datumDigest); + } - @Override - public String toString() { - return "SlotDiffDigestRequest{" + "slotTableEpoch=" + slotTableEpoch + ", slotId=" + slotId - + ", digests=" + datumDigest.size() + '}'; - } + @Override + public String toString() { + return "SlotDiffDigestRequest{" + + "slotTableEpoch=" + + slotTableEpoch + + ", slotId=" + + slotId + + ", digests=" + + datumDigest.size() + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffDigestResult.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffDigestResult.java index 2d08ad008..12f749468 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffDigestResult.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffDigestResult.java @@ -17,99 +17,93 @@ package com.alipay.sofa.registry.common.model.slot; import com.alipay.sofa.registry.common.model.ProcessId; -import com.alipay.sofa.registry.common.model.store.Publisher; import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; - import java.io.Serializable; import java.util.Collections; import java.util.List; -import java.util.Map; -import java.util.Set; +import org.apache.commons.collections.CollectionUtils; /** * @author yuzhi.lyz * @version v 0.1 2020-11-05 17:04 yuzhi.lyz Exp $ */ public class DataSlotDiffDigestResult implements Serializable { - private long slotTableEpoch; - private final List updatedDataInfoIds; - private final List addedDataInfoIds; - private final List removedDataInfoIds; - // if from session, return the sessionProcessId for lease - private ProcessId sessionProcessId; - - public DataSlotDiffDigestResult(List updatedDataInfoIds, List addedDataInfoIds, - List removedDataInfoIds) { - this.updatedDataInfoIds = Lists.newArrayList(updatedDataInfoIds); - this.addedDataInfoIds = Lists.newArrayList(addedDataInfoIds); - this.removedDataInfoIds = Lists.newArrayList(removedDataInfoIds); - } + private long slotTableEpoch; + private final List updatedDataInfoIds; + private final List addedDataInfoIds; + private final List removedDataInfoIds; + // if from session, return the sessionProcessId for lease + private ProcessId sessionProcessId; - /** - * Getter method for property slotTableEpoch. - * - * @return property value of slotTableEpoch - */ - public long getSlotTableEpoch() { - return slotTableEpoch; - } + public DataSlotDiffDigestResult( + List updatedDataInfoIds, + List addedDataInfoIds, + List removedDataInfoIds) { + this.updatedDataInfoIds = Lists.newArrayList(updatedDataInfoIds); + this.addedDataInfoIds = Lists.newArrayList(addedDataInfoIds); + this.removedDataInfoIds = Lists.newArrayList(removedDataInfoIds); + } - /** - * Setter method for property slotTableEpoch. - * - * @param slotTableEpoch value to be assigned to property slotTableEpoch - */ - public void setSlotTableEpoch(long slotTableEpoch) { - this.slotTableEpoch = slotTableEpoch; - } + /** + * Getter method for property slotTableEpoch. + * + * @return property value of slotTableEpoch + */ + public long getSlotTableEpoch() { + return slotTableEpoch; + } - public List getUpdatedDataInfoIds() { - return Collections.unmodifiableList(updatedDataInfoIds); - } + /** + * Setter method for property slotTableEpoch. + * + * @param slotTableEpoch value to be assigned to property slotTableEpoch + */ + public void setSlotTableEpoch(long slotTableEpoch) { + this.slotTableEpoch = slotTableEpoch; + } - /** - * Getter method for property removedDataInfoIds. - * - * @return property value of removedDataInfoIds - */ - public List getRemovedDataInfoIds() { - return Collections.unmodifiableList(removedDataInfoIds); - } + public List getUpdatedDataInfoIds() { + return Collections.unmodifiableList(updatedDataInfoIds); + } - public List getAddedDataInfoIds() { - return Collections.unmodifiableList(addedDataInfoIds); - } + /** + * Getter method for property removedDataInfoIds. + * + * @return property value of removedDataInfoIds + */ + public List getRemovedDataInfoIds() { + return Collections.unmodifiableList(removedDataInfoIds); + } - /** - * Getter method for property sessionProcessId. - * - * @return property value of sessionProcessId - */ - public ProcessId getSessionProcessId() { - return sessionProcessId; - } + public List getAddedDataInfoIds() { + return Collections.unmodifiableList(addedDataInfoIds); + } - /** - * Setter method for property sessionProcessId. - * - * @param sessionProcessId value to be assigned to property sessionProcessId - */ - public void setSessionProcessId(ProcessId sessionProcessId) { - this.sessionProcessId = sessionProcessId; - } + /** + * Getter method for property sessionProcessId. + * + * @return property value of sessionProcessId + */ + public ProcessId getSessionProcessId() { + return sessionProcessId; + } - public boolean isEmpty() { - return CollectionUtils.isEmpty(updatedDataInfoIds) - && CollectionUtils.isEmpty(removedDataInfoIds) - && CollectionUtils.isEmpty(addedDataInfoIds); - } + /** + * Setter method for property sessionProcessId. + * + * @param sessionProcessId value to be assigned to property sessionProcessId + */ + public void setSessionProcessId(ProcessId sessionProcessId) { + this.sessionProcessId = sessionProcessId; + } - public int getUpdateAndAddSize() { - return updatedDataInfoIds.size() + addedDataInfoIds.size(); - } + public boolean isEmpty() { + return CollectionUtils.isEmpty(updatedDataInfoIds) + && CollectionUtils.isEmpty(removedDataInfoIds) + && CollectionUtils.isEmpty(addedDataInfoIds); + } + public int getUpdateAndAddSize() { + return updatedDataInfoIds.size() + addedDataInfoIds.size(); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffPublisherRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffPublisherRequest.java index 11d54d3c9..e23ddd87f 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffPublisherRequest.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffPublisherRequest.java @@ -18,53 +18,59 @@ import com.alipay.sofa.registry.common.model.dataserver.DatumSummary; import com.google.common.collect.Lists; - import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.List; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-05 14:24 yuzhi.lyz Exp $ */ public class DataSlotDiffPublisherRequest implements Serializable { - private final long slotTableEpoch; - // parts of the summary to diff sync - private final List datumSummaries; - private final int slotId; + private final long slotTableEpoch; + // parts of the summary to diff sync + private final List datumSummaries; + private final int slotId; - public DataSlotDiffPublisherRequest(long slotTableEpoch, int slotId, - Collection datumSummaries) { - this.slotTableEpoch = slotTableEpoch; - this.slotId = slotId; - this.datumSummaries = Collections.unmodifiableList(Lists.newArrayList(datumSummaries)); - } + public DataSlotDiffPublisherRequest( + long slotTableEpoch, int slotId, Collection datumSummaries) { + this.slotTableEpoch = slotTableEpoch; + this.slotId = slotId; + this.datumSummaries = Collections.unmodifiableList(Lists.newArrayList(datumSummaries)); + } - /** - * Getter method for property slotId. - * @return property value of slotId - */ - public int getSlotId() { - return slotId; - } + /** + * Getter method for property slotId. + * + * @return property value of slotId + */ + public int getSlotId() { + return slotId; + } - /** - * Getter method for property slotTableEpoch. - * @return property value of slotTableEpoch - */ - public long getSlotTableEpoch() { - return slotTableEpoch; - } + /** + * Getter method for property slotTableEpoch. + * + * @return property value of slotTableEpoch + */ + public long getSlotTableEpoch() { + return slotTableEpoch; + } - public List getDatumSummaries() { - return datumSummaries; - } + public List getDatumSummaries() { + return datumSummaries; + } - @Override - public String toString() { - return "SlotDiffPublisherRequest{" + ", slotId=" + slotId + ", slotTableEpoch=" - + slotTableEpoch + ", summaries=" + datumSummaries.size() + '}'; - } + @Override + public String toString() { + return "SlotDiffPublisherRequest{" + + ", slotId=" + + slotId + + ", slotTableEpoch=" + + slotTableEpoch + + ", summaries=" + + datumSummaries.size() + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffPublisherResult.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffPublisherResult.java index fbd46d747..00f63c2c8 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffPublisherResult.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffPublisherResult.java @@ -18,116 +18,119 @@ import com.alipay.sofa.registry.common.model.ProcessId; import com.alipay.sofa.registry.common.model.store.Publisher; -import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.collections.MapUtils; - import java.io.Serializable; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.commons.collections.MapUtils; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-05 17:04 yuzhi.lyz Exp $ */ public class DataSlotDiffPublisherResult implements Serializable { - private long slotTableEpoch; - private final Map> updatedPublishers; - private final Map> removedPublishers; - // if from session, return the sessionProcessId for lease - private ProcessId sessionProcessId; - // contains all the updated/added publishers - private final boolean hasRemain; + private long slotTableEpoch; + private final Map> updatedPublishers; + private final Map> removedPublishers; + // if from session, return the sessionProcessId for lease + private ProcessId sessionProcessId; + // contains all the updated/added publishers + private final boolean hasRemain; - public DataSlotDiffPublisherResult(boolean hasRemain, - Map> updatedPublishers, - Map> removedPublishers) { - this.updatedPublishers = Maps.newHashMap(updatedPublishers); - this.removedPublishers = Maps.newHashMap(removedPublishers); - this.hasRemain = hasRemain; - } + public DataSlotDiffPublisherResult( + boolean hasRemain, + Map> updatedPublishers, + Map> removedPublishers) { + this.updatedPublishers = Maps.newHashMap(updatedPublishers); + this.removedPublishers = Maps.newHashMap(removedPublishers); + this.hasRemain = hasRemain; + } - public boolean isHasRemain() { - return hasRemain; - } + public boolean isHasRemain() { + return hasRemain; + } - /** - * Getter method for property slotTableEpoch. - * @return property value of slotTableEpoch - */ - public long getSlotTableEpoch() { - return slotTableEpoch; - } + /** + * Getter method for property slotTableEpoch. + * + * @return property value of slotTableEpoch + */ + public long getSlotTableEpoch() { + return slotTableEpoch; + } - /** - * Setter method for property slotTableEpoch. - * @param slotTableEpoch value to be assigned to property slotTableEpoch - */ - public void setSlotTableEpoch(long slotTableEpoch) { - this.slotTableEpoch = slotTableEpoch; - } + /** + * Setter method for property slotTableEpoch. + * + * @param slotTableEpoch value to be assigned to property slotTableEpoch + */ + public void setSlotTableEpoch(long slotTableEpoch) { + this.slotTableEpoch = slotTableEpoch; + } - /** - * Getter method for property updatedPublishers. - * @return property value of updatedPublishers - */ - public Map> getUpdatedPublishers() { - return Collections.unmodifiableMap(updatedPublishers); - } + /** + * Getter method for property updatedPublishers. + * + * @return property value of updatedPublishers + */ + public Map> getUpdatedPublishers() { + return Collections.unmodifiableMap(updatedPublishers); + } - /** - * Getter method for property removedPublishers. - * @return property value of removedPublishers - */ - public Map> getRemovedPublishers() { - return Collections.unmodifiableMap(removedPublishers); - } + /** + * Getter method for property removedPublishers. + * + * @return property value of removedPublishers + */ + public Map> getRemovedPublishers() { + return Collections.unmodifiableMap(removedPublishers); + } - public int getRemovedPublishersCount() { - int count = 0; - for (List list : removedPublishers.values()) { - count += list.size(); - } - return count; + public int getRemovedPublishersCount() { + int count = 0; + for (List list : removedPublishers.values()) { + count += list.size(); } + return count; + } - public int getUpdatedPublishersCount() { - int count = 0; - for (List list : updatedPublishers.values()) { - count += list.size(); - } - return count; + public int getUpdatedPublishersCount() { + int count = 0; + for (List list : updatedPublishers.values()) { + count += list.size(); } + return count; + } - /** - * Getter method for property sessionProcessId. - * @return property value of sessionProcessId - */ - public ProcessId getSessionProcessId() { - return sessionProcessId; - } + /** + * Getter method for property sessionProcessId. + * + * @return property value of sessionProcessId + */ + public ProcessId getSessionProcessId() { + return sessionProcessId; + } - /** - * Setter method for property sessionProcessId. - * @param sessionProcessId value to be assigned to property sessionProcessId - */ - public void setSessionProcessId(ProcessId sessionProcessId) { - this.sessionProcessId = sessionProcessId; - } + /** + * Setter method for property sessionProcessId. + * + * @param sessionProcessId value to be assigned to property sessionProcessId + */ + public void setSessionProcessId(ProcessId sessionProcessId) { + this.sessionProcessId = sessionProcessId; + } - public boolean isEmpty() { - return MapUtils.isEmpty(updatedPublishers) && MapUtils.isEmpty(removedPublishers); - } + public boolean isEmpty() { + return MapUtils.isEmpty(updatedPublishers) && MapUtils.isEmpty(removedPublishers); + } - public Set syncDataInfoIds() { - Set ret = Sets.newHashSet(); - ret.addAll(updatedPublishers.keySet()); - ret.addAll(removedPublishers.keySet()); - return ret; - } + public Set syncDataInfoIds() { + Set ret = Sets.newHashSet(); + ret.addAll(updatedPublishers.keySet()); + ret.addAll(removedPublishers.keySet()); + return ret; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffUtils.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffUtils.java index 865a26cfe..a8866e545 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffUtils.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffUtils.java @@ -26,7 +26,6 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; - import java.util.*; /** @@ -34,116 +33,125 @@ * @version v 0.1 2020-11-24 15:46 yuzhi.lyz Exp $ */ public final class DataSlotDiffUtils { - private static final Logger SYNC_LOGGER = LoggerFactory.getLogger("SYNC-SRV"); + private static final Logger SYNC_LOGGER = LoggerFactory.getLogger("SYNC-SRV"); - private DataSlotDiffUtils() { - } + private DataSlotDiffUtils() {} - public static DataSlotDiffDigestResult diffDigestPublishers(Map targetDigestMap, - Map> sourcePublishers) { - Map sourceSummaryMap = PublisherUtils - .getDatumSummary(sourcePublishers); - Map digestMap = PublisherDigestUtil.digest(sourceSummaryMap); - return diffDigest(targetDigestMap, digestMap); - } + public static DataSlotDiffDigestResult diffDigestPublishers( + Map targetDigestMap, + Map> sourcePublishers) { + Map sourceSummaryMap = PublisherUtils.getDatumSummary(sourcePublishers); + Map digestMap = PublisherDigestUtil.digest(sourceSummaryMap); + return diffDigest(targetDigestMap, digestMap); + } - public static DataSlotDiffDigestResult diffDigest(Map targetDigestMap, - Map sourceDigestMap) { - List adds = Lists.newArrayList(); - List updates = Lists.newArrayList(); - for (Map.Entry e : sourceDigestMap.entrySet()) { - final String dataInfoId = e.getKey(); - DatumDigest targetDigest = targetDigestMap.get(dataInfoId); - if (targetDigest == null) { - adds.add(dataInfoId); - continue; - } - if (!targetDigest.equals(e.getValue())) { - updates.add(dataInfoId); - } - } + public static DataSlotDiffDigestResult diffDigest( + Map targetDigestMap, Map sourceDigestMap) { + List adds = Lists.newArrayList(); + List updates = Lists.newArrayList(); + for (Map.Entry e : sourceDigestMap.entrySet()) { + final String dataInfoId = e.getKey(); + DatumDigest targetDigest = targetDigestMap.get(dataInfoId); + if (targetDigest == null) { + adds.add(dataInfoId); + continue; + } + if (!targetDigest.equals(e.getValue())) { + updates.add(dataInfoId); + } + } - // find the removed dataInfoIds - List removes = new ArrayList<>(); - for (String dataInfoId : targetDigestMap.keySet()) { - if (!sourceDigestMap.containsKey(dataInfoId)) { - removes.add(dataInfoId); - } - } - DataSlotDiffDigestResult result = new DataSlotDiffDigestResult(updates, adds, removes); - return result; + // find the removed dataInfoIds + List removes = new ArrayList<>(); + for (String dataInfoId : targetDigestMap.keySet()) { + if (!sourceDigestMap.containsKey(dataInfoId)) { + removes.add(dataInfoId); + } } + DataSlotDiffDigestResult result = new DataSlotDiffDigestResult(updates, adds, removes); + return result; + } - public static DataSlotDiffPublisherResult diffPublishersResult(Collection targetDatumSummaries, - Map> sourcePublishers, - int publisherMaxNum) { - Map> updatePublishers = Maps.newHashMapWithExpectedSize(targetDatumSummaries.size()); - Map> removedPublishers = new HashMap<>(); + public static DataSlotDiffPublisherResult diffPublishersResult( + Collection targetDatumSummaries, + Map> sourcePublishers, + int publisherMaxNum) { + Map> updatePublishers = + Maps.newHashMapWithExpectedSize(targetDatumSummaries.size()); + Map> removedPublishers = new HashMap<>(); - int publisherCount = 0; - int checkRound = 0; - for (DatumSummary summary : targetDatumSummaries) { - checkRound++; - final String dataInfoId = summary.getDataInfoId(); - Map publisherMap = sourcePublishers.get(dataInfoId); - if (publisherMap == null) { - // the dataInfoId has removed, do not handle it, diffDataInfoIds will handle it - continue; - } - Set registerIds = summary.getPublisherVersions().keySet(); - for (String registerId : registerIds) { - if (!publisherMap.containsKey(registerId)) { - List list = removedPublishers.computeIfAbsent(dataInfoId, k -> new ArrayList<>()); - list.add(registerId); - } - } - List publishers = new ArrayList<>(); - Map versions = summary.getPublisherVersions(); - for (Map.Entry p : publisherMap.entrySet()) { - final String registerId = p.getKey(); - if (!versions.containsKey(registerId)) { - publishers.add(p.getValue()); - continue; - } - // compare version - if (p.getValue().registerVersion().equals(versions.get(registerId))) { - // the same - continue; - } - publishers.add(p.getValue()); - } - if (!publishers.isEmpty()) { - publisherCount += publishers.size(); - updatePublishers.put(dataInfoId, publishers); - } - if (publisherCount >= publisherMaxNum) { - // too many publishers, mark has remain - break; - } + int publisherCount = 0; + int checkRound = 0; + for (DatumSummary summary : targetDatumSummaries) { + checkRound++; + final String dataInfoId = summary.getDataInfoId(); + Map publisherMap = sourcePublishers.get(dataInfoId); + if (publisherMap == null) { + // the dataInfoId has removed, do not handle it, diffDataInfoIds will handle it + continue; + } + Set registerIds = summary.getPublisherVersions().keySet(); + for (String registerId : registerIds) { + if (!publisherMap.containsKey(registerId)) { + List list = removedPublishers.computeIfAbsent(dataInfoId, k -> new ArrayList<>()); + list.add(registerId); + } + } + List publishers = new ArrayList<>(); + Map versions = summary.getPublisherVersions(); + for (Map.Entry p : publisherMap.entrySet()) { + final String registerId = p.getKey(); + if (!versions.containsKey(registerId)) { + publishers.add(p.getValue()); + continue; + } + // compare version + if (p.getValue().registerVersion().equals(versions.get(registerId))) { + // the same + continue; } - // the iter has break - final boolean hasRemian = checkRound != targetDatumSummaries.size(); - DataSlotDiffPublisherResult result = new DataSlotDiffPublisherResult(hasRemian, updatePublishers, removedPublishers); - return result; + publishers.add(p.getValue()); + } + if (!publishers.isEmpty()) { + publisherCount += publishers.size(); + updatePublishers.put(dataInfoId, publishers); + } + if (publisherCount >= publisherMaxNum) { + // too many publishers, mark has remain + break; + } } + // the iter has break + final boolean hasRemian = checkRound != targetDatumSummaries.size(); + DataSlotDiffPublisherResult result = + new DataSlotDiffPublisherResult(hasRemian, updatePublishers, removedPublishers); + return result; + } - public static void logDiffResult(DataSlotDiffPublisherResult result, int slotId) { - if (!result.isEmpty()) { - SYNC_LOGGER.info( - "DiffPublisher, slotId={}, remain={}, update={}/{}, remove={}/{}, removes={}", - slotId, result.isHasRemain(), result.getUpdatedPublishers().size(), - result.getUpdatedPublishersCount(), result.getRemovedPublishers().size(), - result.getRemovedPublishersCount(), result.getRemovedPublishers().keySet()); - } + public static void logDiffResult(DataSlotDiffPublisherResult result, int slotId) { + if (!result.isEmpty()) { + SYNC_LOGGER.info( + "DiffPublisher, slotId={}, remain={}, update={}/{}, remove={}/{}, removes={}", + slotId, + result.isHasRemain(), + result.getUpdatedPublishers().size(), + result.getUpdatedPublishersCount(), + result.getRemovedPublishers().size(), + result.getRemovedPublishersCount(), + result.getRemovedPublishers().keySet()); } + } - public static void logDiffResult(DataSlotDiffDigestResult result, int slotId) { - if (!result.isEmpty()) { - SYNC_LOGGER.info( - "DiffDigest, slotId={}, update={}, add={}, remove={}, adds={}, removes={}", slotId, - result.getUpdatedDataInfoIds().size(), result.getAddedDataInfoIds().size(), result - .getRemovedDataInfoIds().size(), result.getAddedDataInfoIds(), result - .getRemovedDataInfoIds()); - } + public static void logDiffResult(DataSlotDiffDigestResult result, int slotId) { + if (!result.isEmpty()) { + SYNC_LOGGER.info( + "DiffDigest, slotId={}, update={}, add={}, remove={}, adds={}, removes={}", + slotId, + result.getUpdatedDataInfoIds().size(), + result.getAddedDataInfoIds().size(), + result.getRemovedDataInfoIds().size(), + result.getAddedDataInfoIds(), + result.getRemovedDataInfoIds()); } + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/FollowerSlotStatus.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/FollowerSlotStatus.java index 10d76072d..01e37bff3 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/FollowerSlotStatus.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/FollowerSlotStatus.java @@ -20,59 +20,73 @@ /** * @author chen.zhu - *

- * Mar 01, 2021 + *

Mar 01, 2021 */ public class FollowerSlotStatus extends BaseSlotStatus implements Serializable { - private final long lastSyncTaskStartTime; + private final long lastSyncTaskStartTime; - private final long lastLeaderSyncTime; + private final long lastLeaderSyncTime; - /** - * Constructor. - * - * @param slotId the slot id - * @param slotLeaderEpoch the slot leader epoch - * @param server the server - * @param lastSyncTaskStartTime the last sync task start time - * @param lastLeaderSyncTime the last leader sync time - */ - public FollowerSlotStatus(int slotId, long slotLeaderEpoch, String server, - long lastSyncTaskStartTime, long lastLeaderSyncTime) { - super(slotId, slotLeaderEpoch, Slot.Role.Follower, server); - this.lastSyncTaskStartTime = lastSyncTaskStartTime; - this.lastLeaderSyncTime = lastLeaderSyncTime; - } + /** + * Constructor. + * + * @param slotId the slot id + * @param slotLeaderEpoch the slot leader epoch + * @param server the server + * @param lastSyncTaskStartTime the last sync task start time + * @param lastLeaderSyncTime the last leader sync time + */ + public FollowerSlotStatus( + int slotId, + long slotLeaderEpoch, + String server, + long lastSyncTaskStartTime, + long lastLeaderSyncTime) { + super(slotId, slotLeaderEpoch, Slot.Role.Follower, server); + this.lastSyncTaskStartTime = lastSyncTaskStartTime; + this.lastLeaderSyncTime = lastLeaderSyncTime; + } - /** - * Gets get last sync task start time. - * - * @return the get last sync task start time - */ - public long getLastSyncTaskStartTime() { - return lastSyncTaskStartTime; - } + /** + * Gets get last sync task start time. + * + * @return the get last sync task start time + */ + public long getLastSyncTaskStartTime() { + return lastSyncTaskStartTime; + } - /** - * Gets get last follower sync time. - * - * @return the get last follower sync time - */ - public long getLastLeaderSyncTime() { - return lastLeaderSyncTime; - } + /** + * Gets get last follower sync time. + * + * @return the get last follower sync time + */ + public long getLastLeaderSyncTime() { + return lastLeaderSyncTime; + } - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "FollowerSlotStatus{" + "lastSyncTaskStartTime=" + lastSyncTaskStartTime - + ", lastLeaderSyncTime=" + lastLeaderSyncTime + ", slotId=" + slotId - + ", slotLeaderEpoch=" + slotLeaderEpoch + ", role=" + role + ", server='" + server - + '\'' + '}'; - } + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "FollowerSlotStatus{" + + "lastSyncTaskStartTime=" + + lastSyncTaskStartTime + + ", lastLeaderSyncTime=" + + lastLeaderSyncTime + + ", slotId=" + + slotId + + ", slotLeaderEpoch=" + + slotLeaderEpoch + + ", role=" + + role + + ", server='" + + server + + '\'' + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/LeaderSlotStatus.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/LeaderSlotStatus.java index 437bc0381..10c9ce05c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/LeaderSlotStatus.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/LeaderSlotStatus.java @@ -20,40 +20,49 @@ /** * @author chen.zhu - *

- * Mar 01, 2021 + *

Mar 01, 2021 */ public class LeaderSlotStatus extends BaseSlotStatus implements Serializable { - private LeaderStatus leaderStatus = LeaderStatus.INIT; + private LeaderStatus leaderStatus = LeaderStatus.INIT; - /** - * Constructor. - * - * @param slotId the slot id - * @param slotLeaderEpoch the slot leader epoch - * @param server the server - * @param leaderStatus the leader status - */ - public LeaderSlotStatus(int slotId, long slotLeaderEpoch, String server, - LeaderStatus leaderStatus) { - super(slotId, slotLeaderEpoch, Slot.Role.Leader, server); - this.leaderStatus = leaderStatus; - } + /** + * Constructor. + * + * @param slotId the slot id + * @param slotLeaderEpoch the slot leader epoch + * @param server the server + * @param leaderStatus the leader status + */ + public LeaderSlotStatus( + int slotId, long slotLeaderEpoch, String server, LeaderStatus leaderStatus) { + super(slotId, slotLeaderEpoch, Slot.Role.Leader, server); + this.leaderStatus = leaderStatus; + } - /** - * Gets get leader status. - * - * @return the get leader status - */ - public LeaderStatus getLeaderStatus() { - return leaderStatus; - } + /** + * Gets get leader status. + * + * @return the get leader status + */ + public LeaderStatus getLeaderStatus() { + return leaderStatus; + } - @Override - public String toString() { - return "LeaderSlotStatus{" + "leaderStatus=" + leaderStatus + ", slotId=" + slotId - + ", slotLeaderEpoch=" + slotLeaderEpoch + ", role=" + role + ", server='" + server - + '\'' + '}'; - } + @Override + public String toString() { + return "LeaderSlotStatus{" + + "leaderStatus=" + + leaderStatus + + ", slotId=" + + slotId + + ", slotLeaderEpoch=" + + slotLeaderEpoch + + ", role=" + + role + + ", server='" + + server + + '\'' + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/Slot.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/Slot.java index fdfd50678..13e6cb36b 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/Slot.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/Slot.java @@ -18,7 +18,6 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; - import java.io.Serializable; import java.util.*; @@ -27,81 +26,97 @@ * @version v 0.1 2020-10-30 10:12 yuzhi.lyz Exp $ */ public final class Slot implements Serializable, Cloneable { - public enum Role { - Leader, Follower, - } + public enum Role { + Leader, + Follower, + } - private final int id; - private final String leader; - private final long leaderEpoch; - private final Set followers; + private final int id; + private final String leader; + private final long leaderEpoch; + private final Set followers; - @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) - public Slot(@JsonProperty("id") int id, @JsonProperty("leader") String leader, - @JsonProperty("leaderEpoch") long leaderEpoch, - @JsonProperty("followers") Collection followers) { - this.id = id; - this.leader = leader; - this.leaderEpoch = leaderEpoch; - this.followers = Collections.unmodifiableSet(new HashSet<>(followers)); - } + @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) + public Slot( + @JsonProperty("id") int id, + @JsonProperty("leader") String leader, + @JsonProperty("leaderEpoch") long leaderEpoch, + @JsonProperty("followers") Collection followers) { + this.id = id; + this.leader = leader; + this.leaderEpoch = leaderEpoch; + this.followers = Collections.unmodifiableSet(new HashSet<>(followers)); + } - @Override - protected Slot clone() { - return new Slot(this.id, this.leader, this.leaderEpoch, this.followers); - } + @Override + protected Slot clone() { + return new Slot(this.id, this.leader, this.leaderEpoch, this.followers); + } - /** - * Getter method for property id. - * @return property value of id - */ - public int getId() { - return id; - } + /** + * Getter method for property id. + * + * @return property value of id + */ + public int getId() { + return id; + } - /** - * Getter method for property leader. - * @return property value of leader - */ - public String getLeader() { - return leader; - } + /** + * Getter method for property leader. + * + * @return property value of leader + */ + public String getLeader() { + return leader; + } - /** - * Getter method for property followers. - * @return property value of followers - */ - public Set getFollowers() { - return followers; - } + /** + * Getter method for property followers. + * + * @return property value of followers + */ + public Set getFollowers() { + return followers; + } - /** - * Getter method for property leaderEpoch. - * @return property value of leaderEpoch - */ - public long getLeaderEpoch() { - return leaderEpoch; - } + /** + * Getter method for property leaderEpoch. + * + * @return property value of leaderEpoch + */ + public long getLeaderEpoch() { + return leaderEpoch; + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (!(o instanceof Slot)) - return false; - Slot slot = (Slot) o; - return id == slot.id && leaderEpoch == slot.leaderEpoch - && Objects.equals(leader, slot.leader) && Objects.equals(followers, slot.followers); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (!(o instanceof Slot)) return false; + Slot slot = (Slot) o; + return id == slot.id + && leaderEpoch == slot.leaderEpoch + && Objects.equals(leader, slot.leader) + && Objects.equals(followers, slot.followers); + } - @Override - public int hashCode() { - return Objects.hash(id, leader, leaderEpoch, followers); - } + @Override + public int hashCode() { + return Objects.hash(id, leader, leaderEpoch, followers); + } - @Override - public String toString() { - return "Slot{" + "id=" + id + ", leader='" + leader + '\'' + ", leaderEpoch=" + leaderEpoch - + ", followers=" + followers + '}'; - } + @Override + public String toString() { + return "Slot{" + + "id=" + + id + + ", leader='" + + leader + + '\'' + + ", leaderEpoch=" + + leaderEpoch + + ", followers=" + + followers + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotAccess.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotAccess.java index 3ddf4a2ed..89944ba1a 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotAccess.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotAccess.java @@ -23,57 +23,68 @@ * @version v 0.1 2020-10-30 10:34 yuzhi.lyz Exp $ */ public final class SlotAccess implements Serializable { - public enum Status { - Accept, Migrating, Moved, MisMatch, - } + public enum Status { + Accept, + Migrating, + Moved, + MisMatch, + } - private final int slotId; - private final Status status; - private final long slotTableEpoch; - private final long slotLeaderEpoch; + private final int slotId; + private final Status status; + private final long slotTableEpoch; + private final long slotLeaderEpoch; - public SlotAccess(int slotId, long slotTableEpoch, Status status, long slotLeaderEpoch) { - this.slotTableEpoch = slotTableEpoch; - this.slotId = slotId; - this.status = status; - this.slotLeaderEpoch = slotLeaderEpoch; - } + public SlotAccess(int slotId, long slotTableEpoch, Status status, long slotLeaderEpoch) { + this.slotTableEpoch = slotTableEpoch; + this.slotId = slotId; + this.status = status; + this.slotLeaderEpoch = slotLeaderEpoch; + } - public boolean isMoved() { - return status == Status.Moved; - } + public boolean isMoved() { + return status == Status.Moved; + } - public boolean isMigrating() { - return status == Status.Migrating; - } + public boolean isMigrating() { + return status == Status.Migrating; + } - public boolean isAccept() { - return status == Status.Accept; - } + public boolean isAccept() { + return status == Status.Accept; + } - public boolean isMisMatch() { - return status == Status.MisMatch; - } + public boolean isMisMatch() { + return status == Status.MisMatch; + } - public Status getStatus() { - return status; - } + public Status getStatus() { + return status; + } - public int getSlotId() { - return slotId; - } + public int getSlotId() { + return slotId; + } - public long getSlotTableEpoch() { - return slotTableEpoch; - } + public long getSlotTableEpoch() { + return slotTableEpoch; + } - public long getSlotLeaderEpoch() { - return slotLeaderEpoch; - } + public long getSlotLeaderEpoch() { + return slotLeaderEpoch; + } - @Override - public String toString() { - return "SlotAccess{" + "slotId=" + slotId + ", status=" + status + ", tableEpoch=" - + slotTableEpoch + ", leaderEpoch=" + slotLeaderEpoch + '}'; - } + @Override + public String toString() { + return "SlotAccess{" + + "slotId=" + + slotId + + ", status=" + + status + + ", tableEpoch=" + + slotTableEpoch + + ", leaderEpoch=" + + slotLeaderEpoch + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotAccessGenericResponse.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotAccessGenericResponse.java index afdb9927c..cf2f1e18b 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotAccessGenericResponse.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotAccessGenericResponse.java @@ -19,41 +19,42 @@ import com.alipay.sofa.registry.common.model.GenericResponse; /** - * * @author yuzhi.lyz * @version v 0.1 2020-10-30 11:05 yuzhi.lyz Exp $ */ public final class SlotAccessGenericResponse extends GenericResponse { - private final SlotAccess slotAccess; - - private SlotAccessGenericResponse(boolean success, String message, SlotAccess slotAccess, T data) { - this.slotAccess = slotAccess; - this.setData(data); - this.setSuccess(success); - this.setMessage(message); - } - - /** - * Getter method for property slotAccess. - * @return property value of slotAccess - */ - public SlotAccess getSlotAccess() { - return slotAccess; - } - - public static SlotAccessGenericResponse successResponse(SlotAccess access, T data) { - return new SlotAccessGenericResponse(true, null, access, data); - } - - public static SlotAccessGenericResponse failedResponse(SlotAccess access) { - return new SlotAccessGenericResponse(false, access.toString(), access, null); - } - - public static SlotAccessGenericResponse failedResponse(SlotAccess access, String msg) { - return new SlotAccessGenericResponse(false, msg, access, null); - } - - public static SlotAccessGenericResponse failedResponse(String msg) { - return new SlotAccessGenericResponse(false, msg, null, null); - } + private final SlotAccess slotAccess; + + private SlotAccessGenericResponse( + boolean success, String message, SlotAccess slotAccess, T data) { + this.slotAccess = slotAccess; + this.setData(data); + this.setSuccess(success); + this.setMessage(message); + } + + /** + * Getter method for property slotAccess. + * + * @return property value of slotAccess + */ + public SlotAccess getSlotAccess() { + return slotAccess; + } + + public static SlotAccessGenericResponse successResponse(SlotAccess access, T data) { + return new SlotAccessGenericResponse(true, null, access, data); + } + + public static SlotAccessGenericResponse failedResponse(SlotAccess access) { + return new SlotAccessGenericResponse(false, access.toString(), access, null); + } + + public static SlotAccessGenericResponse failedResponse(SlotAccess access, String msg) { + return new SlotAccessGenericResponse(false, msg, access, null); + } + + public static SlotAccessGenericResponse failedResponse(String msg) { + return new SlotAccessGenericResponse(false, msg, null, null); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotConfig.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotConfig.java index 5a612ca58..956e72c7c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotConfig.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotConfig.java @@ -19,94 +19,91 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.util.SystemUtils; - import java.io.Serializable; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-13 20:00 yuzhi.lyz Exp $ */ public final class SlotConfig { - private static final Logger LOGGER = LoggerFactory - .getLogger(SlotConfig.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SlotConfig.class); - private static final String KEY_DATA_SLOT_NUM = "data.slot.num"; - private static final String KEY_DATA_SLOT_FUNC = "data.slot.func"; - private static final String KEY_DATA_SLOT_REPLICAS = "data.slot.replicas"; - public static final int SLOT_NUM; - public static final int SLOT_REPLICAS; - public static final String FUNC; + private static final String KEY_DATA_SLOT_NUM = "data.slot.num"; + private static final String KEY_DATA_SLOT_FUNC = "data.slot.func"; + private static final String KEY_DATA_SLOT_REPLICAS = "data.slot.replicas"; + public static final int SLOT_NUM; + public static final int SLOT_REPLICAS; + public static final String FUNC; - private SlotConfig() { - } + private SlotConfig() {} - static { - SLOT_NUM = SystemUtils.getSystemInteger(KEY_DATA_SLOT_NUM, 16); - if (SLOT_NUM <= 0) { - throw new IllegalArgumentException("illegal " + KEY_DATA_SLOT_NUM - + ":" + SLOT_NUM); - } - SLOT_REPLICAS = SystemUtils.getSystemInteger(KEY_DATA_SLOT_REPLICAS, 2); - if (SLOT_REPLICAS <= 0) { - throw new IllegalArgumentException("illegal " - + KEY_DATA_SLOT_REPLICAS + ":" + SLOT_REPLICAS); - } - FUNC = SystemUtils.getSystem(KEY_DATA_SLOT_FUNC, "crc32c"); - LOGGER.info("{}={}, {}={}, {}={}", KEY_DATA_SLOT_NUM, SLOT_NUM, - KEY_DATA_SLOT_REPLICAS, SLOT_REPLICAS, KEY_DATA_SLOT_FUNC, FUNC); - } + static { + SLOT_NUM = SystemUtils.getSystemInteger(KEY_DATA_SLOT_NUM, 16); + if (SLOT_NUM <= 0) { + throw new IllegalArgumentException("illegal " + KEY_DATA_SLOT_NUM + ":" + SLOT_NUM); + } + SLOT_REPLICAS = SystemUtils.getSystemInteger(KEY_DATA_SLOT_REPLICAS, 2); + if (SLOT_REPLICAS <= 0) { + throw new IllegalArgumentException("illegal " + KEY_DATA_SLOT_REPLICAS + ":" + SLOT_REPLICAS); + } + FUNC = SystemUtils.getSystem(KEY_DATA_SLOT_FUNC, "crc32c"); + LOGGER.info( + "{}={}, {}={}, {}={}", + KEY_DATA_SLOT_NUM, + SLOT_NUM, + KEY_DATA_SLOT_REPLICAS, + SLOT_REPLICAS, + KEY_DATA_SLOT_FUNC, + FUNC); + } - public static class SlotBasicInfo implements Serializable { + public static class SlotBasicInfo implements Serializable { - private final int slotNum; + private final int slotNum; - private final int slotReplicas; + private final int slotReplicas; - private final String slotFunc; + private final String slotFunc; - /** - * Constructor. - * - * @param slotNum - * the slot num - * @param slotReplicas - * the slot replicas - * @param slotFunc - * the slot func - */ - public SlotBasicInfo(int slotNum, int slotReplicas, String slotFunc) { - this.slotNum = slotNum; - this.slotReplicas = slotReplicas; - this.slotFunc = slotFunc; - } + /** + * Constructor. + * + * @param slotNum the slot num + * @param slotReplicas the slot replicas + * @param slotFunc the slot func + */ + public SlotBasicInfo(int slotNum, int slotReplicas, String slotFunc) { + this.slotNum = slotNum; + this.slotReplicas = slotReplicas; + this.slotFunc = slotFunc; + } - /** - * Gets get slot num. - * - * @return the get slot num - */ - public int getSlotNum() { - return slotNum; - } + /** + * Gets get slot num. + * + * @return the get slot num + */ + public int getSlotNum() { + return slotNum; + } - /** - * Gets get slot replicas. - * - * @return the get slot replicas - */ - public int getSlotReplicas() { - return slotReplicas; - } + /** + * Gets get slot replicas. + * + * @return the get slot replicas + */ + public int getSlotReplicas() { + return slotReplicas; + } - /** - * Gets get slot func. - * - * @return the get slot func - */ - public String getSlotFunc() { - return slotFunc; - } - } + /** + * Gets get slot func. + * + * @return the get slot func + */ + public String getSlotFunc() { + return slotFunc; + } + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotTable.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotTable.java index e859001cc..b52b98164 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotTable.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/SlotTable.java @@ -22,7 +22,6 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.google.common.collect.Maps; import com.google.common.collect.Sets; - import java.io.Serializable; import java.util.*; @@ -31,240 +30,254 @@ * @version v 0.1 2020-10-30 10:08 yuzhi.lyz Exp $ */ public final class SlotTable implements Serializable { - public static final SlotTable INIT = new SlotTable(-1, Collections.emptyList()); - private final long epoch; - private final Map slots; - - private SlotTable(long epoch, Map slots) { - this.epoch = epoch; - this.slots = Collections.unmodifiableSortedMap(new TreeMap<>(slots)); - } - - public SlotTable(long epoch, final Collection slots) { - this.epoch = epoch; - SortedMap slotMap = Maps.newTreeMap(); - slots.forEach(slot->{ - Slot exist = slotMap.putIfAbsent(slot.getId(), slot); - if (exist != null) { - throw new SofaRegistrySlotTableException("dup slot when construct slot table: " - + JsonUtils.writeValueAsString(slots)); - } + public static final SlotTable INIT = new SlotTable(-1, Collections.emptyList()); + private final long epoch; + private final Map slots; + + private SlotTable(long epoch, Map slots) { + this.epoch = epoch; + this.slots = Collections.unmodifiableSortedMap(new TreeMap<>(slots)); + } + + public SlotTable(long epoch, final Collection slots) { + this.epoch = epoch; + SortedMap slotMap = Maps.newTreeMap(); + slots.forEach( + slot -> { + Slot exist = slotMap.putIfAbsent(slot.getId(), slot); + if (exist != null) { + throw new SofaRegistrySlotTableException( + "dup slot when construct slot table: " + JsonUtils.writeValueAsString(slots)); + } }); - this.slots = Collections.unmodifiableSortedMap(slotMap); + this.slots = Collections.unmodifiableSortedMap(slotMap); + } + + public List getSlots() { + return new ArrayList<>(slots.values()); + } + + @JsonIgnore + public Map getSlotMap() { + return Maps.newHashMap(slots); + } + + @JsonIgnore + public Set getSlotIds() { + return new TreeSet<>(slots.keySet()); + } + + public Slot getSlot(int slotId) { + return slots.get(slotId); + } + + public Map slotLeaders() { + Map ret = Maps.newTreeMap(); + for (Map.Entry e : slots.entrySet()) { + ret.put(e.getKey(), e.getValue().getLeader()); } - - public List getSlots() { - return new ArrayList<>(slots.values()); - } - - @JsonIgnore - public Map getSlotMap() { - return Maps.newHashMap(slots); + return ret; + } + + /** + * Getter method for property epoch. + * + * @return property value of epoch + */ + public long getEpoch() { + return epoch; + } + + @Override + public String toString() { + return StringFormatter.format( + "SlotTable{epoch={}, num={}, leaders={}}", epoch, slots.size(), slotLeaders()); + } + + /** the slot table is too big for rpc */ + public List transfer(String targetDataNode, boolean ignoreFollowers) { + Map> leadersMap = new HashMap<>(); + Map> followersMap = new HashMap<>(); + for (Slot slot : slots.values()) { + if (targetDataNode == null) { + List leaders = + leadersMap.computeIfAbsent(slot.getLeader(), k -> new ArrayList<>()); + leaders.add(slot.getId()); + if (!ignoreFollowers) { + for (String follower : slot.getFollowers()) { + List followers = + followersMap.computeIfAbsent(follower, k -> new ArrayList<>()); + followers.add(slot.getId()); + } + } + continue; + } + if (!ignoreFollowers && slot.getFollowers().contains(targetDataNode)) { + List followers = + followersMap.computeIfAbsent(targetDataNode, k -> new ArrayList<>()); + followers.add(slot.getId()); + } + if (targetDataNode.equals(slot.getLeader())) { + List leaders = + leadersMap.computeIfAbsent(slot.getLeader(), k -> new ArrayList<>()); + leaders.add(slot.getId()); + } } - - @JsonIgnore - public Set getSlotIds() { - return new TreeSet<>(slots.keySet()); + Map dataNodeSlotMap = Maps.newHashMapWithExpectedSize(leadersMap.size()); + for (Map.Entry> e : leadersMap.entrySet()) { + DataNodeSlot dataNodeSlot = + dataNodeSlotMap.computeIfAbsent(e.getKey(), k -> new DataNodeSlot(k)); + Collections.sort(e.getValue()); + dataNodeSlot.addLeader(e.getValue()); } - - public Slot getSlot(int slotId) { - return slots.get(slotId); + for (Map.Entry> e : followersMap.entrySet()) { + DataNodeSlot dataNodeSlot = + dataNodeSlotMap.computeIfAbsent(e.getKey(), k -> new DataNodeSlot(k)); + Collections.sort(e.getValue()); + dataNodeSlot.addFollower(e.getValue()); } - - public Map slotLeaders() { - Map ret = Maps.newTreeMap(); - for (Map.Entry e : slots.entrySet()) { - ret.put(e.getKey(), e.getValue().getLeader()); - } - return ret; + return new ArrayList<>(dataNodeSlotMap.values()); + } + + public Set getDataServers() { + final Set servers = Sets.newTreeSet(); + slots + .values() + .forEach( + s -> { + servers.add(s.getLeader()); + servers.addAll(s.getFollowers()); + }); + return servers; + } + + public SlotTable filter(String ip) { + if (slots.isEmpty()) { + return this; } - - /** - * Getter method for property epoch. - * @return property value of epoch - */ - public long getEpoch() { - return epoch; + final Map slotMap = Maps.newHashMapWithExpectedSize(slots.size()); + slots.forEach( + (k, v) -> { + if (v.getLeader().equals(ip) || v.getFollowers().contains(ip)) { + slotMap.put(k, v); + } + }); + return new SlotTable(epoch, slotMap); + } + + public int getLeaderNum(String dataServerIp) { + return (int) slots.values().stream().filter(s -> dataServerIp.equals(s.getLeader())).count(); + } + + public int getFollowerNum(String dataServerIp) { + return (int) + slots.values().stream().filter(s -> s.getFollowers().contains(dataServerIp)).count(); + } + + public void assertSlotLessThan(SlotTable slotTable) { + slots + .values() + .forEach( + s -> { + Slot newSlot = slotTable.getSlot(s.getId()); + if (newSlot == null) { + return; + } + if (s.getLeaderEpoch() > newSlot.getLeaderEpoch()) { + throw new RuntimeException( + String.format("not expect Slot.LeaderEpoch, %s, %s", s, newSlot)); + } + }); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - @Override - public String toString() { - return StringFormatter.format("SlotTable{epoch={}, num={}, leaders={}}", epoch, - slots.size(), slotLeaders()); + if (o == null || getClass() != o.getClass()) { + return false; } + SlotTable slotTable = (SlotTable) o; + return epoch == slotTable.epoch && slots.equals(slotTable.slots); + } - /** - * the slot table is too big for rpc - */ - public List transfer(String targetDataNode, boolean ignoreFollowers) { - Map> leadersMap = new HashMap<>(); - Map> followersMap = new HashMap<>(); - for (Slot slot : slots.values()) { - if (targetDataNode == null) { - List leaders = leadersMap.computeIfAbsent(slot.getLeader(), k -> new ArrayList<>()); - leaders.add(slot.getId()); - if (!ignoreFollowers) { - for (String follower : slot.getFollowers()) { - List followers = followersMap.computeIfAbsent(follower, k -> new ArrayList<>()); - followers.add(slot.getId()); - } - } - continue; - } - if (!ignoreFollowers && slot.getFollowers().contains(targetDataNode)) { - List followers = followersMap.computeIfAbsent(targetDataNode, k -> new ArrayList<>()); - followers.add(slot.getId()); - } - if (targetDataNode.equals(slot.getLeader())) { - List leaders = leadersMap.computeIfAbsent(slot.getLeader(), k -> new ArrayList<>()); - leaders.add(slot.getId()); - } - } - Map dataNodeSlotMap = Maps.newHashMapWithExpectedSize(leadersMap.size()); - for (Map.Entry> e : leadersMap.entrySet()) { - DataNodeSlot dataNodeSlot = dataNodeSlotMap.computeIfAbsent(e.getKey(), k -> new DataNodeSlot(k)); - Collections.sort(e.getValue()); - dataNodeSlot.addLeader(e.getValue()); - } - for (Map.Entry> e : followersMap.entrySet()) { - DataNodeSlot dataNodeSlot = dataNodeSlotMap.computeIfAbsent(e.getKey(), k -> new DataNodeSlot(k)); - Collections.sort(e.getValue()); - dataNodeSlot.addFollower(e.getValue()); - } - return new ArrayList<>(dataNodeSlotMap.values()); - } + @Override + public int hashCode() { + return Objects.hash(epoch, slots); + } - public Set getDataServers() { - final Set servers = Sets.newTreeSet(); - slots.values().forEach(s -> { - servers.add(s.getLeader()); - servers.addAll(s.getFollowers()); - }); - return servers; - } + public static final class SlotTableBuilder { - public SlotTable filter(String ip) { - if (slots.isEmpty()) { - return this; - } - final Map slotMap = Maps.newHashMapWithExpectedSize(slots.size()); - slots.forEach((k, v) -> { - if (v.getLeader().equals(ip) || v.getFollowers().contains(ip)) { - slotMap.put(k, v); - } - }); - return new SlotTable(epoch, slotMap); - } + private final long epoch; - public int getLeaderNum(String dataServerIp) { - return (int) slots.values().stream().filter(s -> dataServerIp.equals(s.getLeader())).count(); - } + private final Map slotBuilderMap = Maps.newHashMap(); - public int getFollowerNum(String dataServerIp) { - return (int) slots.values().stream().filter(s -> s.getFollowers().contains(dataServerIp)).count(); + private SlotTableBuilder(long epoch) { + this.epoch = epoch; } - public void assertSlotLessThan(SlotTable slotTable) { - slots.values().forEach(s -> { - Slot newSlot = slotTable.getSlot(s.getId()); - if (newSlot == null) { - return; - } - if (s.getLeaderEpoch() > newSlot.getLeaderEpoch()) { - throw new RuntimeException(String.format("not expect Slot.LeaderEpoch, %s, %s", s, newSlot)); - } - }); + public SlotTableBuilder slotLeader(int slotId, String leader) { + slotBuilderMap.putIfAbsent(slotId, new SlotBuilder(slotId)); + slotBuilderMap.get(slotId).leader(leader); + return this; } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - SlotTable slotTable = (SlotTable) o; - return epoch == slotTable.epoch && slots.equals(slotTable.slots); + public SlotTableBuilder slotFollower(int slotId, String follower) { + slotBuilderMap.putIfAbsent(slotId, new SlotBuilder(slotId)); + slotBuilderMap.get(slotId).follower(follower); + return this; } - @Override - public int hashCode() { - return Objects.hash(epoch, slots); + public SlotTable build() { + Map slotMap = Maps.newHashMap(); + for (Map.Entry entry : slotBuilderMap.entrySet()) { + slotMap.put(entry.getKey(), entry.getValue().build()); + } + return new SlotTable(epoch, slotMap); } + } - public final static class SlotTableBuilder { + private static final class SlotBuilder { - private final long epoch; + private final int slotId; - private final Map slotBuilderMap = Maps.newHashMap(); + private String leader; - private SlotTableBuilder(long epoch) { - this.epoch = epoch; - } + private long leaderEpoch; - public SlotTableBuilder slotLeader(int slotId, String leader) { - slotBuilderMap.putIfAbsent(slotId, new SlotBuilder(slotId)); - slotBuilderMap.get(slotId).leader(leader); - return this; - } + private final Set followers = Sets.newHashSet(); - public SlotTableBuilder slotFollower(int slotId, String follower) { - slotBuilderMap.putIfAbsent(slotId, new SlotBuilder(slotId)); - slotBuilderMap.get(slotId).follower(follower); - return this; - } - - public SlotTable build() { - Map slotMap = Maps.newHashMap(); - for (Map.Entry entry : slotBuilderMap.entrySet()) { - slotMap.put(entry.getKey(), entry.getValue().build()); - } - return new SlotTable(epoch, slotMap); - } + public SlotBuilder(int slotId) { + this.slotId = slotId; } - private final static class SlotBuilder { - - private final int slotId; - - private String leader; - - private long leaderEpoch; - - private final Set followers = Sets.newHashSet(); - - public SlotBuilder(int slotId) { - this.slotId = slotId; - } - - public SlotBuilder leader(String leader) { - if (this.leader != null) { - throw new IllegalStateException(String.format("leader is not null(%s), but try to set (%s)", - this.leader, leader)); - } - this.leader = leader; - return this; - } - - public SlotBuilder followers(String ...follower) { - followers.addAll(Arrays.asList(follower)); - return this; - } + public SlotBuilder leader(String leader) { + if (this.leader != null) { + throw new IllegalStateException( + String.format("leader is not null(%s), but try to set (%s)", this.leader, leader)); + } + this.leader = leader; + return this; + } - public SlotBuilder follower(String foll) { - followers.add(foll); - return this; - } + public SlotBuilder followers(String... follower) { + followers.addAll(Arrays.asList(follower)); + return this; + } - public SlotBuilder leaderEpoch(long leaderEpoch) { - this.leaderEpoch = leaderEpoch; - return this; - } + public SlotBuilder follower(String foll) { + followers.add(foll); + return this; + } - public Slot build() { - return new Slot(slotId, leader, leaderEpoch, followers); - } + public SlotBuilder leaderEpoch(long leaderEpoch) { + this.leaderEpoch = leaderEpoch; + return this; } + public Slot build() { + return new Slot(slotId, leader, leaderEpoch, followers); + } + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/Crc32cSlotFunction.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/Crc32cSlotFunction.java index c98f309c9..9c5ed4d46 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/Crc32cSlotFunction.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/Crc32cSlotFunction.java @@ -19,47 +19,45 @@ import com.alipay.sofa.registry.common.model.slot.SlotConfig; import com.google.common.hash.HashFunction; import com.google.common.hash.Hashing; - import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public class Crc32cSlotFunction implements SlotFunction { - public static final Crc32cSlotFunction INSTANCE = new Crc32cSlotFunction(); - private final int slotMask; - private final HashFunction crc32c = Hashing.crc32c(); - - public Crc32cSlotFunction() { - this(SlotConfig.SLOT_NUM); - } - - public Crc32cSlotFunction(int slotNums) { - this.slotMask = slotNums - 1; - } - - @Override - public String name() { - return "crc32c"; - } - - @Override - public int maxSlots() { - return slotMask + 1; - } - - @Override - public int slotOf(Object o) { - return getCrc32Code(o) & slotMask; - } - - private int getCrc32Code(Object o) { - byte[] bytes = o.toString().getBytes(UTF8); - return Math.abs(crc32c.hashBytes(bytes).asInt()); - } - - private static final Charset UTF8 = StandardCharsets.UTF_8; + public static final Crc32cSlotFunction INSTANCE = new Crc32cSlotFunction(); + private final int slotMask; + private final HashFunction crc32c = Hashing.crc32c(); + + public Crc32cSlotFunction() { + this(SlotConfig.SLOT_NUM); + } + + public Crc32cSlotFunction(int slotNums) { + this.slotMask = slotNums - 1; + } + + @Override + public String name() { + return "crc32c"; + } + + @Override + public int maxSlots() { + return slotMask + 1; + } + + @Override + public int slotOf(Object o) { + return getCrc32Code(o) & slotMask; + } + + private int getCrc32Code(Object o) { + byte[] bytes = o.toString().getBytes(UTF8); + return Math.abs(crc32c.hashBytes(bytes).asInt()); + } + + private static final Charset UTF8 = StandardCharsets.UTF_8; } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/HashFunction.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/HashFunction.java index 5063de1cb..04adaec5d 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/HashFunction.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/HashFunction.java @@ -18,18 +18,17 @@ /** * Hash Function - * + * * @author zhuoyu.sjw * @version $Id: HashFunction.java, v 0.1 2016-11-01 15:19 zhuoyu.sjw Exp $$ */ public interface HashFunction { - /** - * return object's int hashCode - * - * @param o - * object - * @return int hashCode - */ - int hash(Object o); + /** + * return object's int hashCode + * + * @param o object + * @return int hashCode + */ + int hash(Object o); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/MD5HashFunction.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/MD5HashFunction.java index 7bb26eb45..12350fcfa 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/MD5HashFunction.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/MD5HashFunction.java @@ -17,44 +17,36 @@ package com.alipay.sofa.registry.common.model.slot.func; import com.alipay.sofa.registry.util.MessageDigests; - import java.nio.charset.Charset; /** * MD5 hash function + * * @author zhuoyu.sjw * @version $Id: MD5HashFunction.java, v 0.1 2016-11-01 15:19 zhuoyu.sjw Exp $$ */ public class MD5HashFunction implements HashFunction { - /** - * Default charset of UTF-8 - */ - private static final Charset UTF8 = Charset.forName("UTF-8"); - - /** - * Instantiates a new MD5 hash function. - */ - public MD5HashFunction() { - } + /** Default charset of UTF-8 */ + private static final Charset UTF8 = Charset.forName("UTF-8"); - /** - * @see HashFunction#hash(Object) - */ - @Override - public int hash(Object s) { - byte[] hash = MessageDigests.md5().digest(s.toString().getBytes(UTF8)); + /** Instantiates a new MD5 hash function. */ + public MD5HashFunction() {} - // HACK just take the first 4 digits and make it an integer. - // apparently this is what other algorithms use to turn it into an int - // value. + /** @see HashFunction#hash(Object) */ + @Override + public int hash(Object s) { + byte[] hash = MessageDigests.md5().digest(s.toString().getBytes(UTF8)); - int h0 = (hash[0] & 0xFF); - int h1 = (hash[1] & 0xFF) << 8; - int h2 = (hash[2] & 0xFF) << 16; - int h3 = (hash[3] & 0xFF) << 24; + // HACK just take the first 4 digits and make it an integer. + // apparently this is what other algorithms use to turn it into an int + // value. - return h0 + h1 + h2 + h3; - } + int h0 = (hash[0] & 0xFF); + int h1 = (hash[1] & 0xFF) << 8; + int h2 = (hash[2] & 0xFF) << 16; + int h3 = (hash[3] & 0xFF) << 24; + return h0 + h1 + h2 + h3; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/MD5SlotFunction.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/MD5SlotFunction.java index acd0a3e8c..ca8e899f2 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/MD5SlotFunction.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/MD5SlotFunction.java @@ -19,34 +19,33 @@ import com.alipay.sofa.registry.common.model.slot.SlotConfig; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-02 15:43 yuzhi.lyz Exp $ */ public final class MD5SlotFunction implements SlotFunction { - public static final MD5SlotFunction INSTANCE = new MD5SlotFunction(); + public static final MD5SlotFunction INSTANCE = new MD5SlotFunction(); - private final int maxSlots; - private final MD5HashFunction md5HashFunction = new MD5HashFunction(); + private final int maxSlots; + private final MD5HashFunction md5HashFunction = new MD5HashFunction(); - private MD5SlotFunction() { - this.maxSlots = SlotConfig.SLOT_NUM; - } + private MD5SlotFunction() { + this.maxSlots = SlotConfig.SLOT_NUM; + } - @Override - public String name() { - return "md5"; - } + @Override + public String name() { + return "md5"; + } - @Override - public int maxSlots() { - return maxSlots; - } + @Override + public int maxSlots() { + return maxSlots; + } - @Override - public int slotOf(Object o) { - // make sure >=0 - final int hash = Math.abs(md5HashFunction.hash(o)); - return hash % maxSlots; - } + @Override + public int slotOf(Object o) { + // make sure >=0 + final int hash = Math.abs(md5HashFunction.hash(o)); + return hash % maxSlots; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/SlotFunction.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/SlotFunction.java index 41aabb290..ae16c926c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/SlotFunction.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/SlotFunction.java @@ -17,14 +17,13 @@ package com.alipay.sofa.registry.common.model.slot.func; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-02 15:35 yuzhi.lyz Exp $ */ public interface SlotFunction { - String name(); + String name(); - int maxSlots(); + int maxSlots(); - int slotOf(Object o); + int slotOf(Object o); } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/SlotFunctionRegistry.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/SlotFunctionRegistry.java index a1228b5f2..8c8d3078c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/SlotFunctionRegistry.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/slot/func/SlotFunctionRegistry.java @@ -18,28 +18,25 @@ import com.alipay.sofa.registry.common.model.slot.SlotConfig; import com.google.common.collect.Maps; - import java.util.Map; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-28 12:24 yuzhi.lyz Exp $ */ public final class SlotFunctionRegistry { - private static final Map funcs = Maps.newConcurrentMap(); - - static { - register(Crc32cSlotFunction.INSTANCE); - register(MD5SlotFunction.INSTANCE); - } + private static final Map funcs = Maps.newConcurrentMap(); - public static void register(SlotFunction func) { - funcs.put(func.name(), func); - } + static { + register(Crc32cSlotFunction.INSTANCE); + register(MD5SlotFunction.INSTANCE); + } - public static SlotFunction getFunc() { - return funcs.get(SlotConfig.FUNC); - } + public static void register(SlotFunction func) { + funcs.put(func.name(), func); + } + public static SlotFunction getFunc() { + return funcs.get(SlotConfig.FUNC); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/AppRevision.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/AppRevision.java index 045ed5976..c601cb3f7 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/AppRevision.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/AppRevision.java @@ -25,150 +25,165 @@ public class AppRevision implements Serializable { - private String dataCenter; - - private String revision; - - private String appName; - - private String clientVersion; - - private Map> baseParams = Maps.newHashMap(); - - private Map interfaceMap = Maps.newHashMap(); - - private Date lastHeartbeat; - - public AppRevision() { - } - - public AppRevision(String dataCenter, String revision, Date lastHeartbeat) { - this.dataCenter = dataCenter; - this.revision = revision; - this.lastHeartbeat = lastHeartbeat; - } - - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } - - /** - * Setter method for property dataCenter. - * - * @param dataCenter value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } - - /** - * Getter method for property revision. - * - * @return property value of revision - */ - public String getRevision() { - return revision; - } - - /** - * Setter method for property revision. - * - * @param revision value to be assigned to property revision - */ - public void setRevision(String revision) { - this.revision = revision; - } - - /** - * Getter method for property appName. - * - * @return property value of appName - */ - public String getAppName() { - return appName; - } - - /** - * Setter method for property appName. - * - * @param appName value to be assigned to property appName - */ - public void setAppName(String appName) { - this.appName = appName; - } - - /** - * Getter method for property baseParams. - * - * @return property value of baseParams - */ - public Map> getBaseParams() { - return baseParams; - } - - /** - * Setter method for property baseParams. - * - * @param baseParams value to be assigned to property baseParams - */ - public void setBaseParams(Map> baseParams) { - this.baseParams = baseParams; - } - - public Map getInterfaceMap() { - return interfaceMap; - } - - public void setInterfaceMap(Map interfaceMap) { - this.interfaceMap = interfaceMap; - } - - /** - * Getter method for property lastHeartbeat. - * - * @return property value of lastHeartbeat - */ - public Date getLastHeartbeat() { - return lastHeartbeat; - } - - /** - * Setter method for property lastHeartbeat. - * - * @param lastHeartbeat value to be assigned to property lastHeartbeat - */ - public void setLastHeartbeat(Date lastHeartbeat) { - this.lastHeartbeat = lastHeartbeat; - } - - /** - * Getter method for property clientVersion. - * - * @return property value of clientVersion - */ - public String getClientVersion() { - return clientVersion; - } - - /** - * Setter method for property clientVersion. - * - * @param clientVersion value to be assigned to property clientVersion - */ - public void setClientVersion(String clientVersion) { - this.clientVersion = clientVersion; - } - - @Override - public String toString() { - return "AppRevision{" + "dataCenter='" + dataCenter + '\'' + ", revision='" + revision - + '\'' + ", appName='" + appName + '\'' + ", clientVersion='" + clientVersion + '\'' - + ", baseParams=" + baseParams + ", interfaceMap=" + interfaceMap - + ", lastHeartbeat=" + lastHeartbeat + '}'; - } + private String dataCenter; + + private String revision; + + private String appName; + + private String clientVersion; + + private Map> baseParams = Maps.newHashMap(); + + private Map interfaceMap = Maps.newHashMap(); + + private Date lastHeartbeat; + + public AppRevision() {} + + public AppRevision(String dataCenter, String revision, Date lastHeartbeat) { + this.dataCenter = dataCenter; + this.revision = revision; + this.lastHeartbeat = lastHeartbeat; + } + + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * Setter method for property dataCenter. + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } + + /** + * Getter method for property revision. + * + * @return property value of revision + */ + public String getRevision() { + return revision; + } + + /** + * Setter method for property revision. + * + * @param revision value to be assigned to property revision + */ + public void setRevision(String revision) { + this.revision = revision; + } + + /** + * Getter method for property appName. + * + * @return property value of appName + */ + public String getAppName() { + return appName; + } + + /** + * Setter method for property appName. + * + * @param appName value to be assigned to property appName + */ + public void setAppName(String appName) { + this.appName = appName; + } + + /** + * Getter method for property baseParams. + * + * @return property value of baseParams + */ + public Map> getBaseParams() { + return baseParams; + } + + /** + * Setter method for property baseParams. + * + * @param baseParams value to be assigned to property baseParams + */ + public void setBaseParams(Map> baseParams) { + this.baseParams = baseParams; + } + + public Map getInterfaceMap() { + return interfaceMap; + } + + public void setInterfaceMap(Map interfaceMap) { + this.interfaceMap = interfaceMap; + } + + /** + * Getter method for property lastHeartbeat. + * + * @return property value of lastHeartbeat + */ + public Date getLastHeartbeat() { + return lastHeartbeat; + } + + /** + * Setter method for property lastHeartbeat. + * + * @param lastHeartbeat value to be assigned to property lastHeartbeat + */ + public void setLastHeartbeat(Date lastHeartbeat) { + this.lastHeartbeat = lastHeartbeat; + } + + /** + * Getter method for property clientVersion. + * + * @return property value of clientVersion + */ + public String getClientVersion() { + return clientVersion; + } + + /** + * Setter method for property clientVersion. + * + * @param clientVersion value to be assigned to property clientVersion + */ + public void setClientVersion(String clientVersion) { + this.clientVersion = clientVersion; + } + + @Override + public String toString() { + return "AppRevision{" + + "dataCenter='" + + dataCenter + + '\'' + + ", revision='" + + revision + + '\'' + + ", appName='" + + appName + + '\'' + + ", clientVersion='" + + clientVersion + + '\'' + + ", baseParams=" + + baseParams + + ", interfaceMap=" + + interfaceMap + + ", lastHeartbeat=" + + lastHeartbeat + + '}'; + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/BaseInfo.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/BaseInfo.java index d1d364fd9..c9d5e63a5 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/BaseInfo.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/BaseInfo.java @@ -16,409 +16,406 @@ */ package com.alipay.sofa.registry.common.model.store; +import com.alipay.sofa.registry.common.model.ConnectId; +import com.alipay.sofa.registry.common.model.RegisterVersion; +import com.fasterxml.jackson.annotation.JsonIgnore; import java.io.Serializable; import java.util.Collections; import java.util.HashMap; import java.util.Map; -import java.util.Set; - -import com.alipay.sofa.registry.common.model.ConnectId; -import com.alipay.sofa.registry.common.model.RegisterVersion; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.google.common.collect.Sets; /** - * * @author shangyu.wh * @version $Id: BaseInfo.java, v 0.1 2017-11-30 16:31 shangyu.wh Exp $ */ public abstract class BaseInfo implements Serializable, StoreData { - private static final long serialVersionUID = -6263388188316303789L; - - private String dataInfoId; - - private String dataId; - - private String clientId; - - private String instanceId; - - private String cell; - - private String appName; - - private String processId; - - private String registerId; - - private Long version; - - private URL sourceAddress; - - private URL targetAddress; - - private ClientVersion clientVersion; - - private String group; - - private long registerTimestamp; + private static final long serialVersionUID = -6263388188316303789L; - private long clientRegisterTimestamp; + private String dataInfoId; - private Map attributes; + private String dataId; - /** - * ClientVersion Enum - */ - public enum ClientVersion { - /** */ - ProtocolPackage("1.x"), - /** */ - NProtocolpackage("2.x"), - /** */ - MProtocolpackage("3.x"), - /** */ - StoreData("4.x"); - - private String version; - - /** - * Set version val - * @param version - */ - ClientVersion(String version) { - this.version = version; - } - } + private String clientId; - /** - * Getter method for property cell. - * - * @return property value of cell - */ - public String getCell() { - return cell; - } + private String instanceId; - /** - * Setter method for property cell. - * - * @param cell value to be assigned to property cell - */ - public void setCell(String cell) { - this.cell = WordCache.getWordCache(cell); - } + private String cell; - /** - * Getter method for property appName. - * - * @return property value of appName - */ - public String getAppName() { - return appName; - } + private String appName; - /** - * Setter method for property appName. - * - * @param appName value to be assigned to property appName - */ - public void setAppName(String appName) { - this.appName = WordCache.getWordCache(appName); - } + private String processId; - /** - * Getter method for property processId. - * - * @return property value of processId - */ - public String getProcessId() { - return processId; - } + private String registerId; - /** - * Setter method for property processId. - * - * @param processId value to be assigned to property processId - */ - public void setProcessId(String processId) { - this.processId = WordCache.getWordCache(processId); - } + private Long version; - /** - * Getter method for property version. - * - * @return property value of version - */ - public Long getVersion() { - return version; - } + private URL sourceAddress; - /** - * Setter method for property version. - * - * @param version value to be assigned to property version - */ - public void setVersion(Long version) { - this.version = version; - } + private URL targetAddress; - /** - * Getter method for property sourceAddress. - * - * @return property value of sourceAddress - */ - public URL getSourceAddress() { - return sourceAddress; - } + private ClientVersion clientVersion; - /** - * Setter method for property sourceAddress. - * - * @param sourceAddress value to be assigned to property sourceAddress - */ - public void setSourceAddress(URL sourceAddress) { - this.sourceAddress = sourceAddress; - } + private String group; - /** - * Getter method for property targetAddress. - * - * @return property value of targetAddress - */ - public URL getTargetAddress() { - return targetAddress; - } + private long registerTimestamp; - /** - * Setter method for property targetAddress. - * - * @param targetAddress value to be assigned to property targetAddress - */ - public void setTargetAddress(URL targetAddress) { - this.targetAddress = targetAddress; - } + private long clientRegisterTimestamp; - /** - * Getter method for property attributes. - * - * @return property value of attributes - */ - public synchronized Map getAttributes() { - if (attributes == null) { - return Collections.EMPTY_MAP; - } - return new HashMap<>(attributes); - } + private Map attributes; - /** - * Setter method for property attributes. - * - * @param attributes value to be assigned to property attributes - */ - public synchronized void setAttributes(Map attributes) { - if (attributes == null || attributes.isEmpty()) { - this.attributes = null; - } else { - this.attributes = new HashMap<>(attributes); - } - } + /** ClientVersion Enum */ + public enum ClientVersion { + /** */ + ProtocolPackage("1.x"), + /** */ + NProtocolpackage("2.x"), + /** */ + MProtocolpackage("3.x"), + /** */ + StoreData("4.x"); - /** - * Getter method for property dataInfoId. - * - * @return property value of dataInfoId - */ - public String getDataInfoId() { - return dataInfoId; - } + private String version; /** - * Setter method for property dataInfoId. + * Set version val * - * @param dataInfoId value to be assigned to property dataInfoId - */ - public void setDataInfoId(String dataInfoId) { - this.dataInfoId = WordCache.getWordCache(dataInfoId); - } - - @Override - @JsonIgnore - public String getId() { - return registerId; - } - - /** - * Getter method for property registerId. - * - * @return property value of registerId - */ - public String getRegisterId() { - return registerId; - } - - /** - * Setter method for property registerId. - * - * @param registerId value to be assigned to property registerId - */ - public void setRegisterId(String registerId) { - this.registerId = registerId; - } - - /** - * Getter method for property dataId. - * - * @return property value of dataId - */ - public String getDataId() { - return dataId; - } - - /** - * Setter method for property dataId. - * - * @param dataId value to be assigned to property dataId - */ - public void setDataId(String dataId) { - this.dataId = WordCache.getWordCache(dataId); - } - - /** - * Getter method for property clientId. - * - * @return property value of clientId - */ - public String getClientId() { - return clientId; - } - - /** - * Setter method for property clientId. - * - * @param clientId value to be assigned to property clientId - */ - public void setClientId(String clientId) { - this.clientId = WordCache.getWordCache(clientId); - } - - /** - * Getter method for property instanceId. - * - * @return property value of instanceId - */ - public String getInstanceId() { - return instanceId; - } - - /** - * Setter method for property instanceId. - * - * @param instanceId value to be assigned to property instanceId - */ - public void setInstanceId(String instanceId) { - this.instanceId = WordCache.getWordCache(instanceId); - } - - /** - * Getter method for property group. - * - * @return property value of group - */ - public String getGroup() { - return group; - } - - /** - * Setter method for property group. - * - * @param group value to be assigned to property group - */ - public void setGroup(String group) { - this.group = WordCache.getWordCache(group); - } - - /** - * Getter method for property registerTimestamp. - * - * @return property value of registerTimestamp - */ - public long getRegisterTimestamp() { - return registerTimestamp; - } - - /** - * Setter method for property registerTimestamp. - * - * @param registerTimestamp value to be assigned to property registerTimestamp - */ - public void setRegisterTimestamp(long registerTimestamp) { - this.registerTimestamp = registerTimestamp; - } - - /** - * Getter method for property clientVersion. - * - * @return property value of clientVersion - */ - public ClientVersion getClientVersion() { - return clientVersion; - } - - /** - * Setter method for property clientVersion. - * - * @param clientVersion value to be assigned to property clientVersion - */ - public void setClientVersion(ClientVersion clientVersion) { - this.clientVersion = clientVersion; - } - - public long getClientRegisterTimestamp() { - return clientRegisterTimestamp; - } - - /** - * Setter method for property clientRegisterTimestamp. - * - * @param clientRegisterTimestamp value to be assigned to property clientRegisterTimestamp - */ - public void setClientRegisterTimestamp(long clientRegisterTimestamp) { - this.clientRegisterTimestamp = clientRegisterTimestamp; - } - - protected String getOtherInfo() { - return ""; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder(getDataType().toString()); - sb.append("{dataInfoId='").append(dataInfoId).append('\''); - sb.append(", clientId='").append(clientId).append('\''); - sb.append(", cell='").append(cell).append('\''); - sb.append(", appName='").append(appName).append('\''); - sb.append(", processId='").append(processId).append('\''); - sb.append(", registerId='").append(registerId).append('\''); - sb.append(", version=").append(version); - sb.append(", sourceAddress=").append(sourceAddress); - sb.append(", clientVersion=").append(clientVersion); - sb.append(", registerTimestamp=").append(registerTimestamp); - sb.append(", clientRegisterTimestamp=").append(clientRegisterTimestamp); - sb.append(", otherInfo=").append(getOtherInfo()); - sb.append(", attributes=").append(attributes); - sb.append('}'); - return sb.toString(); - } - - public ConnectId connectId() { - return new ConnectId(getSourceAddress().getIpAddress(), getSourceAddress().getPort(), - getTargetAddress().getIpAddress(), getTargetAddress().getPort()); - } - - public RegisterVersion registerVersion() { - return RegisterVersion.of(getVersion(), getRegisterTimestamp()); - } - -} \ No newline at end of file + * @param version + */ + ClientVersion(String version) { + this.version = version; + } + } + + /** + * Getter method for property cell. + * + * @return property value of cell + */ + public String getCell() { + return cell; + } + + /** + * Setter method for property cell. + * + * @param cell value to be assigned to property cell + */ + public void setCell(String cell) { + this.cell = WordCache.getWordCache(cell); + } + + /** + * Getter method for property appName. + * + * @return property value of appName + */ + public String getAppName() { + return appName; + } + + /** + * Setter method for property appName. + * + * @param appName value to be assigned to property appName + */ + public void setAppName(String appName) { + this.appName = WordCache.getWordCache(appName); + } + + /** + * Getter method for property processId. + * + * @return property value of processId + */ + public String getProcessId() { + return processId; + } + + /** + * Setter method for property processId. + * + * @param processId value to be assigned to property processId + */ + public void setProcessId(String processId) { + this.processId = WordCache.getWordCache(processId); + } + + /** + * Getter method for property version. + * + * @return property value of version + */ + public Long getVersion() { + return version; + } + + /** + * Setter method for property version. + * + * @param version value to be assigned to property version + */ + public void setVersion(Long version) { + this.version = version; + } + + /** + * Getter method for property sourceAddress. + * + * @return property value of sourceAddress + */ + public URL getSourceAddress() { + return sourceAddress; + } + + /** + * Setter method for property sourceAddress. + * + * @param sourceAddress value to be assigned to property sourceAddress + */ + public void setSourceAddress(URL sourceAddress) { + this.sourceAddress = sourceAddress; + } + + /** + * Getter method for property targetAddress. + * + * @return property value of targetAddress + */ + public URL getTargetAddress() { + return targetAddress; + } + + /** + * Setter method for property targetAddress. + * + * @param targetAddress value to be assigned to property targetAddress + */ + public void setTargetAddress(URL targetAddress) { + this.targetAddress = targetAddress; + } + + /** + * Getter method for property attributes. + * + * @return property value of attributes + */ + public synchronized Map getAttributes() { + if (attributes == null) { + return Collections.EMPTY_MAP; + } + return new HashMap<>(attributes); + } + + /** + * Setter method for property attributes. + * + * @param attributes value to be assigned to property attributes + */ + public synchronized void setAttributes(Map attributes) { + if (attributes == null || attributes.isEmpty()) { + this.attributes = null; + } else { + this.attributes = new HashMap<>(attributes); + } + } + + /** + * Getter method for property dataInfoId. + * + * @return property value of dataInfoId + */ + public String getDataInfoId() { + return dataInfoId; + } + + /** + * Setter method for property dataInfoId. + * + * @param dataInfoId value to be assigned to property dataInfoId + */ + public void setDataInfoId(String dataInfoId) { + this.dataInfoId = WordCache.getWordCache(dataInfoId); + } + + @Override + @JsonIgnore + public String getId() { + return registerId; + } + + /** + * Getter method for property registerId. + * + * @return property value of registerId + */ + public String getRegisterId() { + return registerId; + } + + /** + * Setter method for property registerId. + * + * @param registerId value to be assigned to property registerId + */ + public void setRegisterId(String registerId) { + this.registerId = registerId; + } + + /** + * Getter method for property dataId. + * + * @return property value of dataId + */ + public String getDataId() { + return dataId; + } + + /** + * Setter method for property dataId. + * + * @param dataId value to be assigned to property dataId + */ + public void setDataId(String dataId) { + this.dataId = WordCache.getWordCache(dataId); + } + + /** + * Getter method for property clientId. + * + * @return property value of clientId + */ + public String getClientId() { + return clientId; + } + + /** + * Setter method for property clientId. + * + * @param clientId value to be assigned to property clientId + */ + public void setClientId(String clientId) { + this.clientId = WordCache.getWordCache(clientId); + } + + /** + * Getter method for property instanceId. + * + * @return property value of instanceId + */ + public String getInstanceId() { + return instanceId; + } + + /** + * Setter method for property instanceId. + * + * @param instanceId value to be assigned to property instanceId + */ + public void setInstanceId(String instanceId) { + this.instanceId = WordCache.getWordCache(instanceId); + } + + /** + * Getter method for property group. + * + * @return property value of group + */ + public String getGroup() { + return group; + } + + /** + * Setter method for property group. + * + * @param group value to be assigned to property group + */ + public void setGroup(String group) { + this.group = WordCache.getWordCache(group); + } + + /** + * Getter method for property registerTimestamp. + * + * @return property value of registerTimestamp + */ + public long getRegisterTimestamp() { + return registerTimestamp; + } + + /** + * Setter method for property registerTimestamp. + * + * @param registerTimestamp value to be assigned to property registerTimestamp + */ + public void setRegisterTimestamp(long registerTimestamp) { + this.registerTimestamp = registerTimestamp; + } + + /** + * Getter method for property clientVersion. + * + * @return property value of clientVersion + */ + public ClientVersion getClientVersion() { + return clientVersion; + } + + /** + * Setter method for property clientVersion. + * + * @param clientVersion value to be assigned to property clientVersion + */ + public void setClientVersion(ClientVersion clientVersion) { + this.clientVersion = clientVersion; + } + + public long getClientRegisterTimestamp() { + return clientRegisterTimestamp; + } + + /** + * Setter method for property clientRegisterTimestamp. + * + * @param clientRegisterTimestamp value to be assigned to property clientRegisterTimestamp + */ + public void setClientRegisterTimestamp(long clientRegisterTimestamp) { + this.clientRegisterTimestamp = clientRegisterTimestamp; + } + + protected String getOtherInfo() { + return ""; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder(getDataType().toString()); + sb.append("{dataInfoId='").append(dataInfoId).append('\''); + sb.append(", clientId='").append(clientId).append('\''); + sb.append(", cell='").append(cell).append('\''); + sb.append(", appName='").append(appName).append('\''); + sb.append(", processId='").append(processId).append('\''); + sb.append(", registerId='").append(registerId).append('\''); + sb.append(", version=").append(version); + sb.append(", sourceAddress=").append(sourceAddress); + sb.append(", clientVersion=").append(clientVersion); + sb.append(", registerTimestamp=").append(registerTimestamp); + sb.append(", clientRegisterTimestamp=").append(clientRegisterTimestamp); + sb.append(", otherInfo=").append(getOtherInfo()); + sb.append(", attributes=").append(attributes); + sb.append('}'); + return sb.toString(); + } + + public ConnectId connectId() { + return new ConnectId( + getSourceAddress().getIpAddress(), + getSourceAddress().getPort(), + getTargetAddress().getIpAddress(), + getTargetAddress().getPort()); + } + + public RegisterVersion registerVersion() { + return RegisterVersion.of(getVersion(), getRegisterTimestamp()); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/DataInfo.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/DataInfo.java index 59f446947..de54e1a52 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/DataInfo.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/DataInfo.java @@ -18,172 +18,166 @@ import com.alipay.sofa.registry.common.model.constants.ValueConstants; import com.alipay.sofa.registry.util.ParaCheckUtil; - import java.io.Serializable; import java.util.Objects; /** - * * @author shangyu.wh * @version $Id: DataInfo.java, v 0.1 2017-11-30 16:09 shangyu.wh Exp $ */ public class DataInfo implements Serializable { - private String dataInfoId; - - private String instanceId; - - private String dataId; - - private String group; - - /** symbol : */ - public static final String DELIMITER = "#@#"; - - public static final int DATAID_LENTH = 3; - - /** - * @param instanceId - * @param dataId - * @param group - */ - public DataInfo(String instanceId, String dataId, String group) { - this.instanceId = instanceId; - this.dataId = dataId; - this.group = group; - this.dataInfoId = toDataInfoId(dataId, instanceId, group); - } - - /** - * @param dataId - * @param instanceId - * @param group - * @return - */ - public static String toDataInfoId(String dataId, String instanceId, String group) { - StringBuilder buf = new StringBuilder(); - if (dataId == null || dataId.isEmpty()) { - throw new IllegalArgumentException("error dataId:" + dataId); - } - if (ValueConstants.DISABLE_DATA_ID_CASE_SENSITIVE) { - buf.append(dataId.toUpperCase()); - } else { - buf.append(dataId); - } - - if (instanceId == null || instanceId.isEmpty()) { - throw new IllegalArgumentException("error instanceId:" + instanceId); - } - buf.append(DELIMITER).append(instanceId); - - if (group == null || group.isEmpty()) { - throw new IllegalArgumentException("error group:" + group); - } - buf.append(DELIMITER).append(group); - - return buf.toString(); - } - - /** - * - * @param dataInfoId - * @return - */ - public static DataInfo valueOf(String dataInfoId) { - ParaCheckUtil.checkNotBlank(dataInfoId, "dataInfoId"); - String[] str = dataInfoId.split(DELIMITER); - if (str.length != DATAID_LENTH) { - throw new IllegalArgumentException("dataInfoId input error!"); - } - - return new DataInfo(str[1], str[0], str[2]); - } - - /** - * Getter method for property dataInfoId. - * - * @return property value of dataInfoId - */ - public String getDataInfoId() { - return dataInfoId; - } - - /** - * Setter method for property dataInfoId. - * - * @param dataInfoId value to be assigned to property dataInfoId - */ - public void setDataInfoId(String dataInfoId) { - this.dataInfoId = dataInfoId; + private String dataInfoId; + + private String instanceId; + + private String dataId; + + private String group; + + /** symbol : */ + public static final String DELIMITER = "#@#"; + + public static final int DATAID_LENTH = 3; + + /** + * @param instanceId + * @param dataId + * @param group + */ + public DataInfo(String instanceId, String dataId, String group) { + this.instanceId = instanceId; + this.dataId = dataId; + this.group = group; + this.dataInfoId = toDataInfoId(dataId, instanceId, group); + } + + /** + * @param dataId + * @param instanceId + * @param group + * @return + */ + public static String toDataInfoId(String dataId, String instanceId, String group) { + StringBuilder buf = new StringBuilder(); + if (dataId == null || dataId.isEmpty()) { + throw new IllegalArgumentException("error dataId:" + dataId); } - - /** - * Getter method for property instanceId. - * - * @return property value of instanceId - */ - public String getInstanceId() { - return instanceId; + if (ValueConstants.DISABLE_DATA_ID_CASE_SENSITIVE) { + buf.append(dataId.toUpperCase()); + } else { + buf.append(dataId); } - /** - * Setter method for property instanceId. - * - * @param instanceId value to be assigned to property instanceId - */ - public void setInstanceId(String instanceId) { - this.instanceId = instanceId; + if (instanceId == null || instanceId.isEmpty()) { + throw new IllegalArgumentException("error instanceId:" + instanceId); } + buf.append(DELIMITER).append(instanceId); - /** - * Getter method for property dataId. - * - * @return property value of dataId - */ - public String getDataId() { - return dataId; + if (group == null || group.isEmpty()) { + throw new IllegalArgumentException("error group:" + group); } - - /** - * Setter method for property dataId. - * - * @param dataId value to be assigned to property dataId - */ - public void setDataId(String dataId) { - this.dataId = dataId; - } - - /** - * Getter method for property dataType. - * - * @return property value of dataType - */ - public String getGroup() { - return group; - } - - /** - * Setter method for property dataType. - * - * @param group value to be assigned to property dataType - */ - public void setGroup(String group) { - this.group = group; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - DataInfo dataInfo = (DataInfo) o; - return dataInfoId.equals(dataInfo.dataInfoId); - } - - @Override - public int hashCode() { - return Objects.hash(dataInfoId); + buf.append(DELIMITER).append(group); + + return buf.toString(); + } + + /** + * @param dataInfoId + * @return + */ + public static DataInfo valueOf(String dataInfoId) { + ParaCheckUtil.checkNotBlank(dataInfoId, "dataInfoId"); + String[] str = dataInfoId.split(DELIMITER); + if (str.length != DATAID_LENTH) { + throw new IllegalArgumentException("dataInfoId input error!"); } -} \ No newline at end of file + return new DataInfo(str[1], str[0], str[2]); + } + + /** + * Getter method for property dataInfoId. + * + * @return property value of dataInfoId + */ + public String getDataInfoId() { + return dataInfoId; + } + + /** + * Setter method for property dataInfoId. + * + * @param dataInfoId value to be assigned to property dataInfoId + */ + public void setDataInfoId(String dataInfoId) { + this.dataInfoId = dataInfoId; + } + + /** + * Getter method for property instanceId. + * + * @return property value of instanceId + */ + public String getInstanceId() { + return instanceId; + } + + /** + * Setter method for property instanceId. + * + * @param instanceId value to be assigned to property instanceId + */ + public void setInstanceId(String instanceId) { + this.instanceId = instanceId; + } + + /** + * Getter method for property dataId. + * + * @return property value of dataId + */ + public String getDataId() { + return dataId; + } + + /** + * Setter method for property dataId. + * + * @param dataId value to be assigned to property dataId + */ + public void setDataId(String dataId) { + this.dataId = dataId; + } + + /** + * Getter method for property dataType. + * + * @return property value of dataType + */ + public String getGroup() { + return group; + } + + /** + * Setter method for property dataType. + * + * @param group value to be assigned to property dataType + */ + public void setGroup(String group) { + this.group = group; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DataInfo dataInfo = (DataInfo) o; + return dataInfoId.equals(dataInfo.dataInfoId); + } + + @Override + public int hashCode() { + return Objects.hash(dataInfoId); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/ProcessIdCache.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/ProcessIdCache.java index 90dc5383e..4a91cc2ea 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/ProcessIdCache.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/ProcessIdCache.java @@ -21,15 +21,14 @@ import com.google.common.collect.Interners; public final class ProcessIdCache { - private static final Interner interners = Interners.newWeakInterner(); + private static final Interner interners = Interners.newWeakInterner(); - private ProcessIdCache() { - } + private ProcessIdCache() {} - public static ProcessId cache(ProcessId pid) { - if (pid == null) { - return null; - } - return interners.intern(pid); + public static ProcessId cache(ProcessId pid) { + if (pid == null) { + return null; } + return interners.intern(pid); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Publisher.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Publisher.java index a9d4f4197..7ea77aa05 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Publisher.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Publisher.java @@ -16,116 +16,113 @@ */ package com.alipay.sofa.registry.common.model.store; -import java.util.List; - import com.alipay.sofa.registry.common.model.*; -import com.fasterxml.jackson.annotation.JsonIgnore; - import com.alipay.sofa.registry.common.model.PublishType; import com.alipay.sofa.registry.common.model.ServerDataBox; +import com.fasterxml.jackson.annotation.JsonIgnore; +import java.util.List; /** - * * @author shangyu.wh * @version $Id: Publisher.java, v 0.1 2017-11-30 16:04 shangyu.wh Exp $ */ public class Publisher extends BaseInfo { - /** UID */ - private static final long serialVersionUID = 5859214992132895021L; - - private List dataList; - - private PublishType publishType = PublishType.NORMAL; - - @JsonIgnore - private ProcessId sessionProcessId; - - public Publisher() { - } - - /** - * Getter method for property sessionProcessId. - * @return property value of sessionProcessId - */ - public ProcessId getSessionProcessId() { - return sessionProcessId; - } - - /** - * Setter method for property sessionProcessId. - * @param sessionProcessId value to be assigned to property sessionProcessId - */ - public void setSessionProcessId(ProcessId sessionProcessId) { - this.sessionProcessId = sessionProcessId; + /** UID */ + private static final long serialVersionUID = 5859214992132895021L; + + private List dataList; + + private PublishType publishType = PublishType.NORMAL; + + @JsonIgnore private ProcessId sessionProcessId; + + public Publisher() {} + + /** + * Getter method for property sessionProcessId. + * + * @return property value of sessionProcessId + */ + public ProcessId getSessionProcessId() { + return sessionProcessId; + } + + /** + * Setter method for property sessionProcessId. + * + * @param sessionProcessId value to be assigned to property sessionProcessId + */ + public void setSessionProcessId(ProcessId sessionProcessId) { + this.sessionProcessId = sessionProcessId; + } + + /** + * Getter method for property dataList. + * + * @return property value of dataList + */ + public List getDataList() { + return dataList; + } + + /** + * Setter method for property dataList. + * + * @param dataList value to be assigned to property dataList + */ + public void setDataList(List dataList) { + this.dataList = dataList; + } + + public PublishType getPublishType() { + return publishType; + } + + /** + * Setter method for property publishType. + * + * @param publishType value to be assigned to property publishType + */ + public void setPublishType(PublishType publishType) { + this.publishType = publishType; + } + + @Override + @JsonIgnore + public DataType getDataType() { + return DataType.PUBLISHER; + } + + @Override + protected String getOtherInfo() { + final StringBuilder sb = new StringBuilder("dataList="); + if (dataList != null) { + sb.append(dataList.size()); + } else { + sb.append("null"); } - - /** - * Getter method for property dataList. - * - * @return property value of dataList - */ - public List getDataList() { - return dataList; - } - - /** - * Setter method for property dataList. - * - * @param dataList value to be assigned to property dataList - */ - public void setDataList(List dataList) { - this.dataList = dataList; - } - - public PublishType getPublishType() { - return publishType; - } - - /** - * Setter method for property publishType. - * - * @param publishType value to be assigned to property publishType - */ - public void setPublishType(PublishType publishType) { - this.publishType = publishType; - } - - @Override - @JsonIgnore - public DataType getDataType() { - return DataType.PUBLISHER; - } - - @Override - protected String getOtherInfo() { - final StringBuilder sb = new StringBuilder("dataList="); - if (dataList != null) { - sb.append(dataList.size()); - } else { - sb.append("null"); - } - sb.append(",").append("publishType=").append(publishType); - return sb.toString(); - } - - /** - * change publisher word cache - * @param publisher - * @return - */ - public static Publisher internPublisher(Publisher publisher) { - publisher.setRegisterId(publisher.getRegisterId()); - publisher.setDataInfoId(publisher.getDataInfoId()); - publisher.setInstanceId(publisher.getInstanceId()); - publisher.setGroup(publisher.getGroup()); - publisher.setDataId(publisher.getDataId()); - publisher.setClientId(publisher.getClientId()); - publisher.setCell(publisher.getCell()); - publisher.setProcessId(publisher.getProcessId()); - publisher.setAppName(publisher.getAppName()); - - return publisher; - } - -} \ No newline at end of file + sb.append(",").append("publishType=").append(publishType); + return sb.toString(); + } + + /** + * change publisher word cache + * + * @param publisher + * @return + */ + public static Publisher internPublisher(Publisher publisher) { + publisher.setRegisterId(publisher.getRegisterId()); + publisher.setDataInfoId(publisher.getDataInfoId()); + publisher.setInstanceId(publisher.getInstanceId()); + publisher.setGroup(publisher.getGroup()); + publisher.setDataId(publisher.getDataId()); + publisher.setClientId(publisher.getClientId()); + publisher.setCell(publisher.getCell()); + publisher.setProcessId(publisher.getProcessId()); + publisher.setAppName(publisher.getAppName()); + + return publisher; + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/StoreData.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/StoreData.java index 5746a45f8..7884b89e0 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/StoreData.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/StoreData.java @@ -17,28 +17,30 @@ package com.alipay.sofa.registry.common.model.store; /** - * * @author shangyu.wh * @version $Id: StoreData.java, v 0.1 2017-11-30 19:48 shangyu.wh Exp $ */ public interface StoreData { - /** - * DataType enum - */ - enum DataType { - SUBSCRIBER, PUBLISHER, WATCHER, UN_PUBLISHER - } + /** DataType enum */ + enum DataType { + SUBSCRIBER, + PUBLISHER, + WATCHER, + UN_PUBLISHER + } - /** - * get store dataType - * @return - */ - DataType getDataType(); + /** + * get store dataType + * + * @return + */ + DataType getDataType(); - /** - * get store data ID - * @return - */ - ID getId(); -} \ No newline at end of file + /** + * get store data ID + * + * @return + */ + ID getId(); +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/SubDatum.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/SubDatum.java index 0dfe75eb0..6dff21812 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/SubDatum.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/SubDatum.java @@ -18,106 +18,119 @@ import com.alipay.sofa.registry.util.StringFormatter; import com.google.common.collect.Lists; - import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.List; public final class SubDatum implements Serializable { - private static final long serialVersionUID = 5307489721610438103L; + private static final long serialVersionUID = 5307489721610438103L; - private final String dataInfoId; + private final String dataInfoId; - private final String dataCenter; + private final String dataCenter; - private final String dataId; + private final String dataId; - private final String instanceId; + private final String instanceId; - private final String group; + private final String group; - private final List publishers; + private final List publishers; - private final long version; + private final long version; - public SubDatum(String dataInfoId, String dataCenter, long version, - Collection publishers, String dataId, String instanceId, - String group) { - this.dataInfoId = dataInfoId; - this.dataCenter = dataCenter; - this.version = version; - this.publishers = Collections.unmodifiableList(Lists.newArrayList(publishers)); - this.dataId = dataId; - this.instanceId = instanceId; - this.group = group; - } + public SubDatum( + String dataInfoId, + String dataCenter, + long version, + Collection publishers, + String dataId, + String instanceId, + String group) { + this.dataInfoId = dataInfoId; + this.dataCenter = dataCenter; + this.version = version; + this.publishers = Collections.unmodifiableList(Lists.newArrayList(publishers)); + this.dataId = dataId; + this.instanceId = instanceId; + this.group = group; + } - public String getDataInfoId() { - return dataInfoId; - } + public String getDataInfoId() { + return dataInfoId; + } - public String getDataCenter() { - return dataCenter; - } + public String getDataCenter() { + return dataCenter; + } - public String getDataId() { - return dataId; - } + public String getDataId() { + return dataId; + } - public String getInstanceId() { - return instanceId; - } + public String getInstanceId() { + return instanceId; + } - public String getGroup() { - return group; - } + public String getGroup() { + return group; + } - public List getPublishers() { - return publishers; - } + public List getPublishers() { + return publishers; + } - public long getVersion() { - return version; - } + public long getVersion() { + return version; + } - public boolean isEmpty() { - return publishers.isEmpty(); - } + public boolean isEmpty() { + return publishers.isEmpty(); + } - public int getDataBoxBytes() { - int bytes = 0; - for (SubPublisher p : publishers) { - bytes += p.getDataBoxBytes(); - } - return bytes; + public int getDataBoxBytes() { + int bytes = 0; + for (SubPublisher p : publishers) { + bytes += p.getDataBoxBytes(); } - - @Override - public String toString() { - return StringFormatter.format("SubDatum{{},{},{},num={},bytes={}}", dataInfoId, dataCenter, - version, publishers.size(), getDataBoxBytes()); + return bytes; + } + + @Override + public String toString() { + return StringFormatter.format( + "SubDatum{{},{},{},num={},bytes={}}", + dataInfoId, + dataCenter, + version, + publishers.size(), + getDataBoxBytes()); + } + + public static SubDatum intern(SubDatum datum) { + if (datum == null) { + return null; } - - public static SubDatum intern(SubDatum datum) { - if (datum == null) { - return null; - } - final String dataInfoId = WordCache.getWordCache(datum.dataInfoId); - final String dataCenter = WordCache.getWordCache(datum.dataCenter); - - final String dataId = WordCache.getWordCache(datum.dataId); - final String instanceId = WordCache.getWordCache(datum.instanceId); - final String group = WordCache.getWordCache(datum.group); - - List publishers = Lists.newArrayListWithCapacity(datum.publishers.size()); - for (SubPublisher publisher : datum.publishers) { - final String cell = WordCache.getWordCache(publisher.getCell()); - publishers.add(new SubPublisher(cell, publisher.getDataList(), publisher.getClientId(), - publisher.getSrcAddressString(), publisher.getRegisterTimestamp())); - } - return new SubDatum(dataInfoId, dataCenter, datum.version, publishers, dataId, instanceId, - group); + final String dataInfoId = WordCache.getWordCache(datum.dataInfoId); + final String dataCenter = WordCache.getWordCache(datum.dataCenter); + + final String dataId = WordCache.getWordCache(datum.dataId); + final String instanceId = WordCache.getWordCache(datum.instanceId); + final String group = WordCache.getWordCache(datum.group); + + List publishers = Lists.newArrayListWithCapacity(datum.publishers.size()); + for (SubPublisher publisher : datum.publishers) { + final String cell = WordCache.getWordCache(publisher.getCell()); + publishers.add( + new SubPublisher( + cell, + publisher.getDataList(), + publisher.getClientId(), + publisher.getSrcAddressString(), + publisher.getRegisterTimestamp())); } - + return new SubDatum( + dataInfoId, dataCenter, datum.version, publishers, dataId, instanceId, group); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/SubPublisher.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/SubPublisher.java index a6c4436e3..d2ae7238c 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/SubPublisher.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/SubPublisher.java @@ -19,59 +19,67 @@ import com.alipay.sofa.registry.common.model.ServerDataBox; import com.alipay.sofa.registry.util.StringFormatter; import com.google.common.collect.Lists; - import java.io.Serializable; import java.util.Collections; import java.util.List; public final class SubPublisher implements Serializable { - private final String cell; - private final String clientId; - private final String srcAddressString; - private final List dataList; - private final long registerTimestamp; + private final String cell; + private final String clientId; + private final String srcAddressString; + private final List dataList; + private final long registerTimestamp; - public SubPublisher(String cell, List dataList, String clientId, - String srcAddressString, long registerTimestamp) { - this.cell = cell; - this.clientId = clientId; - this.srcAddressString = srcAddressString; - this.dataList = Collections.unmodifiableList(Lists.newArrayList(dataList)); - this.registerTimestamp = registerTimestamp; - } + public SubPublisher( + String cell, + List dataList, + String clientId, + String srcAddressString, + long registerTimestamp) { + this.cell = cell; + this.clientId = clientId; + this.srcAddressString = srcAddressString; + this.dataList = Collections.unmodifiableList(Lists.newArrayList(dataList)); + this.registerTimestamp = registerTimestamp; + } - public String getCell() { - return cell; - } + public String getCell() { + return cell; + } - public List getDataList() { - return dataList; - } + public List getDataList() { + return dataList; + } - public String getClientId() { - return clientId; - } + public String getClientId() { + return clientId; + } - public String getSrcAddressString() { - return srcAddressString; - } + public String getSrcAddressString() { + return srcAddressString; + } - public long getRegisterTimestamp() { - return registerTimestamp; - } + public long getRegisterTimestamp() { + return registerTimestamp; + } - public int getDataBoxBytes() { - int bytes = 0; - for (ServerDataBox box : dataList) { - bytes += box.byteSize(); - } - return bytes; + public int getDataBoxBytes() { + int bytes = 0; + for (ServerDataBox box : dataList) { + bytes += box.byteSize(); } + return bytes; + } - @Override - public String toString() { - return StringFormatter - .format("SubPublisher{{},cell={},src={},datas={},bytes={},ts={}}", clientId, cell, - srcAddressString, dataList.size(), getDataBoxBytes(), registerTimestamp); - } + @Override + public String toString() { + return StringFormatter.format( + "SubPublisher{{},cell={},src={},datas={},bytes={},ts={}}", + clientId, + cell, + srcAddressString, + dataList.size(), + getDataBoxBytes(), + registerTimestamp); + } } diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Subscriber.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Subscriber.java index f3020ef42..4fce66a78 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Subscriber.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Subscriber.java @@ -16,12 +16,11 @@ */ package com.alipay.sofa.registry.common.model.store; -import java.util.*; - import com.alipay.sofa.registry.common.model.ElementType; import com.alipay.sofa.registry.core.model.ScopeEnum; import com.alipay.sofa.registry.util.StringFormatter; import com.fasterxml.jackson.annotation.JsonIgnore; +import java.util.*; /** * @author shangyu.wh @@ -29,140 +28,129 @@ */ public class Subscriber extends BaseInfo { - /** - * UID - */ - private static final long serialVersionUID = 98433360274932292L; - /** - * - */ - private ScopeEnum scope; - /** - * - */ - private ElementType elementType; - /** - * - */ - - /** - * last push context - */ - private final Map lastPushContexts = new HashMap<>(4); - - /** - * Getter method for property scope. - * - * @return property value of scope - */ - public ScopeEnum getScope() { - return scope; - } - - /** - * Setter method for property scope. - * - * @param scope value to be assigned to property scope - */ - public void setScope(ScopeEnum scope) { - this.scope = scope; - } - - public ElementType getElementType() { - return elementType; - } - - // check the version - public synchronized boolean checkVersion(String dataCenter, long version) { - final PushContext ctx = lastPushContexts.get(dataCenter); - if (ctx == null) { - return true; - } - return ctx.pushVersion < version; + /** UID */ + private static final long serialVersionUID = 98433360274932292L; + /** */ + private ScopeEnum scope; + /** */ + private ElementType elementType; + /** */ + + /** last push context */ + private final Map lastPushContexts = new HashMap<>(4); + + /** + * Getter method for property scope. + * + * @return property value of scope + */ + public ScopeEnum getScope() { + return scope; + } + + /** + * Setter method for property scope. + * + * @param scope value to be assigned to property scope + */ + public void setScope(ScopeEnum scope) { + this.scope = scope; + } + + public ElementType getElementType() { + return elementType; + } + + // check the version + public synchronized boolean checkVersion(String dataCenter, long version) { + final PushContext ctx = lastPushContexts.get(dataCenter); + if (ctx == null) { + return true; } + return ctx.pushVersion < version; + } - public synchronized boolean checkAndUpdateVersion(String dataCenter, long pushVersion) { - final PushContext ctx = lastPushContexts.computeIfAbsent(dataCenter, k -> new PushContext()); + public synchronized boolean checkAndUpdateVersion(String dataCenter, long pushVersion) { + final PushContext ctx = lastPushContexts.computeIfAbsent(dataCenter, k -> new PushContext()); - if (ctx.pushVersion < pushVersion) { - ctx.pushVersion = pushVersion; - return true; - } - return false; + if (ctx.pushVersion < pushVersion) { + ctx.pushVersion = pushVersion; + return true; } + return false; + } - public synchronized boolean hasPushed() { - // TODO now not care multi-datacenter - if (lastPushContexts.isEmpty()) { - return false; - } - for (PushContext ctx : lastPushContexts.values()) { - if (ctx.pushVersion != 0) { - return true; - } - } - return false; + public synchronized boolean hasPushed() { + // TODO now not care multi-datacenter + if (lastPushContexts.isEmpty()) { + return false; } - - /** - * Setter method for property elementType. - * - * @param elementType value to be assigned to property elementType - */ - public void setElementType(ElementType elementType) { - this.elementType = elementType; + for (PushContext ctx : lastPushContexts.values()) { + if (ctx.pushVersion != 0) { + return true; + } } + return false; + } + + /** + * Setter method for property elementType. + * + * @param elementType value to be assigned to property elementType + */ + public void setElementType(ElementType elementType) { + this.elementType = elementType; + } + + @Override + @JsonIgnore + public DataType getDataType() { + return DataType.SUBSCRIBER; + } + + @Override + protected String getOtherInfo() { + final StringBuilder sb = new StringBuilder("scope="); + sb.append(scope).append(","); + sb.append("elementType=").append(elementType).append(","); + sb.append("ctx=").append(lastPushContexts); + return sb.toString(); + } + + public String printPushContext() { + final StringBuilder sb = new StringBuilder(128); + return sb.append(lastPushContexts).toString(); + } + + public synchronized long getPushVersion(String dataCenter) { + PushContext ctx = lastPushContexts.get(dataCenter); + return ctx == null ? 0 : ctx.pushVersion; + } + + /** + * change subscriber word cache + * + * @param subscriber + * @return + */ + public static Subscriber internSubscriber(Subscriber subscriber) { + subscriber.setDataInfoId(subscriber.getDataInfoId()); + subscriber.setInstanceId(subscriber.getInstanceId()); + subscriber.setGroup(subscriber.getGroup()); + subscriber.setDataId(subscriber.getDataId()); + subscriber.setCell(subscriber.getCell()); + subscriber.setProcessId(subscriber.getProcessId()); + subscriber.setAppName(subscriber.getAppName()); + + return subscriber; + } + + private static class PushContext { + long pushVersion; @Override - @JsonIgnore - public DataType getDataType() { - return DataType.SUBSCRIBER; + public String toString() { + return StringFormatter.format("PushCtx{{}}", pushVersion); } - - @Override - protected String getOtherInfo() { - final StringBuilder sb = new StringBuilder("scope="); - sb.append(scope).append(","); - sb.append("elementType=").append(elementType).append(","); - sb.append("ctx=").append(lastPushContexts); - return sb.toString(); - } - - public String printPushContext() { - final StringBuilder sb = new StringBuilder(128); - return sb.append(lastPushContexts).toString(); - } - - public synchronized long getPushVersion(String dataCenter) { - PushContext ctx = lastPushContexts.get(dataCenter); - return ctx == null ? 0 : ctx.pushVersion; - } - - /** - * change subscriber word cache - * - * @param subscriber - * @return - */ - public static Subscriber internSubscriber(Subscriber subscriber) { - subscriber.setDataInfoId(subscriber.getDataInfoId()); - subscriber.setInstanceId(subscriber.getInstanceId()); - subscriber.setGroup(subscriber.getGroup()); - subscriber.setDataId(subscriber.getDataId()); - subscriber.setCell(subscriber.getCell()); - subscriber.setProcessId(subscriber.getProcessId()); - subscriber.setAppName(subscriber.getAppName()); - - return subscriber; - } - - private static class PushContext { - long pushVersion; - - @Override - public String toString() { - return StringFormatter.format("PushCtx{{}}", pushVersion); - } - } - -} \ No newline at end of file + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/URL.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/URL.java index cd7179083..27a0e7123 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/URL.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/URL.java @@ -18,7 +18,6 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; - import java.io.Serializable; import java.net.InetAddress; import java.net.InetSocketAddress; @@ -27,258 +26,276 @@ import java.util.Objects; /** - * * @author shangyu.wh * @version $Id: URL.java, v 0.1 2017-11-20 21:21 shangyu.wh Exp $ */ public final class URL implements Serializable { - private static final Logger LOGGER = LoggerFactory.getLogger(URL.class); - - /** symbol : */ - public static final char COLON = ':'; - - public static final byte HESSIAN_2 = 1; - - public static final byte PROTOBUF = 11; - - public static final byte JSON = 2; - - private ProtocolType protocol; - - private String host; - - private String ipAddress; - - private int port; - - private String path; - - private Byte serializerIndex; - - private Map parameters; - - private String addressString; - - /** - * ProtocolType Enum - */ - public enum ProtocolType { - TR, BOLT, HTTP + private static final Logger LOGGER = LoggerFactory.getLogger(URL.class); + + /** symbol : */ + public static final char COLON = ':'; + + public static final byte HESSIAN_2 = 1; + + public static final byte PROTOBUF = 11; + + public static final byte JSON = 2; + + private ProtocolType protocol; + + private String host; + + private String ipAddress; + + private int port; + + private String path; + + private Byte serializerIndex; + + private Map parameters; + + private String addressString; + + /** ProtocolType Enum */ + public enum ProtocolType { + TR, + BOLT, + HTTP + } + + public URL() {} + + /** + * constructor + * + * @param protocol + * @param ipAddress + * @param port + * @param host + * @param path + * @param serializerIndex + * @param parameters + */ + public URL( + ProtocolType protocol, + String ipAddress, + int port, + String host, + String path, + Byte serializerIndex, + Map parameters) { + this.protocol = protocol; + this.host = host; + this.ipAddress = WordCache.getWordCache(getIPAddressFromDomain(ipAddress)); + this.port = port; + this.addressString = WordCache.getWordCache(buildAddressString()); + this.path = path; + this.serializerIndex = serializerIndex; + this.parameters = parameters; + } + + /** + * constructor + * + * @param ipAddress + * @param port + */ + public URL(String ipAddress, int port) { + this(null, ipAddress, port, "", "", HESSIAN_2, null); + } + + /** + * constructor + * + * @param address + */ + public URL(InetSocketAddress address) { + this(null, address.getAddress().getHostAddress(), address.getPort(), "", "", HESSIAN_2, null); + } + + /** + * constructor + * + * @param address + * @param serializerIndex + */ + public URL(InetSocketAddress address, Byte serializerIndex) { + this( + null, + address.getAddress().getHostAddress(), + address.getPort(), + "", + "", + serializerIndex, + null); + } + + /** + * constructor + * + * @param ipAddress + */ + public URL(String ipAddress) { + this(ipAddress, 0); + } + + /** + * url transfer to InetSocketAddress + * + * @param url + * @return + */ + public static InetSocketAddress toInetSocketAddress(URL url) { + return new InetSocketAddress(url.getIpAddress(), url.getPort()); + } + + /** + * Getter method for property protocol. + * + * @return property value of protocol + */ + public ProtocolType getProtocol() { + return protocol; + } + + /** + * Getter method for property host. + * + * @return property value of host + */ + public String getHost() { + return host; + } + + /** + * Getter method for property ipAddress. + * + * @return property value of ipAddress + */ + public String getIpAddress() { + return ipAddress; + } + + /** + * Getter method for property port. + * + * @return property value of port + */ + public int getPort() { + return port; + } + + /** + * Getter method for property path. + * + * @return property value of path + */ + public String getPath() { + return path; + } + + /** + * Getter method for property parameters. + * + * @return property value of parameters + */ + public Map getParameters() { + return parameters; + } + + /** + * Getter method for property addressString. + * + * @return property value of addressString + */ + public String getAddressString() { + return addressString; + } + + /** + * build address string + * + * @return + */ + public String buildAddressString() { + StringBuilder sb = new StringBuilder(32); + sb.append(ipAddress).append(COLON).append(port); + return sb.toString(); + } + + /** + * Getter method for property serializerIndex. + * + * @return property value of serializerIndex + */ + public Byte getSerializerIndex() { + return serializerIndex; + } + + private String getIPAddressFromDomain(String domain) { + try { + InetAddress a = InetAddress.getByName(domain); + return a.getHostAddress(); + } catch (UnknownHostException e) { + LOGGER.error("Can not resolve " + domain + " really ip."); } - - public URL() { + return domain; + } + + /** + * TODO Other protocol + * + * @param url + * @return + */ + public static URL valueOf(String url) { + + if (url == null || (url = url.trim()).length() == 0) { + throw new IllegalArgumentException("url == null"); } - - /** - * constructor - * @param protocol - * @param ipAddress - * @param port - * @param host - * @param path - * @param serializerIndex - * @param parameters - */ - public URL(ProtocolType protocol, String ipAddress, int port, String host, String path, - Byte serializerIndex, Map parameters) { - this.protocol = protocol; - this.host = host; - this.ipAddress = WordCache.getWordCache(getIPAddressFromDomain(ipAddress)); - this.port = port; - this.addressString = WordCache.getWordCache(buildAddressString()); - this.path = path; - this.serializerIndex = serializerIndex; - this.parameters = parameters; + String ipAddress = ""; + String path = ""; + int port = 0; + ProtocolType protocol = null; + Map parameters = null; + + int i = url.indexOf(":"); + if (i >= 0 && i < url.length() - 1) { + port = Integer.parseInt(url.substring(i + 1)); + url = url.substring(0, i); } - - /** - * constructor - * @param ipAddress - * @param port - */ - public URL(String ipAddress, int port) { - this(null, ipAddress, port, "", "", HESSIAN_2, null); + if (url.length() > 0) { + ipAddress = url; } - /** - * constructor - * @param address - */ - public URL(InetSocketAddress address) { - this(null, address.getAddress().getHostAddress(), address.getPort(), "", "", HESSIAN_2, - null); - } - - /** - * constructor - * @param address - * @param serializerIndex - */ - public URL(InetSocketAddress address, Byte serializerIndex) { - this(null, address.getAddress().getHostAddress(), address.getPort(), "", "", - serializerIndex, null); - } - - /** - * constructor - * @param ipAddress - */ - public URL(String ipAddress) { - this(ipAddress, 0); - } - - /** - * url transfer to InetSocketAddress - * @param url - * @return - */ - public static InetSocketAddress toInetSocketAddress(URL url) { - return new InetSocketAddress(url.getIpAddress(), url.getPort()); - } - - /** - * Getter method for property protocol. - * - * @return property value of protocol - */ - public ProtocolType getProtocol() { - return protocol; - } - - /** - * Getter method for property host. - * - * @return property value of host - */ - public String getHost() { - return host; - } - - /** - * Getter method for property ipAddress. - * - * @return property value of ipAddress - */ - public String getIpAddress() { - return ipAddress; - } - - /** - * Getter method for property port. - * - * @return property value of port - */ - public int getPort() { - return port; - } - - /** - * Getter method for property path. - * - * @return property value of path - */ - public String getPath() { - return path; - } - - /** - * Getter method for property parameters. - * - * @return property value of parameters - */ - public Map getParameters() { - return parameters; - } - - /** - * Getter method for property addressString. - * - * @return property value of addressString - */ - public String getAddressString() { - return addressString; - } - - /** - * build address string - * @return - */ - public String buildAddressString() { - StringBuilder sb = new StringBuilder(32); - sb.append(ipAddress).append(COLON).append(port); - return sb.toString(); - } - - /** - * Getter method for property serializerIndex. - * - * @return property value of serializerIndex - */ - public Byte getSerializerIndex() { - return serializerIndex; - } - - private String getIPAddressFromDomain(String domain) { - try { - InetAddress a = InetAddress.getByName(domain); - return a.getHostAddress(); - } catch (UnknownHostException e) { - LOGGER.error("Can not resolve " + domain + " really ip."); - } - return domain; - } - - /** - * TODO Other protocol - * @param url - * @return - */ - public static URL valueOf(String url) { - - if (url == null || (url = url.trim()).length() == 0) { - throw new IllegalArgumentException("url == null"); - } - String ipAddress = ""; - String path = ""; - int port = 0; - ProtocolType protocol = null; - Map parameters = null; - - int i = url.indexOf(":"); - if (i >= 0 && i < url.length() - 1) { - port = Integer.parseInt(url.substring(i + 1)); - url = url.substring(0, i); - } - if (url.length() > 0) { - ipAddress = url; - } - - return new URL(protocol, ipAddress, port, "", path, HESSIAN_2, parameters); - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - URL url = (URL) o; - return port == url.port && protocol == url.protocol && Objects.equals(host, url.host) - && Objects.equals(ipAddress, url.ipAddress) && Objects.equals(path, url.path) - && Objects.equals(parameters, url.parameters) - && Objects.equals(addressString, url.addressString); - } - - @Override - public int hashCode() { - return Objects.hash(protocol, host, ipAddress, port, path, parameters, addressString); - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("URL{"); - sb.append("address='").append(addressString).append('\''); - sb.append('}'); - return sb.toString(); - } -} \ No newline at end of file + return new URL(protocol, ipAddress, port, "", path, HESSIAN_2, parameters); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + URL url = (URL) o; + return port == url.port + && protocol == url.protocol + && Objects.equals(host, url.host) + && Objects.equals(ipAddress, url.ipAddress) + && Objects.equals(path, url.path) + && Objects.equals(parameters, url.parameters) + && Objects.equals(addressString, url.addressString); + } + + @Override + public int hashCode() { + return Objects.hash(protocol, host, ipAddress, port, path, parameters, addressString); + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("URL{"); + sb.append("address='").append(addressString).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/UnPublisher.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/UnPublisher.java index 661a4fe98..761cfa229 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/UnPublisher.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/UnPublisher.java @@ -19,41 +19,46 @@ import com.alipay.sofa.registry.common.model.ProcessId; /** - * * @author qian.lqlq * @version $Id: UnPublisher.java, v 0.1 2018-01-11 20:05 qian.lqlq Exp $ */ public class UnPublisher extends Publisher { - /** - * - * @param dataInfoId - * @param registerId - * @param registerTimeStamp - */ - public UnPublisher(String dataInfoId, ProcessId sessionProcessId, String registerId, - long registerTimeStamp, long version) { - setDataInfoId(dataInfoId); - setRegisterId(registerId); - setRegisterTimestamp(registerTimeStamp); - setVersion(version); - //avoid new datum dataId is null - DataInfo dataInfo = DataInfo.valueOf(dataInfoId); - setDataId(dataInfo.getDataId()); - setGroup(dataInfo.getGroup()); - setInstanceId(dataInfo.getInstanceId()); - - setSessionProcessId(sessionProcessId); + /** + * @param dataInfoId + * @param registerId + * @param registerTimeStamp + */ + public UnPublisher( + String dataInfoId, + ProcessId sessionProcessId, + String registerId, + long registerTimeStamp, + long version) { + setDataInfoId(dataInfoId); + setRegisterId(registerId); + setRegisterTimestamp(registerTimeStamp); + setVersion(version); + // avoid new datum dataId is null + DataInfo dataInfo = DataInfo.valueOf(dataInfoId); + setDataId(dataInfo.getDataId()); + setGroup(dataInfo.getGroup()); + setInstanceId(dataInfo.getInstanceId()); - } + setSessionProcessId(sessionProcessId); + } - @Override - public DataType getDataType() { - return DataType.UN_PUBLISHER; - } + @Override + public DataType getDataType() { + return DataType.UN_PUBLISHER; + } - public static UnPublisher of(Publisher publisher) { - return new UnPublisher(publisher.getDataInfoId(), publisher.getSessionProcessId(), - publisher.getRegisterId(), publisher.getRegisterTimestamp(), publisher.getVersion()); - } -} \ No newline at end of file + public static UnPublisher of(Publisher publisher) { + return new UnPublisher( + publisher.getDataInfoId(), + publisher.getSessionProcessId(), + publisher.getRegisterId(), + publisher.getRegisterTimestamp(), + publisher.getVersion()); + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Watcher.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Watcher.java index f369d5e4e..9e5b75036 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Watcher.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/Watcher.java @@ -17,33 +17,33 @@ package com.alipay.sofa.registry.common.model.store; /** - * * @author shangyu.wh * @version $Id: Watcher.java, v 0.1 2018-04-17 18:22 shangyu.wh Exp $ */ public class Watcher extends BaseInfo { - @Override - public DataType getDataType() { - return DataType.WATCHER; - } + @Override + public DataType getDataType() { + return DataType.WATCHER; + } - /** - * change watcher word cache - * @param watcher - * @return - */ - public static Watcher internWatcher(Watcher watcher) { - watcher.setRegisterId(watcher.getRegisterId()); - watcher.setDataInfoId(watcher.getDataInfoId()); - watcher.setInstanceId(watcher.getInstanceId()); - watcher.setGroup(watcher.getGroup()); - watcher.setDataId(watcher.getDataId()); - watcher.setClientId(watcher.getClientId()); - watcher.setCell(watcher.getCell()); - watcher.setProcessId(watcher.getProcessId()); - watcher.setAppName(watcher.getAppName()); + /** + * change watcher word cache + * + * @param watcher + * @return + */ + public static Watcher internWatcher(Watcher watcher) { + watcher.setRegisterId(watcher.getRegisterId()); + watcher.setDataInfoId(watcher.getDataInfoId()); + watcher.setInstanceId(watcher.getInstanceId()); + watcher.setGroup(watcher.getGroup()); + watcher.setDataId(watcher.getDataId()); + watcher.setClientId(watcher.getClientId()); + watcher.setCell(watcher.getCell()); + watcher.setProcessId(watcher.getProcessId()); + watcher.setAppName(watcher.getAppName()); - return watcher; - } -} \ No newline at end of file + return watcher; + } +} diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/WordCache.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/WordCache.java index 2e84f0784..9480c21c4 100644 --- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/WordCache.java +++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/store/WordCache.java @@ -20,29 +20,23 @@ import com.google.common.collect.Interners; /** - * * @author shangyu.wh * @version $Id: WordCache.java, v 0.1 2018-11-06 12:01 shangyu.wh Exp $ */ public final class WordCache { - private WordCache() { - } + private WordCache() {} - /** - * word cache map - */ - private static final Interner interners = Interners.newWeakInterner(); + /** word cache map */ + private static final Interner interners = Interners.newWeakInterner(); - /** - * - * @param s - * @return String - */ - public static String getWordCache(String s) { - if (s == null) { - return null; - } - return interners.intern(s); + /** + * @param s + * @return String + */ + public static String getWordCache(String s) { + if (s == null) { + return null; } - -} \ No newline at end of file + return interners.intern(s); + } +} diff --git a/server/common/model/src/test/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffSyncResultTest.java b/server/common/model/src/test/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffSyncResultTest.java index 6d84b5abb..3ea9814d0 100644 --- a/server/common/model/src/test/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffSyncResultTest.java +++ b/server/common/model/src/test/java/com/alipay/sofa/registry/common/model/slot/DataSlotDiffSyncResultTest.java @@ -26,215 +26,212 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.junit.Assert; -import org.junit.Test; - import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; +import org.junit.Assert; +import org.junit.Test; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-24 16:44 yuzhi.lyz Exp $ */ public class DataSlotDiffSyncResultTest { - private static final Logger LOG = LoggerFactory.getLogger(DataSlotDiffSyncResultTest.class); - private static final AtomicLong SEQ = new AtomicLong(); - - @Test - public void testDiffDigestResult_emptyTarget() { - Map m = Maps.newHashMap(); - m.put("a", 100); - m.put("b", 200); - Map> publishers = randPublishers(m); - DataSlotDiffDigestResult result = DataSlotDiffUtils.diffDigestPublishers( - Collections.emptyMap(), publishers); - Assert.assertFalse(result.getAddedDataInfoIds().isEmpty()); - Assert.assertEquals(result.getAddedDataInfoIds(), Lists.newArrayList("a", "b")); - Assert.assertTrue(result.getRemovedDataInfoIds().isEmpty()); + private static final Logger LOG = LoggerFactory.getLogger(DataSlotDiffSyncResultTest.class); + private static final AtomicLong SEQ = new AtomicLong(); + + @Test + public void testDiffDigestResult_emptyTarget() { + Map m = Maps.newHashMap(); + m.put("a", 100); + m.put("b", 200); + Map> publishers = randPublishers(m); + DataSlotDiffDigestResult result = + DataSlotDiffUtils.diffDigestPublishers(Collections.emptyMap(), publishers); + Assert.assertFalse(result.getAddedDataInfoIds().isEmpty()); + Assert.assertEquals(result.getAddedDataInfoIds(), Lists.newArrayList("a", "b")); + Assert.assertTrue(result.getRemovedDataInfoIds().isEmpty()); + } + + @Test + public void testDiffDigestResult_target() { + Map m = Maps.newHashMap(); + m.put("a", 100); + m.put("b", 200); + Map> publishers = randPublishers(m); + Map summaryMap = PublisherUtils.getDatumSummary(publishers); + Map digestMap = PublisherDigestUtil.digest(summaryMap); + DataSlotDiffDigestResult result = DataSlotDiffUtils.diffDigestPublishers(digestMap, publishers); + Assert.assertTrue(result.getAddedDataInfoIds().isEmpty()); + Assert.assertTrue(result.getRemovedDataInfoIds().isEmpty()); + + Map test = Maps.newHashMap(digestMap); + + test.put("c", new DatumDigest(1, 0, 0, 0)); + result = DataSlotDiffUtils.diffDigestPublishers(test, publishers); + Assert.assertTrue(result.getAddedDataInfoIds().isEmpty()); + Assert.assertFalse(result.getRemovedDataInfoIds().isEmpty()); + + Assert.assertEquals(result.getRemovedDataInfoIds(), Lists.newArrayList("c")); + + test = Maps.newHashMap(digestMap); + test.remove("b"); + test.put("c", new DatumDigest(1, 0, 0, 0)); + result = DataSlotDiffUtils.diffDigestPublishers(test, publishers); + // add "b" + Assert.assertEquals(result.getAddedDataInfoIds(), Lists.newArrayList("b")); + + // delete "c" + Assert.assertTrue(result.getRemovedDataInfoIds().size() == 1); + Assert.assertTrue(result.getRemovedDataInfoIds().contains("c")); + DataSlotDiffUtils.logDiffResult(result, 10); + } + + @Test + public void testDiffPublishersResult() { + Map m = Maps.newHashMap(); + m.put("a", 100); + m.put("b", 200); + + Map> publishers = randPublishers(m); + + // the same + Map summaryMap = PublisherUtils.getDatumSummary(publishers); + DataSlotDiffPublisherResult result = + DataSlotDiffUtils.diffPublishersResult(summaryMap.values(), publishers, 400); + Assert.assertFalse(result.isHasRemain()); + Assert.assertTrue(result.getUpdatedPublishers().isEmpty()); + Assert.assertTrue(result.getRemovedPublishers().isEmpty()); + + // now add c, d + Map newM = Maps.newHashMap(); + newM.put("c", 300); + newM.put("d", 400); + m.putAll(newM); + Map> addPublishers = randPublishers(newM); + publishers.putAll(addPublishers); + + // not reach max.publishers + summaryMap.put("c", new DatumSummary("c")); + summaryMap.put("d", new DatumSummary("d")); + result = DataSlotDiffUtils.diffPublishersResult(summaryMap.values(), publishers, 1000); + Assert.assertFalse(result.isHasRemain()); + Assert.assertTrue(result.getRemovedPublishers().isEmpty()); + + Assert.assertEquals(result.getUpdatedPublishers().keySet(), Sets.newHashSet("c", "d")); + checkUpdatedSize(m, result); + checkAddedPublisher(publishers, result); + + // reach max.publishers + result = DataSlotDiffUtils.diffPublishersResult(summaryMap.values(), publishers, 100); + Assert.assertTrue(result.isHasRemain()); + Assert.assertTrue(result.getRemovedPublishers().isEmpty()); + + Assert.assertEquals(result.getUpdatedPublishers().size(), 1); + Assert.assertTrue( + result.getUpdatedPublishers().keySet().contains("c") + || result.getUpdatedPublishers().keySet().contains("d")); + + checkUpdatedSize(m, result); + checkAddedPublisher(publishers, result); + + // delete a dataInfoId, delete b.publisher, modify c.publisher, add d.publisher + summaryMap = PublisherUtils.getDatumSummary(publishers); + publishers.remove("a"); + + Iterator> iter = publishers.get("b").entrySet().iterator(); + Publisher removedB = iter.next().getValue(); + iter.remove(); + + Publisher modifyC = null; + for (Map.Entry e : publishers.get("c").entrySet()) { + modifyC = e.getValue(); + modifyC.setRegisterTimestamp(System.nanoTime()); + break; } - - @Test - public void testDiffDigestResult_target() { - Map m = Maps.newHashMap(); - m.put("a", 100); - m.put("b", 200); - Map> publishers = randPublishers(m); - Map summaryMap = PublisherUtils.getDatumSummary(publishers); - Map digestMap = PublisherDigestUtil.digest(summaryMap); - DataSlotDiffDigestResult result = DataSlotDiffUtils.diffDigestPublishers(digestMap, - publishers); - Assert.assertTrue(result.getAddedDataInfoIds().isEmpty()); - Assert.assertTrue(result.getRemovedDataInfoIds().isEmpty()); - - Map test = Maps.newHashMap(digestMap); - - test.put("c", new DatumDigest(1, 0, 0, 0)); - result = DataSlotDiffUtils.diffDigestPublishers(test, publishers); - Assert.assertTrue(result.getAddedDataInfoIds().isEmpty()); - Assert.assertFalse(result.getRemovedDataInfoIds().isEmpty()); - - Assert.assertEquals(result.getRemovedDataInfoIds(), Lists.newArrayList("c")); - - test = Maps.newHashMap(digestMap); - test.remove("b"); - test.put("c", new DatumDigest(1, 0, 0, 0)); - result = DataSlotDiffUtils.diffDigestPublishers(test, publishers); - // add "b" - Assert.assertEquals(result.getAddedDataInfoIds(), Lists.newArrayList("b")); - - // delete "c" - Assert.assertTrue(result.getRemovedDataInfoIds().size() == 1); - Assert.assertTrue(result.getRemovedDataInfoIds().contains("c")); - DataSlotDiffUtils.logDiffResult(result, 10); - + Publisher addD = randPublisher(); + publishers.get("d").put(addD.getRegisterId(), addD); + + // not reach max + result = DataSlotDiffUtils.diffPublishersResult(summaryMap.values(), publishers, 400); + Assert.assertFalse(result.isHasRemain()); + Assert.assertTrue(result.getRemovedPublishers().get("b").size() == 1); + Assert.assertEquals(result.getRemovedPublishers().get("b").get(0), removedB.getRegisterId()); + + Assert.assertEquals(result.getUpdatedPublishers().keySet(), Sets.newHashSet("c", "d")); + Assert.assertEquals(result.getUpdatedPublishers().get("c").size(), 1); + Assert.assertEquals(result.getUpdatedPublishers().get("d").size(), 1); + Assert.assertEquals(result.getUpdatedPublishers().get("c").get(0), modifyC); + Assert.assertEquals(result.getUpdatedPublishers().get("d").get(0), addD); + + DataSlotDiffUtils.logDiffResult(result, 10); + + // reach max + result = DataSlotDiffUtils.diffPublishersResult(summaryMap.values(), publishers, 1); + Assert.assertTrue(result.isHasRemain()); + Assert.assertTrue(result.getRemovedPublishers().get("b").size() == 1); + Assert.assertEquals(result.getRemovedPublishers().get("b").get(0), removedB.getRegisterId()); + + Assert.assertTrue( + result.getUpdatedPublishers().containsKey("c") + || result.getUpdatedPublishers().containsKey("d")); + + Assert.assertEquals(result.getUpdatedPublishers().size(), 1); + + if (result.getUpdatedPublishers().containsKey("c")) { + Assert.assertEquals(result.getUpdatedPublishers().get("c").size(), 1); + Assert.assertEquals(result.getUpdatedPublishers().get("c").get(0), modifyC); } - @Test - public void testDiffPublishersResult() { - Map m = Maps.newHashMap(); - m.put("a", 100); - m.put("b", 200); - - Map> publishers = randPublishers(m); - - // the same - Map summaryMap = PublisherUtils.getDatumSummary(publishers); - DataSlotDiffPublisherResult result = DataSlotDiffUtils.diffPublishersResult( - summaryMap.values(), publishers, 400); - Assert.assertFalse(result.isHasRemain()); - Assert.assertTrue(result.getUpdatedPublishers().isEmpty()); - Assert.assertTrue(result.getRemovedPublishers().isEmpty()); - - // now add c, d - Map newM = Maps.newHashMap(); - newM.put("c", 300); - newM.put("d", 400); - m.putAll(newM); - Map> addPublishers = randPublishers(newM); - publishers.putAll(addPublishers); - - // not reach max.publishers - summaryMap.put("c", new DatumSummary("c")); - summaryMap.put("d", new DatumSummary("d")); - result = DataSlotDiffUtils.diffPublishersResult(summaryMap.values(), publishers, 1000); - Assert.assertFalse(result.isHasRemain()); - Assert.assertTrue(result.getRemovedPublishers().isEmpty()); - - Assert.assertEquals(result.getUpdatedPublishers().keySet(), Sets.newHashSet("c", "d")); - checkUpdatedSize(m, result); - checkAddedPublisher(publishers, result); - - // reach max.publishers - result = DataSlotDiffUtils.diffPublishersResult(summaryMap.values(), publishers, 100); - Assert.assertTrue(result.isHasRemain()); - Assert.assertTrue(result.getRemovedPublishers().isEmpty()); - - Assert.assertEquals(result.getUpdatedPublishers().size(), 1); - Assert.assertTrue(result.getUpdatedPublishers().keySet().contains("c") - || result.getUpdatedPublishers().keySet().contains("d")); - - checkUpdatedSize(m, result); - checkAddedPublisher(publishers, result); - - // delete a dataInfoId, delete b.publisher, modify c.publisher, add d.publisher - summaryMap = PublisherUtils.getDatumSummary(publishers); - publishers.remove("a"); - - Iterator> iter = publishers.get("b").entrySet().iterator(); - Publisher removedB = iter.next().getValue(); - iter.remove(); - - Publisher modifyC = null; - for (Map.Entry e : publishers.get("c").entrySet()) { - modifyC = e.getValue(); - modifyC.setRegisterTimestamp(System.nanoTime()); - break; - } - Publisher addD = randPublisher(); - publishers.get("d").put(addD.getRegisterId(), addD); - - // not reach max - result = DataSlotDiffUtils.diffPublishersResult(summaryMap.values(), publishers, 400); - Assert.assertFalse(result.isHasRemain()); - Assert.assertTrue(result.getRemovedPublishers().get("b").size() == 1); - Assert - .assertEquals(result.getRemovedPublishers().get("b").get(0), removedB.getRegisterId()); - - Assert.assertEquals(result.getUpdatedPublishers().keySet(), Sets.newHashSet("c", "d")); - Assert.assertEquals(result.getUpdatedPublishers().get("c").size(), 1); - Assert.assertEquals(result.getUpdatedPublishers().get("d").size(), 1); - Assert.assertEquals(result.getUpdatedPublishers().get("c").get(0), modifyC); - Assert.assertEquals(result.getUpdatedPublishers().get("d").get(0), addD); - - DataSlotDiffUtils.logDiffResult(result, 10); - - // reach max - result = DataSlotDiffUtils.diffPublishersResult(summaryMap.values(), publishers, 1); - Assert.assertTrue(result.isHasRemain()); - Assert.assertTrue(result.getRemovedPublishers().get("b").size() == 1); - Assert - .assertEquals(result.getRemovedPublishers().get("b").get(0), removedB.getRegisterId()); - - Assert.assertTrue(result.getUpdatedPublishers().containsKey("c") - || result.getUpdatedPublishers().containsKey("d")); - - Assert.assertEquals(result.getUpdatedPublishers().size(), 1); - - if (result.getUpdatedPublishers().containsKey("c")) { - Assert.assertEquals(result.getUpdatedPublishers().get("c").size(), 1); - Assert.assertEquals(result.getUpdatedPublishers().get("c").get(0), modifyC); - } - - if (result.getUpdatedPublishers().containsKey("d")) { - Assert.assertEquals(result.getUpdatedPublishers().get("d").size(), 1); - Assert.assertEquals(result.getUpdatedPublishers().get("d").get(0), addD); - } - DataSlotDiffUtils.logDiffResult(result, 10); - + if (result.getUpdatedPublishers().containsKey("d")) { + Assert.assertEquals(result.getUpdatedPublishers().get("d").size(), 1); + Assert.assertEquals(result.getUpdatedPublishers().get("d").get(0), addD); } - - private static void checkAddedPublisher(Map> publishers, - DataSlotDiffPublisherResult result) { - for (Map.Entry> e : result.getUpdatedPublishers().entrySet()) { - Map publisherMap = publishers.get(e.getKey()); - Assert.assertEquals(publisherMap.size(), e.getValue().size()); - for (Publisher p : e.getValue()) { - Assert.assertTrue(p == publisherMap.get(p.getRegisterId())); - } - } + DataSlotDiffUtils.logDiffResult(result, 10); + } + + private static void checkAddedPublisher( + Map> publishers, DataSlotDiffPublisherResult result) { + for (Map.Entry> e : result.getUpdatedPublishers().entrySet()) { + Map publisherMap = publishers.get(e.getKey()); + Assert.assertEquals(publisherMap.size(), e.getValue().size()); + for (Publisher p : e.getValue()) { + Assert.assertTrue(p == publisherMap.get(p.getRegisterId())); + } } - - private static void checkUpdatedSize(Map m, DataSlotDiffPublisherResult result) { - for (Map.Entry e : m.entrySet()) { - List publisherList = result.getUpdatedPublishers().get(e.getKey()); - if (publisherList != null) { - Assert.assertEquals(e.getValue().intValue(), publisherList.size()); - } - } + } + + private static void checkUpdatedSize(Map m, DataSlotDiffPublisherResult result) { + for (Map.Entry e : m.entrySet()) { + List publisherList = result.getUpdatedPublishers().get(e.getKey()); + if (publisherList != null) { + Assert.assertEquals(e.getValue().intValue(), publisherList.size()); + } } - - private static Publisher randPublisher() { - Publisher p = new Publisher(); - p.setRegisterTimestamp(System.nanoTime()); - p.setRegisterId(System.currentTimeMillis() + "_" + SEQ.incrementAndGet()); - p.setVersion(1L); - return p; - } - - private static Map> randPublishers(Map publishers) { - Map> m = Maps.newHashMap(); - publishers.forEach((k, i) -> { - Map publisherMap = Maps.newHashMap(); - for (int j = 0; j < i; j++) { - Publisher p = randPublisher(); - publisherMap.put(p.getRegisterId(), p); - } - m.put(k, publisherMap); + } + + private static Publisher randPublisher() { + Publisher p = new Publisher(); + p.setRegisterTimestamp(System.nanoTime()); + p.setRegisterId(System.currentTimeMillis() + "_" + SEQ.incrementAndGet()); + p.setVersion(1L); + return p; + } + + private static Map> randPublishers( + Map publishers) { + Map> m = Maps.newHashMap(); + publishers.forEach( + (k, i) -> { + Map publisherMap = Maps.newHashMap(); + for (int j = 0; j < i; j++) { + Publisher p = randPublisher(); + publisherMap.put(p.getRegisterId(), p); + } + m.put(k, publisherMap); }); - return m; - } + return m; + } } diff --git a/server/common/model/src/test/java/com/alipay/sofa/registry/common/model/store/SubTest.java b/server/common/model/src/test/java/com/alipay/sofa/registry/common/model/store/SubTest.java index 56b38082a..027d92b44 100644 --- a/server/common/model/src/test/java/com/alipay/sofa/registry/common/model/store/SubTest.java +++ b/server/common/model/src/test/java/com/alipay/sofa/registry/common/model/store/SubTest.java @@ -17,8 +17,6 @@ package com.alipay.sofa.registry.common.model.store; import com.google.common.collect.Maps; - -import java.util.Collections; import java.util.Map; /** @@ -27,40 +25,40 @@ */ public class SubTest { - static final int count = 500; - static final int tests = 1000000; - static final String dataCenter = "abcdefgaaaaaaa"; - static final int ver = 0; + static final int count = 500; + static final int tests = 1000000; + static final String dataCenter = "abcdefgaaaaaaa"; + static final int ver = 0; - public static void main(String[] args) { - Map subs = Maps.newConcurrentMap(); - initMap(subs, count); - for (int i = 0; i < tests; i++) { - test1(subs, dataCenter, ver); - } - long start = System.currentTimeMillis(); - for (int i = 0; i < tests; i++) { - test1(subs, dataCenter, ver); - } - long end = System.currentTimeMillis(); - System.out.println("@@" + (end - start)); + public static void main(String[] args) { + Map subs = Maps.newConcurrentMap(); + initMap(subs, count); + for (int i = 0; i < tests; i++) { + test1(subs, dataCenter, ver); + } + long start = System.currentTimeMillis(); + for (int i = 0; i < tests; i++) { + test1(subs, dataCenter, ver); } + long end = System.currentTimeMillis(); + System.out.println("@@" + (end - start)); + } - private static boolean test1(Map map, String dataCenter, long ver) { - for (Subscriber s : map.values()) { - if (s.checkVersion(dataCenter, ver)) { - return true; - } - } - return false; + private static boolean test1(Map map, String dataCenter, long ver) { + for (Subscriber s : map.values()) { + if (s.checkVersion(dataCenter, ver)) { + return true; + } } + return false; + } - private static void initMap(Map map, int count) { - String key = String.valueOf(System.currentTimeMillis()); - for (int i = 0; i < count; i++) { - Subscriber sub = new Subscriber(); - sub.checkVersion(dataCenter, 10L); - map.put(key + "_" + i, sub); - } + private static void initMap(Map map, int count) { + String key = String.valueOf(System.currentTimeMillis()); + for (int i = 0; i < count; i++) { + Subscriber sub = new Subscriber(); + sub.checkVersion(dataCenter, 10L); + map.put(key + "_" + i, sub); } + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/converter/ScopeEnumConverter.java b/server/common/util/src/main/java/com/alipay/sofa/registry/converter/ScopeEnumConverter.java index 07bea1e1f..8e2b73bd4 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/converter/ScopeEnumConverter.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/converter/ScopeEnumConverter.java @@ -19,23 +19,21 @@ import com.alipay.sofa.registry.core.model.ScopeEnum; /** - * * @author zhuoyu.sjw - * @version $Id: ScopeEnumConverter.java, v 0.1 2018-03-01 21:08 zhuoyu.sjw Exp - * $$ + * @version $Id: ScopeEnumConverter.java, v 0.1 2018-03-01 21:08 zhuoyu.sjw Exp $$ */ public class ScopeEnumConverter { - /** - * scope convert func - * - * @param name - * @return - */ - public static ScopeEnum convertToScope(String name) { - if (ScopeEnum.contains(name)) { - return ScopeEnum.valueOf(name); - } - return ScopeEnum.zone; - } + /** + * scope convert func + * + * @param name + * @return + */ + public static ScopeEnum convertToScope(String name) { + if (ScopeEnum.contains(name)) { + return ScopeEnum.valueOf(name); + } + return ScopeEnum.zone; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/datacenter/DataCenterAware.java b/server/common/util/src/main/java/com/alipay/sofa/registry/datacenter/DataCenterAware.java index c594bbc0e..b96fefe86 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/datacenter/DataCenterAware.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/datacenter/DataCenterAware.java @@ -18,9 +18,8 @@ /** * @author chen.zhu - *

- * Nov 19, 2020 + *

Nov 19, 2020 */ public interface DataCenterAware { - String getDc(); + String getDc(); } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/DisposeException.java b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/DisposeException.java index 86b742d4a..d9ed8e4a5 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/DisposeException.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/DisposeException.java @@ -18,19 +18,18 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public class DisposeException extends SofaRegistryException { - public DisposeException(String message) { - super(message); - } + public DisposeException(String message) { + super(message); + } - public DisposeException(String message, Throwable th) { - super(message, th); - } + public DisposeException(String message, Throwable th) { + super(message, th); + } - public DisposeException(Throwable th) { - super(th); - } + public DisposeException(Throwable th) { + super(th); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/InitializeException.java b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/InitializeException.java index 584fc061e..eb0a9a833 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/InitializeException.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/InitializeException.java @@ -18,20 +18,19 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public class InitializeException extends SofaRegistryException { - public InitializeException(String message) { - super(message); - } + public InitializeException(String message) { + super(message); + } - public InitializeException(String message, Throwable th) { - super(message, th); - } + public InitializeException(String message, Throwable th) { + super(message, th); + } - public InitializeException(Throwable th) { - super(th); - } + public InitializeException(Throwable th) { + super(th); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryException.java b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryException.java index e22f04f1e..532ae0b7c 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryException.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryException.java @@ -18,22 +18,21 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public class SofaRegistryException extends Exception { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public SofaRegistryException(String message) { - super(message); - } + public SofaRegistryException(String message) { + super(message); + } - public SofaRegistryException(String message, Throwable th) { - super(message, th); - } + public SofaRegistryException(String message, Throwable th) { + super(message, th); + } - public SofaRegistryException(Throwable th) { - super(th); - } + public SofaRegistryException(Throwable th) { + super(th); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryIOException.java b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryIOException.java index 1ad67ec59..a8fe1b0a5 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryIOException.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryIOException.java @@ -18,19 +18,18 @@ /** * @author chen.zhu - *

- * Mar 05, 2021 + *

Mar 05, 2021 */ public class SofaRegistryIOException extends SofaRegistryException { - public SofaRegistryIOException(String message) { - super(message); - } + public SofaRegistryIOException(String message) { + super(message); + } - public SofaRegistryIOException(String message, Throwable th) { - super(message, th); - } + public SofaRegistryIOException(String message, Throwable th) { + super(message, th); + } - public SofaRegistryIOException(Throwable th) { - super(th); - } + public SofaRegistryIOException(Throwable th) { + super(th); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryMetaLeaderException.java b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryMetaLeaderException.java index eccf4368d..10166bd61 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryMetaLeaderException.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryMetaLeaderException.java @@ -18,43 +18,42 @@ /** * @author chen.zhu - *

- * Mar 09, 2021 + *

Mar 09, 2021 */ -public class SofaRegistryMetaLeaderException - extends - SofaRegistryRuntimeException { +public class SofaRegistryMetaLeaderException extends SofaRegistryRuntimeException { - private final String leader; + private final String leader; - private final long epoch; + private final long epoch; - public SofaRegistryMetaLeaderException(String leader, long epoch, - String message) { - super(message); - this.leader = leader; - this.epoch = epoch; - } + public SofaRegistryMetaLeaderException(String leader, long epoch, String message) { + super(message); + this.leader = leader; + this.epoch = epoch; + } - public SofaRegistryMetaLeaderException(String leader, long epoch, - String message, Throwable cause) { - super(message, cause); - this.leader = leader; - this.epoch = epoch; - } + public SofaRegistryMetaLeaderException( + String leader, long epoch, String message, Throwable cause) { + super(message, cause); + this.leader = leader; + this.epoch = epoch; + } - public SofaRegistryMetaLeaderException(String leader, long epoch, - Throwable cause) { - super(cause); - this.leader = leader; - this.epoch = epoch; - } + public SofaRegistryMetaLeaderException(String leader, long epoch, Throwable cause) { + super(cause); + this.leader = leader; + this.epoch = epoch; + } - public SofaRegistryMetaLeaderException(String leader, long epoch, - String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - this.leader = leader; - this.epoch = epoch; - } + public SofaRegistryMetaLeaderException( + String leader, + long epoch, + String message, + Throwable cause, + boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + this.leader = leader; + this.epoch = epoch; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryRaftException.java b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryRaftException.java index cdbe02e79..d962b5227 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryRaftException.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryRaftException.java @@ -18,25 +18,24 @@ /** * @author chen.zhu - *

- * Jan 06, 2021 + *

Jan 06, 2021 */ public class SofaRegistryRaftException extends SofaRegistryRuntimeException { - public SofaRegistryRaftException(String message) { - super(message); - } + public SofaRegistryRaftException(String message) { + super(message); + } - public SofaRegistryRaftException(String message, Throwable cause) { - super(message, cause); - } + public SofaRegistryRaftException(String message, Throwable cause) { + super(message, cause); + } - public SofaRegistryRaftException(Throwable cause) { - super(cause); - } + public SofaRegistryRaftException(Throwable cause) { + super(cause); + } - public SofaRegistryRaftException(String message, Throwable cause, - boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + public SofaRegistryRaftException( + String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryRuntimeException.java b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryRuntimeException.java index c86cb06b1..20632d545 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryRuntimeException.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistryRuntimeException.java @@ -18,25 +18,24 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public class SofaRegistryRuntimeException extends RuntimeException { - public SofaRegistryRuntimeException(String message) { - super(message); - } + public SofaRegistryRuntimeException(String message) { + super(message); + } - public SofaRegistryRuntimeException(String message, Throwable cause) { - super(message, cause); - } + public SofaRegistryRuntimeException(String message, Throwable cause) { + super(message, cause); + } - public SofaRegistryRuntimeException(Throwable cause) { - super(cause); - } + public SofaRegistryRuntimeException(Throwable cause) { + super(cause); + } - public SofaRegistryRuntimeException(String message, Throwable cause, - boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + public SofaRegistryRuntimeException( + String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistrySlotTableException.java b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistrySlotTableException.java index 33f14b085..a8589a8d5 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistrySlotTableException.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/SofaRegistrySlotTableException.java @@ -18,26 +18,23 @@ /** * @author chen.zhu - *

- * Jan 26, 2021 + *

Jan 26, 2021 */ -public class SofaRegistrySlotTableException - extends - SofaRegistryRuntimeException { - public SofaRegistrySlotTableException(String message) { - super(message); - } +public class SofaRegistrySlotTableException extends SofaRegistryRuntimeException { + public SofaRegistrySlotTableException(String message) { + super(message); + } - public SofaRegistrySlotTableException(String message, Throwable cause) { - super(message, cause); - } + public SofaRegistrySlotTableException(String message, Throwable cause) { + super(message, cause); + } - public SofaRegistrySlotTableException(Throwable cause) { - super(cause); - } + public SofaRegistrySlotTableException(Throwable cause) { + super(cause); + } - public SofaRegistrySlotTableException(String message, Throwable cause, - boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + public SofaRegistrySlotTableException( + String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/StartException.java b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/StartException.java index 88920e84e..097ba4645 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/StartException.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/StartException.java @@ -18,20 +18,19 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public class StartException extends SofaRegistryException { - public StartException(String message) { - super(message); - } + public StartException(String message) { + super(message); + } - public StartException(String message, Throwable th) { - super(message, th); - } + public StartException(String message, Throwable th) { + super(message, th); + } - public StartException(Throwable th) { - super(th); - } + public StartException(Throwable th) { + super(th); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/StopException.java b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/StopException.java index 0feb22aa2..9d0ca33ed 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/exception/StopException.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/exception/StopException.java @@ -18,19 +18,18 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public class StopException extends SofaRegistryException { - public StopException(String message) { - super(message); - } + public StopException(String message) { + super(message); + } - public StopException(String message, Throwable th) { - super(message, th); - } + public StopException(String message, Throwable th) { + super(message, th); + } - public StopException(Throwable th) { - super(th); - } + public StopException(Throwable th) { + super(th); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Disposable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Disposable.java index acbcb1e65..3597ce5f3 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Disposable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Disposable.java @@ -20,14 +20,13 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public interface Disposable { - public static final String PHASE_NAME_BEGIN = "disposing"; + public static final String PHASE_NAME_BEGIN = "disposing"; - public static final String PHASE_NAME_END = "disposed"; + public static final String PHASE_NAME_END = "disposed"; - void dispose() throws DisposeException; + void dispose() throws DisposeException; } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Initializable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Initializable.java index a449f59de..afbe5cd03 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Initializable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Initializable.java @@ -20,14 +20,13 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public interface Initializable { - public static final String PHASE_NAME_BEGIN = "initializing"; + public static final String PHASE_NAME_BEGIN = "initializing"; - public static final String PHASE_NAME_END = "initialized"; + public static final String PHASE_NAME_END = "initialized"; - void initialize() throws InitializeException; + void initialize() throws InitializeException; } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Lifecycle.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Lifecycle.java index 8e1a40efe..01992a5d4 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Lifecycle.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Lifecycle.java @@ -18,14 +18,7 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public interface Lifecycle - extends - Initializable, - Startable, - Stoppable, - Disposable, - LifecycleStateAware { -} + extends Initializable, Startable, Stoppable, Disposable, LifecycleStateAware {} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleController.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleController.java index 4fcb5bd6c..caf7b0441 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleController.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleController.java @@ -18,16 +18,15 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public interface LifecycleController { - boolean canInitialize(LifecycleState.LifecyclePhase phase); + boolean canInitialize(LifecycleState.LifecyclePhase phase); - boolean canStart(LifecycleState.LifecyclePhase phase); + boolean canStart(LifecycleState.LifecyclePhase phase); - boolean canStop(LifecycleState.LifecyclePhase phase); + boolean canStop(LifecycleState.LifecyclePhase phase); - boolean canDispose(LifecycleState.LifecyclePhase phase); + boolean canDispose(LifecycleState.LifecyclePhase phase); } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleState.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleState.java index 940e69283..641304abc 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleState.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleState.java @@ -18,100 +18,97 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public interface LifecycleState { - boolean isEmpty(); - - boolean isInitializing(); - - boolean isInitialized(); - - boolean isStarting(); - - boolean isStarted(); - - boolean isStopping(); - - boolean isStopped(); - - boolean isPositivelyStopped(); - - boolean isDisposing(); - - boolean isDisposed(); - - boolean isPositivelyDisposed(); - - LifecyclePhase getPhase(); - - void setPhase(LifecyclePhase phase); - - /** - * rollback to previous state - */ - void rollback(Exception e); - - boolean canInitialize(); - - boolean canStart(); - - boolean canStop(); - - boolean canDispose(); - - enum LifecyclePhase { - INITIALIZING { - @Override - LifecyclePhase next() { - return INITIALIZED; - } - }, - INITIALIZED { - @Override - LifecyclePhase next() { - return STARTING; - } - }, - STARTING { - @Override - LifecyclePhase next() { - return STARTED; - } - }, - STARTED { - @Override - LifecyclePhase next() { - return STOPPING; - } - }, - STOPPING { - @Override - LifecyclePhase next() { - return STOPPED; - } - }, - STOPPED { - @Override - LifecyclePhase next() { - return DISPOSING; - } - }, - DISPOSING { - @Override - LifecyclePhase next() { - return DISPOSED; - } - }, - DISPOSED { - @Override - LifecyclePhase next() { - return INITIALIZING; - } - }; - - abstract LifecyclePhase next(); - } + boolean isEmpty(); + + boolean isInitializing(); + + boolean isInitialized(); + + boolean isStarting(); + + boolean isStarted(); + + boolean isStopping(); + + boolean isStopped(); + + boolean isPositivelyStopped(); + + boolean isDisposing(); + + boolean isDisposed(); + + boolean isPositivelyDisposed(); + + LifecyclePhase getPhase(); + + void setPhase(LifecyclePhase phase); + + /** rollback to previous state */ + void rollback(Exception e); + + boolean canInitialize(); + + boolean canStart(); + + boolean canStop(); + + boolean canDispose(); + + enum LifecyclePhase { + INITIALIZING { + @Override + LifecyclePhase next() { + return INITIALIZED; + } + }, + INITIALIZED { + @Override + LifecyclePhase next() { + return STARTING; + } + }, + STARTING { + @Override + LifecyclePhase next() { + return STARTED; + } + }, + STARTED { + @Override + LifecyclePhase next() { + return STOPPING; + } + }, + STOPPING { + @Override + LifecyclePhase next() { + return STOPPED; + } + }, + STOPPED { + @Override + LifecyclePhase next() { + return DISPOSING; + } + }, + DISPOSING { + @Override + LifecyclePhase next() { + return DISPOSED; + } + }, + DISPOSED { + @Override + LifecyclePhase next() { + return INITIALIZING; + } + }; + + abstract LifecyclePhase next(); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleStateAware.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleStateAware.java index 7bc963e40..7068f31c4 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleStateAware.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LifecycleStateAware.java @@ -18,10 +18,9 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public interface LifecycleStateAware { - LifecycleState getLifecycleState(); + LifecycleState getLifecycleState(); } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LiteLifecycle.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LiteLifecycle.java index fc78d6e2a..ca7e3c8b9 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LiteLifecycle.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/LiteLifecycle.java @@ -18,8 +18,6 @@ /** * @author chen.zhu - *

- * Nov 20, 2020 + *

Nov 20, 2020 */ -public interface LiteLifecycle extends Startable, Stoppable { -} +public interface LiteLifecycle extends Startable, Stoppable {} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/SmartSpringLifecycle.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/SmartSpringLifecycle.java index c0f69fb8b..053620503 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/SmartSpringLifecycle.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/SmartSpringLifecycle.java @@ -24,11 +24,9 @@ /** * @author zhuchen * @date Nov 24, 2020, 4:24:34 PM - * - * Annotation for whom install, an auto lifecycle start/end process - * will triggered through spring PostConstruct and PreDestroy + *

Annotation for whom install, an auto lifecycle start/end process will triggered through + * spring PostConstruct and PreDestroy */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) -public @interface SmartSpringLifecycle { -} +public @interface SmartSpringLifecycle {} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Startable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Startable.java index c876e3047..8dda02066 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Startable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Startable.java @@ -20,14 +20,13 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public interface Startable { - public static final String PHASE_NAME_BEGIN = "starting"; + public static final String PHASE_NAME_BEGIN = "starting"; - public static final String PHASE_NAME_END = "started"; + public static final String PHASE_NAME_END = "started"; - void start() throws StartException; + void start() throws StartException; } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Stoppable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Stoppable.java index da2c99513..3aed8506b 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Stoppable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Stoppable.java @@ -20,14 +20,13 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public interface Stoppable { - public static final String PHASE_NAME_BEGIN = "stopping"; + public static final String PHASE_NAME_BEGIN = "stopping"; - public static final String PHASE_NAME_END = "stopped"; + public static final String PHASE_NAME_END = "stopped"; - void stop() throws StopException; + void stop() throws StopException; } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Suspendable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Suspendable.java index a06d92930..bf367d788 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Suspendable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/Suspendable.java @@ -18,14 +18,13 @@ /** * @author chen.zhu - *

- * Mar 08, 2021 + *

Mar 08, 2021 */ public interface Suspendable { - void suspend(); + void suspend(); - void resume(); + void resume(); - boolean isSuspended(); + boolean isSuspended(); } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/AbstractLifecycle.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/AbstractLifecycle.java index f91218e0c..5ee2921b5 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/AbstractLifecycle.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/AbstractLifecycle.java @@ -26,111 +26,106 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public abstract class AbstractLifecycle implements Lifecycle, LifecycleStateAware { - protected Logger logger = LoggerFactory.getLogger(getClass()); + protected Logger logger = LoggerFactory.getLogger(getClass()); - private final LifecycleState lifecycleState; - private final LifecycleController lifecycleController; + private final LifecycleState lifecycleState; + private final LifecycleController lifecycleController; - public AbstractLifecycle() { - this.lifecycleController = new DefaultLifecycleController(); - this.lifecycleState = new DefaultLifecycleState(this, lifecycleController, logger); - } + public AbstractLifecycle() { + this.lifecycleController = new DefaultLifecycleController(); + this.lifecycleState = new DefaultLifecycleState(this, lifecycleController, logger); + } - public AbstractLifecycle(LifecycleState lifecycleState, LifecycleController lifecycleController) { - this.lifecycleState = lifecycleState; - this.lifecycleController = lifecycleController; - } + public AbstractLifecycle(LifecycleState lifecycleState, LifecycleController lifecycleController) { + this.lifecycleState = lifecycleState; + this.lifecycleController = lifecycleController; + } - @Override - public void initialize() throws InitializeException { - LifecycleState.LifecyclePhase phaseName = lifecycleState.getPhase(); - if (!lifecycleController.canInitialize(phaseName)) { - logger.error("[initialize][can not init]{}, {}", phaseName, this); - throw new IllegalStateException("can not initialize:" + phaseName + "," + this); - } - - try { - lifecycleState.setPhase(LifecycleState.LifecyclePhase.INITIALIZING); - doInitialize(); - lifecycleState.setPhase(LifecycleState.LifecyclePhase.INITIALIZED); - } catch (Exception e) { - lifecycleState.rollback(e); - throw new InitializeException(e); - } + @Override + public void initialize() throws InitializeException { + LifecycleState.LifecyclePhase phaseName = lifecycleState.getPhase(); + if (!lifecycleController.canInitialize(phaseName)) { + logger.error("[initialize][can not init]{}, {}", phaseName, this); + throw new IllegalStateException("can not initialize:" + phaseName + "," + this); } - protected void doInitialize() throws InitializeException { + try { + lifecycleState.setPhase(LifecycleState.LifecyclePhase.INITIALIZING); + doInitialize(); + lifecycleState.setPhase(LifecycleState.LifecyclePhase.INITIALIZED); + } catch (Exception e) { + lifecycleState.rollback(e); + throw new InitializeException(e); } + } - @Override - public void start() throws StartException { - LifecycleState.LifecyclePhase phaseName = lifecycleState.getPhase(); - if (!lifecycleController.canStart(phaseName)) { - logger.error("[initialize][can not start]{},{}", phaseName, this); - throw new IllegalStateException("can not start:" + phaseName + ", " + this); - } - - try { - lifecycleState.setPhase(LifecycleState.LifecyclePhase.STARTING); - doStart(); - lifecycleState.setPhase(LifecycleState.LifecyclePhase.STARTED); - } catch (Exception e) { - lifecycleState.rollback(e); - throw new StartException(e); - } - } + protected void doInitialize() throws InitializeException {} - protected void doStart() throws StartException { + @Override + public void start() throws StartException { + LifecycleState.LifecyclePhase phaseName = lifecycleState.getPhase(); + if (!lifecycleController.canStart(phaseName)) { + logger.error("[initialize][can not start]{},{}", phaseName, this); + throw new IllegalStateException("can not start:" + phaseName + ", " + this); } - @Override - public void stop() throws StopException { - LifecycleState.LifecyclePhase phaseName = lifecycleState.getPhase(); - if (!lifecycleController.canStop(phaseName)) { - logger.error("[initialize][can not stop]{}, {}", phaseName, this); - throw new IllegalStateException("can not stop:" + phaseName + "," + this); - } - - try { - lifecycleState.setPhase(LifecycleState.LifecyclePhase.STOPPING); - doStop(); - lifecycleState.setPhase(LifecycleState.LifecyclePhase.STOPPED); - } catch (Exception e) { - lifecycleState.rollback(e); - throw new StopException(e); - } + try { + lifecycleState.setPhase(LifecycleState.LifecyclePhase.STARTING); + doStart(); + lifecycleState.setPhase(LifecycleState.LifecyclePhase.STARTED); + } catch (Exception e) { + lifecycleState.rollback(e); + throw new StartException(e); } + } - protected void doStop() throws StopException { - } + protected void doStart() throws StartException {} - @Override - public void dispose() throws DisposeException { - LifecycleState.LifecyclePhase phaseName = lifecycleState.getPhase(); - if (!lifecycleController.canDispose(phaseName)) { - logger.error("[initialize][can not stop]{}, {}", phaseName, this); - throw new IllegalStateException("can not dispose:" + phaseName + "," + this); - } - try { - lifecycleState.setPhase(LifecycleState.LifecyclePhase.DISPOSING); - doDispose(); - lifecycleState.setPhase(LifecycleState.LifecyclePhase.DISPOSED); - } catch (Exception e) { - lifecycleState.rollback(e); - throw new DisposeException(e); - } + @Override + public void stop() throws StopException { + LifecycleState.LifecyclePhase phaseName = lifecycleState.getPhase(); + if (!lifecycleController.canStop(phaseName)) { + logger.error("[initialize][can not stop]{}, {}", phaseName, this); + throw new IllegalStateException("can not stop:" + phaseName + "," + this); } - protected void doDispose() throws DisposeException { + try { + lifecycleState.setPhase(LifecycleState.LifecyclePhase.STOPPING); + doStop(); + lifecycleState.setPhase(LifecycleState.LifecyclePhase.STOPPED); + } catch (Exception e) { + lifecycleState.rollback(e); + throw new StopException(e); } + } - @Override - public LifecycleState getLifecycleState() { - return this.lifecycleState; + protected void doStop() throws StopException {} + + @Override + public void dispose() throws DisposeException { + LifecycleState.LifecyclePhase phaseName = lifecycleState.getPhase(); + if (!lifecycleController.canDispose(phaseName)) { + logger.error("[initialize][can not stop]{}, {}", phaseName, this); + throw new IllegalStateException("can not dispose:" + phaseName + "," + this); + } + try { + lifecycleState.setPhase(LifecycleState.LifecyclePhase.DISPOSING); + doDispose(); + lifecycleState.setPhase(LifecycleState.LifecyclePhase.DISPOSED); + } catch (Exception e) { + lifecycleState.rollback(e); + throw new DisposeException(e); } + } + + protected void doDispose() throws DisposeException {} + + @Override + public LifecycleState getLifecycleState() { + return this.lifecycleState; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/AbstractLiteLifecycle.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/AbstractLiteLifecycle.java index cb37bcab0..daaa02733 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/AbstractLiteLifecycle.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/AbstractLiteLifecycle.java @@ -19,48 +19,46 @@ import com.alipay.sofa.registry.exception.StartException; import com.alipay.sofa.registry.exception.StopException; import com.alipay.sofa.registry.lifecycle.LiteLifecycle; +import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.util.concurrent.atomic.AtomicBoolean; - /** * @author chen.zhu - *

- * Nov 20, 2020 + *

Nov 20, 2020 */ public abstract class AbstractLiteLifecycle implements LiteLifecycle { - private AtomicBoolean isStarted = new AtomicBoolean(false); + private AtomicBoolean isStarted = new AtomicBoolean(false); - protected Logger logger = LoggerFactory.getLogger(getClass()); + protected Logger logger = LoggerFactory.getLogger(getClass()); - @Override - public void start() throws StartException { + @Override + public void start() throws StartException { - if (isStarted.compareAndSet(false, true)) { - logger.info("[start]{}", this); - doStart(); - } else { - logger.warn("[start][already started]"); - } + if (isStarted.compareAndSet(false, true)) { + logger.info("[start]{}", this); + doStart(); + } else { + logger.warn("[start][already started]"); } + } - protected abstract void doStart() throws StartException; + protected abstract void doStart() throws StartException; - @Override - public void stop() throws StopException { - if (isStarted.compareAndSet(true, false)) { - logger.info("[stop]{}", this); - doStop(); - } else { - logger.warn("[stop][already stopped]"); - } + @Override + public void stop() throws StopException { + if (isStarted.compareAndSet(true, false)) { + logger.info("[stop]{}", this); + doStop(); + } else { + logger.warn("[stop][already stopped]"); } + } - protected abstract void doStop() throws StopException; + protected abstract void doStop() throws StopException; - public boolean isStarted() { - return isStarted.get(); - } + public boolean isStarted() { + return isStarted.get(); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/DefaultLifecycleController.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/DefaultLifecycleController.java index b32c4184b..c2a2ea8c6 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/DefaultLifecycleController.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/DefaultLifecycleController.java @@ -20,36 +20,35 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public class DefaultLifecycleController implements LifecycleController { - @Override - public boolean canInitialize(LifecycleState.LifecyclePhase phase) { + @Override + public boolean canInitialize(LifecycleState.LifecyclePhase phase) { - return phase == null || phase.equals(LifecycleState.LifecyclePhase.DISPOSED); - } + return phase == null || phase.equals(LifecycleState.LifecyclePhase.DISPOSED); + } - @Override - public boolean canStart(LifecycleState.LifecyclePhase phase) { + @Override + public boolean canStart(LifecycleState.LifecyclePhase phase) { - return phase != null - && (phase.equals(LifecycleState.LifecyclePhase.INITIALIZED) || phase - .equals(LifecycleState.LifecyclePhase.STOPPED)); - } + return phase != null + && (phase.equals(LifecycleState.LifecyclePhase.INITIALIZED) + || phase.equals(LifecycleState.LifecyclePhase.STOPPED)); + } - @Override - public boolean canStop(LifecycleState.LifecyclePhase phase) { + @Override + public boolean canStop(LifecycleState.LifecyclePhase phase) { - return phase != null && (phase.equals(LifecycleState.LifecyclePhase.STARTED)); - } + return phase != null && (phase.equals(LifecycleState.LifecyclePhase.STARTED)); + } - @Override - public boolean canDispose(LifecycleState.LifecyclePhase phase) { + @Override + public boolean canDispose(LifecycleState.LifecyclePhase phase) { - return phase != null - && (phase.equals(LifecycleState.LifecyclePhase.INITIALIZED) || phase - .equals(LifecycleState.LifecyclePhase.STOPPED)); - } + return phase != null + && (phase.equals(LifecycleState.LifecyclePhase.INITIALIZED) + || phase.equals(LifecycleState.LifecyclePhase.STOPPED)); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/DefaultLifecycleState.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/DefaultLifecycleState.java index e126faf59..6784274a4 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/DefaultLifecycleState.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/DefaultLifecycleState.java @@ -19,177 +19,189 @@ import com.alipay.sofa.registry.lifecycle.*; import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; - import java.util.concurrent.atomic.AtomicReference; /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public class DefaultLifecycleState implements LifecycleState { - private final Logger logger; + private final Logger logger; - private AtomicReference phase = new AtomicReference<>(); + private AtomicReference phase = new AtomicReference<>(); - private AtomicReference previoisPhase = new AtomicReference<>(); + private AtomicReference previoisPhase = new AtomicReference<>(); - private Lifecycle lifecycle; + private Lifecycle lifecycle; - private LifecycleController lifecycleController; + private LifecycleController lifecycleController; - public DefaultLifecycleState(Lifecycle lifecycle, LifecycleController lifecycleController) { - this(lifecycle, lifecycleController, LoggerFactory.getLogger(lifecycle.getClass())); - } + public DefaultLifecycleState(Lifecycle lifecycle, LifecycleController lifecycleController) { + this(lifecycle, lifecycleController, LoggerFactory.getLogger(lifecycle.getClass())); + } - public DefaultLifecycleState(Lifecycle lifecycle, LifecycleController lifecycleController, - Logger logger) { - this.lifecycle = lifecycle; - this.lifecycleController = lifecycleController; - this.logger = logger; - } + public DefaultLifecycleState( + Lifecycle lifecycle, LifecycleController lifecycleController, Logger logger) { + this.lifecycle = lifecycle; + this.lifecycleController = lifecycleController; + this.logger = logger; + } - @Override - public boolean isEmpty() { - return phase.get() == null; - } + @Override + public boolean isEmpty() { + return phase.get() == null; + } - @Override - public boolean isInitializing() { + @Override + public boolean isInitializing() { - LifecyclePhase currentPhase = getPhase(); - return currentPhase != null && currentPhase.equals(LifecyclePhase.INITIALIZING); - } - - @Override - public boolean isInitialized() { + LifecyclePhase currentPhase = getPhase(); + return currentPhase != null && currentPhase.equals(LifecyclePhase.INITIALIZING); + } - LifecyclePhase currentPhase = getPhase(); - return phase != null - && phaseNameIn(currentPhase, LifecyclePhase.INITIALIZED, LifecyclePhase.STARTING, - LifecyclePhase.STARTED, LifecyclePhase.STOPPING, LifecyclePhase.STOPPED); - } - - @Override - public boolean isStarting() { - - LifecyclePhase currentPhase = getPhase(); - return currentPhase != null && currentPhase.equals(LifecyclePhase.STARTING); - } - - @Override - public boolean isStarted() { - - LifecyclePhase currentPhase = getPhase(); - return currentPhase == LifecyclePhase.STARTED; - } - - @Override - public boolean isStopping() { - - LifecyclePhase currentPhase = getPhase(); - return currentPhase == LifecyclePhase.STOPPING; - } - - @Override - public boolean isStopped() { - - LifecyclePhase phaseName = getPhase(); - return phaseName == null - || (phaseNameIn(phaseName, LifecyclePhase.INITIALIZED, LifecyclePhase.STOPPED, - LifecyclePhase.DISPOSING, LifecyclePhase.DISPOSED)); - } - - @Override - public boolean isPositivelyStopped() { - - LifecyclePhase phaseName = getPhase(); - return phaseName != null - && phaseNameIn(phaseName, LifecyclePhase.STOPPED, LifecyclePhase.DISPOSING, - LifecyclePhase.DISPOSED); - } - - private boolean phaseNameIn(LifecyclePhase phase, LifecyclePhase... ins) { - - for (LifecyclePhase in : ins) { - if (phase == in) { - return true; - } - } - return false; - } + @Override + public boolean isInitialized() { - @Override - public boolean isDisposing() { - - LifecyclePhase phaseName = getPhase(); - return phaseName == LifecyclePhase.DISPOSING; - } - - @Override - public boolean isDisposed() { - - LifecyclePhase phaseName = getPhase(); - return phaseName == null || phaseName == LifecyclePhase.DISPOSED; - } - - @Override - public boolean isPositivelyDisposed() { - - LifecyclePhase phaseName = getPhase(); - return phaseName != null && phaseNameIn(getPhase(), LifecyclePhase.DISPOSED); - } - - @Override - public LifecyclePhase getPhase() { - return phase.get(); - } - - @Override - public void setPhase(LifecyclePhase currentPhase) { - if (logger.isInfoEnabled()) { - logger.info("[setPhaseName]{}({}) --> {}", lifecycle, lifecycle.getClass() - .getSimpleName(), currentPhase); - } - previoisPhase.set(phase.get()); - phase.set(currentPhase); - } - - @Override - public String toString() { - return String.format("%s, %s", lifecycle.toString(), phase.get()); - } - - /** - * only support rollback once - */ - @Override - public void rollback(Exception e) { - if (logger.isInfoEnabled()) { - logger.info("[rollback]{},{} -> {}, reason:{}", this, phase.get(), previoisPhase.get(), - e.getMessage()); - } - phase.set(previoisPhase.get()); - } - - @Override - public boolean canInitialize() { - return lifecycleController.canInitialize(getPhase()); - } - - @Override - public boolean canStart() { - return lifecycleController.canStart(getPhase()); - } - - @Override - public boolean canStop() { - return lifecycleController.canStop(getPhase()); - } - - @Override - public boolean canDispose() { - return lifecycleController.canDispose(getPhase()); - } + LifecyclePhase currentPhase = getPhase(); + return phase != null + && phaseNameIn( + currentPhase, + LifecyclePhase.INITIALIZED, + LifecyclePhase.STARTING, + LifecyclePhase.STARTED, + LifecyclePhase.STOPPING, + LifecyclePhase.STOPPED); + } + + @Override + public boolean isStarting() { + + LifecyclePhase currentPhase = getPhase(); + return currentPhase != null && currentPhase.equals(LifecyclePhase.STARTING); + } + + @Override + public boolean isStarted() { + + LifecyclePhase currentPhase = getPhase(); + return currentPhase == LifecyclePhase.STARTED; + } + + @Override + public boolean isStopping() { + + LifecyclePhase currentPhase = getPhase(); + return currentPhase == LifecyclePhase.STOPPING; + } + + @Override + public boolean isStopped() { + + LifecyclePhase phaseName = getPhase(); + return phaseName == null + || (phaseNameIn( + phaseName, + LifecyclePhase.INITIALIZED, + LifecyclePhase.STOPPED, + LifecyclePhase.DISPOSING, + LifecyclePhase.DISPOSED)); + } + + @Override + public boolean isPositivelyStopped() { + + LifecyclePhase phaseName = getPhase(); + return phaseName != null + && phaseNameIn( + phaseName, LifecyclePhase.STOPPED, LifecyclePhase.DISPOSING, LifecyclePhase.DISPOSED); + } + + private boolean phaseNameIn(LifecyclePhase phase, LifecyclePhase... ins) { + + for (LifecyclePhase in : ins) { + if (phase == in) { + return true; + } + } + return false; + } + + @Override + public boolean isDisposing() { + + LifecyclePhase phaseName = getPhase(); + return phaseName == LifecyclePhase.DISPOSING; + } + + @Override + public boolean isDisposed() { + + LifecyclePhase phaseName = getPhase(); + return phaseName == null || phaseName == LifecyclePhase.DISPOSED; + } + + @Override + public boolean isPositivelyDisposed() { + + LifecyclePhase phaseName = getPhase(); + return phaseName != null && phaseNameIn(getPhase(), LifecyclePhase.DISPOSED); + } + + @Override + public LifecyclePhase getPhase() { + return phase.get(); + } + + @Override + public void setPhase(LifecyclePhase currentPhase) { + if (logger.isInfoEnabled()) { + logger.info( + "[setPhaseName]{}({}) --> {}", + lifecycle, + lifecycle.getClass().getSimpleName(), + currentPhase); + } + previoisPhase.set(phase.get()); + phase.set(currentPhase); + } + + @Override + public String toString() { + return String.format("%s, %s", lifecycle.toString(), phase.get()); + } + + /** only support rollback once */ + @Override + public void rollback(Exception e) { + if (logger.isInfoEnabled()) { + logger.info( + "[rollback]{},{} -> {}, reason:{}", + this, + phase.get(), + previoisPhase.get(), + e.getMessage()); + } + phase.set(previoisPhase.get()); + } + + @Override + public boolean canInitialize() { + return lifecycleController.canInitialize(getPhase()); + } + + @Override + public boolean canStart() { + return lifecycleController.canStart(getPhase()); + } + + @Override + public boolean canStop() { + return lifecycleController.canStop(getPhase()); + } + + @Override + public boolean canDispose() { + return lifecycleController.canDispose(getPhase()); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/LifecycleHelper.java b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/LifecycleHelper.java index 4cf79216d..51924f89e 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/LifecycleHelper.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/lifecycle/impl/LifecycleHelper.java @@ -24,42 +24,34 @@ /** * @author chen.zhu - *

- * Nov 20, 2020 + *

Nov 20, 2020 */ public class LifecycleHelper { - public static void initializeIfPossible(Object obj) - throws InitializeException { + public static void initializeIfPossible(Object obj) throws InitializeException { - if (obj instanceof Lifecycle - && ((Lifecycle) obj).getLifecycleState().canInitialize()) { - ((Lifecycle) obj).initialize(); - } + if (obj instanceof Lifecycle && ((Lifecycle) obj).getLifecycleState().canInitialize()) { + ((Lifecycle) obj).initialize(); + } + } - } + public static void startIfPossible(Object obj) throws StartException { - public static void startIfPossible(Object obj) throws StartException { + if (obj instanceof Lifecycle && ((Lifecycle) obj).getLifecycleState().canStart()) { + ((Lifecycle) obj).start(); + } + } - if (obj instanceof Lifecycle - && ((Lifecycle) obj).getLifecycleState().canStart()) { - ((Lifecycle) obj).start(); - } + public static void stopIfPossible(Object obj) throws StopException { - } + if (obj instanceof Lifecycle && ((Lifecycle) obj).getLifecycleState().canStop()) { + ((Lifecycle) obj).stop(); + } + } - public static void stopIfPossible(Object obj) throws StopException { - - if (obj instanceof Lifecycle - && ((Lifecycle) obj).getLifecycleState().canStop()) { - ((Lifecycle) obj).stop(); - } - } - - public static void disposeIfPossible(Object obj) throws DisposeException { - if (obj instanceof Lifecycle - && ((Lifecycle) obj).getLifecycleState().canDispose()) { - ((Lifecycle) obj).dispose(); - } - } + public static void disposeIfPossible(Object obj) throws DisposeException { + if (obj instanceof Lifecycle && ((Lifecycle) obj).getLifecycleState().canDispose()) { + ((Lifecycle) obj).dispose(); + } + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/log/Logger.java b/server/common/util/src/main/java/com/alipay/sofa/registry/log/Logger.java index ab15880c5..a5fd406c2 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/log/Logger.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/log/Logger.java @@ -17,233 +17,252 @@ package com.alipay.sofa.registry.log; /** - * import slf4j + * import slf4j * * @author shangyu.wh * @version $Id: Logger.java, v 0.1 2017-12-22 15:56 shangyu.wh Exp $ */ public interface Logger { - /** - * TRACE level - * - * @return - * - */ - boolean isTraceEnabled(); - - /** - * Log TRACE level - * - * @param msg - */ - void trace(String msg); - - /** - * Log TRACE level - * @param format - * @param arg - */ - void trace(String format, Object arg); - - /** - * Log TRACE level - * @param format - * @param arg1 - * @param arg2 - */ - void trace(String format, Object arg1, Object arg2); - - /** - * Log TRACE level - * @param format - * @param arguments - */ - void trace(String format, Object... arguments); - - /** - * Log TRACE level - * @param msg - * @param t - */ - void trace(String msg, Throwable t); - - /** - * DEBUG level - * - * @return - */ - boolean isDebugEnabled(); - - /** - * Log DEBUG level. - * - * @param msg - */ - void debug(String msg); - - /** - * Log DEBUG level. - * @param format - * @param arg - */ - void debug(String format, Object arg); - - /** - * Log DEBUG level. - * @param format - * @param arg1 - * @param arg2 - */ - void debug(String format, Object arg1, Object arg2); - - /** - * Log DEBUG level. - * @param format - * @param arguments - */ - void debug(String format, Object... arguments); - - /** - * Log DEBUG level. - * @param msg - * @param t - */ - void debug(String msg, Throwable t); - - /** - * INFO level - * - * @return True if this Logger is enabled for the INFO level, - * false otherwise. - */ - boolean isInfoEnabled(); - - /** - * Log INFO level. - * - * @param msg - */ - void info(String msg); - - /** - * Log INFO level. - * @param format - * @param arg - */ - void info(String format, Object arg); - - /** - * Log INFO level. - * @param format - * @param arg1 - * @param arg2 - */ - void info(String format, Object arg1, Object arg2); - - /** - * Log INFO level. - * @param format - * @param arguments - */ - void info(String format, Object... arguments); - - /** - * Log INFO level. - * @param msg - * @param t - */ - void info(String msg, Throwable t); - - /** - * WARN level - * - * @return - */ - boolean isWarnEnabled(); - - /** - * Log WARN level. - * @param msg - */ - void warn(String msg); - - /** - * Log WARN level. - * @param format - * @param arg - */ - void warn(String format, Object arg); - - /** - * Log WARN level. - * @param format - * @param arguments - */ - void warn(String format, Object... arguments); - - /** - * Log WARN level. - * @param format - * @param arg1 - * @param arg2 - */ - void warn(String format, Object arg1, Object arg2); - - /** - * Log WARN level. - * @param msg - * @param t - */ - void warn(String msg, Throwable t); - - /** - * ERROR level - * - * @return - */ - boolean isErrorEnabled(); - - /** - * Log ERROR level. - * - * @param msg the message string to be logged - */ - void error(String msg); - - /** - * Log ERROR level. - * @param format - * @param arg - */ - void error(String format, Object arg); - - /** - * Log ERROR level. - * @param format - * @param arg1 - * @param arg2 - */ - void error(String format, Object arg1, Object arg2); - - /** - * Log ERROR level. - * @param format - * @param arguments - */ - void error(String format, Object... arguments); - - /** - * Log ERROR level. - * @param msg - * @param t - */ - void error(String msg, Throwable t); - - /** - * get actually logger - * @return - */ - Object getLogger(); - -} \ No newline at end of file + /** + * TRACE level + * + * @return + */ + boolean isTraceEnabled(); + + /** + * Log TRACE level + * + * @param msg + */ + void trace(String msg); + + /** + * Log TRACE level + * + * @param format + * @param arg + */ + void trace(String format, Object arg); + + /** + * Log TRACE level + * + * @param format + * @param arg1 + * @param arg2 + */ + void trace(String format, Object arg1, Object arg2); + + /** + * Log TRACE level + * + * @param format + * @param arguments + */ + void trace(String format, Object... arguments); + + /** + * Log TRACE level + * + * @param msg + * @param t + */ + void trace(String msg, Throwable t); + + /** + * DEBUG level + * + * @return + */ + boolean isDebugEnabled(); + + /** + * Log DEBUG level. + * + * @param msg + */ + void debug(String msg); + + /** + * Log DEBUG level. + * + * @param format + * @param arg + */ + void debug(String format, Object arg); + + /** + * Log DEBUG level. + * + * @param format + * @param arg1 + * @param arg2 + */ + void debug(String format, Object arg1, Object arg2); + + /** + * Log DEBUG level. + * + * @param format + * @param arguments + */ + void debug(String format, Object... arguments); + + /** + * Log DEBUG level. + * + * @param msg + * @param t + */ + void debug(String msg, Throwable t); + + /** + * INFO level + * + * @return True if this Logger is enabled for the INFO level, false otherwise. + */ + boolean isInfoEnabled(); + + /** + * Log INFO level. + * + * @param msg + */ + void info(String msg); + + /** + * Log INFO level. + * + * @param format + * @param arg + */ + void info(String format, Object arg); + + /** + * Log INFO level. + * + * @param format + * @param arg1 + * @param arg2 + */ + void info(String format, Object arg1, Object arg2); + + /** + * Log INFO level. + * + * @param format + * @param arguments + */ + void info(String format, Object... arguments); + + /** + * Log INFO level. + * + * @param msg + * @param t + */ + void info(String msg, Throwable t); + + /** + * WARN level + * + * @return + */ + boolean isWarnEnabled(); + + /** + * Log WARN level. + * + * @param msg + */ + void warn(String msg); + + /** + * Log WARN level. + * + * @param format + * @param arg + */ + void warn(String format, Object arg); + + /** + * Log WARN level. + * + * @param format + * @param arguments + */ + void warn(String format, Object... arguments); + + /** + * Log WARN level. + * + * @param format + * @param arg1 + * @param arg2 + */ + void warn(String format, Object arg1, Object arg2); + + /** + * Log WARN level. + * + * @param msg + * @param t + */ + void warn(String msg, Throwable t); + + /** + * ERROR level + * + * @return + */ + boolean isErrorEnabled(); + + /** + * Log ERROR level. + * + * @param msg the message string to be logged + */ + void error(String msg); + + /** + * Log ERROR level. + * + * @param format + * @param arg + */ + void error(String format, Object arg); + + /** + * Log ERROR level. + * + * @param format + * @param arg1 + * @param arg2 + */ + void error(String format, Object arg1, Object arg2); + + /** + * Log ERROR level. + * + * @param format + * @param arguments + */ + void error(String format, Object... arguments); + + /** + * Log ERROR level. + * + * @param msg + * @param t + */ + void error(String msg, Throwable t); + + /** + * get actually logger + * + * @return + */ + Object getLogger(); +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/log/LoggerFactory.java b/server/common/util/src/main/java/com/alipay/sofa/registry/log/LoggerFactory.java index 878024dc4..dbef78494 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/log/LoggerFactory.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/log/LoggerFactory.java @@ -17,51 +17,50 @@ package com.alipay.sofa.registry.log; /** - * * @author shangyu.wh * @version $Id: LoggerFactory.java, v 0.1 2017-12-22 15:55 shangyu.wh Exp $ */ public class LoggerFactory { - /** - * get logger - * - * @param name - * @return - */ - public static Logger getLogger(String name) { - return new SLF4JLogger(name); - } + /** + * get logger + * + * @param name + * @return + */ + public static Logger getLogger(String name) { + return new SLF4JLogger(name); + } - /** - * get logger - * - * @param clazz - * @return - */ - public static Logger getLogger(Class clazz) { - return new SLF4JLogger(clazz); - } + /** + * get logger + * + * @param clazz + * @return + */ + public static Logger getLogger(Class clazz) { + return new SLF4JLogger(clazz); + } - /** - * get logger - * - * @param name - * @param prefix - * @return - */ - public static Logger getLogger(String name, String prefix) { - return new SLF4JLogger(name, prefix); - } + /** + * get logger + * + * @param name + * @param prefix + * @return + */ + public static Logger getLogger(String name, String prefix) { + return new SLF4JLogger(name, prefix); + } - /** - * get logger - * - * @param clazz - * @param prefix - * @return - */ - public static Logger getLogger(Class clazz, String prefix) { - return new SLF4JLogger(clazz, prefix); - } -} \ No newline at end of file + /** + * get logger + * + * @param clazz + * @param prefix + * @return + */ + public static Logger getLogger(Class clazz, String prefix) { + return new SLF4JLogger(clazz, prefix); + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/log/SLF4JLogger.java b/server/common/util/src/main/java/com/alipay/sofa/registry/log/SLF4JLogger.java index d402b574b..73930487e 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/log/SLF4JLogger.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/log/SLF4JLogger.java @@ -16,310 +16,302 @@ */ package com.alipay.sofa.registry.log; -import org.slf4j.LoggerFactory; - import java.io.File; import java.io.Serializable; +import org.slf4j.LoggerFactory; /** - * * @author shangyu.wh * @version $Id: SLF4JLogger.java, v 0.1 2017-12-22 16:04 shangyu.wh Exp $ */ public class SLF4JLogger implements Logger, Serializable { - private static final long serialVersionUID = 1L; - - private static final String LOG_PATH = "logging.path"; - private static final String LOG_PATH_DEFAULT = System.getProperty("user.home") - + File.separator + "logs"; - private static final String SERVER_LOG_LEVEL = "com.alipay.sofa.registry.server.log.level"; - private static final String SERVER_LOG_LEVEL_DEFAULT = "INFO"; - - private final String name; - - private final org.slf4j.Logger logger; - - private final String msgPrefix; - - /** symbol : */ - public static final char SPACE = ' '; - - static { - - String logPath = System.getProperty(LOG_PATH); - String logLevel = System.getProperty(SERVER_LOG_LEVEL); - if (logPath == null || logPath.isEmpty()) { - System.setProperty(LOG_PATH, LOG_PATH_DEFAULT); - } - if (logLevel == null || logLevel.isEmpty()) { - System.setProperty(SERVER_LOG_LEVEL, SERVER_LOG_LEVEL_DEFAULT); - } - + private static final long serialVersionUID = 1L; + + private static final String LOG_PATH = "logging.path"; + private static final String LOG_PATH_DEFAULT = + System.getProperty("user.home") + File.separator + "logs"; + private static final String SERVER_LOG_LEVEL = "com.alipay.sofa.registry.server.log.level"; + private static final String SERVER_LOG_LEVEL_DEFAULT = "INFO"; + + private final String name; + + private final org.slf4j.Logger logger; + + private final String msgPrefix; + + /** symbol : */ + public static final char SPACE = ' '; + + static { + String logPath = System.getProperty(LOG_PATH); + String logLevel = System.getProperty(SERVER_LOG_LEVEL); + if (logPath == null || logPath.isEmpty()) { + System.setProperty(LOG_PATH, LOG_PATH_DEFAULT); + } + if (logLevel == null || logLevel.isEmpty()) { + System.setProperty(SERVER_LOG_LEVEL, SERVER_LOG_LEVEL_DEFAULT); } - - /** - * @param name - */ - public SLF4JLogger(String name) { - this.name = name; - this.msgPrefix = ""; - this.logger = getLoggerBySpace(name); + } + + /** @param name */ + public SLF4JLogger(String name) { + this.name = name; + this.msgPrefix = ""; + this.logger = getLoggerBySpace(name); + } + + /** @param clazz */ + public SLF4JLogger(Class clazz) { + String loggerName = clazz.getCanonicalName(); + if (loggerName == null) { + loggerName = clazz.getName(); } + this.name = loggerName; + this.msgPrefix = ""; + this.logger = getLoggerBySpace(name); + } - /** - * @param clazz - */ - public SLF4JLogger(Class clazz) { - String loggerName = clazz.getCanonicalName(); - if (loggerName == null) { - loggerName = clazz.getName(); - } - this.name = loggerName; - this.msgPrefix = ""; - this.logger = getLoggerBySpace(name); - } + /** + * @param name + * @param msgPrefix + */ + public SLF4JLogger(String name, String msgPrefix) { + this.name = name; + this.msgPrefix = msgPrefix; + this.logger = getLoggerBySpace(name); + } - /** - * @param name - * @param msgPrefix - */ - public SLF4JLogger(String name, String msgPrefix) { - this.name = name; - this.msgPrefix = msgPrefix; - this.logger = getLoggerBySpace(name); - } + /** + * @param clazz + * @param msgPrefix + */ + public SLF4JLogger(Class clazz, String msgPrefix) { + this.name = clazz.getCanonicalName(); + this.msgPrefix = msgPrefix; + this.logger = getLoggerBySpace(name); + } - /** - * @param clazz - * @param msgPrefix - */ - public SLF4JLogger(Class clazz, String msgPrefix) { - this.name = clazz.getCanonicalName(); - this.msgPrefix = msgPrefix; - this.logger = getLoggerBySpace(name); + /** + * @param name + * @return + */ + public org.slf4j.Logger getLoggerBySpace(String name) { + if (name == null || name.isEmpty()) { + return null; } + return LoggerFactory.getLogger(name); + } - /** - * @param name - * @return - */ - public org.slf4j.Logger getLoggerBySpace(String name) { - if (name == null || name.isEmpty()) { - return null; - } - return LoggerFactory.getLogger(name); + @Override + public void trace(String msg) { + if (logger.isTraceEnabled()) { + logger.trace(processMsg(msg)); } + } - @Override - public void trace(String msg) { - if (logger.isTraceEnabled()) { - logger.trace(processMsg(msg)); - } + @Override + public void trace(String format, Object arg) { + if (logger.isTraceEnabled()) { + logger.trace(processMsg(format), arg); } + } - @Override - public void trace(String format, Object arg) { - if (logger.isTraceEnabled()) { - logger.trace(processMsg(format), arg); - } + @Override + public void trace(String format, Object arg1, Object arg2) { + if (logger.isTraceEnabled()) { + logger.trace(processMsg(format), arg1, arg2); } + } - @Override - public void trace(String format, Object arg1, Object arg2) { - if (logger.isTraceEnabled()) { - logger.trace(processMsg(format), arg1, arg2); - } + @Override + public void trace(String format, Object... arguments) { + if (logger.isTraceEnabled()) { + logger.trace(processMsg(format), arguments); } + } - @Override - public void trace(String format, Object... arguments) { - if (logger.isTraceEnabled()) { - logger.trace(processMsg(format), arguments); - } + @Override + public void trace(String msg, Throwable e) { + if (logger.isTraceEnabled()) { + logger.trace(processMsg(msg), e); } + } - @Override - public void trace(String msg, Throwable e) { - if (logger.isTraceEnabled()) { - logger.trace(processMsg(msg), e); - } + @Override + public void debug(String msg) { + if (logger.isDebugEnabled()) { + logger.debug(processMsg(msg)); } + } - @Override - public void debug(String msg) { - if (logger.isDebugEnabled()) { - logger.debug(processMsg(msg)); - } + @Override + public void debug(String format, Object arg) { + if (logger.isDebugEnabled()) { + logger.debug(processMsg(format), arg); } + } - @Override - public void debug(String format, Object arg) { - if (logger.isDebugEnabled()) { - logger.debug(processMsg(format), arg); - } + @Override + public void debug(String format, Object arg1, Object arg2) { + if (logger.isDebugEnabled()) { + logger.debug(processMsg(format), arg1, arg2); } + } - @Override - public void debug(String format, Object arg1, Object arg2) { - if (logger.isDebugEnabled()) { - logger.debug(processMsg(format), arg1, arg2); - } + @Override + public void debug(String format, Object... arguments) { + if (logger.isDebugEnabled()) { + logger.debug(processMsg(format), arguments); } + } - @Override - public void debug(String format, Object... arguments) { - if (logger.isDebugEnabled()) { - logger.debug(processMsg(format), arguments); - } + @Override + public void debug(String msg, Throwable e) { + if (logger.isDebugEnabled()) { + logger.debug(processMsg(msg), e); } + } - @Override - public void debug(String msg, Throwable e) { - if (logger.isDebugEnabled()) { - logger.debug(processMsg(msg), e); - } + @Override + public void info(String msg) { + if (logger.isInfoEnabled()) { + logger.info(processMsg(msg)); } + } - @Override - public void info(String msg) { - if (logger.isInfoEnabled()) { - logger.info(processMsg(msg)); - } + @Override + public void info(String format, Object arg) { + if (logger.isInfoEnabled()) { + logger.info(processMsg(format), arg); } + } - @Override - public void info(String format, Object arg) { - if (logger.isInfoEnabled()) { - logger.info(processMsg(format), arg); - } + @Override + public void info(String format, Object arg1, Object arg2) { + if (logger.isInfoEnabled()) { + logger.info(processMsg(format), arg1, arg2); } + } - @Override - public void info(String format, Object arg1, Object arg2) { - if (logger.isInfoEnabled()) { - logger.info(processMsg(format), arg1, arg2); - } + @Override + public void info(String format, Object... arguments) { + if (logger.isInfoEnabled()) { + logger.info(processMsg(format), arguments); } + } - @Override - public void info(String format, Object... arguments) { - if (logger.isInfoEnabled()) { - logger.info(processMsg(format), arguments); - } + @Override + public void info(String msg, Throwable e) { + if (logger.isInfoEnabled()) { + logger.info(processMsg(msg), e); } + } - @Override - public void info(String msg, Throwable e) { - if (logger.isInfoEnabled()) { - logger.info(processMsg(msg), e); - } + @Override + public void warn(String msg) { + if (logger.isWarnEnabled()) { + logger.warn(processMsg(msg)); } + } - @Override - public void warn(String msg) { - if (logger.isWarnEnabled()) { - logger.warn(processMsg(msg)); - } + @Override + public void warn(String format, Object arg) { + if (logger.isWarnEnabled()) { + logger.warn(processMsg(format), arg); } + } - @Override - public void warn(String format, Object arg) { - if (logger.isWarnEnabled()) { - logger.warn(processMsg(format), arg); - } + @Override + public void warn(String format, Object... arguments) { + if (logger.isWarnEnabled()) { + logger.warn(processMsg(format), arguments); } + } - @Override - public void warn(String format, Object... arguments) { - if (logger.isWarnEnabled()) { - logger.warn(processMsg(format), arguments); - } + @Override + public void warn(String format, Object arg1, Object arg2) { + if (logger.isWarnEnabled()) { + logger.warn(processMsg(format), arg1, arg2); } + } - @Override - public void warn(String format, Object arg1, Object arg2) { - if (logger.isWarnEnabled()) { - logger.warn(processMsg(format), arg1, arg2); - } + @Override + public void warn(String msg, Throwable e) { + if (logger.isWarnEnabled()) { + logger.warn(processMsg(msg), e); } + } - @Override - public void warn(String msg, Throwable e) { - if (logger.isWarnEnabled()) { - logger.warn(processMsg(msg), e); - } + @Override + public void error(String msg) { + if (logger.isErrorEnabled()) { + logger.error(processMsg(msg)); } + } - @Override - public void error(String msg) { - if (logger.isErrorEnabled()) { - logger.error(processMsg(msg)); - } + @Override + public void error(String format, Object arg) { + if (logger.isErrorEnabled()) { + logger.error(processMsg(format), arg); } + } - @Override - public void error(String format, Object arg) { - if (logger.isErrorEnabled()) { - logger.error(processMsg(format), arg); - } + @Override + public void error(String format, Object arg1, Object arg2) { + if (logger.isErrorEnabled()) { + logger.error(processMsg(format), arg1, arg2); } + } - @Override - public void error(String format, Object arg1, Object arg2) { - if (logger.isErrorEnabled()) { - logger.error(processMsg(format), arg1, arg2); - } + @Override + public void error(String format, Object... arguments) { + if (logger.isErrorEnabled()) { + logger.error(processMsg(format), arguments); } + } - @Override - public void error(String format, Object... arguments) { - if (logger.isErrorEnabled()) { - logger.error(processMsg(format), arguments); - } + @Override + public void error(String msg, Throwable e) { + if (logger.isErrorEnabled()) { + logger.error(processMsg(msg), e); } + } - @Override - public void error(String msg, Throwable e) { - if (logger.isErrorEnabled()) { - logger.error(processMsg(msg), e); - } - } + @Override + public boolean isTraceEnabled() { + return logger.isTraceEnabled(); + } - @Override - public boolean isTraceEnabled() { - return logger.isTraceEnabled(); - } + @Override + public boolean isDebugEnabled() { + return logger.isDebugEnabled(); + } - @Override - public boolean isDebugEnabled() { - return logger.isDebugEnabled(); - } + @Override + public boolean isInfoEnabled() { + return logger.isInfoEnabled(); + } - @Override - public boolean isInfoEnabled() { - return logger.isInfoEnabled(); - } + @Override + public boolean isWarnEnabled() { + return logger.isWarnEnabled(); + } - @Override - public boolean isWarnEnabled() { - return logger.isWarnEnabled(); - } + @Override + public boolean isErrorEnabled() { + return logger.isErrorEnabled(); + } - @Override - public boolean isErrorEnabled() { - return logger.isErrorEnabled(); + private String processMsg(String msg) { + if (msgPrefix.isEmpty()) { + return msg; } + return msgPrefix + SPACE + msg; + } - private String processMsg(String msg) { - if (msgPrefix.isEmpty()) { - return msg; - } - return msgPrefix + SPACE + msg; - } - - @Override - public Object getLogger() { - return logger; - } -} \ No newline at end of file + @Override + public Object getLogger() { + return logger; + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/metrics/ReporterUtils.java b/server/common/util/src/main/java/com/alipay/sofa/registry/metrics/ReporterUtils.java index 77b7af02f..14dfaea77 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/metrics/ReporterUtils.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/metrics/ReporterUtils.java @@ -23,56 +23,53 @@ import io.prometheus.client.CollectorRegistry; import io.prometheus.client.dropwizard.DropwizardExports; import io.prometheus.client.hotspot.DefaultExports; - import java.util.concurrent.TimeUnit; /** - * * @author shangyu.wh * @version $Id: ReporterUtils.java, v 0.1 2018-08-23 13:25 shangyu.wh Exp $ */ public class ReporterUtils { - private static final Logger METRIC_LOGGER = LoggerFactory - .getLogger("REGISTRY-METRICS"); - - /** - * start slf4j reporter - * - * @param period - * @param registry - * @param loggerMetrics - */ - public static void startSlf4jReporter(long period, MetricRegistry registry, - Logger loggerMetrics) { - Slf4jReporter reporter = Slf4jReporter.forRegistry(registry) - .outputTo((org.slf4j.Logger) loggerMetrics.getLogger()) - .convertRatesTo(TimeUnit.SECONDS) - .convertDurationsTo(TimeUnit.MILLISECONDS).build(); - if (period > 0) { - reporter.start(period, TimeUnit.SECONDS); - } else { - reporter.start(30, TimeUnit.SECONDS); - } + private static final Logger METRIC_LOGGER = LoggerFactory.getLogger("REGISTRY-METRICS"); - } + /** + * start slf4j reporter + * + * @param period + * @param registry + * @param loggerMetrics + */ + public static void startSlf4jReporter( + long period, MetricRegistry registry, Logger loggerMetrics) { + Slf4jReporter reporter = + Slf4jReporter.forRegistry(registry) + .outputTo((org.slf4j.Logger) loggerMetrics.getLogger()) + .convertRatesTo(TimeUnit.SECONDS) + .convertDurationsTo(TimeUnit.MILLISECONDS) + .build(); + if (period > 0) { + reporter.start(period, TimeUnit.SECONDS); + } else { + reporter.start(30, TimeUnit.SECONDS); + } + } - /** - * start slf4j reporter - * - * @param period - * @param registry - */ - public static void startSlf4jReporter(long period, MetricRegistry registry) { - startSlf4jReporter(period, registry, METRIC_LOGGER); - } + /** + * start slf4j reporter + * + * @param period + * @param registry + */ + public static void startSlf4jReporter(long period, MetricRegistry registry) { + startSlf4jReporter(period, registry, METRIC_LOGGER); + } - public static void enablePrometheusDefaultExports() { - DefaultExports.initialize(); - } + public static void enablePrometheusDefaultExports() { + DefaultExports.initialize(); + } - public static void registerPrometheusMetrics(MetricRegistry metrics) { - CollectorRegistry.defaultRegistry.register(new DropwizardExports( - metrics)); - } + public static void registerPrometheusMetrics(MetricRegistry metrics) { + CollectorRegistry.defaultRegistry.register(new DropwizardExports(metrics)); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/metrics/TaskMetrics.java b/server/common/util/src/main/java/com/alipay/sofa/registry/metrics/TaskMetrics.java index 43a6df3e0..78adca0db 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/metrics/TaskMetrics.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/metrics/TaskMetrics.java @@ -18,47 +18,45 @@ import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; - import java.util.concurrent.ThreadPoolExecutor; /** - * * @author shangyu.wh * @version $Id: ThreadMetrics.java, v 0.1 2018-11-18 15:19 shangyu.wh Exp $ */ public class TaskMetrics { - private final MetricRegistry metrics = new MetricRegistry(); - - private TaskMetrics() { - } + private final MetricRegistry metrics = new MetricRegistry(); - private final static TaskMetrics instance = new TaskMetrics(); + private TaskMetrics() {} - public static TaskMetrics getInstance() { - return instance; - } + private static final TaskMetrics instance = new TaskMetrics(); - public MetricRegistry getMetricRegistry() { - return this.metrics; - } + public static TaskMetrics getInstance() { + return instance; + } - public void registerThreadExecutor(String executorName, ThreadPoolExecutor executor) { + public MetricRegistry getMetricRegistry() { + return this.metrics; + } - metrics.register(MetricRegistry.name(executorName, "queue"), - (Gauge) () -> executor.getQueue().size()); + public void registerThreadExecutor(String executorName, ThreadPoolExecutor executor) { - metrics.register(MetricRegistry.name(executorName, "current"), - (Gauge) executor::getPoolSize); + metrics.register( + MetricRegistry.name(executorName, "queue"), + (Gauge) () -> executor.getQueue().size()); - metrics.register(MetricRegistry.name(executorName, "active"), - (Gauge) executor::getActiveCount); + metrics.register( + MetricRegistry.name(executorName, "current"), (Gauge) executor::getPoolSize); - metrics.register(MetricRegistry.name(executorName, "completed"), - (Gauge) executor::getCompletedTaskCount); + metrics.register( + MetricRegistry.name(executorName, "active"), (Gauge) executor::getActiveCount); - metrics.register(MetricRegistry.name(executorName, "task"), - (Gauge) executor::getTaskCount); + metrics.register( + MetricRegistry.name(executorName, "completed"), + (Gauge) executor::getCompletedTaskCount); - } -} \ No newline at end of file + metrics.register( + MetricRegistry.name(executorName, "task"), (Gauge) executor::getTaskCount); + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/net/NetUtil.java b/server/common/util/src/main/java/com/alipay/sofa/registry/net/NetUtil.java index 452e7bd2e..8dbcc6a75 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/net/NetUtil.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/net/NetUtil.java @@ -18,7 +18,6 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; - import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; @@ -31,187 +30,178 @@ /** * The type Net util. + * * @author shangyu.wh * @version $Id : NetUtil.java, v 0.1 2017-11-22 12:13 shangyu.wh Exp $ */ public class NetUtil { - private static final Logger LOGGER = LoggerFactory - .getLogger(NetUtil.class); - - /** - * The constant LOCALHOST. - */ - public static final String LOCALHOST = "127.0.0.1"; - - /** - * The constant ANYHOST. - */ - public static final String ANYHOST = "0.0.0.0"; - - /** symbol : */ - public static final char COLON = ':'; - - private static volatile InetAddress LOCAL_ADDRESS = null; - - private static final Pattern IP_PATTERN = Pattern - .compile("\\d{1,3}(\\.\\d{1,3}){3,5}$"); - - public static final String NETWORK_INTERFACE_BINDING = "network_interface_binding"; - public static final String NETWORK_INTERFACE_BINDING_VALUE = System - .getProperty(NETWORK_INTERFACE_BINDING); - public static final String NETWORK_INTERFACE_DENYLIST = "network_interface_denylist"; - public static final List NETWORK_INTERFACE_DENYLIST_VALUE = System - .getProperty(NETWORK_INTERFACE_DENYLIST) == null ? Collections - .emptyList() - : Arrays - .asList(System - .getProperty( - NETWORK_INTERFACE_DENYLIST) - .split(",")); - - /** - * Gen host string. - * - * @param ip the ip - * @param port the port - * @return the string - */ - public static String genHost(String ip, int port) { - return ip + COLON + port; - } - - /** - * Gets local socket address. - * - * @return the local socket address - */ - public static InetSocketAddress getLocalSocketAddress() { - InetAddress address = getLocalAddress(); - String addressStr = address == null ? LOCALHOST : address.getHostAddress(); - return new InetSocketAddress(addressStr, 0); - } - - /** - * Gets ip address from domain. - * - * @param domain the domain - * @return the ip address from domain - */ - public static String getIPAddressFromDomain(String domain) { - try { - InetAddress a = InetAddress.getByName(domain); - if (LOCALHOST.equalsIgnoreCase(a.getHostAddress())) { - a = getLocalAddress(); - } - return a.getHostAddress(); - } catch (UnknownHostException e) { - throw new RuntimeException("Unknown host {" + domain + "}", e); - } + private static final Logger LOGGER = LoggerFactory.getLogger(NetUtil.class); + + /** The constant LOCALHOST. */ + public static final String LOCALHOST = "127.0.0.1"; + + /** The constant ANYHOST. */ + public static final String ANYHOST = "0.0.0.0"; + + /** symbol : */ + public static final char COLON = ':'; + + private static volatile InetAddress LOCAL_ADDRESS = null; + + private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$"); + + public static final String NETWORK_INTERFACE_BINDING = "network_interface_binding"; + public static final String NETWORK_INTERFACE_BINDING_VALUE = + System.getProperty(NETWORK_INTERFACE_BINDING); + public static final String NETWORK_INTERFACE_DENYLIST = "network_interface_denylist"; + public static final List NETWORK_INTERFACE_DENYLIST_VALUE = + System.getProperty(NETWORK_INTERFACE_DENYLIST) == null + ? Collections.emptyList() + : Arrays.asList(System.getProperty(NETWORK_INTERFACE_DENYLIST).split(",")); + + /** + * Gen host string. + * + * @param ip the ip + * @param port the port + * @return the string + */ + public static String genHost(String ip, int port) { + return ip + COLON + port; + } + + /** + * Gets local socket address. + * + * @return the local socket address + */ + public static InetSocketAddress getLocalSocketAddress() { + InetAddress address = getLocalAddress(); + String addressStr = address == null ? LOCALHOST : address.getHostAddress(); + return new InetSocketAddress(addressStr, 0); + } + + /** + * Gets ip address from domain. + * + * @param domain the domain + * @return the ip address from domain + */ + public static String getIPAddressFromDomain(String domain) { + try { + InetAddress a = InetAddress.getByName(domain); + if (LOCALHOST.equalsIgnoreCase(a.getHostAddress())) { + a = getLocalAddress(); + } + return a.getHostAddress(); + } catch (UnknownHostException e) { + throw new RuntimeException("Unknown host {" + domain + "}", e); } - - /** - * - * @param ip - * @return String - */ - public static String getDomainFromIP(String ip) { - try { - InetAddress a = InetAddress.getByName(ip); - return a.getCanonicalHostName(); - } catch (UnknownHostException e) { - LOGGER.error("[NetWorkUtils] Can not resolve ip " + ip + ". error is .", e); - } - return null; + } + + /** + * @param ip + * @return String + */ + public static String getDomainFromIP(String ip) { + try { + InetAddress a = InetAddress.getByName(ip); + return a.getCanonicalHostName(); + } catch (UnknownHostException e) { + LOGGER.error("[NetWorkUtils] Can not resolve ip " + ip + ". error is .", e); } - - /** - * Gets local address. - * - * @return loccal IP all network card - */ - public static InetAddress getLocalAddress() { - if (LOCAL_ADDRESS != null) { - return LOCAL_ADDRESS; - } - InetAddress localAddress = getLocalAddress0(); - LOCAL_ADDRESS = localAddress; - return localAddress; + return null; + } + + /** + * Gets local address. + * + * @return loccal IP all network card + */ + public static InetAddress getLocalAddress() { + if (LOCAL_ADDRESS != null) { + return LOCAL_ADDRESS; } - - /** - * To address string string. - * - * @param address the address - * @return the string - */ - public static String toAddressString(InetSocketAddress address) { - if (address == null || address.getAddress() == null) { - LOGGER - .error("InetSocketAddress to Address String error!In put inetSocketAddress or InetSocketAddress.getAddress is null"); - throw new RuntimeException( - "InetSocketAddress to Address String error!In put inetSocketAddress or InetSocketAddress.getAddress is null!"); - } - return address.getAddress().getHostAddress() + COLON + address.getPort(); + InetAddress localAddress = getLocalAddress0(); + LOCAL_ADDRESS = localAddress; + return localAddress; + } + + /** + * To address string string. + * + * @param address the address + * @return the string + */ + public static String toAddressString(InetSocketAddress address) { + if (address == null || address.getAddress() == null) { + LOGGER.error( + "InetSocketAddress to Address String error!In put inetSocketAddress or InetSocketAddress.getAddress is null"); + throw new RuntimeException( + "InetSocketAddress to Address String error!In put inetSocketAddress or InetSocketAddress.getAddress is null!"); } + return address.getAddress().getHostAddress() + COLON + address.getPort(); + } - private static boolean isValidAddress(InetAddress address) { - if (address == null || address.isLoopbackAddress()) { - return false; - } - String name = address.getHostAddress(); - return (name != null && !ANYHOST.equals(name) && !LOCALHOST.equals(name) && IP_PATTERN - .matcher(name).matches()); + private static boolean isValidAddress(InetAddress address) { + if (address == null || address.isLoopbackAddress()) { + return false; } + String name = address.getHostAddress(); + return (name != null + && !ANYHOST.equals(name) + && !LOCALHOST.equals(name) + && IP_PATTERN.matcher(name).matches()); + } + + private static InetAddress getLocalAddress0() { + InetAddress localAddress = null; + try { + Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); + if (interfaces != null) { + while (interfaces.hasMoreElements()) { + try { + NetworkInterface network = interfaces.nextElement(); + boolean useNi; + if (NETWORK_INTERFACE_BINDING_VALUE != null + && !NETWORK_INTERFACE_BINDING_VALUE.isEmpty()) { + if (NETWORK_INTERFACE_BINDING_VALUE.equals(network.getDisplayName()) + || NETWORK_INTERFACE_BINDING_VALUE.equals(network.getName())) { + useNi = true; + } else { + continue; + } + } else { + if (NETWORK_INTERFACE_DENYLIST_VALUE.contains(network.getDisplayName()) + || NETWORK_INTERFACE_DENYLIST_VALUE.contains(network.getName())) { + continue; + } + useNi = true; + } - private static InetAddress getLocalAddress0() { - InetAddress localAddress = null; - try { - Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); - if (interfaces != null) { - while (interfaces.hasMoreElements()) { - try { - NetworkInterface network = interfaces.nextElement(); - boolean useNi; - if (NETWORK_INTERFACE_BINDING_VALUE != null - && !NETWORK_INTERFACE_BINDING_VALUE.isEmpty()) { - if (NETWORK_INTERFACE_BINDING_VALUE.equals(network.getDisplayName()) - || NETWORK_INTERFACE_BINDING_VALUE.equals(network.getName())) { - useNi = true; - } else { - continue; - } - } else { - if (NETWORK_INTERFACE_DENYLIST_VALUE.contains(network.getDisplayName()) - || NETWORK_INTERFACE_DENYLIST_VALUE.contains(network.getName())) { - continue; - } - useNi = true; - } - - Enumeration addresses = network.getInetAddresses(); - if (addresses != null) { - while (addresses.hasMoreElements()) { - try { - InetAddress address = addresses.nextElement(); - if (useNi && isValidAddress(address)) { - return address; - } - } catch (Throwable e) { - LOGGER.warn( - "Failed to retriving ip address, " + e.getMessage(), e); - } - } - } - } catch (Throwable e) { - LOGGER.warn("Failed to retriving ip address, " + e.getMessage(), e); - } + Enumeration addresses = network.getInetAddresses(); + if (addresses != null) { + while (addresses.hasMoreElements()) { + try { + InetAddress address = addresses.nextElement(); + if (useNi && isValidAddress(address)) { + return address; + } + } catch (Throwable e) { + LOGGER.warn("Failed to retriving ip address, " + e.getMessage(), e); } + } } - } catch (Throwable e) { + } catch (Throwable e) { LOGGER.warn("Failed to retriving ip address, " + e.getMessage(), e); + } } - LOGGER.error("Could not get local host ip address, will use 127.0.0.1 instead."); - return localAddress; + } + } catch (Throwable e) { + LOGGER.warn("Failed to retriving ip address, " + e.getMessage(), e); } -} \ No newline at end of file + LOGGER.error("Could not get local host ip address, will use 127.0.0.1 instead."); + return localAddress; + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/observer/Observable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/observer/Observable.java index 7a4077b86..bf32f001d 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/observer/Observable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/observer/Observable.java @@ -22,7 +22,7 @@ */ public interface Observable { - void addObserver(UnblockingObserver observer); + void addObserver(UnblockingObserver observer); - void removeObserver(UnblockingObserver observer); + void removeObserver(UnblockingObserver observer); } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/observer/UnblockingObserver.java b/server/common/util/src/main/java/com/alipay/sofa/registry/observer/UnblockingObserver.java index 33b10017f..5bce5de38 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/observer/UnblockingObserver.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/observer/UnblockingObserver.java @@ -22,5 +22,5 @@ */ public interface UnblockingObserver { - void update(Observable source, Object message); + void update(Observable source, Object message); } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/observer/impl/AbstractLifecycleObservable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/observer/impl/AbstractLifecycleObservable.java index c8ef227d0..1a588c6a1 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/observer/impl/AbstractLifecycleObservable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/observer/impl/AbstractLifecycleObservable.java @@ -22,45 +22,43 @@ import com.alipay.sofa.registry.lifecycle.impl.AbstractLifecycle; import com.alipay.sofa.registry.observer.Observable; import com.alipay.sofa.registry.observer.UnblockingObserver; - import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; /** * @author chen.zhu - *

- * Nov 25, 2020 + *

Nov 25, 2020 */ -public class AbstractLifecycleObservable extends AbstractLifecycle implements Observable, Lifecycle { - - private List observers = new CopyOnWriteArrayList<>(); +public class AbstractLifecycleObservable extends AbstractLifecycle + implements Observable, Lifecycle { - public AbstractLifecycleObservable() { - } + private List observers = new CopyOnWriteArrayList<>(); - public AbstractLifecycleObservable(LifecycleState lifecycleState, LifecycleController lifecycleController) { - super(lifecycleState, lifecycleController); - } + public AbstractLifecycleObservable() {} - @Override - public void addObserver(UnblockingObserver observer) { - observers.add(observer); - } + public AbstractLifecycleObservable( + LifecycleState lifecycleState, LifecycleController lifecycleController) { + super(lifecycleState, lifecycleController); + } - @Override - public void removeObserver(UnblockingObserver observer) { - observers.remove(observer); - } + @Override + public void addObserver(UnblockingObserver observer) { + observers.add(observer); + } - protected void notifyObservers(final Object message) { + @Override + public void removeObserver(UnblockingObserver observer) { + observers.remove(observer); + } - for (final Object observer : observers) { - try { - ((UnblockingObserver) observer).update(AbstractLifecycleObservable.this, message); - } catch (Exception e) { - logger.error("[notifyObservers][{}]", observer, e); - } + protected void notifyObservers(final Object message) { - } + for (final Object observer : observers) { + try { + ((UnblockingObserver) observer).update(AbstractLifecycleObservable.this, message); + } catch (Exception e) { + logger.error("[notifyObservers][{}]", observer, e); + } } + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/observer/impl/AbstractObservable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/observer/impl/AbstractObservable.java index 33c4f1c27..5ec685aa9 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/observer/impl/AbstractObservable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/observer/impl/AbstractObservable.java @@ -20,7 +20,6 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.observer.Observable; import com.alipay.sofa.registry.observer.UnblockingObserver; - import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -30,38 +29,36 @@ */ public abstract class AbstractObservable implements Observable { - protected Logger logger = LoggerFactory.getLogger(getClass()); - - private List observers = new CopyOnWriteArrayList<>(); + protected Logger logger = LoggerFactory.getLogger(getClass()); - public AbstractObservable() { - } + private List observers = new CopyOnWriteArrayList<>(); - public AbstractObservable setLogger(Logger logger) { - this.logger = logger; - return this; - } + public AbstractObservable() {} - @Override - public void addObserver(UnblockingObserver observer) { - observers.add(observer); - } + public AbstractObservable setLogger(Logger logger) { + this.logger = logger; + return this; + } - @Override - public void removeObserver(UnblockingObserver observer) { - observers.remove(observer); - } + @Override + public void addObserver(UnblockingObserver observer) { + observers.add(observer); + } - protected void notifyObservers(final Object message) { + @Override + public void removeObserver(UnblockingObserver observer) { + observers.remove(observer); + } - for (final Object observer : observers) { + protected void notifyObservers(final Object message) { - try { - ((UnblockingObserver) observer).update(AbstractObservable.this, message); - } catch (Exception e) { - logger.error("[notifyObservers][{}]", observer, e); - } + for (final Object observer : observers) { - } + try { + ((UnblockingObserver) observer).update(AbstractObservable.this, message); + } catch (Exception e) { + logger.error("[notifyObservers][{}]", observer, e); + } } + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/BlockingQueues.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/BlockingQueues.java index c940f39d9..a8d269e06 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/BlockingQueues.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/BlockingQueues.java @@ -21,64 +21,67 @@ import java.util.concurrent.LinkedBlockingQueue; public final class BlockingQueues { - private final BlockingQueue[] queues; - private final int avgQueueBufferSize; - private final int queueBufferSize; - private final int queueNum; + private final BlockingQueue[] queues; + private final int avgQueueBufferSize; + private final int queueBufferSize; + private final int queueNum; - public BlockingQueues(int queueNum, int queueBufferSize, boolean array) { - this.queueNum = queueNum; - this.queues = new BlockingQueue[queueNum]; - for (int i = 0; i < queueNum; i++) { - // safeguard: set the queue.capacity as queueSize - this.queues[i] = array ? new ArrayBlockingQueue<>(queueBufferSize) - : new LinkedBlockingQueue<>(queueBufferSize); - } - // at most, cache double req - this.avgQueueBufferSize = queueBufferSize / queueNum; - this.queueBufferSize = queueBufferSize; + public BlockingQueues(int queueNum, int queueBufferSize, boolean array) { + this.queueNum = queueNum; + this.queues = new BlockingQueue[queueNum]; + for (int i = 0; i < queueNum; i++) { + // safeguard: set the queue.capacity as queueSize + this.queues[i] = + array + ? new ArrayBlockingQueue<>(queueBufferSize) + : new LinkedBlockingQueue<>(queueBufferSize); } + // at most, cache double req + this.avgQueueBufferSize = queueBufferSize / queueNum; + this.queueBufferSize = queueBufferSize; + } - public boolean offer(int idx, T t) { - BlockingQueue q = queues[idx]; - if (q.size() <= avgQueueBufferSize) { - // not reach avg, add - return q.offer(t); - } else { - // reach avg, check total size - int totalSize = getTotalQueueSize(); - if (totalSize < queueBufferSize) { - return q.offer(t); - } - return false; - } + public boolean offer(int idx, T t) { + BlockingQueue q = queues[idx]; + if (q.size() <= avgQueueBufferSize) { + // not reach avg, add + return q.offer(t); + } else { + // reach avg, check total size + int totalSize = getTotalQueueSize(); + if (totalSize < queueBufferSize) { + return q.offer(t); + } + return false; } + } - public void put(int idx, T t) { - if (!offer(idx, t)) { - throw new FastRejectedExecutionException(String.format( - "BlockingQueues.put overflow, idx=%d, totalSize=%d, queueSize=%d", idx, - getTotalQueueSize(), queues[idx].size())); - } + public void put(int idx, T t) { + if (!offer(idx, t)) { + throw new FastRejectedExecutionException( + String.format( + "BlockingQueues.put overflow, idx=%d, totalSize=%d, queueSize=%d", + idx, getTotalQueueSize(), queues[idx].size())); } + } - public BlockingQueue[] getQueues() { - return queues.clone(); - } + public BlockingQueue[] getQueues() { + return queues.clone(); + } - public BlockingQueue getQueue(int idx) { - return queues[idx]; - } + public BlockingQueue getQueue(int idx) { + return queues[idx]; + } - public int queueNum() { - return queueNum; - } + public int queueNum() { + return queueNum; + } - public int getTotalQueueSize() { - int count = 0; - for (BlockingQueue q : queues) { - count += q.size(); - } - return count; + public int getTotalQueueSize() { + int count = 0; + for (BlockingQueue q : queues) { + count += q.size(); } + return count; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/FastRejectedExecutionException.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/FastRejectedExecutionException.java index 589044eeb..f3306eaf8 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/FastRejectedExecutionException.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/FastRejectedExecutionException.java @@ -19,14 +19,13 @@ import java.util.concurrent.RejectedExecutionException; public class FastRejectedExecutionException extends RejectedExecutionException { - public FastRejectedExecutionException(String message) { - super(message); - } - - @Override - public Throwable fillInStackTrace() { - // not fill the stack trace - return this; - } + public FastRejectedExecutionException(String message) { + super(message); + } + @Override + public Throwable fillInStackTrace() { + // not fill the stack trace + return this; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedPreemptThreadPoolExecutor.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedPreemptThreadPoolExecutor.java index 34fa6521c..cfb7223ca 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedPreemptThreadPoolExecutor.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedPreemptThreadPoolExecutor.java @@ -26,97 +26,97 @@ import java.util.concurrent.locks.ReentrantLock; public class KeyedPreemptThreadPoolExecutor extends KeyedThreadPoolExecutor { - private final Comparator comparator; + private final Comparator comparator; - public KeyedPreemptThreadPoolExecutor(String executorName, int coreSize, int coreBufferSize, - Comparator comparator) { - super(executorName, coreSize, coreBufferSize); - this.comparator = comparator; - } + public KeyedPreemptThreadPoolExecutor( + String executorName, + int coreSize, + int coreBufferSize, + Comparator comparator) { + super(executorName, coreSize, coreBufferSize); + this.comparator = comparator; + } - @Override - protected AbstractWorker[] createWorkers(int coreSize, int coreBufferSize) { - AbstractWorker[] workers = new AbstractWorker[coreSize]; - for (int i = 0; i < coreSize; i++) { - AbstractWorker w = new WorkerImpl(i, coreBufferSize / coreSize); - workers[i] = w; - } - return workers; + @Override + protected AbstractWorker[] createWorkers(int coreSize, int coreBufferSize) { + AbstractWorker[] workers = new AbstractWorker[coreSize]; + for (int i = 0; i < coreSize; i++) { + AbstractWorker w = new WorkerImpl(i, coreBufferSize / coreSize); + workers[i] = w; } + return workers; + } - private final class WorkerImpl extends AbstractWorker { - final Map map = new HashMap<>(128); - final LinkedList keysQueue; - final Lock lock = new ReentrantLock(); - final Condition cond = lock.newCondition(); - final int queueSize; + private final class WorkerImpl extends AbstractWorker { + final Map map = new HashMap<>(128); + final LinkedList keysQueue; + final Lock lock = new ReentrantLock(); + final Condition cond = lock.newCondition(); + final int queueSize; - WorkerImpl(int idx, int queueSize) { - super(idx); - this.queueSize = queueSize; - this.keysQueue = new LinkedList<>(); - } + WorkerImpl(int idx, int queueSize) { + super(idx); + this.queueSize = queueSize; + this.keysQueue = new LinkedList<>(); + } - public int size() { - lock.lock(); - try { - return keysQueue.size(); - } finally { - lock.unlock(); - } + public int size() { + lock.lock(); + try { + return keysQueue.size(); + } finally { + lock.unlock(); + } + } + public KeyedTask poll() throws InterruptedException { + // get the key, + lock.lock(); + try { + if (keysQueue.isEmpty()) { + cond.await(180, TimeUnit.SECONDS); } - - public KeyedTask poll() throws InterruptedException { - // get the key, - lock.lock(); - try { - if (keysQueue.isEmpty()) { - cond.await(180, TimeUnit.SECONDS); - } - final Object key = keysQueue.poll(); - if (key == null) { - return null; - } - KeyedTask task = map.remove(key); - return task; - } finally { - lock.unlock(); - } + final Object key = keysQueue.poll(); + if (key == null) { + return null; } + KeyedTask task = map.remove(key); + return task; + } finally { + lock.unlock(); + } + } - public boolean offer(KeyedTask task) { - if (size() >= queueSize && getQueueSize() >= coreBufferSize) { - // reach avg and total size, is full - return false; - } - final Comparator c = (Comparator) comparator; - lock.lock(); - try { - final KeyedTask prev = map.get(task.key); - if (prev != null) { - int comp = c.compare(prev.runnable, task.runnable); - if (comp >= 0) { - // the prev is high priority than current, ignored - return true; - } - } else { - // try add to keys queue to poll - if (!keysQueue.offer(task.key)) { - // queue is full - return false; - } - } - // at last, overwrite the prev or insert the current - // promise that: if map.task exist, the queue.key must be exist - map.put(task.key, task); - cond.signal(); - return true; - } finally { - lock.unlock(); - } + public boolean offer(KeyedTask task) { + if (size() >= queueSize && getQueueSize() >= coreBufferSize) { + // reach avg and total size, is full + return false; + } + final Comparator c = (Comparator) comparator; + lock.lock(); + try { + final KeyedTask prev = map.get(task.key); + if (prev != null) { + int comp = c.compare(prev.runnable, task.runnable); + if (comp >= 0) { + // the prev is high priority than current, ignored + return true; + } + } else { + // try add to keys queue to poll + if (!keysQueue.offer(task.key)) { + // queue is full + return false; + } } - + // at last, overwrite the prev or insert the current + // promise that: if map.task exist, the queue.key must be exist + map.put(task.key, task); + cond.signal(); + return true; + } finally { + lock.unlock(); + } } - + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedTask.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedTask.java index f3af26ec7..1a7e33e20 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedTask.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedTask.java @@ -20,83 +20,96 @@ import com.alipay.sofa.registry.log.LoggerFactory; public class KeyedTask implements Runnable { - private static final Logger LOGGER = LoggerFactory.getLogger(KeyedTask.class); - final long createTime = System.currentTimeMillis(); - final Object key; - final T runnable; - - volatile long startTime; - volatile long endTime; - volatile boolean success; - volatile boolean canceled; - - KeyedTask(Object key, T runnable) { - this.key = key; - this.runnable = runnable; + private static final Logger LOGGER = LoggerFactory.getLogger(KeyedTask.class); + final long createTime = System.currentTimeMillis(); + final Object key; + final T runnable; + + volatile long startTime; + volatile long endTime; + volatile boolean success; + volatile boolean canceled; + + KeyedTask(Object key, T runnable) { + this.key = key; + this.runnable = runnable; + } + + public void cancel() { + this.canceled = true; + } + + @Override + public void run() { + try { + this.startTime = System.currentTimeMillis(); + if (!canceled) { + runnable.run(); + } + this.success = true; + } catch (Throwable e) { + LOGGER.error("failed to run task {}, {}", key, runnable, e); + } finally { + this.endTime = System.currentTimeMillis(); } + } - public void cancel() { - this.canceled = true; - } - - @Override - public void run() { - try { - this.startTime = System.currentTimeMillis(); - if (!canceled) { - runnable.run(); - } - this.success = true; - } catch (Throwable e) { - LOGGER.error("failed to run task {}, {}", key, runnable, e); - } finally { - this.endTime = System.currentTimeMillis(); - } - } - - public boolean isFinished() { - return this.endTime > 0; - } - - public boolean isSuccess() { - return isFinished() && success; - } + public boolean isFinished() { + return this.endTime > 0; + } - public boolean isFailed() { - return isFinished() && !success; - } + public boolean isSuccess() { + return isFinished() && success; + } - public long getCreateTime() { - return createTime; - } + public boolean isFailed() { + return isFinished() && !success; + } - public long getStartTime() { - return startTime; - } + public long getCreateTime() { + return createTime; + } - public long getEndTime() { - return endTime; - } + public long getStartTime() { + return startTime; + } - public Object key() { - return key; - } + public long getEndTime() { + return endTime; + } - public T getRunnable() { - return runnable; - } + public Object key() { + return key; + } - public boolean isOverAfter(int intervalMs) { - if (!isFinished()) { - return false; - } - return canceled || System.currentTimeMillis() - endTime >= intervalMs; - } + public T getRunnable() { + return runnable; + } - @Override - public String toString() { - return "KeyedTask{" + "createTime=" + createTime + ", key=" + key + ", runnable=" - + runnable + ", startTime=" + startTime + ", endTime=" + endTime + ", success=" - + success + ", canceled=" + canceled + '}'; + public boolean isOverAfter(int intervalMs) { + if (!isFinished()) { + return false; } + return canceled || System.currentTimeMillis() - endTime >= intervalMs; + } + + @Override + public String toString() { + return "KeyedTask{" + + "createTime=" + + createTime + + ", key=" + + key + + ", runnable=" + + runnable + + ", startTime=" + + startTime + + ", endTime=" + + endTime + + ", success=" + + success + + ", canceled=" + + canceled + + '}'; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedThreadPoolExecutor.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedThreadPoolExecutor.java index fb9f29207..d42055946 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedThreadPoolExecutor.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/KeyedThreadPoolExecutor.java @@ -20,7 +20,6 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.util.ConcurrentUtils; import io.prometheus.client.Counter; - import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; @@ -31,121 +30,122 @@ * @version v 0.1 2020-12-15 13:38 yuzhi.lyz Exp $ */ public class KeyedThreadPoolExecutor { - private static final Logger LOGGER = LoggerFactory.getLogger(KeyedThreadPoolExecutor.class); - private final AbstractWorker[] workers; - protected final String executorName; - protected final int coreBufferSize; - - private final Counter taskCounter; - - public KeyedThreadPoolExecutor(String executorName, int coreSize, int coreBufferSize) { - this.executorName = executorName; - this.coreBufferSize = coreBufferSize; - this.taskCounter = Counter.build().namespace("keyedExecutor") + private static final Logger LOGGER = LoggerFactory.getLogger(KeyedThreadPoolExecutor.class); + private final AbstractWorker[] workers; + protected final String executorName; + protected final int coreBufferSize; + + private final Counter taskCounter; + + public KeyedThreadPoolExecutor(String executorName, int coreSize, int coreBufferSize) { + this.executorName = executorName; + this.coreBufferSize = coreBufferSize; + this.taskCounter = + Counter.build() + .namespace("keyedExecutor") .help("metrics for keyed executor") - .name(executorName.replace('-', '_') + "_task_total").labelNames("idx", "type") + .name(executorName.replace('-', '_') + "_task_total") + .labelNames("idx", "type") .register(); - workers = createWorkers(coreSize, coreBufferSize); - for (int i = 0; i < coreSize; i++) { - ConcurrentUtils.createDaemonThread(executorName + "_" + i, workers[i]).start(); - } + workers = createWorkers(coreSize, coreBufferSize); + for (int i = 0; i < coreSize; i++) { + ConcurrentUtils.createDaemonThread(executorName + "_" + i, workers[i]).start(); } + } - protected AbstractWorker[] createWorkers(int coreSize, int coreBufferSize) { - BlockingQueues queues = new BlockingQueues<>(coreSize, coreBufferSize, false); - AbstractWorker[] workers = new AbstractWorker[coreSize]; - for (int i = 0; i < coreSize; i++) { - workers[i] = new WorkerImpl(i, queues); - } - return workers; + protected AbstractWorker[] createWorkers(int coreSize, int coreBufferSize) { + BlockingQueues queues = new BlockingQueues<>(coreSize, coreBufferSize, false); + AbstractWorker[] workers = new AbstractWorker[coreSize]; + for (int i = 0; i < coreSize; i++) { + workers[i] = new WorkerImpl(i, queues); } + return workers; + } - protected interface Worker extends Runnable { - int size(); + protected interface Worker extends Runnable { + int size(); - KeyedTask poll() throws InterruptedException; + KeyedTask poll() throws InterruptedException; - boolean offer(KeyedTask task); + boolean offer(KeyedTask task); + } - } - - private final class WorkerImpl extends AbstractWorker { - final BlockingQueues queues; - final BlockingQueue queue; - - WorkerImpl(int idx, BlockingQueues queues) { - super(idx); - this.queues = queues; - this.queue = queues.getQueue(idx); - } - - public int size() { - return queue.size(); - } + private final class WorkerImpl extends AbstractWorker { + final BlockingQueues queues; + final BlockingQueue queue; - public KeyedTask poll() throws InterruptedException { - return queue.poll(180, TimeUnit.SECONDS); - } + WorkerImpl(int idx, BlockingQueues queues) { + super(idx); + this.queues = queues; + this.queue = queues.getQueue(idx); + } - public boolean offer(KeyedTask task) { - return queues.offer(idx, task); - } + public int size() { + return queue.size(); + } + public KeyedTask poll() throws InterruptedException { + return queue.poll(180, TimeUnit.SECONDS); } - protected abstract class AbstractWorker implements Worker { - final int idx; - final Counter.Child workerExecCounter; - final Counter.Child workerCommitCounter; + public boolean offer(KeyedTask task) { + return queues.offer(idx, task); + } + } - protected AbstractWorker(int idx) { - this.idx = idx; - this.workerExecCounter = taskCounter.labels(String.valueOf(idx), "exec"); - this.workerCommitCounter = taskCounter.labels(String.valueOf(idx), "commit"); - } + protected abstract class AbstractWorker implements Worker { + final int idx; + final Counter.Child workerExecCounter; + final Counter.Child workerCommitCounter; - @Override - public void run() { - for (;;) { - try { - final KeyedTask task = poll(); - if (task == null) { - LOGGER.info("{}_{} idle", executorName, idx); - continue; - } - task.run(); - workerExecCounter.inc(); - } catch (Throwable e) { - LOGGER.error("{}_{} run task error", executorName, idx, e); - } - } - } + protected AbstractWorker(int idx) { + this.idx = idx; + this.workerExecCounter = taskCounter.labels(String.valueOf(idx), "exec"); + this.workerCommitCounter = taskCounter.labels(String.valueOf(idx), "commit"); } - protected int getQueueSize() { - int size = 0; - for (Worker w : workers) { - size += w.size(); + @Override + public void run() { + for (; ; ) { + try { + final KeyedTask task = poll(); + if (task == null) { + LOGGER.info("{}_{} idle", executorName, idx); + continue; + } + task.run(); + workerExecCounter.inc(); + } catch (Throwable e) { + LOGGER.error("{}_{} run task error", executorName, idx, e); } - return size; + } } + } - public KeyedTask execute(Object key, T runnable) { - KeyedTask task = new KeyedTask(key, runnable); - AbstractWorker w = workerOf(key); - // should not happen, - if (!w.offer(task)) { - throw new FastRejectedExecutionException(String.format("%s_%d full, max=%d, now=%d", - executorName, w.idx, coreBufferSize, w.size())); - } - w.workerCommitCounter.inc(); - return task; + protected int getQueueSize() { + int size = 0; + for (Worker w : workers) { + size += w.size(); } - - private AbstractWorker workerOf(Object key) { - int n = (key.hashCode() & 0x7fffffff) % workers.length; - return workers[n]; + return size; + } + + public KeyedTask execute(Object key, T runnable) { + KeyedTask task = new KeyedTask(key, runnable); + AbstractWorker w = workerOf(key); + // should not happen, + if (!w.offer(task)) { + throw new FastRejectedExecutionException( + String.format( + "%s_%d full, max=%d, now=%d", executorName, w.idx, coreBufferSize, w.size())); } - + w.workerCommitCounter.inc(); + return task; + } + + private AbstractWorker workerOf(Object key) { + int n = (key.hashCode() & 0x7fffffff) % workers.length; + return workers[n]; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/MetricsableThreadPoolExecutor.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/MetricsableThreadPoolExecutor.java index cd134522e..42d30ec43 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/MetricsableThreadPoolExecutor.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/MetricsableThreadPoolExecutor.java @@ -20,59 +20,77 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.metrics.TaskMetrics; import com.alipay.sofa.registry.util.NamedThreadFactory; - import java.util.concurrent.*; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-15 11:50 yuzhi.lyz Exp $ */ public class MetricsableThreadPoolExecutor extends ThreadPoolExecutor { - private static final Logger LOGGER = LoggerFactory - .getLogger(MetricsableThreadPoolExecutor.class); - - protected final String executorName; + private static final Logger LOGGER = LoggerFactory.getLogger(MetricsableThreadPoolExecutor.class); - public MetricsableThreadPoolExecutor(String executorName, int corePoolSize, - int maximumPoolSize, long keepAliveTime, TimeUnit unit, - BlockingQueue workQueue, - ThreadFactory threadFactory, - RejectedExecutionHandler handler) { - super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); - this.executorName = executorName; - registerTaskMetrics(); - this.setRejectedExecutionHandler(handler); - } + protected final String executorName; - public MetricsableThreadPoolExecutor(String executorName, int corePoolSize, int maximumPoolSize, long keepAliveTime, - TimeUnit unit, BlockingQueue workQueue, - ThreadFactory threadFactory) { - this(executorName, corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, - (r, executor) -> { - String msg = String.format("Task(%s) %s rejected from %s, throw RejectedExecutionException.", - r.getClass(), r, executor); - LOGGER.error(msg); - throw new RejectedExecutionException(msg); - }); - } + public MetricsableThreadPoolExecutor( + String executorName, + int corePoolSize, + int maximumPoolSize, + long keepAliveTime, + TimeUnit unit, + BlockingQueue workQueue, + ThreadFactory threadFactory, + RejectedExecutionHandler handler) { + super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); + this.executorName = executorName; + registerTaskMetrics(); + this.setRejectedExecutionHandler(handler); + } - private void registerTaskMetrics() { - TaskMetrics.getInstance().registerThreadExecutor(executorName, this); - } + public MetricsableThreadPoolExecutor( + String executorName, + int corePoolSize, + int maximumPoolSize, + long keepAliveTime, + TimeUnit unit, + BlockingQueue workQueue, + ThreadFactory threadFactory) { + this( + executorName, + corePoolSize, + maximumPoolSize, + keepAliveTime, + unit, + workQueue, + threadFactory, + (r, executor) -> { + String msg = + String.format( + "Task(%s) %s rejected from %s, throw RejectedExecutionException.", + r.getClass(), r, executor); + LOGGER.error(msg); + throw new RejectedExecutionException(msg); + }); + } - @Override - public String toString() { - return (new StringBuilder(executorName).append(" ").append(super.toString())).toString(); - } + private void registerTaskMetrics() { + TaskMetrics.getInstance().registerThreadExecutor(executorName, this); + } - public static MetricsableThreadPoolExecutor newExecutor(String executorName, int corePoolSize, - int size, - RejectedExecutionHandler handler) { - return new MetricsableThreadPoolExecutor(executorName, corePoolSize, corePoolSize, 60, - TimeUnit.SECONDS, size <= 1024 * 4 ? new ArrayBlockingQueue<>(size) - : new LinkedBlockingQueue<>(size), new NamedThreadFactory(executorName, true), - handler); - } + @Override + public String toString() { + return (new StringBuilder(executorName).append(" ").append(super.toString())).toString(); + } + public static MetricsableThreadPoolExecutor newExecutor( + String executorName, int corePoolSize, int size, RejectedExecutionHandler handler) { + return new MetricsableThreadPoolExecutor( + executorName, + corePoolSize, + corePoolSize, + 60, + TimeUnit.SECONDS, + size <= 1024 * 4 ? new ArrayBlockingQueue<>(size) : new LinkedBlockingQueue<>(size), + new NamedThreadFactory(executorName, true), + handler); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/RejectedLogErrorHandler.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/RejectedLogErrorHandler.java index fbba193d0..12666d85a 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/RejectedLogErrorHandler.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/RejectedLogErrorHandler.java @@ -17,20 +17,19 @@ package com.alipay.sofa.registry.task; import com.alipay.sofa.registry.log.Logger; - import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadPoolExecutor; public final class RejectedLogErrorHandler implements RejectedExecutionHandler { - private final Logger logger; + private final Logger logger; - public RejectedLogErrorHandler(Logger logger) { - this.logger = logger; - } + public RejectedLogErrorHandler(Logger logger) { + this.logger = logger; + } - @Override - public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { - String msg = String.format("Task(%s) %s rejected from %s", r.getClass(), r, executor); - logger.error(msg); - } + @Override + public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { + String msg = String.format("Task(%s) %s rejected from %s", r.getClass(), r, executor); + logger.error(msg); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/Retryable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/Retryable.java index b5ae8afbf..4b7ffa15a 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/Retryable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/Retryable.java @@ -17,15 +17,11 @@ package com.alipay.sofa.registry.task; /** - * * @author shangyu.wh * @version $Id: Retryable.java, v 0.1 2018-02-07 11:31 shangyu.wh Exp $ */ public interface Retryable { - /** - * - * @return - */ - boolean checkRetryTimes(); -} \ No newline at end of file + /** @return */ + boolean checkRetryTimes(); +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/Task.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/Task.java index 25a5856ab..b59857e9c 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/Task.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/Task.java @@ -19,33 +19,20 @@ import com.alipay.sofa.registry.task.listener.TaskEvent; /** - * * @author shangyu.wh * @version $Id: Task.java, v 0.1 2018-01-15 14:23 shangyu.wh Exp $ */ public interface Task { - /** - * - * @return - */ - long getExpiryTime(); + /** @return */ + long getExpiryTime(); - /** - * - * @return - */ - String getTaskId(); + /** @return */ + String getTaskId(); - /** - * - * @param taskEvent - */ - void setTaskEvent(TaskEvent taskEvent); + /** @param taskEvent */ + void setTaskEvent(TaskEvent taskEvent); - /** - * - * @throws Throwable - */ - void execute() throws Throwable; -} \ No newline at end of file + /** @throws Throwable */ + void execute() throws Throwable; +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/AcceptorExecutor.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/AcceptorExecutor.java index c0a26d410..c31ac203d 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/AcceptorExecutor.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/AcceptorExecutor.java @@ -19,7 +19,6 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.task.batcher.TaskProcessor.ProcessingResult; - import java.util.Deque; import java.util.HashMap; import java.util.LinkedList; @@ -36,285 +35,282 @@ /** * An active object with an internal thread accepting tasks from clients, and dispatching them to - * workers in a pull based manner. Workers explicitly request an item or a batch of items whenever they are - * available. This guarantees that data to be processed are always up to date, and no stale data processing is done. + * workers in a pull based manner. Workers explicitly request an item or a batch of items whenever + * they are available. This guarantees that data to be processed are always up to date, and no stale + * data processing is done. * *

Task identification

- * Each task passed for processing has a corresponding task id. This id is used to remove duplicates (replace - * older copies with newer ones). + * + * Each task passed for processing has a corresponding task id. This id is used to remove duplicates + * (replace older copies with newer ones). * *

Re-processing

- * If data processing by a worker failed, and the failure is transient in nature, the worker will put back the - * task(s) back to the {@link AcceptorExecutor}. This data will be merged with current workload, possibly discarded if - * a newer version has been already received. + * + * If data processing by a worker failed, and the failure is transient in nature, the worker will + * put back the task(s) back to the {@link AcceptorExecutor}. This data will be merged with current + * workload, possibly discarded if a newer version has been already received. * * @author Tomasz Bak - * @author shangyu.wh modify * @version $Id: AcceptorExecutor.java, v 0.1 2017-11-14 15:35 shangyu.wh Exp $ */ public class AcceptorExecutor { - private static final Logger LOGGER = LoggerFactory - .getLogger(AcceptorExecutor.class); + private static final Logger LOGGER = LoggerFactory.getLogger(AcceptorExecutor.class); - /** - * Get the maximum number of task that can be allowed to back up in the task pool - * Default 10000 - */ - private final int maxBufferSize; + /** + * Get the maximum number of task that can be allowed to back up in the task pool Default 10000 + */ + private final int maxBufferSize; - private final String name; + private final String name; - private final AtomicBoolean isShutdown = new AtomicBoolean( - false); + private final AtomicBoolean isShutdown = new AtomicBoolean(false); - private final BlockingQueue> acceptorQueue = new LinkedBlockingQueue<>(); - private final BlockingDeque> reprocessQueue = new LinkedBlockingDeque<>(); - private final Thread acceptorThread; + private final BlockingQueue> acceptorQueue = new LinkedBlockingQueue<>(); + private final BlockingDeque> reprocessQueue = new LinkedBlockingDeque<>(); + private final Thread acceptorThread; - private final Map> pendingTasks = new HashMap<>(); - private final Deque processingOrder = new LinkedList<>(); + private final Map> pendingTasks = new HashMap<>(); + private final Deque processingOrder = new LinkedList<>(); - private final Semaphore workSemaphore = new Semaphore(0); - private final BlockingQueue> itemWorkQueue = new LinkedBlockingQueue<>(); + private final Semaphore workSemaphore = new Semaphore(0); + private final BlockingQueue> itemWorkQueue = new LinkedBlockingQueue<>(); - private final Semaphore batchWorkRequests = new Semaphore(0); - private final BlockingQueue>> batchWorkQueue = new LinkedBlockingQueue<>(); + private final Semaphore batchWorkRequests = new Semaphore(0); + private final BlockingQueue>> batchWorkQueue = new LinkedBlockingQueue<>(); - private final TrafficShaper trafficShaper; + private final TrafficShaper trafficShaper; - private AtomicLong acceptedTasks = new AtomicLong(); + private AtomicLong acceptedTasks = new AtomicLong(); - private AtomicLong replayedTasks = new AtomicLong(); + private AtomicLong replayedTasks = new AtomicLong(); - private AtomicLong expiredTasks = new AtomicLong(); + private AtomicLong expiredTasks = new AtomicLong(); - private AtomicLong overriddenTasks = new AtomicLong(); + private AtomicLong overriddenTasks = new AtomicLong(); - private AtomicLong queueOverflows = new AtomicLong(); + private AtomicLong queueOverflows = new AtomicLong(); - AcceptorExecutor(String id, int maxBufferSize, long congestionRetryDelayMs, - long networkFailureRetryMs) { - this.name = "TaskAcceptor-" + id; - this.maxBufferSize = maxBufferSize; - this.trafficShaper = new TrafficShaper(congestionRetryDelayMs, networkFailureRetryMs); + AcceptorExecutor( + String id, int maxBufferSize, long congestionRetryDelayMs, long networkFailureRetryMs) { + this.name = "TaskAcceptor-" + id; + this.maxBufferSize = maxBufferSize; + this.trafficShaper = new TrafficShaper(congestionRetryDelayMs, networkFailureRetryMs); - ThreadGroup threadGroup = new ThreadGroup("serverTaskExecutors"); - this.acceptorThread = new Thread(threadGroup, new AcceptorRunner(), "TaskAcceptor-" + id); - this.acceptorThread.setDaemon(true); - this.acceptorThread.start(); + ThreadGroup threadGroup = new ThreadGroup("serverTaskExecutors"); + this.acceptorThread = new Thread(threadGroup, new AcceptorRunner(), "TaskAcceptor-" + id); + this.acceptorThread.setDaemon(true); + this.acceptorThread.start(); + } - } + void process(ID id, T task, long expiryTime) { + acceptorQueue.add(new TaskHolder<>(id, task, expiryTime)); + acceptedTasks.incrementAndGet(); + } - void process(ID id, T task, long expiryTime) { - acceptorQueue.add(new TaskHolder<>(id, task, expiryTime)); - acceptedTasks.incrementAndGet(); - } + void reprocess(TaskHolder taskHolder, ProcessingResult processingResult) { + reprocessQueue.add(taskHolder); + replayedTasks.incrementAndGet(); + trafficShaper.registerFailure(processingResult); + } - void reprocess(TaskHolder taskHolder, ProcessingResult processingResult) { - reprocessQueue.add(taskHolder); - replayedTasks.incrementAndGet(); - trafficShaper.registerFailure(processingResult); - } + BlockingQueue> requestWorkItem() { + workSemaphore.release(); + return itemWorkQueue; + } - BlockingQueue> requestWorkItem() { - workSemaphore.release(); - return itemWorkQueue; - } + BlockingQueue>> requestWorkItems() { + batchWorkRequests.release(); + return batchWorkQueue; + } - BlockingQueue>> requestWorkItems() { - batchWorkRequests.release(); - return batchWorkQueue; + void shutdown() { + if (isShutdown.compareAndSet(false, true)) { + acceptorThread.interrupt(); } - - void shutdown() { - if (isShutdown.compareAndSet(false, true)) { - acceptorThread.interrupt(); + } + + class AcceptorRunner implements Runnable { + @Override + public void run() { + long scheduleTime = 0; + while (!isShutdown.get()) { + try { + drainInputQueues(); + + int totalItems = processingOrder.size(); + + long now = System.currentTimeMillis(); + if (scheduleTime < now) { + scheduleTime = now + trafficShaper.transmissionDelay(); + } + if (scheduleTime <= now) { + assignItemWork(); + } + + if (totalItems == processingOrder.size()) { + Thread.sleep(10); + } + } catch (InterruptedException ex) { + // Ignore + } catch (Throwable e) { + LOGGER.warn("AcceptorThread error", e); } + } } - class AcceptorRunner implements Runnable { - @Override - public void run() { - long scheduleTime = 0; - while (!isShutdown.get()) { - try { - drainInputQueues(); - - int totalItems = processingOrder.size(); - - long now = System.currentTimeMillis(); - if (scheduleTime < now) { - scheduleTime = now + trafficShaper.transmissionDelay(); - } - if (scheduleTime <= now) { - assignItemWork(); - } - - if (totalItems == processingOrder.size()) { - Thread.sleep(10); - } - } catch (InterruptedException ex) { - // Ignore - } catch (Throwable e) { - LOGGER.warn("AcceptorThread error", e); - } - } - } - - private boolean isFull() { - return pendingTasks.size() >= maxBufferSize; - } - - private void drainInputQueues() throws InterruptedException { - do { - drainReprocessQueue(); - drainAcceptorQueue(); - - if (!isShutdown.get()) { - // If all queues are empty, block for a while on the acceptor queue - if (reprocessQueue.isEmpty() && acceptorQueue.isEmpty() - && pendingTasks.isEmpty()) { - TaskHolder taskHolder = acceptorQueue - .poll(10, TimeUnit.MILLISECONDS); - if (taskHolder != null) { - appendTaskHolder(taskHolder); - } - } - } - } while (!reprocessQueue.isEmpty() || !acceptorQueue.isEmpty() - || pendingTasks.isEmpty()); - } - - private void drainAcceptorQueue() { - while (!acceptorQueue.isEmpty()) { - appendTaskHolder(acceptorQueue.poll()); - } - } - - private void drainReprocessQueue() { - long now = System.currentTimeMillis(); - while (!reprocessQueue.isEmpty() && !isFull()) { - TaskHolder taskHolder = reprocessQueue.pollLast(); - ID id = taskHolder.getId(); - //expiryTime < 0 means task no expired - if (taskHolder.getExpiryTime() > 0 && taskHolder.getExpiryTime() <= now) { - expiredTasks.incrementAndGet(); - } else if (pendingTasks.containsKey(id)) { - overriddenTasks.incrementAndGet(); - } else { - pendingTasks.put(id, taskHolder); - processingOrder.addFirst(id); - } - } - if (isFull()) { - LOGGER - .error( - "Now pending task full,it will clear reprocessQueue in to add new task,reprocessQueue size={},queueOverflows={},name={}", - reprocessQueue.size(), queueOverflows, name); - queueOverflows.addAndGet(reprocessQueue.size()); - reprocessQueue.clear(); - } - } - - private void appendTaskHolder(TaskHolder taskHolder) { - if (isFull()) { - LOGGER - .error( - "Now pending task full,it will remove first one to add task={},queueOverflows={},name={}", - taskHolder.getId(), queueOverflows, name); - pendingTasks.remove(processingOrder.poll()); - queueOverflows.incrementAndGet(); - } - TaskHolder previousTask = pendingTasks.put(taskHolder.getId(), taskHolder); - if (previousTask == null) { - processingOrder.add(taskHolder.getId()); - } else { - overriddenTasks.incrementAndGet(); - } - } + private boolean isFull() { + return pendingTasks.size() >= maxBufferSize; + } - void assignItemWork() { - if (!processingOrder.isEmpty()) { - if (workSemaphore.tryAcquire(1)) { - long now = System.currentTimeMillis(); - while (!processingOrder.isEmpty()) { - ID id = processingOrder.poll(); - TaskHolder holder = pendingTasks.remove(id); - //expiryTime < 0 means task no expired - if (holder.getExpiryTime() < 0 || holder.getExpiryTime() > now) { - itemWorkQueue.add(holder); - return; - } - expiredTasks.incrementAndGet(); - } - workSemaphore.release(); - } + private void drainInputQueues() throws InterruptedException { + do { + drainReprocessQueue(); + drainAcceptorQueue(); + + if (!isShutdown.get()) { + // If all queues are empty, block for a while on the acceptor queue + if (reprocessQueue.isEmpty() && acceptorQueue.isEmpty() && pendingTasks.isEmpty()) { + TaskHolder taskHolder = acceptorQueue.poll(10, TimeUnit.MILLISECONDS); + if (taskHolder != null) { + appendTaskHolder(taskHolder); } + } } - + } while (!reprocessQueue.isEmpty() || !acceptorQueue.isEmpty() || pendingTasks.isEmpty()); } - /** - * Getter method for property maxBufferSize. - * - * @return property value of maxBufferSize - */ - public int getMaxBufferSize() { - return maxBufferSize; + private void drainAcceptorQueue() { + while (!acceptorQueue.isEmpty()) { + appendTaskHolder(acceptorQueue.poll()); + } } - /** - * Getter method for property acceptedTasks. - * - * @return property value of acceptedTasks - */ - public AtomicLong getAcceptedTasks() { - return acceptedTasks; - } - - /** - * Getter method for property replayedTasks. - * - * @return property value of replayedTasks - */ - public AtomicLong getReplayedTasks() { - return replayedTasks; - } - - /** - * Getter method for property expiredTasks. - * - * @return property value of expiredTasks - */ - public AtomicLong getExpiredTasks() { - return expiredTasks; - } - - /** - * Getter method for property overriddenTasks. - * - * @return property value of overriddenTasks - */ - public AtomicLong getOverriddenTasks() { - return overriddenTasks; + private void drainReprocessQueue() { + long now = System.currentTimeMillis(); + while (!reprocessQueue.isEmpty() && !isFull()) { + TaskHolder taskHolder = reprocessQueue.pollLast(); + ID id = taskHolder.getId(); + // expiryTime < 0 means task no expired + if (taskHolder.getExpiryTime() > 0 && taskHolder.getExpiryTime() <= now) { + expiredTasks.incrementAndGet(); + } else if (pendingTasks.containsKey(id)) { + overriddenTasks.incrementAndGet(); + } else { + pendingTasks.put(id, taskHolder); + processingOrder.addFirst(id); + } + } + if (isFull()) { + LOGGER.error( + "Now pending task full,it will clear reprocessQueue in to add new task,reprocessQueue size={},queueOverflows={},name={}", + reprocessQueue.size(), + queueOverflows, + name); + queueOverflows.addAndGet(reprocessQueue.size()); + reprocessQueue.clear(); + } } - /** - * Getter method for property queueOverflows. - * - * @return property value of queueOverflows - */ - public AtomicLong getQueueOverflows() { - return queueOverflows; + private void appendTaskHolder(TaskHolder taskHolder) { + if (isFull()) { + LOGGER.error( + "Now pending task full,it will remove first one to add task={},queueOverflows={},name={}", + taskHolder.getId(), + queueOverflows, + name); + pendingTasks.remove(processingOrder.poll()); + queueOverflows.incrementAndGet(); + } + TaskHolder previousTask = pendingTasks.put(taskHolder.getId(), taskHolder); + if (previousTask == null) { + processingOrder.add(taskHolder.getId()); + } else { + overriddenTasks.incrementAndGet(); + } } - /** - * Get pending task size - * @return - */ - public int getPendingTaskSize() { - return pendingTasks.size(); + void assignItemWork() { + if (!processingOrder.isEmpty()) { + if (workSemaphore.tryAcquire(1)) { + long now = System.currentTimeMillis(); + while (!processingOrder.isEmpty()) { + ID id = processingOrder.poll(); + TaskHolder holder = pendingTasks.remove(id); + // expiryTime < 0 means task no expired + if (holder.getExpiryTime() < 0 || holder.getExpiryTime() > now) { + itemWorkQueue.add(holder); + return; + } + expiredTasks.incrementAndGet(); + } + workSemaphore.release(); + } + } } -} \ No newline at end of file + } + + /** + * Getter method for property maxBufferSize. + * + * @return property value of maxBufferSize + */ + public int getMaxBufferSize() { + return maxBufferSize; + } + + /** + * Getter method for property acceptedTasks. + * + * @return property value of acceptedTasks + */ + public AtomicLong getAcceptedTasks() { + return acceptedTasks; + } + + /** + * Getter method for property replayedTasks. + * + * @return property value of replayedTasks + */ + public AtomicLong getReplayedTasks() { + return replayedTasks; + } + + /** + * Getter method for property expiredTasks. + * + * @return property value of expiredTasks + */ + public AtomicLong getExpiredTasks() { + return expiredTasks; + } + + /** + * Getter method for property overriddenTasks. + * + * @return property value of overriddenTasks + */ + public AtomicLong getOverriddenTasks() { + return overriddenTasks; + } + + /** + * Getter method for property queueOverflows. + * + * @return property value of queueOverflows + */ + public AtomicLong getQueueOverflows() { + return queueOverflows; + } + + /** + * Get pending task size + * + * @return + */ + public int getPendingTaskSize() { + return pendingTasks.size(); + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskDispatcher.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskDispatcher.java index 3620065ec..c3f1d8de5 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskDispatcher.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskDispatcher.java @@ -17,34 +17,33 @@ package com.alipay.sofa.registry.task.batcher; /** - * Task dispatcher takes task from clients, and delegates their execution to a configurable number of workers. - * The task can be processed one at a time or in batches. Only non-expired tasks are executed, and if a newer - * task with the same id is scheduled for execution, the old one is deleted. Lazy dispatch of work (only on demand) - * to workers, guarantees that data are always up to date, and no stale task processing takes place. + * Task dispatcher takes task from clients, and delegates their execution to a configurable number + * of workers. The task can be processed one at a time or in batches. Only non-expired tasks are + * executed, and if a newer task with the same id is scheduled for execution, the old one is + * deleted. Lazy dispatch of work (only on demand) to workers, guarantees that data are always up to + * date, and no stale task processing takes place. + * *

Task processor

- * A client of this component must provide an implementation of {@link TaskProcessor} interface, which will do - * the actual work of task processing. This implementation must be thread safe, as it is called concurrently by - * multiple threads. * - * @author Tomasz Bak + * A client of this component must provide an implementation of {@link TaskProcessor} interface, + * which will do the actual work of task processing. This implementation must be thread safe, as it + * is called concurrently by multiple threads. * + * @author Tomasz Bak * @author shangyu.wh modify * @version $Id: TaskDispatcher.java, v 0.1 2017-11-14 15:23 shangyu.wh Exp $ */ public interface TaskDispatcher { - /** - * - * @param id - * @param task - * @param expiryTime - */ - void dispatch(ID id, T task, long expiryTime); + /** + * @param id + * @param task + * @param expiryTime + */ + void dispatch(ID id, T task, long expiryTime); - /** - * - */ - void shutdown(); + /** */ + void shutdown(); - AcceptorExecutor getAcceptorExecutor(); -} \ No newline at end of file + AcceptorExecutor getAcceptorExecutor(); +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskDispatchers.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskDispatchers.java index c7a2d32e6..f20dbea45 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskDispatchers.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskDispatchers.java @@ -23,125 +23,124 @@ * See {@link TaskDispatcher} for an overview. * * @author Tomasz Bak - * * @author shangyu.wh modify * @version $Id: TaskDispatchers.java, v 0.1 2017-11-14 16:11 shangyu.wh Exp $ */ public class TaskDispatchers { - private static Map taskDispatcherMap = new ConcurrentHashMap<>(); - - private static final String TASK_DISPATCHER_END = "Dispatcher"; - - /** - * @param id - * @param taskProcessor - * @param - * @param - * @return - */ - public static TaskDispatcher createDefaultSingleTaskDispatcher(String id, - TaskProcessor taskProcessor) { - final String name = getDispatcherName(id); - - TaskDispatcher taskDispatcher = taskDispatcherMap.computeIfAbsent(name, - k->{ - - final AcceptorExecutor acceptorExecutor = new AcceptorExecutor( - name, 1000, 1000, 100 - ); - final TaskExecutors taskExecutor = TaskExecutors.createTaskExecutors(name, 20, taskProcessor, - acceptorExecutor); - - return new TaskDispatcher() { - @Override - public void dispatch(ID id, T task, long expiryTime) { - acceptorExecutor.process(id, task, expiryTime); - } - - @Override - public void shutdown() { - acceptorExecutor.shutdown(); - taskExecutor.shutdown(); - } - - @Override - public AcceptorExecutor getAcceptorExecutor() { - return acceptorExecutor; - } - }; - }); - return taskDispatcher; - } - - /** - * - */ - public static void stopDefaultSingleTaskDispatcher() { - taskDispatcherMap.forEach((k, v) -> { - if (v != null) { - v.shutdown(); - } - }); - } - - /** - * @param id - * @param maxBufferSize - * @param workerCount - * @param congestionRetryDelayMs - * @param networkFailureRetryMs - * @param taskProcessor - * @param - * @param - * @return - */ - public static TaskDispatcher createSingleTaskDispatcher(String id, - int maxBufferSize, - int workerCount, - long congestionRetryDelayMs, - long networkFailureRetryMs, - TaskProcessor taskProcessor) { - - return taskDispatcherMap.computeIfAbsent(id,k->{ - - final AcceptorExecutor acceptorExecutor = new AcceptorExecutor( - id, maxBufferSize, congestionRetryDelayMs, networkFailureRetryMs - ); - final TaskExecutors taskExecutor = TaskExecutors.createTaskExecutors(id, workerCount, taskProcessor, - acceptorExecutor); - - return new TaskDispatcher() { + private static Map taskDispatcherMap = new ConcurrentHashMap<>(); + + private static final String TASK_DISPATCHER_END = "Dispatcher"; + + /** + * @param id + * @param taskProcessor + * @param + * @param + * @return + */ + public static TaskDispatcher createDefaultSingleTaskDispatcher( + String id, TaskProcessor taskProcessor) { + final String name = getDispatcherName(id); + + TaskDispatcher taskDispatcher = + taskDispatcherMap.computeIfAbsent( + name, + k -> { + final AcceptorExecutor acceptorExecutor = + new AcceptorExecutor(name, 1000, 1000, 100); + final TaskExecutors taskExecutor = + TaskExecutors.createTaskExecutors(name, 20, taskProcessor, acceptorExecutor); + + return new TaskDispatcher() { @Override public void dispatch(ID id, T task, long expiryTime) { - acceptorExecutor.process(id, task, expiryTime); + acceptorExecutor.process(id, task, expiryTime); } @Override public void shutdown() { - acceptorExecutor.shutdown(); - taskExecutor.shutdown(); + acceptorExecutor.shutdown(); + taskExecutor.shutdown(); } @Override public AcceptorExecutor getAcceptorExecutor() { - return acceptorExecutor; + return acceptorExecutor; } - }; + }; + }); + return taskDispatcher; + } + + /** */ + public static void stopDefaultSingleTaskDispatcher() { + taskDispatcherMap.forEach( + (k, v) -> { + if (v != null) { + v.shutdown(); + } }); + } + + /** + * @param id + * @param maxBufferSize + * @param workerCount + * @param congestionRetryDelayMs + * @param networkFailureRetryMs + * @param taskProcessor + * @param + * @param + * @return + */ + public static TaskDispatcher createSingleTaskDispatcher( + String id, + int maxBufferSize, + int workerCount, + long congestionRetryDelayMs, + long networkFailureRetryMs, + TaskProcessor taskProcessor) { + + return taskDispatcherMap.computeIfAbsent( + id, + k -> { + final AcceptorExecutor acceptorExecutor = + new AcceptorExecutor( + id, maxBufferSize, congestionRetryDelayMs, networkFailureRetryMs); + final TaskExecutors taskExecutor = + TaskExecutors.createTaskExecutors(id, workerCount, taskProcessor, acceptorExecutor); + + return new TaskDispatcher() { + @Override + public void dispatch(ID id, T task, long expiryTime) { + acceptorExecutor.process(id, task, expiryTime); + } - } - - public static String getDispatcherName(String name) { - return name + TASK_DISPATCHER_END; - } - - /** - * Getter method for property taskDispatcherMap. - * - * @return property value of taskDispatcherMap - */ - public static Map getTaskDispatcherMap() { - return taskDispatcherMap; - } -} \ No newline at end of file + @Override + public void shutdown() { + acceptorExecutor.shutdown(); + taskExecutor.shutdown(); + } + + @Override + public AcceptorExecutor getAcceptorExecutor() { + return acceptorExecutor; + } + }; + }); + } + + public static String getDispatcherName(String name) { + return name + TASK_DISPATCHER_END; + } + + /** + * Getter method for property taskDispatcherMap. + * + * @return property value of taskDispatcherMap + */ + public static Map getTaskDispatcherMap() { + return taskDispatcherMap; + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskExecutors.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskExecutors.java index b9176318e..d78c8d52c 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskExecutors.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskExecutors.java @@ -19,7 +19,6 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.task.batcher.TaskProcessor.ProcessingResult; - import java.util.ArrayList; import java.util.List; import java.util.concurrent.BlockingQueue; @@ -28,137 +27,138 @@ import java.util.function.Function; /** - * {@link TaskExecutors} instance holds a number of worker threads that cooperate with {@link AcceptorExecutor}. - * Each worker sends a job request to {@link AcceptorExecutor} whenever it is available, and processes it once - * provided with a task(s). + * {@link TaskExecutors} instance holds a number of worker threads that cooperate with {@link + * AcceptorExecutor}. Each worker sends a job request to {@link AcceptorExecutor} whenever it is + * available, and processes it once provided with a task(s). * * @author Tomasz Bak - * * @author shangyu.wh modify * @version $Id: TaskExecutors.java, v 0.1 2017-11-14 16:00 shangyu.wh Exp $ */ public class TaskExecutors { - private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutors.class); + private static final Logger LOGGER = LoggerFactory.getLogger(TaskExecutors.class); - private final AtomicBoolean isShutdown; - private final List workerThreads; + private final AtomicBoolean isShutdown; + private final List workerThreads; - /** - * constructor - * @param workerRunnableFactory - * @param workerCount - * @param isShutdown - */ - TaskExecutors(Function> workerRunnableFactory, int workerCount, - AtomicBoolean isShutdown) { - this.isShutdown = isShutdown; - this.workerThreads = new ArrayList<>(); + /** + * constructor + * + * @param workerRunnableFactory + * @param workerCount + * @param isShutdown + */ + TaskExecutors( + Function> workerRunnableFactory, + int workerCount, + AtomicBoolean isShutdown) { + this.isShutdown = isShutdown; + this.workerThreads = new ArrayList<>(); - ThreadGroup threadGroup = new ThreadGroup("serverTaskExecutors"); - for (int i = 0; i < workerCount; i++) { - WorkerRunnable runnable = workerRunnableFactory.apply(i); - Thread workerThread = new Thread(threadGroup, runnable, runnable.getWorkerName()); - workerThreads.add(workerThread); - workerThread.setDaemon(true); - workerThread.start(); - } + ThreadGroup threadGroup = new ThreadGroup("serverTaskExecutors"); + for (int i = 0; i < workerCount; i++) { + WorkerRunnable runnable = workerRunnableFactory.apply(i); + Thread workerThread = new Thread(threadGroup, runnable, runnable.getWorkerName()); + workerThreads.add(workerThread); + workerThread.setDaemon(true); + workerThread.start(); } + } - /** - * - * @param name - * @param workerCount - * @param processor - * @param acceptorExecutor - * @param - * @param - * @return - */ - static TaskExecutors createTaskExecutors(final String name, - int workerCount, - final TaskProcessor processor, - final AcceptorExecutor acceptorExecutor) { - final AtomicBoolean isShutdown = new AtomicBoolean(); - return new TaskExecutors<>(idx -> new WorkerRunnable<>(name + '-' + idx, isShutdown, - processor, - acceptorExecutor), workerCount, isShutdown); - } + /** + * @param name + * @param workerCount + * @param processor + * @param acceptorExecutor + * @param + * @param + * @return + */ + static TaskExecutors createTaskExecutors( + final String name, + int workerCount, + final TaskProcessor processor, + final AcceptorExecutor acceptorExecutor) { + final AtomicBoolean isShutdown = new AtomicBoolean(); + return new TaskExecutors<>( + idx -> new WorkerRunnable<>(name + '-' + idx, isShutdown, processor, acceptorExecutor), + workerCount, + isShutdown); + } - /** - * shutdown workerThread - */ - void shutdown() { - if (isShutdown.compareAndSet(false, true)) { - for (Thread workerThread : workerThreads) { - workerThread.interrupt(); - } - } + /** shutdown workerThread */ + void shutdown() { + if (isShutdown.compareAndSet(false, true)) { + for (Thread workerThread : workerThreads) { + workerThread.interrupt(); + } } + } - /** - * - * @param - * @param - */ - static class WorkerRunnable implements Runnable { + /** + * @param + * @param + */ + static class WorkerRunnable implements Runnable { - final String workerName; - final AtomicBoolean isShutdown; - final TaskProcessor processor; - final AcceptorExecutor acceptorExecutor; + final String workerName; + final AtomicBoolean isShutdown; + final TaskProcessor processor; + final AcceptorExecutor acceptorExecutor; - WorkerRunnable(String workerName, AtomicBoolean isShutdown, TaskProcessor processor, - AcceptorExecutor acceptorExecutor) { - this.workerName = workerName; - this.isShutdown = isShutdown; - this.processor = processor; - this.acceptorExecutor = acceptorExecutor; - } + WorkerRunnable( + String workerName, + AtomicBoolean isShutdown, + TaskProcessor processor, + AcceptorExecutor acceptorExecutor) { + this.workerName = workerName; + this.isShutdown = isShutdown; + this.processor = processor; + this.acceptorExecutor = acceptorExecutor; + } - String getWorkerName() { - return workerName; - } + String getWorkerName() { + return workerName; + } - @Override - public void run() { - try { - while (!isShutdown.get()) { - try { - BlockingQueue> workQueue = acceptorExecutor - .requestWorkItem(); - TaskHolder taskHolder; - while ((taskHolder = workQueue.poll(1, TimeUnit.SECONDS)) == null) { - if (isShutdown.get()) { - return; - } - } - ProcessingResult result = processor.process(taskHolder.getTask()); - switch (result) { - case Success: - break; - case Congestion: - acceptorExecutor.reprocess(taskHolder, result); - break; - case TransientError: - acceptorExecutor.reprocess(taskHolder, result); - break; - case PermanentError: - LOGGER.warn("Discarding a task of {} due to permanent error", - workerName); - break; - default: - break; - } - } catch (InterruptedException e) { - // Ignore - } catch (Throwable e) { - LOGGER.error("Single WorkerThread process error", e); - } - } - } catch (Throwable e) { - LOGGER.error("WorkerThread error", e); + @Override + public void run() { + try { + while (!isShutdown.get()) { + try { + BlockingQueue> workQueue = acceptorExecutor.requestWorkItem(); + TaskHolder taskHolder; + while ((taskHolder = workQueue.poll(1, TimeUnit.SECONDS)) == null) { + if (isShutdown.get()) { + return; + } + } + ProcessingResult result = processor.process(taskHolder.getTask()); + switch (result) { + case Success: + break; + case Congestion: + acceptorExecutor.reprocess(taskHolder, result); + break; + case TransientError: + acceptorExecutor.reprocess(taskHolder, result); + break; + case PermanentError: + LOGGER.warn("Discarding a task of {} due to permanent error", workerName); + break; + default: + break; } + } catch (InterruptedException e) { + // Ignore + } catch (Throwable e) { + LOGGER.error("Single WorkerThread process error", e); + } } + } catch (Throwable e) { + LOGGER.error("WorkerThread error", e); + } } -} \ No newline at end of file + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskHolder.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskHolder.java index 304395eb1..e3b76476c 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskHolder.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskHolder.java @@ -18,63 +18,63 @@ /** * @author Tomasz Bak - * * @author shangyu.wh modify * @version $Id: TaskHolder.java, v 0.1 2017-11-14 14:57 shangyu.wh Exp $ */ public class TaskHolder { - private final ID id; - private final T task; - private final long expiryTime; - private final long submitTimestamp; + private final ID id; + private final T task; + private final long expiryTime; + private final long submitTimestamp; - /** - * constructor - * @param id - * @param task - * @param expiryTime - */ - TaskHolder(ID id, T task, long expiryTime) { - this.id = id; - this.expiryTime = expiryTime; - this.task = task; - this.submitTimestamp = System.currentTimeMillis(); - } + /** + * constructor + * + * @param id + * @param task + * @param expiryTime + */ + TaskHolder(ID id, T task, long expiryTime) { + this.id = id; + this.expiryTime = expiryTime; + this.task = task; + this.submitTimestamp = System.currentTimeMillis(); + } - /** - * Getter method for property id. - * - * @return property value of id - */ - public ID getId() { - return id; - } + /** + * Getter method for property id. + * + * @return property value of id + */ + public ID getId() { + return id; + } - /** - * Getter method for property task. - * - * @return property value of task - */ - public T getTask() { - return task; - } + /** + * Getter method for property task. + * + * @return property value of task + */ + public T getTask() { + return task; + } - /** - * Getter method for property expiryTime. - * - * @return property value of expiryTime - */ - public long getExpiryTime() { - return expiryTime; - } + /** + * Getter method for property expiryTime. + * + * @return property value of expiryTime + */ + public long getExpiryTime() { + return expiryTime; + } - /** - * Getter method for property submitTimestamp. - * - * @return property value of submitTimestamp - */ - public long getSubmitTimestamp() { - return submitTimestamp; - } -} \ No newline at end of file + /** + * Getter method for property submitTimestamp. + * + * @return property value of submitTimestamp + */ + public long getSubmitTimestamp() { + return submitTimestamp; + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskProcessor.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskProcessor.java index 886f627bf..1d43ef6c9 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskProcessor.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TaskProcessor.java @@ -22,33 +22,34 @@ * An interface to be implemented by clients for task execution. * * @author Tomasz Bak - * * @author shangyu.wh modify * @version $Id: TaskProcessor.java, v 0.1 2017-11-14 15:27 shangyu.wh Exp $ */ public interface TaskProcessor { - /** - * A processed task/task list ends up in one of the following states: - *
    - *
  • {@code Success} processing finished successfully
  • - *
  • {@code TransientError} processing failed, but shall be retried later
  • - *
  • {@code PermanentError} processing failed, and is non recoverable
  • - *
- */ - enum ProcessingResult { - Success, Congestion, TransientError, PermanentError - } + /** + * A processed task/task list ends up in one of the following states: + * + *
    + *
  • {@code Success} processing finished successfully + *
  • {@code TransientError} processing failed, but shall be retried later + *
  • {@code PermanentError} processing failed, and is non recoverable + *
+ */ + enum ProcessingResult { + Success, + Congestion, + TransientError, + PermanentError + } - /** - * In non-batched mode a single task is processed at a time. - */ - ProcessingResult process(T task); + /** In non-batched mode a single task is processed at a time. */ + ProcessingResult process(T task); - /** - * For batched mode a collection of tasks is run at a time. The result is provided for the aggregated result, - * and all tasks are handled in the same way according to what is returned (for example are rescheduled, if the - * error is transient). - */ - ProcessingResult process(List tasks); -} \ No newline at end of file + /** + * For batched mode a collection of tasks is run at a time. The result is provided for the + * aggregated result, and all tasks are handled in the same way according to what is returned (for + * example are rescheduled, if the error is transient). + */ + ProcessingResult process(List tasks); +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TrafficShaper.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TrafficShaper.java index 726a0cc5d..17b5646f0 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TrafficShaper.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/batcher/TrafficShaper.java @@ -19,75 +19,64 @@ import com.alipay.sofa.registry.task.batcher.TaskProcessor.ProcessingResult; /** - * {@link TrafficShaper} provides admission control policy prior to dispatching - * tasks to workers. It reacts to events coming via reprocess requests - * (transient failures, congestion), and delays the processing depending on this - * feedback. - * + * {@link TrafficShaper} provides admission control policy prior to dispatching tasks to workers. It + * reacts to events coming via reprocess requests (transient failures, congestion), and delays the + * processing depending on this feedback. + * * @author Tomasz Bak - * * @author shangyu.wh modify * @version $Id: TrafficShaper.java, v 0.1 2017-11-14 15:37 shangyu.wh Exp $ */ public class TrafficShaper { - private static final long MAX_DELAY = 30 * 1000; + private static final long MAX_DELAY = 30 * 1000; - private final long congestionRetryDelayMs; - private final long networkFailureRetryMs; + private final long congestionRetryDelayMs; + private final long networkFailureRetryMs; - private volatile long lastCongestionError; - private volatile long lastNetworkFailure; + private volatile long lastCongestionError; + private volatile long lastNetworkFailure; - /** - * - * @param congestionRetryDelayMs - * @param networkFailureRetryMs - */ - TrafficShaper(long congestionRetryDelayMs, long networkFailureRetryMs) { - this.congestionRetryDelayMs = Math.min(MAX_DELAY, - congestionRetryDelayMs); - this.networkFailureRetryMs = Math.min(MAX_DELAY, networkFailureRetryMs); - } + /** + * @param congestionRetryDelayMs + * @param networkFailureRetryMs + */ + TrafficShaper(long congestionRetryDelayMs, long networkFailureRetryMs) { + this.congestionRetryDelayMs = Math.min(MAX_DELAY, congestionRetryDelayMs); + this.networkFailureRetryMs = Math.min(MAX_DELAY, networkFailureRetryMs); + } - /** - * - * @param processingResult - */ - void registerFailure(ProcessingResult processingResult) { - if (processingResult == ProcessingResult.Congestion) { - lastCongestionError = System.currentTimeMillis(); - } else if (processingResult == ProcessingResult.TransientError) { - lastNetworkFailure = System.currentTimeMillis(); - } - } + /** @param processingResult */ + void registerFailure(ProcessingResult processingResult) { + if (processingResult == ProcessingResult.Congestion) { + lastCongestionError = System.currentTimeMillis(); + } else if (processingResult == ProcessingResult.TransientError) { + lastNetworkFailure = System.currentTimeMillis(); + } + } - /** - * - * @return - */ - long transmissionDelay() { - if (lastCongestionError == -1 && lastNetworkFailure == -1) { - return 0; - } + /** @return */ + long transmissionDelay() { + if (lastCongestionError == -1 && lastNetworkFailure == -1) { + return 0; + } - long now = System.currentTimeMillis(); - if (lastCongestionError != -1) { - long congestionDelay = now - lastCongestionError; - if (congestionDelay >= 0 - && congestionDelay < congestionRetryDelayMs) { - return congestionRetryDelayMs - congestionDelay; - } - lastCongestionError = -1; - } + long now = System.currentTimeMillis(); + if (lastCongestionError != -1) { + long congestionDelay = now - lastCongestionError; + if (congestionDelay >= 0 && congestionDelay < congestionRetryDelayMs) { + return congestionRetryDelayMs - congestionDelay; + } + lastCongestionError = -1; + } - if (lastNetworkFailure != -1) { - long failureDelay = now - lastNetworkFailure; - if (failureDelay >= 0 && failureDelay < networkFailureRetryMs) { - return networkFailureRetryMs - failureDelay; - } - lastNetworkFailure = -1; - } - return 0; - } -} \ No newline at end of file + if (lastNetworkFailure != -1) { + long failureDelay = now - lastNetworkFailure; + if (failureDelay >= 0 && failureDelay < networkFailureRetryMs) { + return networkFailureRetryMs - failureDelay; + } + lastNetworkFailure = -1; + } + return 0; + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/DefaultTaskListenerManager.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/DefaultTaskListenerManager.java index a0aa07b2f..6ee622822 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/DefaultTaskListenerManager.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/DefaultTaskListenerManager.java @@ -16,11 +16,10 @@ */ package com.alipay.sofa.registry.task.listener; -import java.util.Collection; - import com.alipay.sofa.registry.task.listener.TaskEvent.TaskType; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; +import java.util.Collection; /** * @author xuanbei @@ -28,23 +27,23 @@ */ public class DefaultTaskListenerManager implements TaskListenerManager { - private Multimap taskListeners = ArrayListMultimap.create(); + private Multimap taskListeners = ArrayListMultimap.create(); - @Override - public Multimap getTaskListeners() { - return taskListeners; - } + @Override + public Multimap getTaskListeners() { + return taskListeners; + } - @Override - public void addTaskListener(TaskListener taskListener) { - taskListeners.put(taskListener.support(), taskListener); - } + @Override + public void addTaskListener(TaskListener taskListener) { + taskListeners.put(taskListener.support(), taskListener); + } - @Override - public void sendTaskEvent(TaskEvent taskEvent) { - Collection taskListeners = this.taskListeners.get(taskEvent.getTaskType()); - for (TaskListener taskListener : taskListeners) { - taskListener.handleEvent(taskEvent); - } + @Override + public void sendTaskEvent(TaskEvent taskEvent) { + Collection taskListeners = this.taskListeners.get(taskEvent.getTaskType()); + for (TaskListener taskListener : taskListeners) { + taskListener.handleEvent(taskEvent); } + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskEvent.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskEvent.java index ea9339474..4bdee6103 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskEvent.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskEvent.java @@ -21,166 +21,170 @@ import java.util.concurrent.atomic.AtomicInteger; /** - * * @author shangyu.wh * @version $Id: TaskEvent.java, v 0.1 2017-12-07 18:12 shangyu.wh Exp $ */ public class TaskEvent { - public enum TaskType { - //Session task - WATCHER_REGISTER_FETCH_TASK("WatcherRegisterFetchTask"), // - RECEIVED_DATA_CONFIG_PUSH_TASK("ReceivedDataConfigPushTask"), // - SYNC_PUBLISHER_TASK("SyncPublisherTask"), // - SYNC_UNPUBLISHER_TASK("SyncUnPublisherTask"), // - SYNC_SUBSCRIBER_TASK("SyncSubscriberTask"), // - SYNC_UNSUBSCRIBER_TASK("SyncUnSubscriberTask"), // - PROVIDE_DATA_CHANGE_FETCH_TASK("ProvideDataChangeFetchTask"), // - - //MetaServer task - PERSISTENCE_DATA_CHANGE_NOTIFY_TASK("PersistenceDataChangeNotifyTask"), // - ; + public enum TaskType { + // Session task + WATCHER_REGISTER_FETCH_TASK("WatcherRegisterFetchTask"), // + RECEIVED_DATA_CONFIG_PUSH_TASK("ReceivedDataConfigPushTask"), // + SYNC_PUBLISHER_TASK("SyncPublisherTask"), // + SYNC_UNPUBLISHER_TASK("SyncUnPublisherTask"), // + SYNC_SUBSCRIBER_TASK("SyncSubscriberTask"), // + SYNC_UNSUBSCRIBER_TASK("SyncUnSubscriberTask"), // + PROVIDE_DATA_CHANGE_FETCH_TASK("ProvideDataChangeFetchTask"), // - private String name; + // MetaServer task + PERSISTENCE_DATA_CHANGE_NOTIFY_TASK("PersistenceDataChangeNotifyTask"), // + ; - private AtomicInteger nextId = new AtomicInteger(0); + private String name; - TaskType(String name) { - this.name = name; - } + private AtomicInteger nextId = new AtomicInteger(0); - public String getName() { - return name; - } + TaskType(String name) { + this.name = name; } - private Object eventObj; - - private TaskType taskType; - - private long sendTimeStamp; - - private long createTime; - - private final String taskId; - - private final Map attributes = new ConcurrentHashMap(); - - /** - * constructor - * @param taskType - */ - public TaskEvent(TaskType taskType) { - this.taskType = taskType; - this.createTime = System.currentTimeMillis(); - this.taskId = String.format("%s-%s-%s", taskType.name, this.createTime, - taskType.nextId.getAndIncrement()); + public String getName() { + return name; } - - /** - * constructor - * @param eventObj - * @param taskType - */ - public TaskEvent(Object eventObj, TaskType taskType) { - this(taskType); - this.eventObj = eventObj; - } - - /** - * Getter method for property taskId. - * - * @return property value of taskId - */ - public String getTaskId() { - return taskId; - } - - /** - * Getter method for property eventObj. - * - * @return property value of eventObj - */ - public Object getEventObj() { - return eventObj; - } - - /** - * Setter method for property eventObj. - * - * @param eventObj value to be assigned to property eventObj - */ - public void setEventObj(Object eventObj) { - this.eventObj = eventObj; - } - - /** - * Getter method for property taskType. - * - * @return property value of taskType - */ - public TaskType getTaskType() { - return taskType; - } - - /** - * get attribute by key - * @param key - * @return - */ - public Object getAttribute(String key) { - return attributes.get(key); - } - - /** - * set attribute - * @param key - * @param value - */ - public void setAttribute(String key, Object value) { - if (value == null) { - //The null value is not allowed in the ConcurrentHashMap. - attributes.remove(key); - } else { - attributes.put(key, value); - } - } - - /** - * Getter method for property sendTimeStamp. - * - * @return property value of sendTimeStamp - */ - public long getSendTimeStamp() { - return sendTimeStamp; - } - - /** - * Setter method for property sendTimeStamp. - * - * @param sendTimeStamp value to be assigned to property sendTimeStamp - */ - public void setSendTimeStamp(long sendTimeStamp) { - this.sendTimeStamp = sendTimeStamp; - } - - /** - * Getter method for property createTime. - * - * @return property value of createTime - */ - public long getCreateTime() { - return createTime; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("TaskEvent{"); - sb.append("eventObj=").append(eventObj); - sb.append(", sendTimeStamp=").append(sendTimeStamp); - sb.append(", attributes=").append(attributes); - sb.append(", taskId='").append(taskId).append('\''); - sb.append('}'); - return sb.toString(); + } + + private Object eventObj; + + private TaskType taskType; + + private long sendTimeStamp; + + private long createTime; + + private final String taskId; + + private final Map attributes = new ConcurrentHashMap(); + + /** + * constructor + * + * @param taskType + */ + public TaskEvent(TaskType taskType) { + this.taskType = taskType; + this.createTime = System.currentTimeMillis(); + this.taskId = + String.format( + "%s-%s-%s", taskType.name, this.createTime, taskType.nextId.getAndIncrement()); + } + + /** + * constructor + * + * @param eventObj + * @param taskType + */ + public TaskEvent(Object eventObj, TaskType taskType) { + this(taskType); + this.eventObj = eventObj; + } + + /** + * Getter method for property taskId. + * + * @return property value of taskId + */ + public String getTaskId() { + return taskId; + } + + /** + * Getter method for property eventObj. + * + * @return property value of eventObj + */ + public Object getEventObj() { + return eventObj; + } + + /** + * Setter method for property eventObj. + * + * @param eventObj value to be assigned to property eventObj + */ + public void setEventObj(Object eventObj) { + this.eventObj = eventObj; + } + + /** + * Getter method for property taskType. + * + * @return property value of taskType + */ + public TaskType getTaskType() { + return taskType; + } + + /** + * get attribute by key + * + * @param key + * @return + */ + public Object getAttribute(String key) { + return attributes.get(key); + } + + /** + * set attribute + * + * @param key + * @param value + */ + public void setAttribute(String key, Object value) { + if (value == null) { + // The null value is not allowed in the ConcurrentHashMap. + attributes.remove(key); + } else { + attributes.put(key, value); } -} \ No newline at end of file + } + + /** + * Getter method for property sendTimeStamp. + * + * @return property value of sendTimeStamp + */ + public long getSendTimeStamp() { + return sendTimeStamp; + } + + /** + * Setter method for property sendTimeStamp. + * + * @param sendTimeStamp value to be assigned to property sendTimeStamp + */ + public void setSendTimeStamp(long sendTimeStamp) { + this.sendTimeStamp = sendTimeStamp; + } + + /** + * Getter method for property createTime. + * + * @return property value of createTime + */ + public long getCreateTime() { + return createTime; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("TaskEvent{"); + sb.append("eventObj=").append(eventObj); + sb.append(", sendTimeStamp=").append(sendTimeStamp); + sb.append(", attributes=").append(attributes); + sb.append(", taskId='").append(taskId).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskListener.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskListener.java index 37920b829..0914703cc 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskListener.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskListener.java @@ -19,23 +19,22 @@ import com.alipay.sofa.registry.task.listener.TaskEvent.TaskType; /** - * * @author shangyu.wh * @version $Id: TaskListener.java, v 0.1 2017-12-07 18:11 shangyu.wh Exp $ */ public interface TaskListener { - /** - * com.alipay.sofa.registry.server.meta.listener type check - * - * @return type - */ - TaskType support(); + /** + * com.alipay.sofa.registry.server.meta.listener type check + * + * @return type + */ + TaskType support(); - /** - * event execute - * - * @param event - */ - void handleEvent(TaskEvent event); -} \ No newline at end of file + /** + * event execute + * + * @param event + */ + void handleEvent(TaskEvent event); +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskListenerManager.java b/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskListenerManager.java index 58be148f8..e5b04c5f6 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskListenerManager.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/task/listener/TaskListenerManager.java @@ -20,27 +20,17 @@ import com.google.common.collect.Multimap; /** - * * @author shangyu.wh * @version $Id: TaskListenerManager.java, v 0.1 2017-12-07 18:14 shangyu.wh Exp $ */ public interface TaskListenerManager { - /** - * - * @return - */ - Multimap getTaskListeners(); + /** @return */ + Multimap getTaskListeners(); - /** - * - * @param taskListener - */ - void addTaskListener(TaskListener taskListener); + /** @param taskListener */ + void addTaskListener(TaskListener taskListener); - /** - * - * @param taskEvent - */ - void sendTaskEvent(TaskEvent taskEvent); -} \ No newline at end of file + /** @param taskEvent */ + void sendTaskEvent(TaskEvent taskEvent); +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/timer/AsyncHashedWheelTimer.java b/server/common/util/src/main/java/com/alipay/sofa/registry/timer/AsyncHashedWheelTimer.java index 7119a88a8..02f53fe30 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/timer/AsyncHashedWheelTimer.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/timer/AsyncHashedWheelTimer.java @@ -16,6 +16,9 @@ */ package com.alipay.sofa.registry.timer; +import io.netty.util.HashedWheelTimer; +import io.netty.util.Timeout; +import io.netty.util.TimerTask; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.RejectedExecutionException; @@ -23,120 +26,119 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import io.netty.util.HashedWheelTimer; -import io.netty.util.Timeout; -import io.netty.util.TimerTask; - /** - * based on HashedWheelTimer, add function: exec TimerTask async + * based on HashedWheelTimer, add function: exec TimerTask async * * @author kezhu.wukz * @version $Id: AsyncHashedWheelTimer.java, v 0.1 2019-01-11 10:54 AM kezhu.wukz Exp $ */ public class AsyncHashedWheelTimer extends HashedWheelTimer { - /** */ - protected final Executor executor; - - /** */ - protected final TaskFailedCallback taskFailedCallback; - - /** - * @param threadFactory - * @param tickDuration - * @param unit - * @param ticksPerWheel - * @param threadSize - * @param queueSize - * @param asyncThreadFactory - */ - public AsyncHashedWheelTimer(ThreadFactory threadFactory, long tickDuration, TimeUnit unit, - int ticksPerWheel, int threadSize, int queueSize, - ThreadFactory asyncThreadFactory, - TaskFailedCallback taskFailedCallback) { - super(threadFactory, tickDuration, unit, ticksPerWheel); - - ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(threadSize, threadSize, - 300L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(queueSize), asyncThreadFactory); - threadPoolExecutor.allowCoreThreadTimeOut(true); - this.executor = threadPoolExecutor; - this.taskFailedCallback = taskFailedCallback; + /** */ + protected final Executor executor; + + /** */ + protected final TaskFailedCallback taskFailedCallback; + + /** + * @param threadFactory + * @param tickDuration + * @param unit + * @param ticksPerWheel + * @param threadSize + * @param queueSize + * @param asyncThreadFactory + */ + public AsyncHashedWheelTimer( + ThreadFactory threadFactory, + long tickDuration, + TimeUnit unit, + int ticksPerWheel, + int threadSize, + int queueSize, + ThreadFactory asyncThreadFactory, + TaskFailedCallback taskFailedCallback) { + super(threadFactory, tickDuration, unit, ticksPerWheel); + + ThreadPoolExecutor threadPoolExecutor = + new ThreadPoolExecutor( + threadSize, + threadSize, + 300L, + TimeUnit.SECONDS, + new LinkedBlockingQueue<>(queueSize), + asyncThreadFactory); + threadPoolExecutor.allowCoreThreadTimeOut(true); + this.executor = threadPoolExecutor; + this.taskFailedCallback = taskFailedCallback; + } + + /** + * @param threadFactory + * @param tickDuration + * @param unit + * @param ticksPerWheel + * @param asyncExecutor + */ + public AsyncHashedWheelTimer( + ThreadFactory threadFactory, + long tickDuration, + TimeUnit unit, + int ticksPerWheel, + Executor asyncExecutor, + TaskFailedCallback taskFailedCallback) { + super(threadFactory, tickDuration, unit, ticksPerWheel); + + this.executor = asyncExecutor; + this.taskFailedCallback = taskFailedCallback; + } + + /** */ + @Override + public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { + return super.newTimeout(new AsyncTimerTask(task), delay, unit); + } + + /** */ + class AsyncTimerTask implements TimerTask, Runnable { + /** */ + TimerTask timerTask; + /** */ + Timeout timeout; + + /** @param timerTask */ + public AsyncTimerTask(TimerTask timerTask) { + super(); + this.timerTask = timerTask; } - /** - * - * @param threadFactory - * @param tickDuration - * @param unit - * @param ticksPerWheel - * @param asyncExecutor - */ - public AsyncHashedWheelTimer(ThreadFactory threadFactory, long tickDuration, TimeUnit unit, - int ticksPerWheel, Executor asyncExecutor, - TaskFailedCallback taskFailedCallback) { - super(threadFactory, tickDuration, unit, ticksPerWheel); - - this.executor = asyncExecutor; - this.taskFailedCallback = taskFailedCallback; - } - - /** - */ + /** */ @Override - public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { - return super.newTimeout(new AsyncTimerTask(task), delay, unit); + public void run(Timeout timeout) { + this.timeout = timeout; + try { + AsyncHashedWheelTimer.this.executor.execute(this); + } catch (RejectedExecutionException e) { + taskFailedCallback.executionRejected(e); + } catch (Throwable e) { + taskFailedCallback.executionFailed(e); + } } - /** - * - */ - class AsyncTimerTask implements TimerTask, Runnable { - /** */ - TimerTask timerTask; - /** */ - Timeout timeout; - - /** - * @param timerTask - */ - public AsyncTimerTask(TimerTask timerTask) { - super(); - this.timerTask = timerTask; - } - - /** - */ - @Override - public void run(Timeout timeout) { - this.timeout = timeout; - try { - AsyncHashedWheelTimer.this.executor.execute(this); - } catch (RejectedExecutionException e) { - taskFailedCallback.executionRejected(e); - } catch (Throwable e) { - taskFailedCallback.executionFailed(e); - } - } - - /** - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - try { - this.timerTask.run(this.timeout); - } catch (Throwable e) { - taskFailedCallback.executionFailed(e); - } - } - + /** @see java.lang.Runnable#run() */ + @Override + public void run() { + try { + this.timerTask.run(this.timeout); + } catch (Throwable e) { + taskFailedCallback.executionFailed(e); + } } + } - public interface TaskFailedCallback { - - void executionRejected(Throwable e); + public interface TaskFailedCallback { - void executionFailed(Throwable e); - - } + void executionRejected(Throwable e); + void executionFailed(Throwable e); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/timer/RecycleAsyncHashedWheelTimer.java b/server/common/util/src/main/java/com/alipay/sofa/registry/timer/RecycleAsyncHashedWheelTimer.java index fb3a0bd63..edbfd8192 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/timer/RecycleAsyncHashedWheelTimer.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/timer/RecycleAsyncHashedWheelTimer.java @@ -16,110 +16,118 @@ */ package com.alipay.sofa.registry.timer; +import io.netty.util.Timeout; +import io.netty.util.TimerTask; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.function.BooleanSupplier; -import io.netty.util.Timeout; -import io.netty.util.TimerTask; - /** - * * @author kezhu.wukz * @version $Id: RecycleAsyncHashedWheelTimer.java, v 0.1 2019-07-27 10:54 kezhu.wukz Exp $ */ public class RecycleAsyncHashedWheelTimer extends AsyncHashedWheelTimer { - public RecycleAsyncHashedWheelTimer(ThreadFactory threadFactory, long tickDuration, - TimeUnit unit, int ticksPerWheel, int threadSize, - int queueSize, ThreadFactory asyncThreadFactory, - TaskFailedCallback taskFailedCallback) { - super(threadFactory, tickDuration, unit, ticksPerWheel, threadSize, queueSize, - asyncThreadFactory, taskFailedCallback); + public RecycleAsyncHashedWheelTimer( + ThreadFactory threadFactory, + long tickDuration, + TimeUnit unit, + int ticksPerWheel, + int threadSize, + int queueSize, + ThreadFactory asyncThreadFactory, + TaskFailedCallback taskFailedCallback) { + super( + threadFactory, + tickDuration, + unit, + ticksPerWheel, + threadSize, + queueSize, + asyncThreadFactory, + taskFailedCallback); + } + + public RecycleAsyncHashedWheelTimer( + ThreadFactory threadFactory, + long tickDuration, + TimeUnit unit, + int ticksPerWheel, + Executor asyncExecutor, + TaskFailedCallback taskFailedCallback) { + super(threadFactory, tickDuration, unit, ticksPerWheel, asyncExecutor, taskFailedCallback); + } + + public Timeout newTimeout( + TimerTask task, + long firstDelay, + long recycleDelay, + TimeUnit unit, + BooleanSupplier checkCondition) { + + return super.newTimeout( + new RecycleAsyncTimerTask(task, recycleDelay, unit, checkCondition), firstDelay, unit); + } + + public Timeout newTimeout( + TimerTask task, long recycleDelay, TimeUnit unit, BooleanSupplier checkCondition) { + + return super.newTimeout( + new RecycleAsyncTimerTask(task, recycleDelay, unit, checkCondition), recycleDelay, unit); + } + + /** */ + class RecycleAsyncTimerTask implements TimerTask, Runnable { + /** */ + private final TimerTask timerTask; + + private final long recycleDelay; + + private final TimeUnit delayUnit; + + private final BooleanSupplier checkCondition; + + /** */ + private Timeout timeout; + + /** @param timerTask */ + public RecycleAsyncTimerTask( + TimerTask timerTask, long recycleDelay, TimeUnit unit, BooleanSupplier checkCondition) { + super(); + this.timerTask = timerTask; + this.recycleDelay = recycleDelay; + this.delayUnit = unit; + this.checkCondition = checkCondition; } - public RecycleAsyncHashedWheelTimer(ThreadFactory threadFactory, long tickDuration, - TimeUnit unit, int ticksPerWheel, Executor asyncExecutor, - TaskFailedCallback taskFailedCallback) { - super(threadFactory, tickDuration, unit, ticksPerWheel, asyncExecutor, taskFailedCallback); - } - - public Timeout newTimeout(TimerTask task, long firstDelay, long recycleDelay, TimeUnit unit, - BooleanSupplier checkCondition) { - - return super.newTimeout( - new RecycleAsyncTimerTask(task, recycleDelay, unit, checkCondition), firstDelay, unit); - } - - public Timeout newTimeout(TimerTask task, long recycleDelay, TimeUnit unit, - BooleanSupplier checkCondition) { - - return super - .newTimeout(new RecycleAsyncTimerTask(task, recycleDelay, unit, checkCondition), - recycleDelay, unit); + /** */ + @Override + public void run(Timeout timeout) { + this.timeout = timeout; + try { + RecycleAsyncHashedWheelTimer.super.executor.execute(this); + } catch (RejectedExecutionException e) { + taskFailedCallback.executionRejected(e); + } catch (Throwable e) { + taskFailedCallback.executionFailed(e); + } } - /** - * - */ - class RecycleAsyncTimerTask implements TimerTask, Runnable { - /** */ - private final TimerTask timerTask; - - private final long recycleDelay; - - private final TimeUnit delayUnit; - - private final BooleanSupplier checkCondition; - - /** */ - private Timeout timeout; - - /** - * @param timerTask - */ - public RecycleAsyncTimerTask(TimerTask timerTask, long recycleDelay, TimeUnit unit, - BooleanSupplier checkCondition) { - super(); - this.timerTask = timerTask; - this.recycleDelay = recycleDelay; - this.delayUnit = unit; - this.checkCondition = checkCondition; + /** @see java.lang.Runnable#run() */ + @Override + public void run() { + try { + this.timerTask.run(this.timeout); + } catch (Throwable e) { + taskFailedCallback.executionFailed(e); + } finally { + if (checkCondition.getAsBoolean()) { + RecycleAsyncHashedWheelTimer.this.newTimeout( + timerTask, recycleDelay, delayUnit, checkCondition); } - - /** - */ - @Override - public void run(Timeout timeout) { - this.timeout = timeout; - try { - RecycleAsyncHashedWheelTimer.super.executor.execute(this); - } catch (RejectedExecutionException e) { - taskFailedCallback.executionRejected(e); - } catch (Throwable e) { - taskFailedCallback.executionFailed(e); - } - } - - /** - * @see java.lang.Runnable#run() - */ - @Override - public void run() { - try { - this.timerTask.run(this.timeout); - } catch (Throwable e) { - taskFailedCallback.executionFailed(e); - } finally { - if (checkCondition.getAsBoolean()) { - RecycleAsyncHashedWheelTimer.this.newTimeout(timerTask, recycleDelay, - delayUnit, checkCondition); - } - } - } - + } } - -} \ No newline at end of file + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/trace/TraceID.java b/server/common/util/src/main/java/com/alipay/sofa/registry/trace/TraceID.java index 1b6d0aa77..889806446 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/trace/TraceID.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/trace/TraceID.java @@ -21,38 +21,40 @@ import java.util.concurrent.atomic.AtomicLong; public final class TraceID implements Serializable { - private transient static final UUID SEED = UUID.randomUUID(); - private transient static final AtomicLong SEQ = new AtomicLong(); - - private final long mostSigBits; - private final long leastSigBits; - private final long seq; - - private transient volatile String string; - - private TraceID(long most, long least, long seq) { - this.mostSigBits = most; - this.leastSigBits = least; - this.seq = seq; - } - - public static TraceID newTraceID() { - return new TraceID(SEED.getMostSignificantBits(), SEED.getLeastSignificantBits(), - SEQ.incrementAndGet()); - } - - @Override - public String toString() { - if (string == null) { - string = createString(); - } - return string; - } - - private String createString() { - StringBuilder sb = new StringBuilder(64); - sb.append(Long.toHexString(mostSigBits)).append(Long.toHexString(leastSigBits)).append('-') - .append(seq); - return sb.toString(); + private static final transient UUID SEED = UUID.randomUUID(); + private static final transient AtomicLong SEQ = new AtomicLong(); + + private final long mostSigBits; + private final long leastSigBits; + private final long seq; + + private transient volatile String string; + + private TraceID(long most, long least, long seq) { + this.mostSigBits = most; + this.leastSigBits = least; + this.seq = seq; + } + + public static TraceID newTraceID() { + return new TraceID( + SEED.getMostSignificantBits(), SEED.getLeastSignificantBits(), SEQ.incrementAndGet()); + } + + @Override + public String toString() { + if (string == null) { + string = createString(); } + return string; + } + + private String createString() { + StringBuilder sb = new StringBuilder(64); + sb.append(Long.toHexString(mostSigBits)) + .append(Long.toHexString(leastSigBits)) + .append('-') + .append(seq); + return sb.toString(); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/BatchCallableRunnable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/BatchCallableRunnable.java index 05f29de7d..b07c50c4e 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/BatchCallableRunnable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/BatchCallableRunnable.java @@ -18,197 +18,190 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; - -import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import javax.annotation.PostConstruct; /** * batch callable with future + * * @author xiaojian.xj * @version $Id: BatchCallableRunnable.java, v 0.1 2021年01月22日 22:00 xiaojian.xj Exp $ */ public abstract class BatchCallableRunnable { - protected Integer sleep; - - protected TimeUnit timeUnit; - - // must have - protected int batchSize; - - // no blocking - private final Queue queue = new ConcurrentLinkedQueue(); - - public InvokeFuture commit(TaskEvent task) { - queue.offer(task); - return task.future; - } - - public abstract boolean batchProcess(List tasks); - - @PostConstruct - public void init() { - setBatchSize(); - setTimeUnit(); - setSleep(); - ConcurrentUtils.createDaemonThread(this.getClass().getSimpleName() + "WatchDog", - new BatchCallableWatchDog()).start(); - } - - private class BatchCallableWatchDog extends LoopRunnable { - - private final Logger LOG = LoggerFactory.getLogger(BatchCallableWatchDog.class); - - @Override - public void runUnthrowable() { - List tasks = new ArrayList<>(); - - for (int i = 0; i < batchSize && !queue.isEmpty(); i++) { - TaskEvent task = queue.poll(); - tasks.add(task); - } - try { - if (batchProcess(tasks)) { - for (TaskEvent task : tasks) { - task.future.finish(); - } - } else { - for (TaskEvent task : tasks) { - task.future.fail(); - } - } - } catch (Throwable t) { - // TODO failed the task - LOG.error("batch run task error.", t); - for (TaskEvent task : tasks) { - task.future.error(t.getMessage()); - } - } + protected Integer sleep; + + protected TimeUnit timeUnit; + + // must have + protected int batchSize; + + // no blocking + private final Queue queue = new ConcurrentLinkedQueue(); + + public InvokeFuture commit(TaskEvent task) { + queue.offer(task); + return task.future; + } + + public abstract boolean batchProcess(List tasks); + + @PostConstruct + public void init() { + setBatchSize(); + setTimeUnit(); + setSleep(); + ConcurrentUtils.createDaemonThread( + this.getClass().getSimpleName() + "WatchDog", new BatchCallableWatchDog()) + .start(); + } + + private class BatchCallableWatchDog extends LoopRunnable { + + private final Logger LOG = LoggerFactory.getLogger(BatchCallableWatchDog.class); + + @Override + public void runUnthrowable() { + List tasks = new ArrayList<>(); + + for (int i = 0; i < batchSize && !queue.isEmpty(); i++) { + TaskEvent task = queue.poll(); + tasks.add(task); + } + try { + if (batchProcess(tasks)) { + for (TaskEvent task : tasks) { + task.future.finish(); + } + } else { + for (TaskEvent task : tasks) { + task.future.fail(); + } } - - @Override - public void waitingUnthrowable() { - ConcurrentUtils.sleepUninterruptibly(sleep, timeUnit); + } catch (Throwable t) { + // TODO failed the task + LOG.error("batch run task error.", t); + for (TaskEvent task : tasks) { + task.future.error(t.getMessage()); } - + } } - public final class TaskEvent { + @Override + public void waitingUnthrowable() { + ConcurrentUtils.sleepUninterruptibly(sleep, timeUnit); + } + } - private T data; + public final class TaskEvent { - private InvokeFuture future; + private T data; - public TaskEvent(T data) { - this.data = data; - this.future = new InvokeFuture(); - } + private InvokeFuture future; - /** - * Getter method for property data. - * - * @return property value of data - */ - public T getData() { - return data; - } - - /** - * Setter method for property data. - * - * @param data value to be assigned to property data - */ - public void setData(T data) { - this.data = data; - } + public TaskEvent(T data) { + this.data = data; + this.future = new InvokeFuture(); + } - /** - * Getter method for property future. - * - * @return property value of future - */ - public InvokeFuture getFuture() { - return future; - } + /** + * Getter method for property data. + * + * @return property value of data + */ + public T getData() { + return data; + } - /** - * Setter method for property future. - * - * @param future value to be assigned to property future - */ - public void setFuture(InvokeFuture future) { - this.future = future; - } + /** + * Setter method for property data. + * + * @param data value to be assigned to property data + */ + public void setData(T data) { + this.data = data; } - public class InvokeFuture { + /** + * Getter method for property future. + * + * @return property value of future + */ + public InvokeFuture getFuture() { + return future; + } - private boolean success; + /** + * Setter method for property future. + * + * @param future value to be assigned to property future + */ + public void setFuture(InvokeFuture future) { + this.future = future; + } + } - private String message; + public class InvokeFuture { - private E response; + private boolean success; - private final CountDownLatch countDownLatch = new CountDownLatch(1); + private String message; - public void finish() { - this.countDownLatch.countDown(); - } + private E response; - public void fail() { - this.success = false; - this.countDownLatch.countDown(); + private final CountDownLatch countDownLatch = new CountDownLatch(1); - } + public void finish() { + this.countDownLatch.countDown(); + } - public void error(String message) { - this.success = false; - this.message = message; - this.countDownLatch.countDown(); - } + public void fail() { + this.success = false; + this.countDownLatch.countDown(); + } - public void putResponse(E response) { - this.success = true; - this.response = response; - } + public void error(String message) { + this.success = false; + this.message = message; + this.countDownLatch.countDown(); + } - public boolean isSuccess() throws InterruptedException { - this.countDownLatch.await(); - return success; - } + public void putResponse(E response) { + this.success = true; + this.response = response; + } - public E getResponse() throws InterruptedException { - this.countDownLatch.await(); - return response; - } + public boolean isSuccess() throws InterruptedException { + this.countDownLatch.await(); + return success; + } - /** - * Getter method for property message. - * - * @return property value of message - */ - public String getMessage() { - return message; - } + public E getResponse() throws InterruptedException { + this.countDownLatch.await(); + return response; } /** - * Setter method for property sleep. - **/ - protected abstract void setSleep(); + * Getter method for property message. + * + * @return property value of message + */ + public String getMessage() { + return message; + } + } - /** - * Setter method for property timeUnit. - **/ - protected abstract void setTimeUnit(); + /** Setter method for property sleep. */ + protected abstract void setSleep(); - /** - * Setter method for property batchSize. - **/ - protected abstract void setBatchSize(); -} \ No newline at end of file + /** Setter method for property timeUnit. */ + protected abstract void setTimeUnit(); + + /** Setter method for property batchSize. */ + protected abstract void setBatchSize(); +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/Bool.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/Bool.java index b157531ee..e99b37e64 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/Bool.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/Bool.java @@ -17,30 +17,29 @@ package com.alipay.sofa.registry.util; /** - * * @author yuzhi.lyz * @version v 0.1 2020-10-30 16:52 yuzhi.lyz Exp $ */ public final class Bool { - private boolean bool; + private boolean bool; - private Bool(boolean b) { - this.bool = b; - } + private Bool(boolean b) { + this.bool = b; + } - public static Bool newTrue() { - return new Bool(true); - } + public static Bool newTrue() { + return new Bool(true); + } - public static Bool newFalse() { - return new Bool(false); - } + public static Bool newFalse() { + return new Bool(false); + } - public boolean isTrue() { - return bool; - } + public boolean isTrue() { + return bool; + } - public void setBool(boolean bool) { - this.bool = bool; - } + public void setBool(boolean bool) { + this.bool = bool; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/CollectionUtils.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/CollectionUtils.java index e43307454..b1f909b85 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/CollectionUtils.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/CollectionUtils.java @@ -21,19 +21,20 @@ /** * The type Collection utils. + * * @author zhuoyu.sjw * @version $Id : CollectionUtils.java, v 0.1 2018-04-12 14:54 zhuoyu.sjw Exp $$ */ public class CollectionUtils { - /** - * Gets random. - * - * @param the type parameter - * @param e the e - * @return the random - */ - public static Optional getRandom(Collection e) { - return e.stream().skip((int) (e.size() * Math.random())).findFirst(); - } + /** + * Gets random. + * + * @param the type parameter + * @param e the e + * @return the random + */ + public static Optional getRandom(Collection e) { + return e.stream().skip((int) (e.size() * Math.random())).findFirst(); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/ConcurrentUtils.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/ConcurrentUtils.java index 92dc7d3ae..1b85bf0b3 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/ConcurrentUtils.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/ConcurrentUtils.java @@ -20,7 +20,6 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.util.concurrent.MoreExecutors; - import java.util.Collection; import java.util.List; import java.util.concurrent.BlockingQueue; @@ -29,89 +28,87 @@ /** * @author chen.zhu - *

- * Nov 23, 2020 + *

Nov 23, 2020 */ public final class ConcurrentUtils { - private static final Logger LOGGER = LoggerFactory.getLogger(ConcurrentUtils.class); - - private ConcurrentUtils() { - } - - public static abstract class SafeParaLoop { - - private static final Logger logger = LoggerFactory.getLogger(SafeParaLoop.class); - - private List list; + private static final Logger LOGGER = LoggerFactory.getLogger(ConcurrentUtils.class); - private Executor executors; + private ConcurrentUtils() {} - public SafeParaLoop(Collection list) { - this(MoreExecutors.directExecutor(), list); - } + public abstract static class SafeParaLoop { - public SafeParaLoop(Executor executors, Collection src) { - this.executors = executors; - this.list = src == null ? null : Lists.newLinkedList(src); - } + private static final Logger logger = LoggerFactory.getLogger(SafeParaLoop.class); - public void run() { - if (list == null) { - return; - } - for (T t : list) { - executors.execute(new Runnable() { - @Override - public void run() { - try { - doRun0(t); - } catch (Throwable e) { - logger.error("[SafeParaLoop][{}]", getInfo(t), e); - } - } - }); + private List list; - } - } + private Executor executors; - protected abstract void doRun0(T t) throws Exception; - - String getInfo(T t) { - return t.toString(); - } + public SafeParaLoop(Collection list) { + this(MoreExecutors.directExecutor(), list); } - public static Thread createDaemonThread(String name, Runnable r) { - Thread t = new Thread(r, name); - t.setDaemon(true); - return t; + public SafeParaLoop(Executor executors, Collection src) { + this.executors = executors; + this.list = src == null ? null : Lists.newLinkedList(src); } - public static void objectWaitUninterruptibly(Object o, int timeoutMs) { - try { - o.wait(timeoutMs); - } catch (InterruptedException ignored) { - // no need to remark Thread.currentThread().interrupt(); - LOGGER.warn("Interrupted waiting", ignored); - } + public void run() { + if (list == null) { + return; + } + for (T t : list) { + executors.execute( + new Runnable() { + @Override + public void run() { + try { + doRun0(t); + } catch (Throwable e) { + logger.error("[SafeParaLoop][{}]", getInfo(t), e); + } + } + }); + } } - public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) { - try { - unit.sleep(sleepFor); - } catch (InterruptedException ignored) { - // no need to remark Thread.currentThread().interrupt(); - LOGGER.warn("Interrupted sleeping", ignored); - } - } + protected abstract void doRun0(T t) throws Exception; - public static T pollUninterruptibly(BlockingQueue queue, long wait, TimeUnit unit) { - try { - return queue.poll(wait, unit); - } catch (InterruptedException ignored) { - // no need to remark Thread.currentThread().interrupt(); - LOGGER.warn("Interrupted polling", ignored); - } - return null; + String getInfo(T t) { + return t.toString(); + } + } + + public static Thread createDaemonThread(String name, Runnable r) { + Thread t = new Thread(r, name); + t.setDaemon(true); + return t; + } + + public static void objectWaitUninterruptibly(Object o, int timeoutMs) { + try { + o.wait(timeoutMs); + } catch (InterruptedException ignored) { + // no need to remark Thread.currentThread().interrupt(); + LOGGER.warn("Interrupted waiting", ignored); + } + } + + public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) { + try { + unit.sleep(sleepFor); + } catch (InterruptedException ignored) { + // no need to remark Thread.currentThread().interrupt(); + LOGGER.warn("Interrupted sleeping", ignored); + } + } + + public static T pollUninterruptibly(BlockingQueue queue, long wait, TimeUnit unit) { + try { + return queue.poll(wait, unit); + } catch (InterruptedException ignored) { + // no need to remark Thread.currentThread().interrupt(); + LOGGER.warn("Interrupted polling", ignored); } + return null; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/DatumVersionUtil.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/DatumVersionUtil.java index 03abb430d..7d2925af8 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/DatumVersionUtil.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/DatumVersionUtil.java @@ -18,65 +18,63 @@ /** * generates ID: 49 bit millisecond timestamp + 15 bit incremental ID - * - * refer to: https://github.com/twitter/snowflake - * + * + *

refer to: https://github.com/twitter/snowflake + * * @author kezhu.wukz * @version $Id: DatumVersionUtil.java, v 0.1 2019-07-04 22:05 kezhu.wukz Exp $ */ public final class DatumVersionUtil { - private DatumVersionUtil() { - } - - private static long sequence = 0L; + private DatumVersionUtil() {} - /** Tue Jan 01 00:00:00 CST 2019 */ - private static long twepoch = 1546272000000L; + private static long sequence = 0L; - private static long sequenceBits = 15L; - private static long timestampLeftShift = sequenceBits; - private static long sequenceMask = -1L ^ (-1L << sequenceBits); + /** Tue Jan 01 00:00:00 CST 2019 */ + private static long twepoch = 1546272000000L; - private static long lastTimestamp = -1L; + private static long sequenceBits = 15L; + private static long timestampLeftShift = sequenceBits; + private static long sequenceMask = -1L ^ (-1L << sequenceBits); - public synchronized static long nextId() { - long timestamp = timeGen(); + private static long lastTimestamp = -1L; - if (timestamp < lastTimestamp) { - throw new RuntimeException( - String.format( - "Clock moved backwards. Refusing to generate id for %d milliseconds", - lastTimestamp - timestamp)); - } + public static synchronized long nextId() { + long timestamp = timeGen(); - if (lastTimestamp == timestamp) { - sequence = (sequence + 1) & sequenceMask; - if (sequence == 0) { - timestamp = untilNextMillis(lastTimestamp); - } - } else { - sequence = 0L; - } + if (timestamp < lastTimestamp) { + throw new RuntimeException( + String.format( + "Clock moved backwards. Refusing to generate id for %d milliseconds", + lastTimestamp - timestamp)); + } - lastTimestamp = timestamp; + if (lastTimestamp == timestamp) { + sequence = (sequence + 1) & sequenceMask; + if (sequence == 0) { + timestamp = untilNextMillis(lastTimestamp); + } + } else { + sequence = 0L; + } - return ((timestamp - twepoch) << timestampLeftShift) | sequence; - } + lastTimestamp = timestamp; - public static long getRealTimestamp(long id) { - return (id >> timestampLeftShift) + twepoch; - } + return ((timestamp - twepoch) << timestampLeftShift) | sequence; + } - private static long untilNextMillis(long lastTimestamp) { - long timestamp = timeGen(); - while (timestamp <= lastTimestamp) { - timestamp = timeGen(); - } - return timestamp; - } + public static long getRealTimestamp(long id) { + return (id >> timestampLeftShift) + twepoch; + } - private static long timeGen() { - return System.currentTimeMillis(); - } + private static long untilNextMillis(long lastTimestamp) { + long timestamp = timeGen(); + while (timestamp <= lastTimestamp) { + timestamp = timeGen(); + } + return timestamp; + } -} \ No newline at end of file + private static long timeGen() { + return System.currentTimeMillis(); + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/DefaultExecutorFactory.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/DefaultExecutorFactory.java index 3136478e5..43325d18b 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/DefaultExecutorFactory.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/DefaultExecutorFactory.java @@ -20,114 +20,165 @@ /** * @author chen.zhu - *

- * Nov 23, 2020 + *

Nov 23, 2020 */ public class DefaultExecutorFactory implements ObjectFactory { - private static final int DEFAULT_MAX_QUEUE_SIZE = 1 << 20; - private static final RejectedExecutionHandler DEFAULT_HANDLER = new ThreadPoolExecutor.CallerRunsPolicy(); - private static final int DEFAULT_CORE_POOL_SIZE = OsUtils - .getCpuCount(); - private static final int DEFAULT_MAX_POOL_SIZE = 4 * OsUtils - .getCpuCount(); - private static final int DEFAULT_KEEPER_ALIVE_TIME_SECONDS = 60; - private static final boolean DEFAULT_ALLOW_CORE_THREAD_TIMEOUT = true; - private static final String DEFAULT_THREAD_PREFIX = "SofaRegistry"; + private static final int DEFAULT_MAX_QUEUE_SIZE = 1 << 20; + private static final RejectedExecutionHandler DEFAULT_HANDLER = + new ThreadPoolExecutor.CallerRunsPolicy(); + private static final int DEFAULT_CORE_POOL_SIZE = OsUtils.getCpuCount(); + private static final int DEFAULT_MAX_POOL_SIZE = 4 * OsUtils.getCpuCount(); + private static final int DEFAULT_KEEPER_ALIVE_TIME_SECONDS = 60; + private static final boolean DEFAULT_ALLOW_CORE_THREAD_TIMEOUT = true; + private static final String DEFAULT_THREAD_PREFIX = "SofaRegistry"; - private int corePoolSize = DEFAULT_CORE_POOL_SIZE; - private int maxPoolSize = DEFAULT_MAX_POOL_SIZE; - private long keepAliveTime = DEFAULT_KEEPER_ALIVE_TIME_SECONDS; - private BlockingQueue workQueue; - private TimeUnit keepAliveTimeUnit = TimeUnit.SECONDS; - private ThreadFactory threadFactory; - private String threadNamePrefix = DEFAULT_THREAD_PREFIX; - private RejectedExecutionHandler rejectedExecutionHandler = DEFAULT_HANDLER; - private boolean allowCoreThreadTimeOut = DEFAULT_ALLOW_CORE_THREAD_TIMEOUT; + private int corePoolSize = DEFAULT_CORE_POOL_SIZE; + private int maxPoolSize = DEFAULT_MAX_POOL_SIZE; + private long keepAliveTime = DEFAULT_KEEPER_ALIVE_TIME_SECONDS; + private BlockingQueue workQueue; + private TimeUnit keepAliveTimeUnit = TimeUnit.SECONDS; + private ThreadFactory threadFactory; + private String threadNamePrefix = DEFAULT_THREAD_PREFIX; + private RejectedExecutionHandler rejectedExecutionHandler = DEFAULT_HANDLER; + private boolean allowCoreThreadTimeOut = DEFAULT_ALLOW_CORE_THREAD_TIMEOUT; - public static DefaultExecutorFactory createAllowCoreTimeout(String threadNamePrefix) { - return new DefaultExecutorFactory(threadNamePrefix, DEFAULT_CORE_POOL_SIZE, true); - } + public static DefaultExecutorFactory createAllowCoreTimeout(String threadNamePrefix) { + return new DefaultExecutorFactory(threadNamePrefix, DEFAULT_CORE_POOL_SIZE, true); + } - public static DefaultExecutorFactory createAllowCoreTimeout(String threadNamePrefix, - int corePoolSize) { - return new DefaultExecutorFactory(threadNamePrefix, corePoolSize, true); - } + public static DefaultExecutorFactory createAllowCoreTimeout( + String threadNamePrefix, int corePoolSize) { + return new DefaultExecutorFactory(threadNamePrefix, corePoolSize, true); + } - public static DefaultExecutorFactory createCachedThreadPoolFactory(String threadNamePrefix, - int corePoolSize, - int corePoolTimeAlive, - TimeUnit corePoolTimeAliveUnit) { - return new DefaultExecutorFactory(threadNamePrefix, corePoolSize, true, Integer.MAX_VALUE, - new SynchronousQueue(), corePoolTimeAlive, corePoolTimeAliveUnit, - DEFAULT_HANDLER); - } + public static DefaultExecutorFactory createCachedThreadPoolFactory( + String threadNamePrefix, + int corePoolSize, + int corePoolTimeAlive, + TimeUnit corePoolTimeAliveUnit) { + return new DefaultExecutorFactory( + threadNamePrefix, + corePoolSize, + true, + Integer.MAX_VALUE, + new SynchronousQueue(), + corePoolTimeAlive, + corePoolTimeAliveUnit, + DEFAULT_HANDLER); + } - public static DefaultExecutorFactory createCachedThreadPoolFactory(String threadNamePrefix, - int corePoolSize, - int corePoolTimeAlive, - TimeUnit corePoolTimeAliveUnit, - RejectedExecutionHandler rejectedExecutionHandler) { - return new DefaultExecutorFactory(threadNamePrefix, corePoolSize, true, Integer.MAX_VALUE, - new SynchronousQueue(), corePoolTimeAlive, corePoolTimeAliveUnit, - rejectedExecutionHandler); - } + public static DefaultExecutorFactory createCachedThreadPoolFactory( + String threadNamePrefix, + int corePoolSize, + int corePoolTimeAlive, + TimeUnit corePoolTimeAliveUnit, + RejectedExecutionHandler rejectedExecutionHandler) { + return new DefaultExecutorFactory( + threadNamePrefix, + corePoolSize, + true, + Integer.MAX_VALUE, + new SynchronousQueue(), + corePoolTimeAlive, + corePoolTimeAliveUnit, + rejectedExecutionHandler); + } - public DefaultExecutorFactory(String threadNamePrefix, int corePoolSize, int maxPoolSize) { - this(threadNamePrefix, corePoolSize, DEFAULT_ALLOW_CORE_THREAD_TIMEOUT, maxPoolSize, - DEFAULT_MAX_QUEUE_SIZE, 60, TimeUnit.SECONDS, DEFAULT_HANDLER); - } + public DefaultExecutorFactory(String threadNamePrefix, int corePoolSize, int maxPoolSize) { + this( + threadNamePrefix, + corePoolSize, + DEFAULT_ALLOW_CORE_THREAD_TIMEOUT, + maxPoolSize, + DEFAULT_MAX_QUEUE_SIZE, + 60, + TimeUnit.SECONDS, + DEFAULT_HANDLER); + } - public DefaultExecutorFactory(String threadNamePrefix, int corePoolSize, int maxPoolSize, - RejectedExecutionHandler rejectedExecutionHandler) { - this(threadNamePrefix, corePoolSize, DEFAULT_ALLOW_CORE_THREAD_TIMEOUT, maxPoolSize, - DEFAULT_MAX_QUEUE_SIZE, 60, TimeUnit.SECONDS, rejectedExecutionHandler); - } + public DefaultExecutorFactory( + String threadNamePrefix, + int corePoolSize, + int maxPoolSize, + RejectedExecutionHandler rejectedExecutionHandler) { + this( + threadNamePrefix, + corePoolSize, + DEFAULT_ALLOW_CORE_THREAD_TIMEOUT, + maxPoolSize, + DEFAULT_MAX_QUEUE_SIZE, + 60, + TimeUnit.SECONDS, + rejectedExecutionHandler); + } - public DefaultExecutorFactory(String threadNamePrefix, int corePoolSize, - boolean allowCoreThreadTimeOut) { - this(threadNamePrefix, corePoolSize, allowCoreThreadTimeOut, DEFAULT_MAX_POOL_SIZE, - DEFAULT_MAX_QUEUE_SIZE, 60, TimeUnit.SECONDS, DEFAULT_HANDLER); - } + public DefaultExecutorFactory( + String threadNamePrefix, int corePoolSize, boolean allowCoreThreadTimeOut) { + this( + threadNamePrefix, + corePoolSize, + allowCoreThreadTimeOut, + DEFAULT_MAX_POOL_SIZE, + DEFAULT_MAX_QUEUE_SIZE, + 60, + TimeUnit.SECONDS, + DEFAULT_HANDLER); + } - public DefaultExecutorFactory(String threadNamePrefix, int corePoolSize, - boolean allowCoreThreadTimeOut, int maxPoolSize, - int maxQueueSize, int keepAliveTime, TimeUnit keepAliveTimeUnit, - RejectedExecutionHandler rejectedExecutionHandler) { - this.threadNamePrefix = threadNamePrefix; - this.corePoolSize = corePoolSize; - this.allowCoreThreadTimeOut = allowCoreThreadTimeOut; - this.maxPoolSize = maxPoolSize; - this.keepAliveTime = keepAliveTime; - this.keepAliveTimeUnit = keepAliveTimeUnit; - this.workQueue = new LinkedBlockingQueue<>(maxQueueSize); - this.rejectedExecutionHandler = rejectedExecutionHandler; - } + public DefaultExecutorFactory( + String threadNamePrefix, + int corePoolSize, + boolean allowCoreThreadTimeOut, + int maxPoolSize, + int maxQueueSize, + int keepAliveTime, + TimeUnit keepAliveTimeUnit, + RejectedExecutionHandler rejectedExecutionHandler) { + this.threadNamePrefix = threadNamePrefix; + this.corePoolSize = corePoolSize; + this.allowCoreThreadTimeOut = allowCoreThreadTimeOut; + this.maxPoolSize = maxPoolSize; + this.keepAliveTime = keepAliveTime; + this.keepAliveTimeUnit = keepAliveTimeUnit; + this.workQueue = new LinkedBlockingQueue<>(maxQueueSize); + this.rejectedExecutionHandler = rejectedExecutionHandler; + } - public DefaultExecutorFactory(String threadNamePrefix, int corePoolSize, - boolean allowCoreThreadTimeOut, int maxPoolSize, - BlockingQueue queue, int keepAliveTime, - TimeUnit keepAliveTimeUnit, - RejectedExecutionHandler rejectedExecutionHandler) { - this.threadNamePrefix = threadNamePrefix; - this.corePoolSize = corePoolSize; - this.allowCoreThreadTimeOut = allowCoreThreadTimeOut; - this.maxPoolSize = maxPoolSize; - this.keepAliveTime = keepAliveTime; - this.keepAliveTimeUnit = keepAliveTimeUnit; - this.workQueue = queue; - this.rejectedExecutionHandler = rejectedExecutionHandler; - } + public DefaultExecutorFactory( + String threadNamePrefix, + int corePoolSize, + boolean allowCoreThreadTimeOut, + int maxPoolSize, + BlockingQueue queue, + int keepAliveTime, + TimeUnit keepAliveTimeUnit, + RejectedExecutionHandler rejectedExecutionHandler) { + this.threadNamePrefix = threadNamePrefix; + this.corePoolSize = corePoolSize; + this.allowCoreThreadTimeOut = allowCoreThreadTimeOut; + this.maxPoolSize = maxPoolSize; + this.keepAliveTime = keepAliveTime; + this.keepAliveTimeUnit = keepAliveTimeUnit; + this.workQueue = queue; + this.rejectedExecutionHandler = rejectedExecutionHandler; + } - @Override - public ExecutorService create() { - // core pool size must be less or equal to max size - int useMaxPoolSize = Math.max(corePoolSize, maxPoolSize); - ThreadPoolExecutor executor = new ThreadPoolExecutor(corePoolSize, useMaxPoolSize, - keepAliveTime, keepAliveTimeUnit, workQueue, threadFactory != null ? threadFactory - : new NamedThreadFactory(threadNamePrefix), rejectedExecutionHandler); + @Override + public ExecutorService create() { + // core pool size must be less or equal to max size + int useMaxPoolSize = Math.max(corePoolSize, maxPoolSize); + ThreadPoolExecutor executor = + new ThreadPoolExecutor( + corePoolSize, + useMaxPoolSize, + keepAliveTime, + keepAliveTimeUnit, + workQueue, + threadFactory != null ? threadFactory : new NamedThreadFactory(threadNamePrefix), + rejectedExecutionHandler); - executor.allowCoreThreadTimeOut(allowCoreThreadTimeOut); - return executor; - } + executor.allowCoreThreadTimeOut(allowCoreThreadTimeOut); + return executor; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/FileUtils.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/FileUtils.java index 6781b3794..e424ea245 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/FileUtils.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/FileUtils.java @@ -26,256 +26,243 @@ import java.io.OutputStream; /** - * * @author shangyu.wh * @version $Id: FileUtils.java, v 0.1 2018-08-23 12:02 shangyu.wh Exp $ */ public class FileUtils { - private static final int EOF = -1; + private static final int EOF = -1; - /** - * write file - * - * @param file - * @param data - * @param append - * @throws IOException - */ - public static void writeByteArrayToFile(File file, byte[] data, - boolean append) throws IOException { - OutputStream out = null; - try { - out = openOutputStream(file, append); - out.write(data); - out.close(); // don't swallow close Exception if copy completes - // normally - } finally { - closeQuietly(out); - } - } + /** + * write file + * + * @param file + * @param data + * @param append + * @throws IOException + */ + public static void writeByteArrayToFile(File file, byte[] data, boolean append) + throws IOException { + OutputStream out = null; + try { + out = openOutputStream(file, append); + out.write(data); + out.close(); // don't swallow close Exception if copy completes + // normally + } finally { + closeQuietly(out); + } + } - /** - * read file - * - * @param file - * @return - * @throws IOException - */ - public static byte[] readFileToByteArray(File file) throws IOException { - InputStream in = null; - try { - in = openInputStream(file); - return toByteArray(in, file.length()); - } finally { - closeQuietly(in); - } - } + /** + * read file + * + * @param file + * @return + * @throws IOException + */ + public static byte[] readFileToByteArray(File file) throws IOException { + InputStream in = null; + try { + in = openInputStream(file); + return toByteArray(in, file.length()); + } finally { + closeQuietly(in); + } + } - /** - * create dir - * - * @param directory - * @throws IOException - */ - public static void forceMkdir(File directory) throws IOException { - if (directory.exists()) { - if (!directory.isDirectory()) { - String message = "File " + directory + " exists and is " - + "not a directory. Unable to create directory."; - throw new IOException(message); - } - } else { - if (!directory.mkdirs()) { - // Double-check that some other thread or process hasn't made - // the directory in the background - if (!directory.isDirectory()) { - String message = "Unable to create directory " + directory; - throw new IOException(message); - } - } - } - } + /** + * create dir + * + * @param directory + * @throws IOException + */ + public static void forceMkdir(File directory) throws IOException { + if (directory.exists()) { + if (!directory.isDirectory()) { + String message = + "File " + + directory + + " exists and is " + + "not a directory. Unable to create directory."; + throw new IOException(message); + } + } else { + if (!directory.mkdirs()) { + // Double-check that some other thread or process hasn't made + // the directory in the background + if (!directory.isDirectory()) { + String message = "Unable to create directory " + directory; + throw new IOException(message); + } + } + } + } - /** - * file output stream - * - * @param file - * @param append - * @return - * @throws IOException - */ - public static FileOutputStream openOutputStream(File file, boolean append) - throws IOException { - if (file.exists()) { - if (file.isDirectory()) { - throw new IOException("File '" + file - + "' exists but is a directory"); - } - if (!file.canWrite()) { - throw new IOException("File '" + file - + "' cannot be written to"); - } - } else { - File parent = file.getParentFile(); - if (parent != null) { - if (!parent.mkdirs() && !parent.isDirectory()) { - throw new IOException("Directory '" + parent - + "' could not be created"); - } - } - } - return new FileOutputStream(file, append); - } + /** + * file output stream + * + * @param file + * @param append + * @return + * @throws IOException + */ + public static FileOutputStream openOutputStream(File file, boolean append) throws IOException { + if (file.exists()) { + if (file.isDirectory()) { + throw new IOException("File '" + file + "' exists but is a directory"); + } + if (!file.canWrite()) { + throw new IOException("File '" + file + "' cannot be written to"); + } + } else { + File parent = file.getParentFile(); + if (parent != null) { + if (!parent.mkdirs() && !parent.isDirectory()) { + throw new IOException("Directory '" + parent + "' could not be created"); + } + } + } + return new FileOutputStream(file, append); + } - /** - * file to inputStream - * - * @param file - * @return - * @throws IOException - */ - public static FileInputStream openInputStream(File file) throws IOException { - if (file.exists()) { - if (file.isDirectory()) { - throw new IOException("File '" + file - + "' exists but is a directory"); - } - if (!file.canRead()) { - throw new IOException("File '" + file + "' cannot be read"); - } - } else { - throw new FileNotFoundException("File '" + file - + "' does not exist"); - } - return new FileInputStream(file); - } + /** + * file to inputStream + * + * @param file + * @return + * @throws IOException + */ + public static FileInputStream openInputStream(File file) throws IOException { + if (file.exists()) { + if (file.isDirectory()) { + throw new IOException("File '" + file + "' exists but is a directory"); + } + if (!file.canRead()) { + throw new IOException("File '" + file + "' cannot be read"); + } + } else { + throw new FileNotFoundException("File '" + file + "' does not exist"); + } + return new FileInputStream(file); + } - /** - * transfer InputStream to byteArray - * - * @param input - * @param size - * @return - * @throws IOException - */ - public static byte[] toByteArray(InputStream input, long size) - throws IOException { + /** + * transfer InputStream to byteArray + * + * @param input + * @param size + * @return + * @throws IOException + */ + public static byte[] toByteArray(InputStream input, long size) throws IOException { - if (size > Integer.MAX_VALUE) { - throw new IllegalArgumentException( - "Size cannot be greater than Integer max value: " + size); - } + if (size > Integer.MAX_VALUE) { + throw new IllegalArgumentException("Size cannot be greater than Integer max value: " + size); + } - return toByteArray(input, (int) size); - } + return toByteArray(input, (int) size); + } - /** - * transfer InputStream to byteArray - * - * @param input - * @param size - * @return - * @throws IOException - */ - public static byte[] toByteArray(InputStream input, int size) - throws IOException { + /** + * transfer InputStream to byteArray + * + * @param input + * @param size + * @return + * @throws IOException + */ + public static byte[] toByteArray(InputStream input, int size) throws IOException { - if (size < 0) { - throw new IllegalArgumentException( - "Size must be equal or greater than zero: " + size); - } + if (size < 0) { + throw new IllegalArgumentException("Size must be equal or greater than zero: " + size); + } - if (size == 0) { - return new byte[0]; - } + if (size == 0) { + return new byte[0]; + } - byte[] data = new byte[size]; - int offset = 0; - int readed; + byte[] data = new byte[size]; + int offset = 0; + int readed; - while (offset < size - && (readed = input.read(data, offset, size - offset)) != EOF) { - offset += readed; - } + while (offset < size && (readed = input.read(data, offset, size - offset)) != EOF) { + offset += readed; + } - if (offset != size) { - throw new IOException("Unexpected readed size. current: " + offset - + ", excepted: " + size); - } + if (offset != size) { + throw new IOException("Unexpected readed size. current: " + offset + ", excepted: " + size); + } - return data; - } + return data; + } - /** - * - * @param closeable - */ - public static void closeQuietly(Closeable closeable) { - try { - if (closeable != null) { - closeable.close(); - } - } catch (IOException ioe) { - // ignore - } - } + /** @param closeable */ + public static void closeQuietly(Closeable closeable) { + try { + if (closeable != null) { + closeable.close(); + } + } catch (IOException ioe) { + // ignore + } + } - public static void forceDelete(File file) throws IOException { - if (!file.exists()) { - return; - } + public static void forceDelete(File file) throws IOException { + if (!file.exists()) { + return; + } - if (file.isDirectory()) { - deleteDirectory(file); - } else { - if (!file.delete()) { - String message = "Unable to delete file: " + file; - throw new IOException(message); - } - } - } + if (file.isDirectory()) { + deleteDirectory(file); + } else { + if (!file.delete()) { + String message = "Unable to delete file: " + file; + throw new IOException(message); + } + } + } - public static void deleteDirectory(File directory) throws IOException { - if (!directory.exists()) { - return; - } + public static void deleteDirectory(File directory) throws IOException { + if (!directory.exists()) { + return; + } - cleanDirectory(directory); - if (!directory.delete()) { - String message = "Unable to delete directory " + directory + "."; - throw new IOException(message); - } - } + cleanDirectory(directory); + if (!directory.delete()) { + String message = "Unable to delete directory " + directory + "."; + throw new IOException(message); + } + } - public static void cleanDirectory(File directory) throws IOException { - if (!directory.exists()) { - String message = directory + " does not exist"; - throw new IllegalArgumentException(message); - } + public static void cleanDirectory(File directory) throws IOException { + if (!directory.exists()) { + String message = directory + " does not exist"; + throw new IllegalArgumentException(message); + } - if (!directory.isDirectory()) { - String message = directory + " is not a directory"; - throw new IllegalArgumentException(message); - } + if (!directory.isDirectory()) { + String message = directory + " is not a directory"; + throw new IllegalArgumentException(message); + } - File[] files = directory.listFiles(); - if (files == null) { // null if security restricted - throw new IOException("Failed to list contents of " + directory); - } + File[] files = directory.listFiles(); + if (files == null) { // null if security restricted + throw new IOException("Failed to list contents of " + directory); + } - IOException exception = null; - for (int i = 0; i < files.length; i++) { - File file = files[i]; - try { - forceDelete(file); - } catch (IOException ioe) { - exception = ioe; - } - } + IOException exception = null; + for (int i = 0; i < files.length; i++) { + File file = files[i]; + try { + forceDelete(file); + } catch (IOException ioe) { + exception = ioe; + } + } - if (null != exception) { - throw exception; - } - } -} \ No newline at end of file + if (null != exception) { + throw exception; + } + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/JsonUtils.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/JsonUtils.java index fcda74520..53984268b 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/JsonUtils.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/JsonUtils.java @@ -20,41 +20,41 @@ import com.fasterxml.jackson.databind.ObjectMapper; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-22 17:30 yuzhi.lyz Exp $ */ public final class JsonUtils { - public static final ThreadLocal JACKSON_MAPPER = ThreadLocal.withInitial(() -> new ObjectMapper()); + public static final ThreadLocal JACKSON_MAPPER = + ThreadLocal.withInitial(() -> new ObjectMapper()); - private JsonUtils() { - } + private JsonUtils() {} - public static ObjectMapper getJacksonObjectMapper() { - return JACKSON_MAPPER.get(); - } + public static ObjectMapper getJacksonObjectMapper() { + return JACKSON_MAPPER.get(); + } - public static T read(String str, Class clazz) { - try { - return JACKSON_MAPPER.get().readValue(str, clazz); - } catch (Throwable e) { - throw new RuntimeException("failed to read json to " + clazz.getName() + ", " + str, e); - } + public static T read(String str, Class clazz) { + try { + return JACKSON_MAPPER.get().readValue(str, clazz); + } catch (Throwable e) { + throw new RuntimeException("failed to read json to " + clazz.getName() + ", " + str, e); } + } - public static T read(String str, TypeReference typeReference) { - try { - return JACKSON_MAPPER.get().readValue(str, typeReference); - } catch (Throwable e) { - throw new RuntimeException("failed to read json to " + typeReference.toString() + ", " + str, e); - } + public static T read(String str, TypeReference typeReference) { + try { + return JACKSON_MAPPER.get().readValue(str, typeReference); + } catch (Throwable e) { + throw new RuntimeException( + "failed to read json to " + typeReference.toString() + ", " + str, e); } + } - public static String writeValueAsString(Object o) { - try { - return JACKSON_MAPPER.get().writeValueAsString(o); - } catch (Throwable e) { - throw new RuntimeException("failed to write json: " + o, e); - } + public static String writeValueAsString(Object o) { + try { + return JACKSON_MAPPER.get().writeValueAsString(o); + } catch (Throwable e) { + throw new RuntimeException("failed to write json: " + o, e); } + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/LoopRunnable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/LoopRunnable.java index 7b0fbd209..999dbe9e5 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/LoopRunnable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/LoopRunnable.java @@ -21,71 +21,69 @@ import com.alipay.sofa.registry.log.LoggerFactory; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-30 16:51 yuzhi.lyz Exp $ */ public abstract class LoopRunnable implements Runnable, Suspendable { - private static final Logger LOGGER = LoggerFactory.getLogger(LoopRunnable.class); + private static final Logger LOGGER = LoggerFactory.getLogger(LoopRunnable.class); - private volatile boolean isClosed = false; + private volatile boolean isClosed = false; - private volatile boolean isSuspend = false; + private volatile boolean isSuspend = false; - public abstract void runUnthrowable(); + public abstract void runUnthrowable(); - public abstract void waitingUnthrowable(); + public abstract void waitingUnthrowable(); - public void unexpectExit(Throwable e) { - LOGGER.error("unexpect exit in LoopRunnable {}", this.getClass().getSimpleName(), e); - } + public void unexpectExit(Throwable e) { + LOGGER.error("unexpect exit in LoopRunnable {}", this.getClass().getSimpleName(), e); + } - public void close() { - isClosed = true; - } + public void close() { + isClosed = true; + } - @Override - public void suspend() { - this.isSuspend = true; - } + @Override + public void suspend() { + this.isSuspend = true; + } - @Override - public void resume() { - this.isSuspend = false; - } + @Override + public void resume() { + this.isSuspend = false; + } - @Override - public boolean isSuspended() { - return isSuspend; - } + @Override + public boolean isSuspended() { + return isSuspend; + } - public void run() { - LOGGER.info("loop-run started {}", this.getClass().getSimpleName()); + public void run() { + LOGGER.info("loop-run started {}", this.getClass().getSimpleName()); + try { + for (; ; ) { + if (isClosed) { + LOGGER.warn("[closed] quit"); + return; + } + if (isSuspend) { + LOGGER.warn("[suspend] break"); + } else { + try { + runUnthrowable(); + } catch (Throwable unexpect) { + LOGGER.error("run unexpect error", unexpect); + } + } try { - for (;;) { - if (isClosed) { - LOGGER.warn("[closed] quit"); - return; - } - if (isSuspend) { - LOGGER.warn("[suspend] break"); - } else { - try { - runUnthrowable(); - } catch (Throwable unexpect) { - LOGGER.error("run unexpect error", unexpect); - } - } - try { - waitingUnthrowable(); - } catch (Throwable unexpect) { - LOGGER.error("waiting unexpect error", unexpect); - } - } - } catch (Throwable e) { - // in oom, this may be happen - unexpectExit(e); + waitingUnthrowable(); + } catch (Throwable unexpect) { + LOGGER.error("waiting unexpect error", unexpect); } - + } + } catch (Throwable e) { + // in oom, this may be happen + unexpectExit(e); } -} \ No newline at end of file + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/MapUtils.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/MapUtils.java index c9338b926..1fdcccb47 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/MapUtils.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/MapUtils.java @@ -20,24 +20,23 @@ /** * @author chen.zhu - *

- * Nov 23, 2020 + *

Nov 23, 2020 */ public class MapUtils { - public static V getOrCreate(ConcurrentMap map, K key, - ObjectFactory objectFactory) { + public static V getOrCreate( + ConcurrentMap map, K key, ObjectFactory objectFactory) { - V value = map.get(key); - if (value != null) { - return value; - } + V value = map.get(key); + if (value != null) { + return value; + } - value = map.get(key); - if (value == null) { - value = objectFactory.create(); - map.put(key, value); - } - return value; + value = map.get(key); + if (value == null) { + value = objectFactory.create(); + map.put(key, value); } + return value; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/MathUtils.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/MathUtils.java index 6dd287389..6ee9607ea 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/MathUtils.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/MathUtils.java @@ -18,24 +18,20 @@ /** * @author chen.zhu - *

- * Jan 12, 2021 + *

Jan 12, 2021 */ public class MathUtils { - /** - * Divide ceil int. dividend divisor quotient 20 / 4 = 5 - * - * @param dividend - * the dividend - * @param divisor - * the divisor - * @return the int - */ - public static int divideCeil(int dividend, int divisor) { - int result = dividend / divisor; - result += dividend % divisor == 0 ? 0 : 1; - return result; - } - + /** + * Divide ceil int. dividend divisor quotient 20 / 4 = 5 + * + * @param dividend the dividend + * @param divisor the divisor + * @return the int + */ + public static int divideCeil(int dividend, int divisor) { + int result = dividend / divisor; + result += dividend % divisor == 0 ? 0 : 1; + return result; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/MessageDigests.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/MessageDigests.java index 6552c5df7..eaa909812 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/MessageDigests.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/MessageDigests.java @@ -21,97 +21,89 @@ import java.security.NoSuchAlgorithmException; /** - * This MessageDigests class provides convenience methods for obtaining - * thread local {@link MessageDigest} instances for MD5, SHA-1, and - * SHA-256 message digests. + * This MessageDigests class provides convenience methods for obtaining thread local {@link + * MessageDigest} instances for MD5, SHA-1, and SHA-256 message digests. * * @author zhuoyu.sjw * @version $Id: MessageDigests.java, v 0.1 2016-11-01 16:29 zhuoyu.sjw Exp $$ */ public final class MessageDigests { - /** MD5 */ - private static final ThreadLocal MD5_DIGEST = createThreadLocalMessageDigest("MD5"); - /** SHA_1 */ - private static final ThreadLocal SHA_1_DIGEST = createThreadLocalMessageDigest("SHA-1"); - /** SHA_256 */ - private static final ThreadLocal SHA_256_DIGEST = createThreadLocalMessageDigest("SHA-256"); - /** */ - private static final char[] HEX_DIGITS = "0123456789abcdef" - .toCharArray(); + /** MD5 */ + private static final ThreadLocal MD5_DIGEST = + createThreadLocalMessageDigest("MD5"); + /** SHA_1 */ + private static final ThreadLocal SHA_1_DIGEST = + createThreadLocalMessageDigest("SHA-1"); + /** SHA_256 */ + private static final ThreadLocal SHA_256_DIGEST = + createThreadLocalMessageDigest("SHA-256"); + /** */ + private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); - /** - * Create thread local message digest thread local. - * - * @param digest the digest - * @return thread local - */ - private static ThreadLocal createThreadLocalMessageDigest(final String digest) { - return ThreadLocal.withInitial(() -> { - try { - return MessageDigest.getInstance(digest); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException( - "unexpected exception creating MessageDigest instance for [" + digest + "]", - e); - } + /** + * Create thread local message digest thread local. + * + * @param digest the digest + * @return thread local + */ + private static ThreadLocal createThreadLocalMessageDigest(final String digest) { + return ThreadLocal.withInitial( + () -> { + try { + return MessageDigest.getInstance(digest); + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException( + "unexpected exception creating MessageDigest instance for [" + digest + "]", e); + } }); - } + } - /** - * - * @return a thread local MD5 {@link MessageDigest} instance - */ - public static MessageDigest md5() { - return get(MD5_DIGEST); - } + /** @return a thread local MD5 {@link MessageDigest} instance */ + public static MessageDigest md5() { + return get(MD5_DIGEST); + } - /** - * - * @return a thread local SHA_1 {@link MessageDigest} instance - */ - public static MessageDigest sha1() { - return get(SHA_1_DIGEST); - } + /** @return a thread local SHA_1 {@link MessageDigest} instance */ + public static MessageDigest sha1() { + return get(SHA_1_DIGEST); + } - /** - * - * @return a thread local SHA_256 {@link MessageDigest} instance - */ - public static MessageDigest sha256() { - return get(SHA_256_DIGEST); - } + /** @return a thread local SHA_256 {@link MessageDigest} instance */ + public static MessageDigest sha256() { + return get(SHA_256_DIGEST); + } - /** - * get and reset thread local {@link MessageDigest} instance - * @param messageDigest threadLocalMessageDigest - * @return a thread local {@link MessageDigest} instance - */ - private static MessageDigest get(ThreadLocal messageDigest) { - MessageDigest instance = messageDigest.get(); - instance.reset(); - return instance; - } - - public static String getMd5String(String digest) { + /** + * get and reset thread local {@link MessageDigest} instance + * + * @param messageDigest threadLocalMessageDigest + * @return a thread local {@link MessageDigest} instance + */ + private static MessageDigest get(ThreadLocal messageDigest) { + MessageDigest instance = messageDigest.get(); + instance.reset(); + return instance; + } - return toHexString(md5().digest(digest.getBytes(StandardCharsets.UTF_8))); - } + public static String getMd5String(String digest) { - /** - * Format a byte array as a hex string. - * - * @param bytes the input to be represented as hex. - * @return a hex representation of the input as a String. - */ - public static String toHexString(byte[] bytes) { - StringBuilder sb = new StringBuilder(2 * bytes.length); + return toHexString(md5().digest(digest.getBytes(StandardCharsets.UTF_8))); + } - for (byte b : bytes) { - sb.append(HEX_DIGITS[b >> 4 & 0xf]).append(HEX_DIGITS[b & 0xf]); - } + /** + * Format a byte array as a hex string. + * + * @param bytes the input to be represented as hex. + * @return a hex representation of the input as a String. + */ + public static String toHexString(byte[] bytes) { + StringBuilder sb = new StringBuilder(2 * bytes.length); - return sb.toString(); + for (byte b : bytes) { + sb.append(HEX_DIGITS[b >> 4 & 0xf]).append(HEX_DIGITS[b & 0xf]); } + return sb.toString(); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/NamedThreadFactory.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/NamedThreadFactory.java index 8ba99732c..0ac4651a4 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/NamedThreadFactory.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/NamedThreadFactory.java @@ -20,46 +20,44 @@ import java.util.concurrent.atomic.AtomicInteger; /** - * * @author shangyu.wh * @version $Id: NamedThreadFactory.java, v 0.1 2018-10-11 11:25 shangyu.wh Exp $ */ public class NamedThreadFactory implements ThreadFactory { - private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); - private final AtomicInteger threadNumber = new AtomicInteger(1); - private final ThreadGroup group; - private final String namePrefix; - private final boolean isDaemon; - - public NamedThreadFactory() { - this("ThreadPool"); + private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1); + private final AtomicInteger threadNumber = new AtomicInteger(1); + private final ThreadGroup group; + private final String namePrefix; + private final boolean isDaemon; + + public NamedThreadFactory() { + this("ThreadPool"); + } + + public NamedThreadFactory(String name) { + this(name, false); + } + + public NamedThreadFactory(String prefix, boolean daemon) { + SecurityManager s = System.getSecurityManager(); + group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); + namePrefix = prefix + "-" + POOL_NUMBER.getAndIncrement() + "-T-"; + isDaemon = daemon; + } + + /** + * Create a thread. + * + * @see ThreadFactory#newThread(Runnable) + */ + @Override + public Thread newThread(Runnable r) { + Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); + t.setDaemon(isDaemon); + if (t.getPriority() != Thread.NORM_PRIORITY) { + t.setPriority(Thread.NORM_PRIORITY); } - - public NamedThreadFactory(String name) { - this(name, false); - } - - public NamedThreadFactory(String prefix, boolean daemon) { - SecurityManager s = System.getSecurityManager(); - group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); - namePrefix = prefix + "-" + POOL_NUMBER.getAndIncrement() + "-T-"; - isDaemon = daemon; - } - - /** - * Create a thread. - * - * @see ThreadFactory#newThread(Runnable) - */ - @Override - public Thread newThread(Runnable r) { - Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); - t.setDaemon(isDaemon); - if (t.getPriority() != Thread.NORM_PRIORITY) { - t.setPriority(Thread.NORM_PRIORITY); - } - return t; - } - -} \ No newline at end of file + return t; + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/ObjectFactory.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/ObjectFactory.java index 858f78bf9..2c4b7ca5d 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/ObjectFactory.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/ObjectFactory.java @@ -18,9 +18,8 @@ /** * @author chen.zhu - *

- * Nov 23, 2020 + *

Nov 23, 2020 */ public interface ObjectFactory { - V create(); + V create(); } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/OsUtils.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/OsUtils.java index a97cd9c10..b42d388a2 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/OsUtils.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/OsUtils.java @@ -18,24 +18,22 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public class OsUtils { - private static final int CPU_COUNT; + private static final int CPU_COUNT; - static { + static { + String cpuCount = System.getProperty("CPU_COUNT"); + if (cpuCount != null) { + CPU_COUNT = Integer.parseInt(cpuCount); + } else { + CPU_COUNT = Runtime.getRuntime().availableProcessors(); + } + } - String cpuCount = System.getProperty("CPU_COUNT"); - if (cpuCount != null) { - CPU_COUNT = Integer.parseInt(cpuCount); - } else { - CPU_COUNT = Runtime.getRuntime().availableProcessors(); - } - } - - public static int getCpuCount() { - return CPU_COUNT; - } + public static int getCpuCount() { + return CPU_COUNT; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/ParaCheckUtil.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/ParaCheckUtil.java index 038dcb244..02366bb65 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/ParaCheckUtil.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/ParaCheckUtil.java @@ -16,85 +16,85 @@ */ package com.alipay.sofa.registry.util; -import org.apache.commons.lang.StringUtils; - import java.util.Collection; import java.util.Objects; import java.util.Set; +import org.apache.commons.lang.StringUtils; /** * @author qian.lqlq * @version $Id: ParaCheckUtil.java, v 0.1 2017-12-06 21:20 qian.lqlq Exp $ */ public final class ParaCheckUtil { - private ParaCheckUtil() { - } + private ParaCheckUtil() {} - /** - * check object not null - * @param param - * @param paraName - * @throws RuntimeException - */ - public static void checkNotNull(Object param, String paraName) { - if (param == null) { - throw new IllegalArgumentException(StringFormatter.format( - "{} is not allowed to be null", paraName)); - } + /** + * check object not null + * + * @param param + * @param paraName + * @throws RuntimeException + */ + public static void checkNotNull(Object param, String paraName) { + if (param == null) { + throw new IllegalArgumentException( + StringFormatter.format("{} is not allowed to be null", paraName)); } + } - public static void checkEquals(Object actual, Object expect, String paraName) { - if (!Objects.equals(actual, expect)) { - throw new IllegalArgumentException(StringFormatter.format("{}={} is not equals {}", - paraName, actual, expect)); - } + public static void checkEquals(Object actual, Object expect, String paraName) { + if (!Objects.equals(actual, expect)) { + throw new IllegalArgumentException( + StringFormatter.format("{}={} is not equals {}", paraName, actual, expect)); } + } - /** - * check string not blank - * @param param - * @param paraName - * @throws RuntimeException - */ - public static void checkNotBlank(String param, String paraName) { - if (StringUtils.isBlank(param)) { - throw new IllegalArgumentException(StringFormatter.format( - "{} is not allowed to be blank", paraName)); - } + /** + * check string not blank + * + * @param param + * @param paraName + * @throws RuntimeException + */ + public static void checkNotBlank(String param, String paraName) { + if (StringUtils.isBlank(param)) { + throw new IllegalArgumentException( + StringFormatter.format("{} is not allowed to be blank", paraName)); } + } - /** - * check param not empty - * @param param - * @param paraName - * @throws RuntimeException - */ - public static void checkNotEmpty(Collection param, String paraName) { - if (param == null || param.size() == 0) { - throw new IllegalArgumentException(StringFormatter.format( - "{} is not allowed to be empty", paraName)); - } + /** + * check param not empty + * + * @param param + * @param paraName + * @throws RuntimeException + */ + public static void checkNotEmpty(Collection param, String paraName) { + if (param == null || param.size() == 0) { + throw new IllegalArgumentException( + StringFormatter.format("{} is not allowed to be empty", paraName)); } + } - public static void checkNonNegative(long v, String paraName) { - if (v < 0) { - throw new IllegalArgumentException(StringFormatter.format( - "{} is not allowed to be negative, {}", paraName, v)); - } + public static void checkNonNegative(long v, String paraName) { + if (v < 0) { + throw new IllegalArgumentException( + StringFormatter.format("{} is not allowed to be negative, {}", paraName, v)); } + } - public static void checkIsPositive(long v, String paraName) { - if (v <= 0) { - throw new IllegalArgumentException(StringFormatter.format("{} is require positive, {}", - paraName, v)); - } + public static void checkIsPositive(long v, String paraName) { + if (v <= 0) { + throw new IllegalArgumentException( + StringFormatter.format("{} is require positive, {}", paraName, v)); } + } - public static void checkContains(Set sets, Object param, String paraName) { - if (!sets.contains(param)) { - throw new IllegalArgumentException(StringFormatter.format( - "{} is not contain in {}, {}", paraName, sets, param)); - } + public static void checkContains(Set sets, Object param, String paraName) { + if (!sets.contains(param)) { + throw new IllegalArgumentException( + StringFormatter.format("{} is not contain in {}, {}", paraName, sets, param)); } - -} \ No newline at end of file + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/PropertySplitter.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/PropertySplitter.java index b56f53e9c..6b3f98121 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/PropertySplitter.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/PropertySplitter.java @@ -17,7 +17,6 @@ package com.alipay.sofa.registry.util; import com.google.common.base.Splitter; - import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -25,74 +24,66 @@ import java.util.Map.Entry; /** - * * @author shangyu.wh * @version $Id: PropertySplitter.java, v 0.1 2018-05-03 16:29 shangyu.wh Exp $ */ public class PropertySplitter { - /** - * Example: one.example.property = KEY1:VALUE1,KEY2:VALUE2 - */ - public Map map(String property) { - if (property == null) { - return new HashMap<>(); - } - return this.map(property, ","); + /** Example: one.example.property = KEY1:VALUE1,KEY2:VALUE2 */ + public Map map(String property) { + if (property == null) { + return new HashMap<>(); } + return this.map(property, ","); + } - /** - * Example: one.example.property = KEY1:VALUE1.1,VALUE1.2|KEY2:VALUE2.1,VALUE2.2 - */ - public Map> mapOfList(String property) { - if (property == null) { - return new HashMap<>(); - } - Map map = this.map(property, "|"); - - Map> mapOfList = new HashMap<>(); - for (Entry entry : map.entrySet()) { - mapOfList.put(entry.getKey(), this.list(entry.getValue())); - } - - return mapOfList; + /** Example: one.example.property = KEY1:VALUE1.1,VALUE1.2|KEY2:VALUE2.1,VALUE2.2 */ + public Map> mapOfList(String property) { + if (property == null) { + return new HashMap<>(); } + Map map = this.map(property, "|"); - /** - * Example: one.example.property = VALUE1,VALUE2,VALUE3,VALUE4 - */ - public Collection list(String property) { - if (property == null) { - return new ArrayList<>(); - } - return this.list(property, ","); + Map> mapOfList = new HashMap<>(); + for (Entry entry : map.entrySet()) { + mapOfList.put(entry.getKey(), this.list(entry.getValue())); } - /** - * Example: one.example.property = VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2 - */ - public Collection> groupedList(String property) { - if (property == null) { - return new ArrayList<>(); - } - Collection unGroupedList = this.list(property, "|"); - - Collection> groupedList = new ArrayList<>(); - for (String group : unGroupedList) { - groupedList.add(this.list(group)); - } - - return groupedList; + return mapOfList; + } + /** Example: one.example.property = VALUE1,VALUE2,VALUE3,VALUE4 */ + public Collection list(String property) { + if (property == null) { + return new ArrayList<>(); } + return this.list(property, ","); + } - private Collection list(String property, String splitter) { - return Splitter.on(splitter).omitEmptyStrings().trimResults().splitToList(property); + /** Example: one.example.property = VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2 */ + public Collection> groupedList(String property) { + if (property == null) { + return new ArrayList<>(); } + Collection unGroupedList = this.list(property, "|"); - private Map map(String property, String splitter) { - return Splitter.on(splitter).omitEmptyStrings().trimResults().withKeyValueSeparator(":") - .split(property); + Collection> groupedList = new ArrayList<>(); + for (String group : unGroupedList) { + groupedList.add(this.list(group)); } -} \ No newline at end of file + return groupedList; + } + + private Collection list(String property, String splitter) { + return Splitter.on(splitter).omitEmptyStrings().trimResults().splitToList(property); + } + + private Map map(String property, String splitter) { + return Splitter.on(splitter) + .omitEmptyStrings() + .trimResults() + .withKeyValueSeparator(":") + .split(property); + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/RevisionUtils.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/RevisionUtils.java index 0dfd03d11..9e7743867 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/RevisionUtils.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/RevisionUtils.java @@ -21,15 +21,14 @@ import java.util.List; public class RevisionUtils { - private static final Charset UTF8 = Charset.forName("utf-8"); + private static final Charset UTF8 = Charset.forName("utf-8"); - public static String revisionsDigest(List keys) { - Collections.sort(keys); - StringBuffer sb = new StringBuffer(); - for (String key : keys) { - sb.append(key); - } - return MessageDigests - .toHexString(MessageDigests.md5().digest(sb.toString().getBytes(UTF8))); + public static String revisionsDigest(List keys) { + Collections.sort(keys); + StringBuffer sb = new StringBuffer(); + for (String key : keys) { + sb.append(key); } + return MessageDigests.toHexString(MessageDigests.md5().digest(sb.toString().getBytes(UTF8))); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/SingleFlight.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/SingleFlight.java index f1660e021..7fece780b 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/SingleFlight.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/SingleFlight.java @@ -22,8 +22,9 @@ /** * SingleFlight implements call deduplication for equal keys. - *

- * Example: + * + *

Example: + * *

  * public Result expensiveOperation(final Parameters parameters) throws Exception {
  *     return singleFlight.execute(parameters, new Callable<Result>() {
@@ -41,82 +42,82 @@
  */
 public class SingleFlight {
 
-    private final ConcurrentMap calls = new ConcurrentHashMap<>();
+  private final ConcurrentMap calls = new ConcurrentHashMap<>();
 
-    /**
-     * Execute a {@link Callable} if no other calls for the same  {@code key} are currently running.
-     * Concurrent calls for the same  {@code key} result in one caller invoking the {@link Callable} and sharing the result
-     * with the other callers.
-     * 

- * The result of an invocation is not cached, only concurrent calls share the same result. - * - * @param key A unique identification of the method call. - * The {@code key} must be uniquely identifiable by it's {@link Object#hashCode()} and {@link Object#equals(Object)} methods. - * @param callable The {@link Callable} where the result can be obtained from. - * @return The result of invoking the {@link Callable}. - * @throws Exception The {@link Exception} which was thrown by the {@link Callable}. - * Alternatively a {@link InterruptedException} can be thrown if - * the executing {@link Thread} was interrupted while waiting for the result. - */ - @SuppressWarnings("unchecked") - public V execute(Object key, Callable callable) throws Exception { - Call call = calls.get(key); - if (call == null) { - call = new Call<>(); - Call other = calls.putIfAbsent(key, call); - if (other == null) { - try { - return call.exec(callable); - } finally { - calls.remove(key); - } - } else { - call = other; - } + /** + * Execute a {@link Callable} if no other calls for the same {@code key} are currently running. + * Concurrent calls for the same {@code key} result in one caller invoking the {@link Callable} + * and sharing the result with the other callers. + * + *

The result of an invocation is not cached, only concurrent calls share the same result. + * + * @param key A unique identification of the method call. The {@code key} must be uniquely + * identifiable by it's {@link Object#hashCode()} and {@link Object#equals(Object)} methods. + * @param callable The {@link Callable} where the result can be obtained from. + * @return The result of invoking the {@link Callable}. + * @throws Exception The {@link Exception} which was thrown by the {@link Callable}. Alternatively + * a {@link InterruptedException} can be thrown if the executing {@link Thread} was + * interrupted while waiting for the result. + */ + @SuppressWarnings("unchecked") + public V execute(Object key, Callable callable) throws Exception { + Call call = calls.get(key); + if (call == null) { + call = new Call<>(); + Call other = calls.putIfAbsent(key, call); + if (other == null) { + try { + return call.exec(callable); + } finally { + calls.remove(key); } - return call.await(); + } else { + call = other; + } } + return call.await(); + } - private static class Call { + private static class Call { - private final Object lock = new Object(); - private boolean finished; - private V result; - private Exception exc; + private final Object lock = new Object(); + private boolean finished; + private V result; + private Exception exc; - void finished(V result, Exception exc) { - synchronized (lock) { - this.finished = true; - this.result = result; - this.exc = exc; - lock.notifyAll(); - } - } + void finished(V result, Exception exc) { + synchronized (lock) { + this.finished = true; + this.result = result; + this.exc = exc; + lock.notifyAll(); + } + } - V await() throws Exception { - synchronized (lock) { - while (!finished) { - lock.wait(); - } - if (exc != null) { - throw exc; - } - return result; - } + V await() throws Exception { + synchronized (lock) { + while (!finished) { + lock.wait(); } - - V exec(Callable callable) throws Exception { - V result = null; - Exception exc = null; - try { - result = callable.call(); - return result; - } catch (Exception e) { - exc = e; - throw e; - } finally { - finished(result, exc); - } + if (exc != null) { + throw exc; } + return result; + } + } + + V exec(Callable callable) throws Exception { + V result = null; + Exception exc = null; + try { + result = callable.call(); + return result; + } catch (Exception e) { + exc = e; + throw e; + } finally { + finished(result, exc); + } } + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/StringFormatter.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/StringFormatter.java index 34f69315a..60c4cdc20 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/StringFormatter.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/StringFormatter.java @@ -20,11 +20,10 @@ import org.slf4j.helpers.MessageFormatter; public final class StringFormatter { - private StringFormatter() { - } + private StringFormatter() {} - public static String format(String messagePattern, Object... argArray) { - FormattingTuple tuple = MessageFormatter.arrayFormat(messagePattern, argArray); - return tuple.getMessage(); - } + public static String format(String messagePattern, Object... argArray) { + FormattingTuple tuple = MessageFormatter.arrayFormat(messagePattern, argArray); + return tuple.getMessage(); + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/SystemUtils.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/SystemUtils.java index 49be24c93..715da6a93 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/SystemUtils.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/SystemUtils.java @@ -17,22 +17,21 @@ package com.alipay.sofa.registry.util; public final class SystemUtils { - private SystemUtils() { - } + private SystemUtils() {} - public static int getSystemInteger(String name, int def) { - String v = System.getProperty(name); - if (v == null) { - v = System.getenv(name); - } - return v == null ? def : Integer.valueOf(v); - } + public static int getSystemInteger(String name, int def) { + String v = System.getProperty(name); + if (v == null) { + v = System.getenv(name); + } + return v == null ? def : Integer.valueOf(v); + } - public static String getSystem(String name, String def) { - String v = System.getProperty(name); - if (v == null) { - v = System.getenv(name); - } - return v == null ? def : v; - } + public static String getSystem(String name, String def) { + String v = System.getProperty(name); + if (v == null) { + v = System.getenv(name); + } + return v == null ? def : v; + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/TimestampUtil.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/TimestampUtil.java index 1456a8fcb..d51f87865 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/TimestampUtil.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/TimestampUtil.java @@ -19,13 +19,12 @@ import java.sql.Timestamp; /** - * * @author xiaojian.xj * @version $Id: TimestampUtil.java, v 0.1 2021年03月01日 15:55 xiaojian.xj Exp $ */ public class TimestampUtil { - public static long getNanosLong(Timestamp timestamp) { - return timestamp.getTime() / 1000 * 1000000000 + timestamp.getNanos(); - } -} \ No newline at end of file + public static long getNanosLong(Timestamp timestamp) { + return timestamp.getTime() / 1000 * 1000000000 + timestamp.getNanos(); + } +} diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/VersionsMapUtils.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/VersionsMapUtils.java index 2c09283af..56cfc3b6a 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/VersionsMapUtils.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/VersionsMapUtils.java @@ -23,24 +23,24 @@ * @since 2019/2/12 */ public class VersionsMapUtils { - public static boolean checkAndUpdateVersions(Map versionsMap, String versionKey, - Long version) { - while (true) { - Long oldValue = versionsMap.get(versionKey); - if (oldValue == null) { - // Add firstly - if (versionsMap.putIfAbsent(versionKey, version) == null) { - return true; - } - } else { - if (version > oldValue) { - if (versionsMap.replace(versionKey, oldValue, version)) { - return true; - } - } else { - return false; - } - } + public static boolean checkAndUpdateVersions( + Map versionsMap, String versionKey, Long version) { + while (true) { + Long oldValue = versionsMap.get(versionKey); + if (oldValue == null) { + // Add firstly + if (versionsMap.putIfAbsent(versionKey, version) == null) { + return true; } + } else { + if (version > oldValue) { + if (versionsMap.replace(versionKey, oldValue, version)) { + return true; + } + } else { + return false; + } + } } + } } diff --git a/server/common/util/src/main/java/com/alipay/sofa/registry/util/WakeUpLoopRunnable.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/WakeUpLoopRunnable.java index db6cb6a33..c81363356 100644 --- a/server/common/util/src/main/java/com/alipay/sofa/registry/util/WakeUpLoopRunnable.java +++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/WakeUpLoopRunnable.java @@ -20,16 +20,16 @@ import java.util.concurrent.TimeUnit; public abstract class WakeUpLoopRunnable extends LoopRunnable { - private final SynchronousQueue bell = new SynchronousQueue<>(); + private final SynchronousQueue bell = new SynchronousQueue<>(); - @Override - public void waitingUnthrowable() { - ConcurrentUtils.pollUninterruptibly(bell, getWaitingMillis(), TimeUnit.MILLISECONDS); - } + @Override + public void waitingUnthrowable() { + ConcurrentUtils.pollUninterruptibly(bell, getWaitingMillis(), TimeUnit.MILLISECONDS); + } - public abstract int getWaitingMillis(); + public abstract int getWaitingMillis(); - public void wakeup() { - bell.offer(this); - } + public void wakeup() { + bell.offer(this); + } } diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/TestScheduler.java b/server/common/util/src/test/java/com/alipay/sofa/registry/TestScheduler.java index 2279e180b..35112a943 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/TestScheduler.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/TestScheduler.java @@ -18,8 +18,6 @@ /** * @author chen.zhu - *

- * Nov 30, 2020 + *

Nov 30, 2020 */ -public class TestScheduler { -} +public class TestScheduler {} diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/converter/ScopeEnumConverterTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/converter/ScopeEnumConverterTest.java index 480b3c6a0..46dd9851e 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/converter/ScopeEnumConverterTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/converter/ScopeEnumConverterTest.java @@ -25,11 +25,11 @@ * @since 2018/12/28 */ public class ScopeEnumConverterTest { - @Test - public void doTest() { - Assert.assertEquals(ScopeEnum.zone, new ScopeEnumConverter().convertToScope("zone")); - Assert.assertEquals(ScopeEnum.dataCenter, ScopeEnumConverter.convertToScope("dataCenter")); - Assert.assertEquals(ScopeEnum.global, ScopeEnumConverter.convertToScope("global")); - Assert.assertEquals(ScopeEnum.zone, ScopeEnumConverter.convertToScope("other value")); - } + @Test + public void doTest() { + Assert.assertEquals(ScopeEnum.zone, new ScopeEnumConverter().convertToScope("zone")); + Assert.assertEquals(ScopeEnum.dataCenter, ScopeEnumConverter.convertToScope("dataCenter")); + Assert.assertEquals(ScopeEnum.global, ScopeEnumConverter.convertToScope("global")); + Assert.assertEquals(ScopeEnum.zone, ScopeEnumConverter.convertToScope("other value")); + } } diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/task/listener/TaskListenerTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/task/listener/TaskListenerTest.java index 4c87300de..2cd173047 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/task/listener/TaskListenerTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/task/listener/TaskListenerTest.java @@ -18,47 +18,46 @@ import static com.alipay.sofa.registry.task.listener.TaskEvent.TaskType.WATCHER_REGISTER_FETCH_TASK; +import com.alipay.sofa.registry.task.listener.TaskEvent.TaskType; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import com.alipay.sofa.registry.task.listener.TaskEvent.TaskType; - /** * @author xuanbei * @since 2018/12/28 */ public class TaskListenerTest { - private static final TaskListenerManager taskListenerManager = new DefaultTaskListenerManager(); - private static volatile boolean watcherRegisterFetchTaskListenerCalled = false; + private static final TaskListenerManager taskListenerManager = new DefaultTaskListenerManager(); + private static volatile boolean watcherRegisterFetchTaskListenerCalled = false; - @BeforeClass - public static void beforeClass() { + @BeforeClass + public static void beforeClass() { - taskListenerManager.addTaskListener(new WatcherRegisterFetchTaskListener()); - } + taskListenerManager.addTaskListener(new WatcherRegisterFetchTaskListener()); + } - @Test - public void doTest() { - Assert.assertEquals(1, taskListenerManager.getTaskListeners().size()); + @Test + public void doTest() { + Assert.assertEquals(1, taskListenerManager.getTaskListeners().size()); - Assert.assertFalse(watcherRegisterFetchTaskListenerCalled); + Assert.assertFalse(watcherRegisterFetchTaskListenerCalled); - taskListenerManager.sendTaskEvent(new TaskEvent(WATCHER_REGISTER_FETCH_TASK)); + taskListenerManager.sendTaskEvent(new TaskEvent(WATCHER_REGISTER_FETCH_TASK)); - Assert.assertTrue(watcherRegisterFetchTaskListenerCalled); - watcherRegisterFetchTaskListenerCalled = false; - } + Assert.assertTrue(watcherRegisterFetchTaskListenerCalled); + watcherRegisterFetchTaskListenerCalled = false; + } - private static class WatcherRegisterFetchTaskListener implements TaskListener { - @Override - public TaskType support() { - return TaskType.WATCHER_REGISTER_FETCH_TASK; - } + private static class WatcherRegisterFetchTaskListener implements TaskListener { + @Override + public TaskType support() { + return TaskType.WATCHER_REGISTER_FETCH_TASK; + } - @Override - public void handleEvent(TaskEvent event) { - watcherRegisterFetchTaskListenerCalled = true; - } + @Override + public void handleEvent(TaskEvent event) { + watcherRegisterFetchTaskListenerCalled = true; } + } } diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/timer/AsyncHashedWheelTimerTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/timer/AsyncHashedWheelTimerTest.java index dbabd7faf..69375edf1 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/timer/AsyncHashedWheelTimerTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/timer/AsyncHashedWheelTimerTest.java @@ -16,58 +16,66 @@ */ package com.alipay.sofa.registry.timer; +import com.google.common.util.concurrent.ThreadFactoryBuilder; +import io.netty.util.Timer; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; - import org.junit.Assert; import org.junit.Test; -import com.google.common.util.concurrent.ThreadFactoryBuilder; - -import io.netty.util.Timer; - /** * @author xuanbei * @since 2019/3/27 */ public class AsyncHashedWheelTimerTest { - private long currentTime; - private long executeTime; - private Throwable executionRejectedThrowable; - private Throwable executionFailedThrowable; + private long currentTime; + private long executeTime; + private Throwable executionRejectedThrowable; + private Throwable executionFailedThrowable; - @Test - public void doTest() throws InterruptedException { - CountDownLatch countDownLatch = new CountDownLatch(2); - ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); - threadFactoryBuilder.setDaemon(true); - final Timer timer = new AsyncHashedWheelTimer(threadFactoryBuilder.setNameFormat( - "AsyncHashedWheelTimerTest").build(), 50, TimeUnit.MILLISECONDS, 10, 5, 10, - threadFactoryBuilder.setNameFormat("Registry-DataNodeServiceImpl-WheelExecutor-%d") - .build(), new AsyncHashedWheelTimer.TaskFailedCallback() { - @Override - public void executionRejected(Throwable t) { + @Test + public void doTest() throws InterruptedException { + CountDownLatch countDownLatch = new CountDownLatch(2); + ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder(); + threadFactoryBuilder.setDaemon(true); + final Timer timer = + new AsyncHashedWheelTimer( + threadFactoryBuilder.setNameFormat("AsyncHashedWheelTimerTest").build(), + 50, + TimeUnit.MILLISECONDS, + 10, + 5, + 10, + threadFactoryBuilder + .setNameFormat("Registry-DataNodeServiceImpl-WheelExecutor-%d") + .build(), + new AsyncHashedWheelTimer.TaskFailedCallback() { + @Override + public void executionRejected(Throwable t) { executionRejectedThrowable = t; - } + } - @Override - public void executionFailed(Throwable t) { + @Override + public void executionFailed(Throwable t) { executionFailedThrowable = t; countDownLatch.countDown(); - } - }); + } + }); - currentTime = System.currentTimeMillis(); - executeTime = currentTime; - timer.newTimeout((timeout)-> { - executeTime = System.currentTimeMillis(); - countDownLatch.countDown(); - throw new Exception("execution failed."); - },1000, TimeUnit.MILLISECONDS); + currentTime = System.currentTimeMillis(); + executeTime = currentTime; + timer.newTimeout( + (timeout) -> { + executeTime = System.currentTimeMillis(); + countDownLatch.countDown(); + throw new Exception("execution failed."); + }, + 1000, + TimeUnit.MILLISECONDS); - countDownLatch.await(3000, TimeUnit.MILLISECONDS); - Assert.assertTrue(executeTime >= currentTime + 1000); - Assert.assertNull(executionRejectedThrowable); - Assert.assertNotNull(executionFailedThrowable); - } + countDownLatch.await(3000, TimeUnit.MILLISECONDS); + Assert.assertTrue(executeTime >= currentTime + 1000); + Assert.assertNull(executionRejectedThrowable); + Assert.assertNotNull(executionFailedThrowable); + } } diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/util/BatchCallableRunnableTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/util/BatchCallableRunnableTest.java index 3cbc87731..41be60417 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/util/BatchCallableRunnableTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/util/BatchCallableRunnableTest.java @@ -18,71 +18,70 @@ import com.alipay.sofa.registry.util.BatchCallableRunnable.InvokeFuture; import com.alipay.sofa.registry.util.BatchCallableRunnable.TaskEvent; -import org.junit.Assert; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import org.junit.Assert; /** - * * @author xiaojian.xj * @version $Id: BatchCallableRunnableTest.java, v 0.1 2021年01月23日 16:11 xiaojian.xj Exp $ */ public class BatchCallableRunnableTest { - @org.junit.Test - public void testBatchRunnable() throws InterruptedException { - Test test = new Test(); + @org.junit.Test + public void testBatchRunnable() throws InterruptedException { + Test test = new Test(); - Map futures = new HashMap<>(); - for (int i = 0; i <= 255; i++) { - TaskEvent taskEvent = test.new TaskEvent(i); - InvokeFuture future = test.commit(taskEvent); - futures.putIfAbsent(i, future); - } + Map futures = new HashMap<>(); + for (int i = 0; i <= 255; i++) { + TaskEvent taskEvent = test.new TaskEvent(i); + InvokeFuture future = test.commit(taskEvent); + futures.putIfAbsent(i, future); + } - for (Entry entry : futures.entrySet()) { + for (Entry entry : futures.entrySet()) { - InvokeFuture future = entry.getValue(); - String result = (String) future.getResponse(); - Assert.assertEquals("hello " + entry.getKey().intValue(), result); - } + InvokeFuture future = entry.getValue(); + String result = (String) future.getResponse(); + Assert.assertEquals("hello " + entry.getKey().intValue(), result); } + } - public class Test extends BatchCallableRunnable { + public class Test extends BatchCallableRunnable { - public Test() { - init(); - } + public Test() { + init(); + } - @Override - public boolean batchProcess(List taskEvents) { - if (taskEvents == null || taskEvents.size() == 0) { - return true; - } + @Override + public boolean batchProcess(List taskEvents) { + if (taskEvents == null || taskEvents.size() == 0) { + return true; + } - for (TaskEvent taskEvent : taskEvents) { - Integer data = taskEvent.getData(); - taskEvent.getFuture().putResponse("hello " + data); - } - return true; - } + for (TaskEvent taskEvent : taskEvents) { + Integer data = taskEvent.getData(); + taskEvent.getFuture().putResponse("hello " + data); + } + return true; + } - @Override - protected void setSleep() { - this.sleep = 1; - } + @Override + protected void setSleep() { + this.sleep = 1; + } - @Override - protected void setTimeUnit() { - this.timeUnit = TimeUnit.SECONDS; - } + @Override + protected void setTimeUnit() { + this.timeUnit = TimeUnit.SECONDS; + } - @Override - protected void setBatchSize() { - this.batchSize = 100; - } + @Override + protected void setBatchSize() { + this.batchSize = 100; } -} \ No newline at end of file + } +} diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/util/CollectionUtilsTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/util/CollectionUtilsTest.java index 5f1da1447..b22ce4cf3 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/util/CollectionUtilsTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/util/CollectionUtilsTest.java @@ -16,35 +16,36 @@ */ package com.alipay.sofa.registry.util; -import org.junit.Assert; -import org.junit.Test; - import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; +import org.junit.Assert; +import org.junit.Test; /** * @author xuanbei * @since 2018/12/28 */ public class CollectionUtilsTest { - Collection stringCollection = new ArrayList<>(Arrays.asList("zhangsan", "lisi", - "wangwu", "zhaoliu", "sunqi", "zhouba")); + Collection stringCollection = + new ArrayList<>(Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu", "sunqi", "zhouba")); - @Test - public void testGetRandom() { - boolean allValueSame = true; - String firstValue = null; - for (int i = 0; i < 10; i++) { - String radomeValue = i % 2 == 0 ? CollectionUtils.getRandom(stringCollection).get() - : new CollectionUtils().getRandom(stringCollection).get(); - Assert.assertTrue(stringCollection.contains(radomeValue)); - if (firstValue == null) { - firstValue = radomeValue; - } else if (!radomeValue.equals(firstValue)) { - allValueSame = false; - } - } - Assert.assertFalse(allValueSame); + @Test + public void testGetRandom() { + boolean allValueSame = true; + String firstValue = null; + for (int i = 0; i < 10; i++) { + String radomeValue = + i % 2 == 0 + ? CollectionUtils.getRandom(stringCollection).get() + : new CollectionUtils().getRandom(stringCollection).get(); + Assert.assertTrue(stringCollection.contains(radomeValue)); + if (firstValue == null) { + firstValue = radomeValue; + } else if (!radomeValue.equals(firstValue)) { + allValueSame = false; + } } + Assert.assertFalse(allValueSame); + } } diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/util/DatumVersionUtilTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/util/DatumVersionUtilTest.java index 31ca1f007..f562b617b 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/util/DatumVersionUtilTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/util/DatumVersionUtilTest.java @@ -16,27 +16,26 @@ */ package com.alipay.sofa.registry.util; +import static org.junit.Assert.*; + import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import org.junit.Test; -import static org.junit.Assert.*; - public class DatumVersionUtilTest { - private final Logger logger = LoggerFactory.getLogger(DatumVersionUtilTest.class); + private final Logger logger = LoggerFactory.getLogger(DatumVersionUtilTest.class); - @Test - public void testNextId() { - long epoch = DatumVersionUtil.nextId(); - long timestamp = System.currentTimeMillis(); - System.out.println(epoch); - System.out.println(timestamp); - logger.info("[epoch] {}", epoch); - logger.info("[timestamp] {}", timestamp); - } + @Test + public void testNextId() { + long epoch = DatumVersionUtil.nextId(); + long timestamp = System.currentTimeMillis(); + System.out.println(epoch); + System.out.println(timestamp); + logger.info("[epoch] {}", epoch); + logger.info("[timestamp] {}", timestamp); + } - @Test - public void testGetRealTimestamp() { - } -} \ No newline at end of file + @Test + public void testGetRealTimestamp() {} +} diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/util/FileUtilsTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/util/FileUtilsTest.java index 1690ae41d..7da7949e8 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/util/FileUtilsTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/util/FileUtilsTest.java @@ -16,49 +16,50 @@ */ package com.alipay.sofa.registry.util; -import org.junit.Test; - -import java.io.File; -import java.io.IOException; - import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.io.File; +import java.io.IOException; +import org.junit.Test; + /** * @author xuanbei * @since 2019/1/16 */ public class FileUtilsTest { - @Test - public void doTest() throws Exception { - File dir = new File(System.getProperty("user.home") + File.separator + "FileUtilsTestDir"); - File file = new File(dir, "FileUtilsTest"); - FileUtils.forceDelete(dir); + @Test + public void doTest() throws Exception { + File dir = new File(System.getProperty("user.home") + File.separator + "FileUtilsTestDir"); + File file = new File(dir, "FileUtilsTest"); + FileUtils.forceDelete(dir); - String data = "FileUtilsTest"; - new FileUtils().writeByteArrayToFile(file, data.getBytes(), true); - byte[] readByte = FileUtils.readFileToByteArray(file); - assertEquals(data, new String(readByte)); + String data = "FileUtilsTest"; + new FileUtils().writeByteArrayToFile(file, data.getBytes(), true); + byte[] readByte = FileUtils.readFileToByteArray(file); + assertEquals(data, new String(readByte)); - boolean throwException = false; - try { - FileUtils.forceMkdir(file); - } catch (Exception e) { - throwException = true; - assertTrue(e.getClass() == IOException.class); - assertTrue(e.getMessage().contains( - "FileUtilsTest exists and is not a directory. Unable to create directory.")); - } - if (!throwException) { - fail("should throw Exception."); - } - FileUtils.forceDelete(file); - FileUtils.forceDelete(dir); - - FileUtils.forceMkdir(dir); - assertTrue(dir.exists()); - assertTrue(dir.isDirectory()); - FileUtils.forceDelete(dir); + boolean throwException = false; + try { + FileUtils.forceMkdir(file); + } catch (Exception e) { + throwException = true; + assertTrue(e.getClass() == IOException.class); + assertTrue( + e.getMessage() + .contains( + "FileUtilsTest exists and is not a directory. Unable to create directory.")); + } + if (!throwException) { + fail("should throw Exception."); } + FileUtils.forceDelete(file); + FileUtils.forceDelete(dir); + + FileUtils.forceMkdir(dir); + assertTrue(dir.exists()); + assertTrue(dir.isDirectory()); + FileUtils.forceDelete(dir); + } } diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/util/MathUtilsTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/util/MathUtilsTest.java index e4dd3f0f2..d5595c380 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/util/MathUtilsTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/util/MathUtilsTest.java @@ -16,17 +16,17 @@ */ package com.alipay.sofa.registry.util; +import static org.junit.Assert.*; + import org.junit.Assert; import org.junit.Test; -import static org.junit.Assert.*; - public class MathUtilsTest { - @Test - public void testDivideCeil() { - Assert.assertEquals(3, MathUtils.divideCeil(5, 2)); - Assert.assertEquals(3, MathUtils.divideCeil(6, 2)); - Assert.assertEquals(4, MathUtils.divideCeil(7, 2)); - } -} \ No newline at end of file + @Test + public void testDivideCeil() { + Assert.assertEquals(3, MathUtils.divideCeil(5, 2)); + Assert.assertEquals(3, MathUtils.divideCeil(6, 2)); + Assert.assertEquals(4, MathUtils.divideCeil(7, 2)); + } +} diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/util/MessageDigestsTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/util/MessageDigestsTest.java index 8211c4f21..a70304c6e 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/util/MessageDigestsTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/util/MessageDigestsTest.java @@ -16,74 +16,96 @@ */ package com.alipay.sofa.registry.util; -import org.junit.Test; +import static org.junit.Assert.assertEquals; import java.security.MessageDigest; - -import static org.junit.Assert.assertEquals; +import org.junit.Test; /** * The type Message digests test. + * * @author zhuoyu.sjw * @version $Id : MessageDigestsTest.java, v 0.1 2018-03-07 11:19 zhuoyu.sjw Exp $$ */ public class MessageDigestsTest { - /** - * Md 5. - */ - @Test - public void md5() { - assertHash("d41d8cd98f00b204e9800998ecf8427e", "", MessageDigests.md5()); - assertHash("900150983cd24fb0d6963f7d28e17f72", "abc", MessageDigests.md5()); - assertHash("8215ef0796a20bcaaae116d3876c664a", - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", MessageDigests.md5()); - assertHash("7707d6ae4e027c70eea2a935c2296f21", - new String(new char[1000000]).replace("\0", "a"), MessageDigests.md5()); - assertHash("9e107d9d372bb6826bd81d3542a419d6", - "The quick brown fox jumps over the lazy dog", MessageDigests.md5()); - assertHash("1055d3e698d289f2af8663725127bd4b", - "The quick brown fox jumps over the lazy cog", MessageDigests.md5()); - } + /** Md 5. */ + @Test + public void md5() { + assertHash("d41d8cd98f00b204e9800998ecf8427e", "", MessageDigests.md5()); + assertHash("900150983cd24fb0d6963f7d28e17f72", "abc", MessageDigests.md5()); + assertHash( + "8215ef0796a20bcaaae116d3876c664a", + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + MessageDigests.md5()); + assertHash( + "7707d6ae4e027c70eea2a935c2296f21", + new String(new char[1000000]).replace("\0", "a"), + MessageDigests.md5()); + assertHash( + "9e107d9d372bb6826bd81d3542a419d6", + "The quick brown fox jumps over the lazy dog", + MessageDigests.md5()); + assertHash( + "1055d3e698d289f2af8663725127bd4b", + "The quick brown fox jumps over the lazy cog", + MessageDigests.md5()); + } - /** - * Sha 1. - */ - @Test - public void sha1() { - assertHash("da39a3ee5e6b4b0d3255bfef95601890afd80709", "", MessageDigests.sha1()); - assertHash("a9993e364706816aba3e25717850c26c9cd0d89d", "abc", MessageDigests.sha1()); - assertHash("84983e441c3bd26ebaae4aa1f95129e5e54670f1", - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", MessageDigests.sha1()); - assertHash("34aa973cd4c4daa4f61eeb2bdbad27316534016f", - new String(new char[1000000]).replace("\0", "a"), MessageDigests.sha1()); - assertHash("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12", - "The quick brown fox jumps over the lazy dog", MessageDigests.sha1()); - assertHash("de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3", - "The quick brown fox jumps over the lazy cog", MessageDigests.sha1()); - } + /** Sha 1. */ + @Test + public void sha1() { + assertHash("da39a3ee5e6b4b0d3255bfef95601890afd80709", "", MessageDigests.sha1()); + assertHash("a9993e364706816aba3e25717850c26c9cd0d89d", "abc", MessageDigests.sha1()); + assertHash( + "84983e441c3bd26ebaae4aa1f95129e5e54670f1", + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + MessageDigests.sha1()); + assertHash( + "34aa973cd4c4daa4f61eeb2bdbad27316534016f", + new String(new char[1000000]).replace("\0", "a"), + MessageDigests.sha1()); + assertHash( + "2fd4e1c67a2d28fced849ee1bb76e7391b93eb12", + "The quick brown fox jumps over the lazy dog", + MessageDigests.sha1()); + assertHash( + "de9f2c7fd25e1b3afad3e85a0bd17d9b100db4b3", + "The quick brown fox jumps over the lazy cog", + MessageDigests.sha1()); + } - /** - * Sha 256. - */ - @Test - public void sha256() { - assertHash("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "", - MessageDigests.sha256()); - assertHash("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "abc", - MessageDigests.sha256()); - assertHash("248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", - "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", MessageDigests.sha256()); - assertHash("cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0", new String( - new char[1000000]).replace("\0", "a"), MessageDigests.sha256()); - assertHash("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592", - "The quick brown fox jumps over the lazy dog", MessageDigests.sha256()); - assertHash("e4c4d8f3bf76b692de791a173e05321150f7a345b46484fe427f6acc7ecc81be", - "The quick brown fox jumps over the lazy cog", MessageDigests.sha256()); - } + /** Sha 256. */ + @Test + public void sha256() { + assertHash( + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + "", + MessageDigests.sha256()); + assertHash( + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + "abc", + MessageDigests.sha256()); + assertHash( + "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1", + "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", + MessageDigests.sha256()); + assertHash( + "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0", + new String(new char[1000000]).replace("\0", "a"), + MessageDigests.sha256()); + assertHash( + "d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592", + "The quick brown fox jumps over the lazy dog", + MessageDigests.sha256()); + assertHash( + "e4c4d8f3bf76b692de791a173e05321150f7a345b46484fe427f6acc7ecc81be", + "The quick brown fox jumps over the lazy cog", + MessageDigests.sha256()); + } - private void assertHash(String expected, String test, MessageDigest messageDigest) { - String actual = MessageDigests.toHexString(messageDigest.digest(test.getBytes())); - assertEquals(expected, actual); - } -} \ No newline at end of file + private void assertHash(String expected, String test, MessageDigest messageDigest) { + String actual = MessageDigests.toHexString(messageDigest.digest(test.getBytes())); + assertEquals(expected, actual); + } +} diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/util/OsUtilsTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/util/OsUtilsTest.java index e540bc531..fe98996d9 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/util/OsUtilsTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/util/OsUtilsTest.java @@ -16,18 +16,18 @@ */ package com.alipay.sofa.registry.util; +import static org.junit.Assert.*; + import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import org.junit.Test; -import static org.junit.Assert.*; - public class OsUtilsTest { - private Logger logger = LoggerFactory.getLogger(OsUtilsTest.class); + private Logger logger = LoggerFactory.getLogger(OsUtilsTest.class); - @Test - public void getCpuCount() { - logger.info("cpu cores: {}", OsUtils.getCpuCount()); - } -} \ No newline at end of file + @Test + public void getCpuCount() { + logger.info("cpu cores: {}", OsUtils.getCpuCount()); + } +} diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/util/ParaCheckUtilTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/util/ParaCheckUtilTest.java index 930ee7e79..e515d6922 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/util/ParaCheckUtilTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/util/ParaCheckUtilTest.java @@ -16,52 +16,51 @@ */ package com.alipay.sofa.registry.util; -import org.junit.Assert; -import org.junit.Test; +import static junit.framework.TestCase.fail; import java.util.ArrayList; import java.util.Arrays; - -import static junit.framework.TestCase.fail; +import org.junit.Assert; +import org.junit.Test; /** * @author xuanbei * @since 2018/12/28 */ public class ParaCheckUtilTest { - @Test - public void testCheckNotNull() { - ParaCheckUtil.checkNotNull("zhangsan", "name"); - try { - ParaCheckUtil.checkNotNull(null, "name"); - fail("cannot access here."); - } catch (Exception e) { - Assert.assertTrue(e instanceof RuntimeException); - Assert.assertEquals("name is not allowed to be null", e.getMessage()); - } + @Test + public void testCheckNotNull() { + ParaCheckUtil.checkNotNull("zhangsan", "name"); + try { + ParaCheckUtil.checkNotNull(null, "name"); + fail("cannot access here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof RuntimeException); + Assert.assertEquals("name is not allowed to be null", e.getMessage()); } + } - @Test - public void testCheckNotBlank() { - ParaCheckUtil.checkNotBlank("zhangsan", "name"); - try { - ParaCheckUtil.checkNotBlank("", "name"); - fail("cannot access here."); - } catch (Exception e) { - Assert.assertTrue(e instanceof RuntimeException); - Assert.assertEquals("name is not allowed to be blank", e.getMessage()); - } + @Test + public void testCheckNotBlank() { + ParaCheckUtil.checkNotBlank("zhangsan", "name"); + try { + ParaCheckUtil.checkNotBlank("", "name"); + fail("cannot access here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof RuntimeException); + Assert.assertEquals("name is not allowed to be blank", e.getMessage()); } + } - @Test - public void testCheckNotEmpty() { - ParaCheckUtil.checkNotEmpty(Arrays.asList("zhangsan", "lisi"), "names"); - try { - ParaCheckUtil.checkNotEmpty(new ArrayList<>(), "names"); - fail("cannot access here."); - } catch (Exception e) { - Assert.assertTrue(e instanceof RuntimeException); - Assert.assertEquals("names is not allowed to be empty", e.getMessage()); - } + @Test + public void testCheckNotEmpty() { + ParaCheckUtil.checkNotEmpty(Arrays.asList("zhangsan", "lisi"), "names"); + try { + ParaCheckUtil.checkNotEmpty(new ArrayList<>(), "names"); + fail("cannot access here."); + } catch (Exception e) { + Assert.assertTrue(e instanceof RuntimeException); + Assert.assertEquals("names is not allowed to be empty", e.getMessage()); } + } } diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/util/PropertySplitterTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/util/PropertySplitterTest.java index 93c1d70f5..6a8b6f107 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/util/PropertySplitterTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/util/PropertySplitterTest.java @@ -16,63 +16,74 @@ */ package com.alipay.sofa.registry.util; +import java.util.List; import org.junit.Assert; import org.junit.Test; -import java.util.List; - /** * @author xuanbei * @since 2018/12/28 */ public class PropertySplitterTest { - private PropertySplitter propertySplitter = new PropertySplitter(); + private PropertySplitter propertySplitter = new PropertySplitter(); - @Test - public void testMap() { - Assert.assertEquals(0, propertySplitter.map(null).size()); - Assert.assertEquals(0, propertySplitter.map("").size()); - Assert.assertEquals(2, propertySplitter.map("KEY1:VALUE1,KEY2:VALUE2").size()); - Assert.assertEquals("VALUE1", propertySplitter.map("KEY1:VALUE1,KEY2:VALUE2").get("KEY1")); - Assert.assertEquals("VALUE2", propertySplitter.map("KEY1:VALUE1,KEY2:VALUE2").get("KEY2")); - } + @Test + public void testMap() { + Assert.assertEquals(0, propertySplitter.map(null).size()); + Assert.assertEquals(0, propertySplitter.map("").size()); + Assert.assertEquals(2, propertySplitter.map("KEY1:VALUE1,KEY2:VALUE2").size()); + Assert.assertEquals("VALUE1", propertySplitter.map("KEY1:VALUE1,KEY2:VALUE2").get("KEY1")); + Assert.assertEquals("VALUE2", propertySplitter.map("KEY1:VALUE1,KEY2:VALUE2").get("KEY2")); + } - @Test - public void testMapOfList() { - Assert.assertEquals(0, propertySplitter.mapOfList(null).size()); - Assert.assertEquals(0, propertySplitter.mapOfList("|").size()); - Assert.assertEquals(2, - propertySplitter.mapOfList("KEY1:VALUE1.1,VALUE1.2|KEY2:VALUE2.1,VALUE2.2").size()); - Assert.assertTrue(propertySplitter.map("KEY1:VALUE1,KEY2:VALUE2").get("KEY1") - .contains("VALUE1")); - Assert.assertTrue(propertySplitter.map("KEY1:VALUE1,KEY2:VALUE2").get("KEY2") - .contains("VALUE2")); - } + @Test + public void testMapOfList() { + Assert.assertEquals(0, propertySplitter.mapOfList(null).size()); + Assert.assertEquals(0, propertySplitter.mapOfList("|").size()); + Assert.assertEquals( + 2, propertySplitter.mapOfList("KEY1:VALUE1.1,VALUE1.2|KEY2:VALUE2.1,VALUE2.2").size()); + Assert.assertTrue( + propertySplitter.map("KEY1:VALUE1,KEY2:VALUE2").get("KEY1").contains("VALUE1")); + Assert.assertTrue( + propertySplitter.map("KEY1:VALUE1,KEY2:VALUE2").get("KEY2").contains("VALUE2")); + } - @Test - public void testList() { - Assert.assertEquals(0, propertySplitter.list(null).size()); - Assert.assertEquals(0, propertySplitter.list("").size()); - Assert.assertEquals(4, propertySplitter.list("VALUE1,VALUE2,VALUE3,VALUE4").size()); - Assert.assertTrue(propertySplitter.list("VALUE1,VALUE2,VALUE3,VALUE4").contains("VALUE1")); - Assert.assertTrue(propertySplitter.list("VALUE1,VALUE2,VALUE3,VALUE4").contains("VALUE2")); - Assert.assertTrue(propertySplitter.list("VALUE1,VALUE2,VALUE3,VALUE4").contains("VALUE3")); - Assert.assertTrue(propertySplitter.list("VALUE1,VALUE2,VALUE3,VALUE4").contains("VALUE4")); - } + @Test + public void testList() { + Assert.assertEquals(0, propertySplitter.list(null).size()); + Assert.assertEquals(0, propertySplitter.list("").size()); + Assert.assertEquals(4, propertySplitter.list("VALUE1,VALUE2,VALUE3,VALUE4").size()); + Assert.assertTrue(propertySplitter.list("VALUE1,VALUE2,VALUE3,VALUE4").contains("VALUE1")); + Assert.assertTrue(propertySplitter.list("VALUE1,VALUE2,VALUE3,VALUE4").contains("VALUE2")); + Assert.assertTrue(propertySplitter.list("VALUE1,VALUE2,VALUE3,VALUE4").contains("VALUE3")); + Assert.assertTrue(propertySplitter.list("VALUE1,VALUE2,VALUE3,VALUE4").contains("VALUE4")); + } - @Test - public void testGroupedList() { - Assert.assertEquals(0, propertySplitter.groupedList(null).size()); - Assert.assertEquals(0, propertySplitter.groupedList("").size()); - Assert.assertEquals(2, propertySplitter.groupedList("VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2") - .size()); - Assert.assertTrue(((List) (((List) propertySplitter - .groupedList("VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2")).get(0))).contains("VALUE1.1")); - Assert.assertTrue(((List) (((List) propertySplitter - .groupedList("VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2")).get(0))).contains("VALUE1.1")); - Assert.assertTrue(((List) (((List) propertySplitter - .groupedList("VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2")).get(1))).contains("VALUE2.1")); - Assert.assertTrue(((List) (((List) propertySplitter - .groupedList("VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2")).get(1))).contains("VALUE2.2")); - } + @Test + public void testGroupedList() { + Assert.assertEquals(0, propertySplitter.groupedList(null).size()); + Assert.assertEquals(0, propertySplitter.groupedList("").size()); + Assert.assertEquals( + 2, propertySplitter.groupedList("VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2").size()); + Assert.assertTrue( + ((List) + (((List) propertySplitter.groupedList("VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2")) + .get(0))) + .contains("VALUE1.1")); + Assert.assertTrue( + ((List) + (((List) propertySplitter.groupedList("VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2")) + .get(0))) + .contains("VALUE1.1")); + Assert.assertTrue( + ((List) + (((List) propertySplitter.groupedList("VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2")) + .get(1))) + .contains("VALUE2.1")); + Assert.assertTrue( + ((List) + (((List) propertySplitter.groupedList("VALUE1.1,VALUE1.2|VALUE2.1,VALUE2.2")) + .get(1))) + .contains("VALUE2.2")); + } } diff --git a/server/common/util/src/test/java/com/alipay/sofa/registry/util/VersionsMapUtilsTest.java b/server/common/util/src/test/java/com/alipay/sofa/registry/util/VersionsMapUtilsTest.java index 93d577781..86ca640ca 100644 --- a/server/common/util/src/test/java/com/alipay/sofa/registry/util/VersionsMapUtilsTest.java +++ b/server/common/util/src/test/java/com/alipay/sofa/registry/util/VersionsMapUtilsTest.java @@ -16,25 +16,23 @@ */ package com.alipay.sofa.registry.util; -import org.junit.Assert; -import org.junit.Test; - import java.util.HashMap; import java.util.Map; +import org.junit.Assert; +import org.junit.Test; /** * @author xuanbei * @since 2019/3/27 */ public class VersionsMapUtilsTest { - @Test - public void doTest() { - Map versionsMap = new HashMap<>(); - Assert.assertTrue(VersionsMapUtils.checkAndUpdateVersions(versionsMap, "mockDataInfoId", - 20L)); - Assert.assertTrue(new VersionsMapUtils().checkAndUpdateVersions(versionsMap, - "mockDataInfoId", 30L)); - Assert.assertFalse(new VersionsMapUtils().checkAndUpdateVersions(versionsMap, - "mockDataInfoId", 10L)); - } + @Test + public void doTest() { + Map versionsMap = new HashMap<>(); + Assert.assertTrue(VersionsMapUtils.checkAndUpdateVersions(versionsMap, "mockDataInfoId", 20L)); + Assert.assertTrue( + new VersionsMapUtils().checkAndUpdateVersions(versionsMap, "mockDataInfoId", 30L)); + Assert.assertFalse( + new VersionsMapUtils().checkAndUpdateVersions(versionsMap, "mockDataInfoId", 10L)); + } } diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/CallbackHandler.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/CallbackHandler.java index 53114f6a7..79048366d 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/CallbackHandler.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/CallbackHandler.java @@ -19,32 +19,31 @@ import java.util.concurrent.Executor; /** - * * @author shangyu.wh * @version $Id: CallbackHandler.java, v 0.1 2017-11-22 15:16 shangyu.wh Exp $ */ public interface CallbackHandler { - /** - * callback handler - * - * @param channel - * @param message - */ - void onCallback(Channel channel, Object message); + /** + * callback handler + * + * @param channel + * @param message + */ + void onCallback(Channel channel, Object message); - /** - * callback exception handler - * - * @param channel - * @param exception - */ - void onException(Channel channel, Throwable exception); + /** + * callback exception handler + * + * @param channel + * @param exception + */ + void onException(Channel channel, Throwable exception); - /** - * override executor - * - * @return - */ - Executor getExecutor(); -} \ No newline at end of file + /** + * override executor + * + * @return + */ + Executor getExecutor(); +} diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Channel.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Channel.java index 5d1271864..23646c6fd 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Channel.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Channel.java @@ -17,62 +17,57 @@ package com.alipay.sofa.registry.remoting; import java.net.InetSocketAddress; - import javax.ws.rs.client.WebTarget; /** - * * @author shangyu.wh * @version $Id: Channel.java, v 0.1 2017-11-20 20:39 shangyu.wh Exp $ */ public interface Channel { - /** - * get remote address. - * - * @return remote address. - */ - InetSocketAddress getRemoteAddress(); + /** + * get remote address. + * + * @return remote address. + */ + InetSocketAddress getRemoteAddress(); - /** - * get local address. - * - * @return local address. - */ - InetSocketAddress getLocalAddress(); + /** + * get local address. + * + * @return local address. + */ + InetSocketAddress getLocalAddress(); - /** - * is connected. - * - * @return connected - */ - boolean isConnected(); + /** + * is connected. + * + * @return connected + */ + boolean isConnected(); - /** - * get attribute. - * - * @param key - * key. - * @return value. - */ - Object getAttribute(String key); + /** + * get attribute. + * + * @param key key. + * @return value. + */ + Object getAttribute(String key); - /** - * set attribute. - * - * @param key - * key. - * @param value - * value. - */ - void setAttribute(String key, Object value); + /** + * set attribute. + * + * @param key key. + * @param value value. + */ + void setAttribute(String key, Object value); - /** - * for rest api - * - * @return - */ - WebTarget getWebTarget(); + /** + * for rest api + * + * @return + */ + WebTarget getWebTarget(); - void close(); -} \ No newline at end of file + void close(); +} diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/ChannelHandler.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/ChannelHandler.java index f913ca32b..cb2dc1251 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/ChannelHandler.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/ChannelHandler.java @@ -19,99 +19,97 @@ import java.util.concurrent.Executor; /** - * * @author shangyu.wh * @version $Id: ChannelHandler.java, v 0.1 2017-11-20 20:45 shangyu.wh Exp $ */ public interface ChannelHandler { - /** - * The enum Handler type. - */ - enum HandlerType { - LISENTER, - PROCESSER - } + /** The enum Handler type. */ + enum HandlerType { + LISENTER, + PROCESSER + } - /** - * The enum Invoke type. - */ - enum InvokeType { - SYNC, - ASYNC - } + /** The enum Invoke type. */ + enum InvokeType { + SYNC, + ASYNC + } - /** - * on channel connected. - * - * @param channel - * @throws RemotingException - */ - void connected(Channel channel) throws RemotingException; + /** + * on channel connected. + * + * @param channel + * @throws RemotingException + */ + void connected(Channel channel) throws RemotingException; - /** - * on channel disconnected. - * - * @param channel channel. - * @throws RemotingException - */ - void disconnected(Channel channel) throws RemotingException; + /** + * on channel disconnected. + * + * @param channel channel. + * @throws RemotingException + */ + void disconnected(Channel channel) throws RemotingException; - /** - * on message received. - * - * @param channel channel. - * @param message message. - * @throws RemotingException - */ - void received(Channel channel, T message) throws RemotingException; + /** + * on message received. + * + * @param channel channel. + * @param message message. + * @throws RemotingException + */ + void received(Channel channel, T message) throws RemotingException; - /** - * on message reply. - * - * @param channel - * @param message - * @return - * @throws RemotingException - */ - Object reply(Channel channel, T message) throws RemotingException; + /** + * on message reply. + * + * @param channel + * @param message + * @return + * @throws RemotingException + */ + Object reply(Channel channel, T message) throws RemotingException; - /** - * on exception caught. - * @param channel channel. - * @param message message. - * @param exception exception. - * @throws RemotingException - */ - void caught(Channel channel, T message, Throwable exception) throws RemotingException; + /** + * on exception caught. + * + * @param channel channel. + * @param message message. + * @param exception exception. + * @throws RemotingException + */ + void caught(Channel channel, T message, Throwable exception) throws RemotingException; - /** - * check handlerType - * - * @return - */ - HandlerType getType(); + /** + * check handlerType + * + * @return + */ + HandlerType getType(); - /** - * return processor request class name - * - * @return - */ - Class interest(); + /** + * return processor request class name + * + * @return + */ + Class interest(); - /** - * Select Sync process by reply or Async process by received - * @return - */ - default InvokeType getInvokeType() { - return InvokeType.SYNC; - } + /** + * Select Sync process by reply or Async process by received + * + * @return + */ + default InvokeType getInvokeType() { + return InvokeType.SYNC; + } - /** - * specify executor for processor handler - * @return - */ - default Executor getExecutor() { - return null; - } -} \ No newline at end of file + /** + * specify executor for processor handler + * + * @return + */ + default Executor getExecutor() { + return null; + } +} diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Client.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Client.java index fddc20a62..c55b8c7af 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Client.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Client.java @@ -19,67 +19,58 @@ import com.alipay.sofa.registry.common.model.store.URL; /** - * * @author shangyu.wh * @version $Id: Client.java, v 0.1 2017-11-20 21:07 shangyu.wh Exp $ */ public interface Client extends Endpoint { - /** - * get channel by url. - * - * @param url - * @return channel - */ - Channel getChannel(URL url); + /** + * get channel by url. + * + * @param url + * @return channel + */ + Channel getChannel(URL url); - /** - * client connect target url server - * - * @param url - * @return - */ - Channel connect(URL url); + /** + * client connect target url server + * + * @param url + * @return + */ + Channel connect(URL url); - /** - * Sync send - * - * @param url - * the url - * @param message - * the message - * @param timeoutMillis - * the timeout millis - * @return object - */ - Object sendSync(final URL url, final Object message, final int timeoutMillis); + /** + * Sync send + * + * @param url the url + * @param message the message + * @param timeoutMillis the timeout millis + * @return object + */ + Object sendSync(final URL url, final Object message, final int timeoutMillis); - /** - * send with callback handler - * - * @param url - * the url - * @param message - * the message - * @param callbackHandler - * the callback handler - * @param timeoutMillis - * the timeout millis - */ - void sendCallback(final URL url, final Object message, - CallbackHandler callbackHandler, final int timeoutMillis); + /** + * send with callback handler + * + * @param url the url + * @param message the message + * @param callbackHandler the callback handler + * @param timeoutMillis the timeout millis + */ + void sendCallback( + final URL url, + final Object message, + CallbackHandler callbackHandler, + final int timeoutMillis); - /** - * Sync send - * - * @param channel - * the channel - * @param message - * the message - * @param timeoutMillis - * the timeout millis - * @return object - */ - Object sendSync(final Channel channel, final Object message, - final int timeoutMillis); -} \ No newline at end of file + /** + * Sync send + * + * @param channel the channel + * @param message the message + * @param timeoutMillis the timeout millis + * @return object + */ + Object sendSync(final Channel channel, final Object message, final int timeoutMillis); +} diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Endpoint.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Endpoint.java index 88d611c8a..40bdd1129 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Endpoint.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Endpoint.java @@ -20,30 +20,27 @@ /** * The interface Endpoint. - * + * * @author shangyu.wh * @author kezhu.wukz * @version $Id : Endpoint.java, v 0.1 2017-11-20 20:03 shangyu.wh Exp $ */ public interface Endpoint { - /** - * get local address. - * - * @return local address. - */ - InetSocketAddress getLocalAddress(); - - /** - * close the channel. - */ - void close(); + /** + * get local address. + * + * @return local address. + */ + InetSocketAddress getLocalAddress(); - /** - * is closed. - * - * @return closed boolean - */ - boolean isClosed(); + /** close the channel. */ + void close(); -} \ No newline at end of file + /** + * is closed. + * + * @return closed boolean + */ + boolean isClosed(); +} diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/RemotingException.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/RemotingException.java index 693d21fb3..8987e36a9 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/RemotingException.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/RemotingException.java @@ -17,18 +17,17 @@ package com.alipay.sofa.registry.remoting; /** - * * @author shangyu.wh * @version $Id: RemotingException.java, v 0.1 2017-11-20 20:43 shangyu.wh Exp $ */ public class RemotingException extends Exception { - /** - * constructor - * - * @param s - */ - public RemotingException(String s) { - super(s); - } -} \ No newline at end of file + /** + * constructor + * + * @param s + */ + public RemotingException(String s) { + super(s); + } +} diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Server.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Server.java index d48b33f0e..91023a916 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Server.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/Server.java @@ -16,75 +16,76 @@ */ package com.alipay.sofa.registry.remoting; +import com.alipay.sofa.registry.common.model.store.URL; import java.net.InetSocketAddress; import java.util.Collection; -import com.alipay.sofa.registry.common.model.store.URL; - /** - * * @author shangyu.wh * @version $Id: Server.java, v 0.1 2017-11-20 21:05 shangyu.wh Exp $ */ public interface Server extends Endpoint { - /** - * get Server status - * - * @return - */ - boolean isOpen(); + /** + * get Server status + * + * @return + */ + boolean isOpen(); - /** - * get channels. - * - * @return channels - */ - Collection getChannels(); + /** + * get channels. + * + * @return channels + */ + Collection getChannels(); - /** - * get channel. - * - * @param remoteAddress - * @return channel - */ - Channel getChannel(InetSocketAddress remoteAddress); + /** + * get channel. + * + * @param remoteAddress + * @return channel + */ + Channel getChannel(InetSocketAddress remoteAddress); - /** - * get channel by url - * - * @param url - * @return channel - */ - Channel getChannel(URL url); + /** + * get channel by url + * + * @param url + * @return channel + */ + Channel getChannel(URL url); - /** - * close the channel. - * - * @param channel - */ - void close(Channel channel); + /** + * close the channel. + * + * @param channel + */ + void close(Channel channel); - int getChannelCount(); + int getChannelCount(); - /** - * send with callback handler - * - * @param channel the channel - * @param message the message - * @param callbackHandler the callback handler - * @param timeoutMillis the timeout millis - */ - void sendCallback(final Channel channel, final Object message, CallbackHandler callbackHandler, - final int timeoutMillis); + /** + * send with callback handler + * + * @param channel the channel + * @param message the message + * @param callbackHandler the callback handler + * @param timeoutMillis the timeout millis + */ + void sendCallback( + final Channel channel, + final Object message, + CallbackHandler callbackHandler, + final int timeoutMillis); - /** - * Sync send - * - * @param channel the channel - * @param message the message - * @param timeoutMillis the timeout millis - * @return object - */ - Object sendSync(final Channel channel, final Object message, final int timeoutMillis); -} \ No newline at end of file + /** + * Sync send + * + * @param channel the channel + * @param message the message + * @param timeoutMillis the timeout millis + * @return object + */ + Object sendSync(final Channel channel, final Object message, final int timeoutMillis); +} diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/Exchange.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/Exchange.java index 05aa49b1e..b56652067 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/Exchange.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/Exchange.java @@ -21,57 +21,62 @@ import com.alipay.sofa.registry.remoting.Server; /** - * * @author shangyu.wh * @version $Id: Exchanger.java, v 0.1 2017-11-20 21:25 shangyu.wh Exp $ */ public interface Exchange { - String SESSION_SERVER_TYPE = "sessionServer"; - String DATA_SERVER_TYPE = "dataServer"; - String META_SERVER_TYPE = "metaServer"; + String SESSION_SERVER_TYPE = "sessionServer"; + String DATA_SERVER_TYPE = "dataServer"; + String META_SERVER_TYPE = "metaServer"; - /** - * connect same type server,one server ip one connection - * such as different server on data server,serverOne and serverTwo,different type server must match different channelHandlers, - * so we must connect by serverType,and get Client instance by serverType - * @param serverType - * @param serverUrl - * @param channelHandlers - * @return - */ - Client connect(String serverType, URL serverUrl, T... channelHandlers); + /** + * connect same type server,one server ip one connection such as different server on data + * server,serverOne and serverTwo,different type server must match different channelHandlers, so + * we must connect by serverType,and get Client instance by serverType + * + * @param serverType + * @param serverUrl + * @param channelHandlers + * @return + */ + Client connect(String serverType, URL serverUrl, T... channelHandlers); - /** - * connect same type server,one server ip one connection - * such as different server on data server,serverOne and serverTwo,different type server must match different channelHandlers, - * so we must connect by serverType,and get Client instance by serverType - * @param serverType - * @param connNum connection number per serverUrl - * @param serverUrl - * @param channelHandlers - * @return - */ - Client connect(String serverType, int connNum, URL serverUrl, T... channelHandlers); + /** + * connect same type server,one server ip one connection such as different server on data + * server,serverOne and serverTwo,different type server must match different channelHandlers, so + * we must connect by serverType,and get Client instance by serverType + * + * @param serverType + * @param connNum connection number per serverUrl + * @param serverUrl + * @param channelHandlers + * @return + */ + Client connect(String serverType, int connNum, URL serverUrl, T... channelHandlers); - /** - * bind server by server port in url parameter,one port must by same server type - * @param url - * @param channelHandlers - * @return - */ - Server open(URL url, T... channelHandlers); + /** + * bind server by server port in url parameter,one port must by same server type + * + * @param url + * @param channelHandlers + * @return + */ + Server open(URL url, T... channelHandlers); - /*** - * get Client instance by serverType,very client instance has different channels match different server ip - * @param serverType - * @return - */ - Client getClient(String serverType); + /** + * * get Client instance by serverType,very client instance has different channels match different + * server ip + * + * @param serverType + * @return + */ + Client getClient(String serverType); - /** - * get server instance by port - * @param port - * @return - */ - Server getServer(Integer port); -} \ No newline at end of file + /** + * get server instance by port + * + * @param port + * @return + */ + Server getServer(Integer port); +} diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/NodeExchanger.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/NodeExchanger.java index 6dc8e9300..1b1db277b 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/NodeExchanger.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/NodeExchanger.java @@ -21,19 +21,17 @@ import com.alipay.sofa.registry.remoting.exchange.message.Response; /** - * * @author shangyu.wh * @version $Id: NodeExchanger.java, v 0.1 2017-12-01 11:48 shangyu.wh Exp $ */ public interface NodeExchanger { - /** - * - * @param request - * @return - * @throws RequestException - */ - Response request(Request request) throws RequestException; + /** + * @param request + * @return + * @throws RequestException + */ + Response request(Request request) throws RequestException; - Client connectServer(); -} \ No newline at end of file + Client connectServer(); +} diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/RequestChannelClosedException.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/RequestChannelClosedException.java index 0e47de03c..373e19774 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/RequestChannelClosedException.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/RequestChannelClosedException.java @@ -19,11 +19,11 @@ import com.alipay.sofa.registry.remoting.exchange.message.Request; public class RequestChannelClosedException extends RequestException { - public RequestChannelClosedException(String message, Request request) { - super(message, request); - } + public RequestChannelClosedException(String message, Request request) { + super(message, request); + } - public RequestChannelClosedException(String message) { - super(message); - } + public RequestChannelClosedException(String message) { + super(message); + } } diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/RequestException.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/RequestException.java index 87d07719d..d768dc135 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/RequestException.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/RequestException.java @@ -19,79 +19,87 @@ import com.alipay.sofa.registry.remoting.exchange.message.Request; /** - * * @author shangyu.wh * @version $Id: RequestException.java, v 0.1 2018-01-15 18:16 shangyu.wh Exp $ */ public class RequestException extends RuntimeException { - private Request request; + private Request request; - /** - * constructor - * @param message - * @param request - */ - public RequestException(String message, Request request) { - super(message); - this.request = request; - } + /** + * constructor + * + * @param message + * @param request + */ + public RequestException(String message, Request request) { + super(message); + this.request = request; + } - /** - * constructor - * @param message - * @param request - * @param cause - */ - public RequestException(String message, Request request, Throwable cause) { - super(message, cause); - this.request = request; - } + /** + * constructor + * + * @param message + * @param request + * @param cause + */ + public RequestException(String message, Request request, Throwable cause) { + super(message, cause); + this.request = request; + } - /** - * constructor - * @param message - */ - public RequestException(String message) { - super(message); - } + /** + * constructor + * + * @param message + */ + public RequestException(String message) { + super(message); + } - /** - * constructor - * @param message - * @param cause - */ - public RequestException(String message, Throwable cause) { - super(message, cause); - } + /** + * constructor + * + * @param message + * @param cause + */ + public RequestException(String message, Throwable cause) { + super(message, cause); + } - /** - * constructor - * @param cause - */ - public RequestException(Throwable cause) { - super(cause); - } + /** + * constructor + * + * @param cause + */ + public RequestException(Throwable cause) { + super(cause); + } - /** - * get requestInfo from Request - * @return - */ - @Override - public String getMessage() { - StringBuilder sb = new StringBuilder(256); - if (request != null) { - final Object requestBody = request.getRequestBody(); - String requestBodyStr = null; - if (requestBody instanceof String) { - requestBodyStr = requestBody.toString(); - } else if (requestBody != null) { - requestBodyStr = request.getRequestBody().getClass().getSimpleName(); - } - sb.append("request url: ").append(request.getRequestUrl()).append(", body: ") - .append(requestBodyStr).append(", "); - } - sb.append(super.getMessage()); - return sb.toString(); + /** + * get requestInfo from Request + * + * @return + */ + @Override + public String getMessage() { + StringBuilder sb = new StringBuilder(256); + if (request != null) { + final Object requestBody = request.getRequestBody(); + String requestBodyStr = null; + if (requestBody instanceof String) { + requestBodyStr = requestBody.toString(); + } else if (requestBody != null) { + requestBodyStr = request.getRequestBody().getClass().getSimpleName(); + } + sb.append("request url: ") + .append(request.getRequestUrl()) + .append(", body: ") + .append(requestBodyStr) + .append(", "); } -} \ No newline at end of file + sb.append(super.getMessage()); + return sb.toString(); + } +} diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/message/Request.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/message/Request.java index 473ed2fc4..bed9d00df 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/message/Request.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/message/Request.java @@ -16,52 +16,52 @@ */ package com.alipay.sofa.registry.remoting.exchange.message; -import java.util.concurrent.atomic.AtomicInteger; - import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.remoting.CallbackHandler; +import java.util.concurrent.atomic.AtomicInteger; /** * The interface Request. * - * @param the type parameter + * @param the type parameter * @author shangyu.wh * @version $Id : Request.java, v 0.1 2017-11-30 17:33 shangyu.wh Exp $ */ public interface Request { - /** - * Gets request body. - * - * @return the request body - */ - T getRequestBody(); + /** + * Gets request body. + * + * @return the request body + */ + T getRequestBody(); - /** - * Gets request url. - * - * @return the request url - */ - URL getRequestUrl(); + /** + * Gets request url. + * + * @return the request url + */ + URL getRequestUrl(); - /** - * Gets call back handler. - * - * @return the call back handler - */ - default CallbackHandler getCallBackHandler() { - return null; - } + /** + * Gets call back handler. + * + * @return the call back handler + */ + default CallbackHandler getCallBackHandler() { + return null; + } - /** - * request send by retry some times - * @return - */ - default AtomicInteger getRetryTimes() { - return new AtomicInteger(); - } + /** + * request send by retry some times + * + * @return + */ + default AtomicInteger getRetryTimes() { + return new AtomicInteger(); + } - default Integer getTimeout() { - return null; - } -} \ No newline at end of file + default Integer getTimeout() { + return null; + } +} diff --git a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/message/Response.java b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/message/Response.java index 83b3ec5a1..a42017104 100644 --- a/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/message/Response.java +++ b/server/remoting/api/src/main/java/com/alipay/sofa/registry/remoting/exchange/message/Response.java @@ -17,23 +17,21 @@ package com.alipay.sofa.registry.remoting.exchange.message; /** - * * @author shangyu.wh * @version $Id: Response.java, v 0.1 2017-11-30 17:39 shangyu.wh Exp $ */ public interface Response { - /** - * The enum for response status - */ - enum ResultStatus { - SUCCESSFUL, FAILED - } - - /** - * Get response result - * @return - */ - T getResult(); + /** The enum for response status */ + enum ResultStatus { + SUCCESSFUL, + FAILED + } -} \ No newline at end of file + /** + * Get response result + * + * @return + */ + T getResult(); +} diff --git a/server/remoting/api/src/test/java/com/alipay/sofa/registry/remoting/RequestExceptionTest.java b/server/remoting/api/src/test/java/com/alipay/sofa/registry/remoting/RequestExceptionTest.java index 03c7f8526..819f79d80 100644 --- a/server/remoting/api/src/test/java/com/alipay/sofa/registry/remoting/RequestExceptionTest.java +++ b/server/remoting/api/src/test/java/com/alipay/sofa/registry/remoting/RequestExceptionTest.java @@ -16,50 +16,50 @@ */ package com.alipay.sofa.registry.remoting; -import org.junit.Assert; -import org.junit.Test; - import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.remoting.exchange.RequestException; import com.alipay.sofa.registry.remoting.exchange.message.Request; +import org.junit.Assert; +import org.junit.Test; /** * @author xuanbei * @since 2019/1/16 */ public class RequestExceptionTest { - @Test - public void doTest() { - RequestException exception = new RequestException("error message"); - Assert.assertEquals("error message", exception.getMessage()); + @Test + public void doTest() { + RequestException exception = new RequestException("error message"); + Assert.assertEquals("error message", exception.getMessage()); - RuntimeException runtimeException = new RuntimeException("error message"); - exception = new RequestException(runtimeException); - Assert.assertEquals("java.lang.RuntimeException: error message", exception.getMessage()); - Assert.assertEquals(runtimeException, exception.getCause()); - Assert.assertEquals("java.lang.RuntimeException: error message", exception.getMessage()); + RuntimeException runtimeException = new RuntimeException("error message"); + exception = new RequestException(runtimeException); + Assert.assertEquals("java.lang.RuntimeException: error message", exception.getMessage()); + Assert.assertEquals(runtimeException, exception.getCause()); + Assert.assertEquals("java.lang.RuntimeException: error message", exception.getMessage()); - exception = new RequestException("error message", runtimeException); - Assert.assertEquals("error message", exception.getMessage()); - Assert.assertEquals(runtimeException, exception.getCause()); + exception = new RequestException("error message", runtimeException); + Assert.assertEquals("error message", exception.getMessage()); + Assert.assertEquals(runtimeException, exception.getCause()); - Request request = new Request() { - @Override - public Object getRequestBody() { - return "request body"; - } + Request request = + new Request() { + @Override + public Object getRequestBody() { + return "request body"; + } - @Override - public URL getRequestUrl() { - return null; - } + @Override + public URL getRequestUrl() { + return null; + } }; - exception = new RequestException("error message", request); - Assert.assertEquals("request url: null, body: request body, error message", - exception.getMessage()); + exception = new RequestException("error message", request); + Assert.assertEquals( + "request url: null, body: request body, error message", exception.getMessage()); - exception = new RequestException("error message", request, runtimeException); - Assert.assertEquals("request url: null, body: request body, error message", - exception.getMessage()); - } + exception = new RequestException("error message", request, runtimeException); + Assert.assertEquals( + "request url: null, body: request body, error message", exception.getMessage()); + } } diff --git a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/AsyncUserProcessorAdapter.java b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/AsyncUserProcessorAdapter.java index 94aa4657a..26199d517 100644 --- a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/AsyncUserProcessorAdapter.java +++ b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/AsyncUserProcessorAdapter.java @@ -22,60 +22,59 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.remoting.ChannelHandler; - import java.util.concurrent.Executor; /** - * * @author shangyu.wh * @version $Id: AsyncUserProcessorAdapter.java, v 0.1 2018-01-18 21:24 shangyu.wh Exp $ */ public class AsyncUserProcessorAdapter extends AsyncUserProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(AsyncUserProcessorAdapter.class); + private static final Logger LOGGER = LoggerFactory.getLogger(AsyncUserProcessorAdapter.class); - private ChannelHandler userProcessorHandler; + private ChannelHandler userProcessorHandler; - /** - * constructor - * @param userProcessorHandler - */ - public AsyncUserProcessorAdapter(ChannelHandler userProcessorHandler) { - this.userProcessorHandler = userProcessorHandler; - } + /** + * constructor + * + * @param userProcessorHandler + */ + public AsyncUserProcessorAdapter(ChannelHandler userProcessorHandler) { + this.userProcessorHandler = userProcessorHandler; + } - @Override - public void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, Object request) { + @Override + public void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, Object request) { - BoltChannel boltChannel = new BoltChannel(); - boltChannel.setAsyncContext(asyncCtx); - boltChannel.setConnection(bizCtx.getConnection()); - try { - if (userProcessorHandler != null) { - userProcessorHandler.received(boltChannel, request); - } - } catch (Exception e) { - LOGGER.error("Handle request error!", e); - throw new RuntimeException("Handle request error!", e); - } + BoltChannel boltChannel = new BoltChannel(); + boltChannel.setAsyncContext(asyncCtx); + boltChannel.setConnection(bizCtx.getConnection()); + try { + if (userProcessorHandler != null) { + userProcessorHandler.received(boltChannel, request); + } + } catch (Exception e) { + LOGGER.error("Handle request error!", e); + throw new RuntimeException("Handle request error!", e); } + } - @Override - public Object handleRequest(BizContext bizCtx, Object request) throws Exception { - return super.handleRequest(bizCtx, request); - } + @Override + public Object handleRequest(BizContext bizCtx, Object request) throws Exception { + return super.handleRequest(bizCtx, request); + } - @Override - public String interest() { - if (userProcessorHandler != null && userProcessorHandler.interest() != null) { - return userProcessorHandler.interest().getName(); - } - - return null; + @Override + public String interest() { + if (userProcessorHandler != null && userProcessorHandler.interest() != null) { + return userProcessorHandler.interest().getName(); } - @Override - public Executor getExecutor() { - return userProcessorHandler.getExecutor(); - } -} \ No newline at end of file + return null; + } + + @Override + public Executor getExecutor() { + return userProcessorHandler.getExecutor(); + } +} diff --git a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltChannel.java b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltChannel.java index c59d0ea3d..c0eca31b9 100644 --- a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltChannel.java +++ b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltChannel.java @@ -16,141 +16,138 @@ */ package com.alipay.sofa.registry.remoting.bolt; -import java.net.InetSocketAddress; -import java.util.HashMap; -import java.util.Map; - -import javax.ws.rs.client.WebTarget; - import com.alipay.remoting.AsyncContext; import com.alipay.remoting.BizContext; import com.alipay.remoting.Connection; import com.alipay.sofa.registry.remoting.Channel; +import java.net.InetSocketAddress; +import java.util.HashMap; +import java.util.Map; +import javax.ws.rs.client.WebTarget; /** - * * @author shangyu.wh * @author kezhu.wukz * @version $Id: BoltChannel.java, v 0.1 2017-11-24 16:46 shangyu.wh Exp $ */ public class BoltChannel implements Channel { - private Connection connection; - - private AsyncContext asyncContext; + private Connection connection; - private BizContext bizContext; + private AsyncContext asyncContext; - private Map attributes; + private BizContext bizContext; - @Override - public InetSocketAddress getRemoteAddress() { - if (connection != null) { - return connection.getRemoteAddress(); - } - return null; - } - - @Override - public InetSocketAddress getLocalAddress() { - if (connection != null) { - return connection.getLocalAddress(); - } - return null; - } + private Map attributes; - @Override - public boolean isConnected() { - if (connection != null) { - return connection.isFine(); - } - return false; + @Override + public InetSocketAddress getRemoteAddress() { + if (connection != null) { + return connection.getRemoteAddress(); } + return null; + } - @Override - public synchronized Object getAttribute(String key) { - return attributes == null ? null : attributes.get(key); + @Override + public InetSocketAddress getLocalAddress() { + if (connection != null) { + return connection.getLocalAddress(); } + return null; + } - @Override - public synchronized void setAttribute(String key, Object value) { - if (attributes == null) { - attributes = new HashMap<>(); - } - if (value == null) { // The null value unallowed in the ConcurrentHashMap. - attributes.remove(key); - } else { - attributes.put(key, value); - } + @Override + public boolean isConnected() { + if (connection != null) { + return connection.isFine(); } - - @Override - public WebTarget getWebTarget() { - return null; + return false; + } + + @Override + public synchronized Object getAttribute(String key) { + return attributes == null ? null : attributes.get(key); + } + + @Override + public synchronized void setAttribute(String key, Object value) { + if (attributes == null) { + attributes = new HashMap<>(); } - - @Override - public void close() { - this.connection.close(); - } - - /** - * Getter method for property connection. - * - * @return property value of connection - */ - public Connection getConnection() { - return connection; - } - - /** - * Setter method for property connection. - * - * @param connection value to be assigned to property connection - */ - public void setConnection(Connection connection) { - this.connection = connection; - } - - /** - * Getter method for property asyncContext. - * - * @return property value of asyncContext - */ - public AsyncContext getAsyncContext() { - return asyncContext; - } - - /** - * Setter method for property asyncContext. - * - * @param asyncContext value to be assigned to property asyncContext - */ - public void setAsyncContext(AsyncContext asyncContext) { - this.asyncContext = asyncContext; - } - - /** - * Getter method for property bizContext. - * - * @return property value of bizContext - */ - public BizContext getBizContext() { - return bizContext; - } - - /** - * Setter method for property bizContext. - * - * @param bizContext value to be assigned to property bizContext - */ - public void setBizContext(BizContext bizContext) { - this.bizContext = bizContext; - } - - @Override - public String toString() { - return String.format("connected=%s, remote=%s, local=%s", isConnected(), - getRemoteAddress(), getLocalAddress()); + if (value == null) { // The null value unallowed in the ConcurrentHashMap. + attributes.remove(key); + } else { + attributes.put(key, value); } -} \ No newline at end of file + } + + @Override + public WebTarget getWebTarget() { + return null; + } + + @Override + public void close() { + this.connection.close(); + } + + /** + * Getter method for property connection. + * + * @return property value of connection + */ + public Connection getConnection() { + return connection; + } + + /** + * Setter method for property connection. + * + * @param connection value to be assigned to property connection + */ + public void setConnection(Connection connection) { + this.connection = connection; + } + + /** + * Getter method for property asyncContext. + * + * @return property value of asyncContext + */ + public AsyncContext getAsyncContext() { + return asyncContext; + } + + /** + * Setter method for property asyncContext. + * + * @param asyncContext value to be assigned to property asyncContext + */ + public void setAsyncContext(AsyncContext asyncContext) { + this.asyncContext = asyncContext; + } + + /** + * Getter method for property bizContext. + * + * @return property value of bizContext + */ + public BizContext getBizContext() { + return bizContext; + } + + /** + * Setter method for property bizContext. + * + * @param bizContext value to be assigned to property bizContext + */ + public void setBizContext(BizContext bizContext) { + this.bizContext = bizContext; + } + + @Override + public String toString() { + return String.format( + "connected=%s, remote=%s, local=%s", isConnected(), getRemoteAddress(), getLocalAddress()); + } +} diff --git a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltChannelUtil.java b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltChannelUtil.java index 95b813d9f..54d0bb024 100644 --- a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltChannelUtil.java +++ b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltChannelUtil.java @@ -24,30 +24,28 @@ * @since 2019/2/15 */ public class BoltChannelUtil { - public static Byte getBoltCustomSerializer(Channel channel) { - if (channel instanceof BoltChannel) { - BoltChannel boltChannel = (BoltChannel) channel; - InvokeContext invokeContext = boltChannel.getBizContext() - .getInvokeContext(); + public static Byte getBoltCustomSerializer(Channel channel) { + if (channel instanceof BoltChannel) { + BoltChannel boltChannel = (BoltChannel) channel; + InvokeContext invokeContext = boltChannel.getBizContext().getInvokeContext(); - if (null != invokeContext) { - // set client custom codec for request command if not null - Object clientCustomCodec = invokeContext - .get(InvokeContext.BOLT_CUSTOM_SERIALIZER); - if (null != clientCustomCodec) { - try { - return (Byte) clientCustomCodec; - } catch (ClassCastException e) { - throw new IllegalArgumentException( - "Illegal custom codec [" - + clientCustomCodec - + "], the type of value should be [byte], but now is [" - + clientCustomCodec.getClass() - .getName() + "]."); - } - } - } - } - return null; - } + if (null != invokeContext) { + // set client custom codec for request command if not null + Object clientCustomCodec = invokeContext.get(InvokeContext.BOLT_CUSTOM_SERIALIZER); + if (null != clientCustomCodec) { + try { + return (Byte) clientCustomCodec; + } catch (ClassCastException e) { + throw new IllegalArgumentException( + "Illegal custom codec [" + + clientCustomCodec + + "], the type of value should be [byte], but now is [" + + clientCustomCodec.getClass().getName() + + "]."); + } + } + } + } + return null; + } } diff --git a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltClient.java b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltClient.java index 24caac2e7..c7cbcccce 100644 --- a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltClient.java +++ b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltClient.java @@ -16,12 +16,6 @@ */ package com.alipay.sofa.registry.remoting.bolt; -import java.net.InetSocketAddress; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Executor; -import java.util.concurrent.atomic.AtomicBoolean; - import com.alipay.remoting.Connection; import com.alipay.remoting.ConnectionEventProcessor; import com.alipay.remoting.ConnectionEventType; @@ -41,6 +35,11 @@ import com.alipay.sofa.registry.remoting.ChannelHandler.HandlerType; import com.alipay.sofa.registry.remoting.ChannelHandler.InvokeType; import com.alipay.sofa.registry.remoting.Client; +import java.net.InetSocketAddress; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicBoolean; /** * The type Bolt client. @@ -51,223 +50,229 @@ */ public class BoltClient implements Client { - private static final Logger LOGGER = LoggerFactory.getLogger(BoltClient.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BoltClient.class); - private final RpcClient rpcClient; + private final RpcClient rpcClient; - private final AtomicBoolean closed = new AtomicBoolean(false); + private final AtomicBoolean closed = new AtomicBoolean(false); - private int connectTimeout = 2000; + private int connectTimeout = 2000; - private final int connNum; + private final int connNum; - /** - * Instantiates a new Bolt client. - */ - public BoltClient(int connNum) { - rpcClient = new RpcClient(); - configIO(); - rpcClient.init(); + /** Instantiates a new Bolt client. */ + public BoltClient(int connNum) { + rpcClient = new RpcClient(); + configIO(); + rpcClient.init(); - this.connNum = connNum; - } + this.connNum = connNum; + } - private void configIO() { - final int low = Integer.getInteger(Configs.NETTY_BUFFER_LOW_WATERMARK, 1024 * 128); - final int high = Integer.getInteger(Configs.NETTY_BUFFER_HIGH_WATERMARK, 1024 * 256); - rpcClient.initWriteBufferWaterMark(low, high); - LOGGER.info("config watermark, low={}, high={}", low, high); - } - - public Map> getConnections() { - return rpcClient.getAllManagedConnections(); - } - - /** - * Setter method for property channelHandlers. - * - * @param channelHandlers value to be assigned to property channelHandlers - */ - public void initHandlers(List channelHandlers) { - ChannelHandler connectionEventHandler = null; - for (ChannelHandler channelHandler : channelHandlers) { - if (HandlerType.LISENTER.equals(channelHandler.getType())) { - connectionEventHandler = channelHandler; - break; - } - } + private void configIO() { + final int low = Integer.getInteger(Configs.NETTY_BUFFER_LOW_WATERMARK, 1024 * 128); + final int high = Integer.getInteger(Configs.NETTY_BUFFER_HIGH_WATERMARK, 1024 * 256); + rpcClient.initWriteBufferWaterMark(low, high); + LOGGER.info("config watermark, low={}, high={}", low, high); + } - rpcClient.addConnectionEventProcessor(ConnectionEventType.CONNECT, - newConnectionEventAdapter(connectionEventHandler, ConnectionEventType.CONNECT)); - rpcClient.addConnectionEventProcessor(ConnectionEventType.CLOSE, - newConnectionEventAdapter(connectionEventHandler, ConnectionEventType.CLOSE)); - rpcClient.addConnectionEventProcessor(ConnectionEventType.EXCEPTION, - newConnectionEventAdapter(connectionEventHandler, ConnectionEventType.EXCEPTION)); + public Map> getConnections() { + return rpcClient.getAllManagedConnections(); + } - for (ChannelHandler channelHandler : channelHandlers) { - if (HandlerType.PROCESSER.equals(channelHandler.getType())) { - if (InvokeType.SYNC.equals(channelHandler.getInvokeType())) { - rpcClient.registerUserProcessor(newSyncProcessor(channelHandler)); - } else { - rpcClient.registerUserProcessor(newAsyncProcessor(channelHandler)); - } - } - } + /** + * Setter method for property channelHandlers. + * + * @param channelHandlers value to be assigned to property channelHandlers + */ + public void initHandlers(List channelHandlers) { + ChannelHandler connectionEventHandler = null; + for (ChannelHandler channelHandler : channelHandlers) { + if (HandlerType.LISENTER.equals(channelHandler.getType())) { + connectionEventHandler = channelHandler; + break; + } } - protected ConnectionEventProcessor newConnectionEventAdapter(ChannelHandler connectionEventHandler, - ConnectionEventType connectEventType) { - return new ConnectionEventAdapter(connectEventType, connectionEventHandler, null); - } - - protected AsyncUserProcessorAdapter newAsyncProcessor(ChannelHandler channelHandler) { - return new AsyncUserProcessorAdapter(channelHandler); + rpcClient.addConnectionEventProcessor( + ConnectionEventType.CONNECT, + newConnectionEventAdapter(connectionEventHandler, ConnectionEventType.CONNECT)); + rpcClient.addConnectionEventProcessor( + ConnectionEventType.CLOSE, + newConnectionEventAdapter(connectionEventHandler, ConnectionEventType.CLOSE)); + rpcClient.addConnectionEventProcessor( + ConnectionEventType.EXCEPTION, + newConnectionEventAdapter(connectionEventHandler, ConnectionEventType.EXCEPTION)); + + for (ChannelHandler channelHandler : channelHandlers) { + if (HandlerType.PROCESSER.equals(channelHandler.getType())) { + if (InvokeType.SYNC.equals(channelHandler.getInvokeType())) { + rpcClient.registerUserProcessor(newSyncProcessor(channelHandler)); + } else { + rpcClient.registerUserProcessor(newAsyncProcessor(channelHandler)); + } + } } + } - protected SyncUserProcessorAdapter newSyncProcessor(ChannelHandler channelHandler) { - return new SyncUserProcessorAdapter(channelHandler); - } + protected ConnectionEventProcessor newConnectionEventAdapter( + ChannelHandler connectionEventHandler, ConnectionEventType connectEventType) { + return new ConnectionEventAdapter(connectEventType, connectionEventHandler, null); + } - @Override - public Channel connect(URL url) { - if (url == null) { - throw new IllegalArgumentException("Create connection url can not be null!"); - } - try { - Connection connection = getBoltConnection(rpcClient, url); - BoltChannel channel = new BoltChannel(); - channel.setConnection(connection); - return channel; + protected AsyncUserProcessorAdapter newAsyncProcessor(ChannelHandler channelHandler) { + return new AsyncUserProcessorAdapter(channelHandler); + } - } catch (RemotingException e) { - LOGGER - .error("Bolt client connect server got a RemotingException! target url:" + url, e); - throw new RuntimeException("Bolt client connect server got a RemotingException!", e); - } - } + protected SyncUserProcessorAdapter newSyncProcessor(ChannelHandler channelHandler) { + return new SyncUserProcessorAdapter(channelHandler); + } - protected Connection getBoltConnection(RpcClient rpcClient, URL url) throws RemotingException { - Url boltUrl = createBoltUrl(url); - try { - Connection connection = rpcClient.getConnection(boltUrl, connectTimeout); - if (connection == null || !connection.isFine()) { - if (connection != null) { - connection.close(); - } - throw new RemotingException("Get bolt connection failed for boltUrl: " + boltUrl); - } - return connection; - } catch (InterruptedException e) { - throw new RuntimeException( - "BoltClient rpcClient.getConnection InterruptedException! target boltUrl:" - + boltUrl, e); - } + @Override + public Channel connect(URL url) { + if (url == null) { + throw new IllegalArgumentException("Create connection url can not be null!"); } - - protected Url createBoltUrl(URL url) { - Url boltUrl = new Url(url.getIpAddress(), url.getPort()); - boltUrl.setProtocol(RpcProtocol.PROTOCOL_CODE); - boltUrl.setConnNum(connNum); - boltUrl.setConnWarmup(true); - return boltUrl; + try { + Connection connection = getBoltConnection(rpcClient, url); + BoltChannel channel = new BoltChannel(); + channel.setConnection(connection); + return channel; + + } catch (RemotingException e) { + LOGGER.error("Bolt client connect server got a RemotingException! target url:" + url, e); + throw new RuntimeException("Bolt client connect server got a RemotingException!", e); } - - @Override - public Channel getChannel(URL url) { - try { - Connection connection = getBoltConnection(rpcClient, url); - BoltChannel channel = new BoltChannel(); - channel.setConnection(connection); - return channel; - } catch (RemotingException e) { - LOGGER - .error("Bolt client connect server got a RemotingException! target url:" + url, e); - throw new RuntimeException("Bolt client connect server got a RemotingException!", e); + } + + protected Connection getBoltConnection(RpcClient rpcClient, URL url) throws RemotingException { + Url boltUrl = createBoltUrl(url); + try { + Connection connection = rpcClient.getConnection(boltUrl, connectTimeout); + if (connection == null || !connection.isFine()) { + if (connection != null) { + connection.close(); } + throw new RemotingException("Get bolt connection failed for boltUrl: " + boltUrl); + } + return connection; + } catch (InterruptedException e) { + throw new RuntimeException( + "BoltClient rpcClient.getConnection InterruptedException! target boltUrl:" + boltUrl, e); } - - @Override - public InetSocketAddress getLocalAddress() { - return NetUtil.getLocalSocketAddress(); + } + + protected Url createBoltUrl(URL url) { + Url boltUrl = new Url(url.getIpAddress(), url.getPort()); + boltUrl.setProtocol(RpcProtocol.PROTOCOL_CODE); + boltUrl.setConnNum(connNum); + boltUrl.setConnWarmup(true); + return boltUrl; + } + + @Override + public Channel getChannel(URL url) { + try { + Connection connection = getBoltConnection(rpcClient, url); + BoltChannel channel = new BoltChannel(); + channel.setConnection(connection); + return channel; + } catch (RemotingException e) { + LOGGER.error("Bolt client connect server got a RemotingException! target url:" + url, e); + throw new RuntimeException("Bolt client connect server got a RemotingException!", e); } + } - @Override - public void close() { - if (closed.compareAndSet(false, true)) { - rpcClient.shutdown(); - } - } + @Override + public InetSocketAddress getLocalAddress() { + return NetUtil.getLocalSocketAddress(); + } - @Override - public boolean isClosed() { - return closed.get(); + @Override + public void close() { + if (closed.compareAndSet(false, true)) { + rpcClient.shutdown(); } - - @Override - public Object sendSync(URL url, Object message, int timeoutMillis) { - try { - return rpcClient.invokeSync(createBoltUrl(url), message, timeoutMillis); - } catch (RemotingException e) { - String msg = "Bolt Client sendSync message RemotingException! target url:" + url; - LOGGER.error(msg, e); - throw new RuntimeException(msg, e); - } catch (InterruptedException e) { - throw new RuntimeException( - "Bolt Client sendSync message InterruptedException! target url:" + url, e); - } + } + + @Override + public boolean isClosed() { + return closed.get(); + } + + @Override + public Object sendSync(URL url, Object message, int timeoutMillis) { + try { + return rpcClient.invokeSync(createBoltUrl(url), message, timeoutMillis); + } catch (RemotingException e) { + String msg = "Bolt Client sendSync message RemotingException! target url:" + url; + LOGGER.error(msg, e); + throw new RuntimeException(msg, e); + } catch (InterruptedException e) { + throw new RuntimeException( + "Bolt Client sendSync message InterruptedException! target url:" + url, e); } - - @Override - public Object sendSync(Channel channel, Object message, int timeoutMillis) { - if (channel != null && channel.isConnected()) { - BoltChannel boltChannel = (BoltChannel) channel; - try { - return rpcClient.invokeSync(boltChannel.getConnection(), message, timeoutMillis); - } catch (RemotingException e) { - LOGGER.error("Bolt Client sendSync message RemotingException! target boltUrl:" - + boltChannel.getRemoteAddress(), e); - throw new RuntimeException("Bolt Client sendSync message RemotingException!", e); - } catch (InterruptedException e) { - LOGGER.error("Bolt Client sendSync message InterruptedException! target boltUrl:" - + boltChannel.getRemoteAddress(), e); - throw new RuntimeException("Bolt Client sendSync message InterruptedException!", e); - } - } - throw new IllegalArgumentException( - "Input channel: " + channel - + " error! channel cannot be null,or channel must be connected!"); + } + + @Override + public Object sendSync(Channel channel, Object message, int timeoutMillis) { + if (channel != null && channel.isConnected()) { + BoltChannel boltChannel = (BoltChannel) channel; + try { + return rpcClient.invokeSync(boltChannel.getConnection(), message, timeoutMillis); + } catch (RemotingException e) { + LOGGER.error( + "Bolt Client sendSync message RemotingException! target boltUrl:" + + boltChannel.getRemoteAddress(), + e); + throw new RuntimeException("Bolt Client sendSync message RemotingException!", e); + } catch (InterruptedException e) { + LOGGER.error( + "Bolt Client sendSync message InterruptedException! target boltUrl:" + + boltChannel.getRemoteAddress(), + e); + throw new RuntimeException("Bolt Client sendSync message InterruptedException!", e); + } } + throw new IllegalArgumentException( + "Input channel: " + + channel + + " error! channel cannot be null,or channel must be connected!"); + } + + @Override + public void sendCallback( + URL url, Object message, CallbackHandler callbackHandler, int timeoutMillis) { + try { + Connection connection = getBoltConnection(rpcClient, url); + BoltChannel channel = new BoltChannel(); + channel.setConnection(connection); + rpcClient.invokeWithCallback( + connection, + message, + new InvokeCallback() { + + @Override + public void onResponse(Object result) { + callbackHandler.onCallback(channel, result); + } - @Override - public void sendCallback(URL url, Object message, CallbackHandler callbackHandler, - int timeoutMillis) { - try { - Connection connection = getBoltConnection(rpcClient, url); - BoltChannel channel = new BoltChannel(); - channel.setConnection(connection); - rpcClient.invokeWithCallback(connection, message, new InvokeCallback() { - - @Override - public void onResponse(Object result) { - callbackHandler.onCallback(channel, result); - } - - @Override - public void onException(Throwable e) { - callbackHandler.onException(channel, e); - } + @Override + public void onException(Throwable e) { + callbackHandler.onException(channel, e); + } - @Override - public Executor getExecutor() { - return callbackHandler.getExecutor(); - } - }, timeoutMillis); - return; - } catch (RemotingException e) { - String msg = "Bolt Client sendSync message RemotingException! target url:" + url; - LOGGER.error(msg, e); - throw new RuntimeException(msg, e); - } + @Override + public Executor getExecutor() { + return callbackHandler.getExecutor(); + } + }, + timeoutMillis); + return; + } catch (RemotingException e) { + String msg = "Bolt Client sendSync message RemotingException! target url:" + url; + LOGGER.error(msg, e); + throw new RuntimeException(msg, e); } - -} \ No newline at end of file + } +} diff --git a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltServer.java b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltServer.java index 807a2197e..1f7b3aa97 100644 --- a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltServer.java +++ b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/BoltServer.java @@ -16,16 +16,6 @@ */ package com.alipay.sofa.registry.remoting.bolt; -import java.net.InetSocketAddress; -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executor; -import java.util.concurrent.atomic.AtomicBoolean; - import com.alipay.remoting.*; import com.alipay.remoting.exception.RemotingException; import com.alipay.remoting.rpc.RpcServer; @@ -41,303 +31,302 @@ import com.alipay.sofa.registry.remoting.ChannelHandler.HandlerType; import com.alipay.sofa.registry.remoting.ChannelHandler.InvokeType; import com.alipay.sofa.registry.remoting.Server; +import java.net.InetSocketAddress; +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.Executor; +import java.util.concurrent.atomic.AtomicBoolean; /** - * * @author shangyu.wh * @version $Id: BoltServer.java, v 0.1 2017-11-24 18:05 shangyu.wh Exp $ */ public class BoltServer implements Server { - private static final Logger LOGGER = LoggerFactory.getLogger(BoltServer.class); - - protected static final Logger PUSH_LOGGER = LoggerFactory.getLogger("SESSION-PUSH", - "[Server]"); - /** - * accoding server port - * can not be null - */ - protected final URL url; - private final List channelHandlers; - /** - * bolt server - */ - private final RpcServer boltServer; - /** - * started status - */ - private final AtomicBoolean isStarted = new AtomicBoolean(false); - private final Map channels = new ConcurrentHashMap<>(); - - private final AtomicBoolean initHandler = new AtomicBoolean(false); - - /** - * constructor - * @param url - * @param channelHandlers - */ - public BoltServer(URL url, List channelHandlers) { - this.channelHandlers = channelHandlers; - this.url = url; - this.boltServer = createRpcServer(); - } - - /** - * start bolt server - */ - public void startServer() { - if (isStarted.compareAndSet(false, true)) { - try { - initHandler(); - boltServer.start(); - - } catch (Exception e) { - isStarted.set(false); - LOGGER.error("Start bolt server error!", e); - throw new RuntimeException("Start bolt server error!", e); - } - } - } - - private void stopServer() { - if (boltServer != null && isStarted.get()) { - try { - boltServer.stop(); - } catch (Exception e) { - LOGGER.error("Stop bolt server error!", e); - throw new RuntimeException("Stop bolt server error!", e); - } - } + private static final Logger LOGGER = LoggerFactory.getLogger(BoltServer.class); + + protected static final Logger PUSH_LOGGER = LoggerFactory.getLogger("SESSION-PUSH", "[Server]"); + /** accoding server port can not be null */ + protected final URL url; + + private final List channelHandlers; + /** bolt server */ + private final RpcServer boltServer; + /** started status */ + private final AtomicBoolean isStarted = new AtomicBoolean(false); + + private final Map channels = new ConcurrentHashMap<>(); + + private final AtomicBoolean initHandler = new AtomicBoolean(false); + + /** + * constructor + * + * @param url + * @param channelHandlers + */ + public BoltServer(URL url, List channelHandlers) { + this.channelHandlers = channelHandlers; + this.url = url; + this.boltServer = createRpcServer(); + } + + /** start bolt server */ + public void startServer() { + if (isStarted.compareAndSet(false, true)) { + try { + initHandler(); + boltServer.start(); + + } catch (Exception e) { + isStarted.set(false); + LOGGER.error("Start bolt server error!", e); + throw new RuntimeException("Start bolt server error!", e); + } } - - /** - * just init cant start - */ - public void initServer() { - try { - initHandler(); - } catch (Exception e) { - LOGGER.error("Init bolt server error!", e); - throw new RuntimeException("Init bolt server error!", e); - } + } + + private void stopServer() { + if (boltServer != null && isStarted.get()) { + try { + boltServer.stop(); + } catch (Exception e) { + LOGGER.error("Stop bolt server error!", e); + throw new RuntimeException("Stop bolt server error!", e); + } } - - protected RpcServer createRpcServer() { - return new RpcServer(url.getPort(), true); + } + + /** just init cant start */ + public void initServer() { + try { + initHandler(); + } catch (Exception e) { + LOGGER.error("Init bolt server error!", e); + throw new RuntimeException("Init bolt server error!", e); } - - private void initHandler() { - if (initHandler.compareAndSet(false, true)) { - boltServer.addConnectionEventProcessor(ConnectionEventType.CONNECT, - newConnectionEventProcessor(ConnectionEventType.CONNECT)); - boltServer.addConnectionEventProcessor(ConnectionEventType.CLOSE, - newConnectionEventProcessor(ConnectionEventType.CLOSE)); - boltServer.addConnectionEventProcessor(ConnectionEventType.EXCEPTION, - newConnectionEventProcessor(ConnectionEventType.EXCEPTION)); - - registerUserProcessorHandler(); - } + } + + protected RpcServer createRpcServer() { + return new RpcServer(url.getPort(), true); + } + + private void initHandler() { + if (initHandler.compareAndSet(false, true)) { + boltServer.addConnectionEventProcessor( + ConnectionEventType.CONNECT, newConnectionEventProcessor(ConnectionEventType.CONNECT)); + boltServer.addConnectionEventProcessor( + ConnectionEventType.CLOSE, newConnectionEventProcessor(ConnectionEventType.CLOSE)); + boltServer.addConnectionEventProcessor( + ConnectionEventType.EXCEPTION, + newConnectionEventProcessor(ConnectionEventType.EXCEPTION)); + + registerUserProcessorHandler(); } + } - protected ConnectionEventProcessor newConnectionEventProcessor(ConnectionEventType type) { - return new ConnectionEventAdapter(type, getConnectionEventHandler(), this); - } + protected ConnectionEventProcessor newConnectionEventProcessor(ConnectionEventType type) { + return new ConnectionEventAdapter(type, getConnectionEventHandler(), this); + } - protected ChannelHandler getConnectionEventHandler() { - if (channelHandlers != null) { - for (ChannelHandler channelHandler : channelHandlers) { - if (HandlerType.LISENTER.equals(channelHandler.getType())) { - return channelHandler; - } - } + protected ChannelHandler getConnectionEventHandler() { + if (channelHandlers != null) { + for (ChannelHandler channelHandler : channelHandlers) { + if (HandlerType.LISENTER.equals(channelHandler.getType())) { + return channelHandler; } - return null; + } } - - private void registerUserProcessorHandler() { - if (channelHandlers != null) { - for (ChannelHandler channelHandler : channelHandlers) { - if (HandlerType.PROCESSER.equals(channelHandler.getType())) { - if (InvokeType.SYNC.equals(channelHandler.getInvokeType())) { - boltServer - .registerUserProcessor(newSyncUserProcessorAdapter(channelHandler)); - } else { - boltServer - .registerUserProcessor(newAsyncUserProcessorAdapter(channelHandler)); - } - } - } + return null; + } + + private void registerUserProcessorHandler() { + if (channelHandlers != null) { + for (ChannelHandler channelHandler : channelHandlers) { + if (HandlerType.PROCESSER.equals(channelHandler.getType())) { + if (InvokeType.SYNC.equals(channelHandler.getInvokeType())) { + boltServer.registerUserProcessor(newSyncUserProcessorAdapter(channelHandler)); + } else { + boltServer.registerUserProcessor(newAsyncUserProcessorAdapter(channelHandler)); + } } + } } - - protected SyncUserProcessor newSyncUserProcessorAdapter(ChannelHandler channelHandler) { - return new SyncUserProcessorAdapter(channelHandler); - } - - protected AsyncUserProcessor newAsyncUserProcessorAdapter(ChannelHandler channelHandler) { - return new AsyncUserProcessorAdapter(channelHandler); - } - - @Override - public boolean isOpen() { - return isStarted.get(); - } - - @Override - public Collection getChannels() { - Collection chs = new HashSet<>(); - if (!this.channels.isEmpty()) { - for (Iterator it = this.channels.values().iterator(); it.hasNext();) { - Channel channel = it.next(); - if (channel.isConnected()) { - chs.add(channel); - } else { - it.remove(); - } - } + } + + protected SyncUserProcessor newSyncUserProcessorAdapter(ChannelHandler channelHandler) { + return new SyncUserProcessorAdapter(channelHandler); + } + + protected AsyncUserProcessor newAsyncUserProcessorAdapter(ChannelHandler channelHandler) { + return new AsyncUserProcessorAdapter(channelHandler); + } + + @Override + public boolean isOpen() { + return isStarted.get(); + } + + @Override + public Collection getChannels() { + Collection chs = new HashSet<>(); + if (!this.channels.isEmpty()) { + for (Iterator it = this.channels.values().iterator(); it.hasNext(); ) { + Channel channel = it.next(); + if (channel.isConnected()) { + chs.add(channel); + } else { + it.remove(); } - return chs; + } } - - @Override - public Channel getChannel(InetSocketAddress remoteAddress) { - Channel channel = channels.get(NetUtil.toAddressString(remoteAddress)); - if (channel != null && channel.isConnected()) { - return channel; - } - return null; + return chs; + } + + @Override + public Channel getChannel(InetSocketAddress remoteAddress) { + Channel channel = channels.get(NetUtil.toAddressString(remoteAddress)); + if (channel != null && channel.isConnected()) { + return channel; } - - @Override - public Channel getChannel(URL url) { - Channel channel = channels.get(url.getAddressString()); - if (channel != null && channel.isConnected()) { - return channel; - } - return null; + return null; + } + + @Override + public Channel getChannel(URL url) { + Channel channel = channels.get(url.getAddressString()); + if (channel != null && channel.isConnected()) { + return channel; } - - @Override - public InetSocketAddress getLocalAddress() { - return new InetSocketAddress(url.getPort()); + return null; + } + + @Override + public InetSocketAddress getLocalAddress() { + return new InetSocketAddress(url.getPort()); + } + + @Override + public void close() { + if (isStarted.compareAndSet(true, false)) { + stopServer(); } - - @Override - public void close() { - if (isStarted.compareAndSet(true, false)) { - stopServer(); - } + } + + @Override + public void close(Channel channel) { + if (null != channel) { + channels.remove(NetUtil.toAddressString(channel.getRemoteAddress())); + BoltChannel boltChannel = (BoltChannel) channel; + Connection connection = boltChannel.getConnection(); + if (null != connection && connection.isFine()) { + connection.close(); + } } - - @Override - public void close(Channel channel) { - if (null != channel) { - channels.remove(NetUtil.toAddressString(channel.getRemoteAddress())); - BoltChannel boltChannel = (BoltChannel) channel; - Connection connection = boltChannel.getConnection(); - if (null != connection && connection.isFine()) { - connection.close(); - } + } + + @Override + public boolean isClosed() { + return !isStarted.get(); + } + + @Override + public Object sendSync(Channel channel, Object message, int timeoutMillis) { + if (channel != null && channel.isConnected()) { + Url boltUrl = null; + try { + boltUrl = + new Url( + channel.getRemoteAddress().getAddress().getHostAddress(), + channel.getRemoteAddress().getPort()); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Bolt Server sendSync message:{} , target url:{}", message, boltUrl); } - } - - @Override - public boolean isClosed() { - return !isStarted.get(); - } - @Override - public Object sendSync(Channel channel, Object message, int timeoutMillis) { - if (channel != null && channel.isConnected()) { - Url boltUrl = null; - try { - boltUrl = new Url(channel.getRemoteAddress().getAddress().getHostAddress(), channel - .getRemoteAddress().getPort()); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Bolt Server sendSync message:{} , target url:{}", message, - boltUrl); - } - - return boltServer.invokeSync(boltUrl, message, newInvokeContext(message), - timeoutMillis); - } catch (RemotingException e) { - LOGGER.error("Bolt Server sendSync message RemotingException! target url:" - + boltUrl, e); - throw new RuntimeException("Bolt Server sendSync message RemotingException!", e); - } catch (InterruptedException e) { - LOGGER.error("Bolt Server sendSync message InterruptedException! target url:" - + boltUrl, e); - throw new RuntimeException("Bolt Server sendSync message InterruptedException!", e); - } - } - throw new IllegalArgumentException( - "Send message connection can not be null or connection not be connected!"); + return boltServer.invokeSync(boltUrl, message, newInvokeContext(message), timeoutMillis); + } catch (RemotingException e) { + LOGGER.error("Bolt Server sendSync message RemotingException! target url:" + boltUrl, e); + throw new RuntimeException("Bolt Server sendSync message RemotingException!", e); + } catch (InterruptedException e) { + LOGGER.error("Bolt Server sendSync message InterruptedException! target url:" + boltUrl, e); + throw new RuntimeException("Bolt Server sendSync message InterruptedException!", e); + } } - - @Override - public void sendCallback(Channel channel, Object message, CallbackHandler callbackHandler, - int timeoutMillis) { - if (channel != null && channel.isConnected()) { - Url boltUrl = null; - try { - boltUrl = new Url(channel.getRemoteAddress().getAddress().getHostAddress(), channel - .getRemoteAddress().getPort()); - - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Bolt Server sendSync message:{} , target url:{}", message, - boltUrl); - } - boltServer.invokeWithCallback(boltUrl, message, newInvokeContext(message), - new InvokeCallback() { - @Override - public void onResponse(Object result) { - callbackHandler.onCallback(channel, result); - } - - @Override - public void onException(Throwable e) { - callbackHandler.onException(channel, e); - } - - @Override - public Executor getExecutor() { - return callbackHandler.getExecutor(); - } - }, timeoutMillis); - return; - } catch (RemotingException e) { - throw new RuntimeException("Bolt Server invoke with callback RemotingException!", e); - } catch (InterruptedException e) { - PUSH_LOGGER.error( - "Bolt Server invoke with callback InterruptedException! target url:" + boltUrl, - e); - throw new RuntimeException( - "Bolt Server invoke with callback InterruptedException!", e); - } + throw new IllegalArgumentException( + "Send message connection can not be null or connection not be connected!"); + } + + @Override + public void sendCallback( + Channel channel, Object message, CallbackHandler callbackHandler, int timeoutMillis) { + if (channel != null && channel.isConnected()) { + Url boltUrl = null; + try { + boltUrl = + new Url( + channel.getRemoteAddress().getAddress().getHostAddress(), + channel.getRemoteAddress().getPort()); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Bolt Server sendSync message:{} , target url:{}", message, boltUrl); } - throw new IllegalArgumentException( - "Send message connection can not be null or connection not be connected!"); - } - - protected InvokeContext newInvokeContext(Object request) { - return null; - } - - public void addChannel(Channel channel) { - channels.putIfAbsent(NetUtil.toAddressString(channel.getRemoteAddress()), channel); - } - - public void removeChannel(Channel channel) { - channels.remove(NetUtil.toAddressString(channel.getRemoteAddress())); - } - - public RpcServer getRpcServer() { - return boltServer; - } - - @Override - public int getChannelCount() { - return channels.size(); + boltServer.invokeWithCallback( + boltUrl, + message, + newInvokeContext(message), + new InvokeCallback() { + @Override + public void onResponse(Object result) { + callbackHandler.onCallback(channel, result); + } + + @Override + public void onException(Throwable e) { + callbackHandler.onException(channel, e); + } + + @Override + public Executor getExecutor() { + return callbackHandler.getExecutor(); + } + }, + timeoutMillis); + return; + } catch (RemotingException e) { + throw new RuntimeException("Bolt Server invoke with callback RemotingException!", e); + } catch (InterruptedException e) { + PUSH_LOGGER.error( + "Bolt Server invoke with callback InterruptedException! target url:" + boltUrl, e); + throw new RuntimeException("Bolt Server invoke with callback InterruptedException!", e); + } } -} \ No newline at end of file + throw new IllegalArgumentException( + "Send message connection can not be null or connection not be connected!"); + } + + protected InvokeContext newInvokeContext(Object request) { + return null; + } + + public void addChannel(Channel channel) { + channels.putIfAbsent(NetUtil.toAddressString(channel.getRemoteAddress()), channel); + } + + public void removeChannel(Channel channel) { + channels.remove(NetUtil.toAddressString(channel.getRemoteAddress())); + } + + public RpcServer getRpcServer() { + return boltServer; + } + + @Override + public int getChannelCount() { + return channels.size(); + } +} diff --git a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/ConnectionEventAdapter.java b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/ConnectionEventAdapter.java index 65b01c73f..10e02e342 100644 --- a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/ConnectionEventAdapter.java +++ b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/ConnectionEventAdapter.java @@ -25,71 +25,72 @@ /** * The type Connection event adapter. + * * @author shangyu.wh * @version $Id : ConnectionEventAdapter.java, v 0.1 2017-11-22 21:01 shangyu.wh Exp $ */ public class ConnectionEventAdapter implements ConnectionEventProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionEventAdapter.class); - - private ConnectionEventType connectionEventType; + private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionEventAdapter.class); - private ChannelHandler connectionEventHandler; + private ConnectionEventType connectionEventType; - private BoltServer boltServer; + private ChannelHandler connectionEventHandler; - /** - * Instantiates a new Connection event adapter. - * - * @param connectionEventType the connection event type - * @param connectionEventHandler the connection event handler - * @param boltServer the bolt server - */ - public ConnectionEventAdapter(ConnectionEventType connectionEventType, - ChannelHandler connectionEventHandler, BoltServer boltServer) { - this.connectionEventType = connectionEventType; - this.connectionEventHandler = connectionEventHandler; - this.boltServer = boltServer; - } + private BoltServer boltServer; - /** - * @see ConnectionEventProcessor#onEvent(String, Connection) - */ - @Override - public void onEvent(String remoteAddr, Connection conn) { - try { - if (connectionEventHandler != null) { - switch (connectionEventType) { - case CONNECT: - BoltChannel boltChannel = new BoltChannel(); - boltChannel.setConnection(conn); - if (boltServer != null) { - boltServer.addChannel(boltChannel); - } - connectionEventHandler.connected(boltChannel); - break; + /** + * Instantiates a new Connection event adapter. + * + * @param connectionEventType the connection event type + * @param connectionEventHandler the connection event handler + * @param boltServer the bolt server + */ + public ConnectionEventAdapter( + ConnectionEventType connectionEventType, + ChannelHandler connectionEventHandler, + BoltServer boltServer) { + this.connectionEventType = connectionEventType; + this.connectionEventHandler = connectionEventHandler; + this.boltServer = boltServer; + } - case CLOSE: - BoltChannel boltChannelClose = new BoltChannel(); - boltChannelClose.setConnection(conn); - if (boltServer != null) { - boltServer.removeChannel(boltChannelClose); - } - connectionEventHandler.disconnected(boltChannelClose); - break; + /** @see ConnectionEventProcessor#onEvent(String, Connection) */ + @Override + public void onEvent(String remoteAddr, Connection conn) { + try { + if (connectionEventHandler != null) { + switch (connectionEventType) { + case CONNECT: + BoltChannel boltChannel = new BoltChannel(); + boltChannel.setConnection(conn); + if (boltServer != null) { + boltServer.addChannel(boltChannel); + } + connectionEventHandler.connected(boltChannel); + break; - case EXCEPTION: - BoltChannel boltChannelException = new BoltChannel(); - boltChannelException.setConnection(conn); - connectionEventHandler.caught(boltChannelException, null, null); - break; - default: - break; - } + case CLOSE: + BoltChannel boltChannelClose = new BoltChannel(); + boltChannelClose.setConnection(conn); + if (boltServer != null) { + boltServer.removeChannel(boltChannelClose); } - } catch (Exception e) { - LOGGER.error("Connection process " + connectionEventType + " error!", e); - throw new RuntimeException("Connection process " + connectionEventType + " error!", e); + connectionEventHandler.disconnected(boltChannelClose); + break; + + case EXCEPTION: + BoltChannel boltChannelException = new BoltChannel(); + boltChannelException.setConnection(conn); + connectionEventHandler.caught(boltChannelException, null, null); + break; + default: + break; } + } + } catch (Exception e) { + LOGGER.error("Connection process " + connectionEventType + " error!", e); + throw new RuntimeException("Connection process " + connectionEventType + " error!", e); } -} \ No newline at end of file + } +} diff --git a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/SyncUserProcessorAdapter.java b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/SyncUserProcessorAdapter.java index 5a312b5a2..e63458dad 100644 --- a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/SyncUserProcessorAdapter.java +++ b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/SyncUserProcessorAdapter.java @@ -20,53 +20,52 @@ import com.alipay.remoting.BizContext; import com.alipay.remoting.rpc.protocol.SyncUserProcessor; import com.alipay.sofa.registry.remoting.ChannelHandler; - import java.util.concurrent.Executor; /** - * * @author shangyu.wh * @version $Id: UserProcessorAdapter.java, v 0.1 2017-11-24 17:10 shangyu.wh Exp $ */ public class SyncUserProcessorAdapter extends SyncUserProcessor { - private ChannelHandler userProcessorHandler; + private ChannelHandler userProcessorHandler; - /** - * constructor - * @param userProcessorHandler - */ - public SyncUserProcessorAdapter(ChannelHandler userProcessorHandler) { - this.userProcessorHandler = userProcessorHandler; - } + /** + * constructor + * + * @param userProcessorHandler + */ + public SyncUserProcessorAdapter(ChannelHandler userProcessorHandler) { + this.userProcessorHandler = userProcessorHandler; + } - @Override - public void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, Object request) { - super.handleRequest(bizCtx, asyncCtx, request); - } + @Override + public void handleRequest(BizContext bizCtx, AsyncContext asyncCtx, Object request) { + super.handleRequest(bizCtx, asyncCtx, request); + } - @Override - public Object handleRequest(BizContext bizCtx, Object request) throws Exception { - BoltChannel boltChannel = new BoltChannel(); - boltChannel.setBizContext(bizCtx); - boltChannel.setConnection(bizCtx.getConnection()); - if (userProcessorHandler != null) { - return userProcessorHandler.reply(boltChannel, request); - } - return null; + @Override + public Object handleRequest(BizContext bizCtx, Object request) throws Exception { + BoltChannel boltChannel = new BoltChannel(); + boltChannel.setBizContext(bizCtx); + boltChannel.setConnection(bizCtx.getConnection()); + if (userProcessorHandler != null) { + return userProcessorHandler.reply(boltChannel, request); } + return null; + } - @Override - public String interest() { - if (userProcessorHandler != null && userProcessorHandler.interest() != null) { - return userProcessorHandler.interest().getName(); - } - - return null; + @Override + public String interest() { + if (userProcessorHandler != null && userProcessorHandler.interest() != null) { + return userProcessorHandler.interest().getName(); } - @Override - public Executor getExecutor() { - return userProcessorHandler.getExecutor(); - } -} \ No newline at end of file + return null; + } + + @Override + public Executor getExecutor() { + return userProcessorHandler.getExecutor(); + } +} diff --git a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/exchange/BoltExchange.java b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/exchange/BoltExchange.java index 52627f664..3c0a9a6b1 100644 --- a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/exchange/BoltExchange.java +++ b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/exchange/BoltExchange.java @@ -16,10 +16,6 @@ */ package com.alipay.sofa.registry.remoting.bolt.exchange; -import java.util.Arrays; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.remoting.ChannelHandler; import com.alipay.sofa.registry.remoting.Client; @@ -27,75 +23,80 @@ import com.alipay.sofa.registry.remoting.bolt.BoltClient; import com.alipay.sofa.registry.remoting.bolt.BoltServer; import com.alipay.sofa.registry.remoting.exchange.Exchange; +import java.util.Arrays; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; /** - * * @author shangyu.wh * @version $Id: BoltExchange.java, v 0.1 2017-11-27 15:47 shangyu.wh Exp $ */ public class BoltExchange implements Exchange { - private Map clients = new ConcurrentHashMap<>(); + private Map clients = new ConcurrentHashMap<>(); - private ConcurrentHashMap serverMap = new ConcurrentHashMap<>(); + private ConcurrentHashMap serverMap = new ConcurrentHashMap<>(); - @Override - public Client connect(String serverType, URL serverUrl, ChannelHandler... channelHandlers) { - return this.connect(serverType, 1, serverUrl, channelHandlers); - } + @Override + public Client connect(String serverType, URL serverUrl, ChannelHandler... channelHandlers) { + return this.connect(serverType, 1, serverUrl, channelHandlers); + } - @Override - public Client connect(String serverType, int connNum, URL serverUrl, ChannelHandler... channelHandlers) { - if (channelHandlers == null) { - throw new IllegalArgumentException("channelHandlers cannot be null!"); - } - Client client = clients.computeIfAbsent(serverType, key -> newBoltClient(connNum, channelHandlers)); - client.connect(serverUrl); - return client; + @Override + public Client connect( + String serverType, int connNum, URL serverUrl, ChannelHandler... channelHandlers) { + if (channelHandlers == null) { + throw new IllegalArgumentException("channelHandlers cannot be null!"); } + Client client = + clients.computeIfAbsent(serverType, key -> newBoltClient(connNum, channelHandlers)); + client.connect(serverUrl); + return client; + } - @Override - public Server open(URL url, ChannelHandler... channelHandlers) { - if (channelHandlers == null) { - throw new IllegalArgumentException("channelHandlers cannot be null!"); - } - - BoltServer server = createBoltServer(url, channelHandlers); - setServer(server, url); - server.startServer(); - return server; + @Override + public Server open(URL url, ChannelHandler... channelHandlers) { + if (channelHandlers == null) { + throw new IllegalArgumentException("channelHandlers cannot be null!"); } - @Override - public Client getClient(String serverType) { - return clients.get(serverType); - } + BoltServer server = createBoltServer(url, channelHandlers); + setServer(server, url); + server.startServer(); + return server; + } - @Override - public Server getServer(Integer port) { - return serverMap.get(port); - } + @Override + public Client getClient(String serverType) { + return clients.get(serverType); + } - /** - * add server into serverMap - * @param server - * @param url - */ - public void setServer(Server server, URL url) { - serverMap.putIfAbsent(url.getPort(), server); - } + @Override + public Server getServer(Integer port) { + return serverMap.get(port); + } - private BoltClient newBoltClient(int connNum, ChannelHandler[] channelHandlers) { - BoltClient boltClient = createBoltClient(connNum); - boltClient.initHandlers(Arrays.asList(channelHandlers)); - return boltClient; - } + /** + * add server into serverMap + * + * @param server + * @param url + */ + public void setServer(Server server, URL url) { + serverMap.putIfAbsent(url.getPort(), server); + } - protected BoltClient createBoltClient(int connNum) { - return new BoltClient(connNum); - } + private BoltClient newBoltClient(int connNum, ChannelHandler[] channelHandlers) { + BoltClient boltClient = createBoltClient(connNum); + boltClient.initHandlers(Arrays.asList(channelHandlers)); + return boltClient; + } - protected BoltServer createBoltServer(URL url, ChannelHandler[] channelHandlers) { - return new BoltServer(url, Arrays.asList(channelHandlers)); - } -} \ No newline at end of file + protected BoltClient createBoltClient(int connNum) { + return new BoltClient(connNum); + } + + protected BoltServer createBoltServer(URL url, ChannelHandler[] channelHandlers) { + return new BoltServer(url, Arrays.asList(channelHandlers)); + } +} diff --git a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/CustomClassSerializerManager.java b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/CustomClassSerializerManager.java index 8c28df888..58896eddd 100644 --- a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/CustomClassSerializerManager.java +++ b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/CustomClassSerializerManager.java @@ -21,33 +21,34 @@ /** * The type Custom class serializer manager. + * * @author zhuoyu.sjw * @version $Id : CustomClassSerializerManager.java, v 0.1 2018-05-05 23:43 zhuoyu.sjw Exp $$ */ public class CustomClassSerializerManager { - private static ConcurrentMap serializerMap = new ConcurrentHashMap<>(); + private static ConcurrentMap serializerMap = new ConcurrentHashMap<>(); - /** - * Register serializer. - * - * @param clazz the clazz - * @param serializer the serializer - */ - public static void registerSerializer(Class clazz, Byte serializer) { - if (clazz == null || serializer == null) { - throw new IllegalArgumentException("class and serializer can not be null"); - } - serializerMap.put(clazz, serializer); + /** + * Register serializer. + * + * @param clazz the clazz + * @param serializer the serializer + */ + public static void registerSerializer(Class clazz, Byte serializer) { + if (clazz == null || serializer == null) { + throw new IllegalArgumentException("class and serializer can not be null"); } + serializerMap.put(clazz, serializer); + } - /** - * Gets protocol. - * - * @param clazz the clazz - * @return the protocol - */ - public static Byte getClassSerializer(Class clazz) { - return serializerMap.get(clazz); - } + /** + * Gets protocol. + * + * @param clazz the clazz + * @return the protocol + */ + public static Byte getClassSerializer(Class clazz) { + return serializerMap.get(clazz); + } } diff --git a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/ProtobufCustomSerializer.java b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/ProtobufCustomSerializer.java index 083544d52..b286fdccf 100644 --- a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/ProtobufCustomSerializer.java +++ b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/ProtobufCustomSerializer.java @@ -29,130 +29,129 @@ /** * The type Protobuf custom serializer. + * * @author zhuoyu.sjw * @version $Id : ProtobufCustomSerializer.java, v 0.1 2018年03月21日 6:14 PM bystander Exp $ */ public class ProtobufCustomSerializer implements CustomSerializer { - private static final Logger LOGGER = LoggerFactory - .getLogger(ProtobufCustomSerializer.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ProtobufCustomSerializer.class); - /** - * The constant PROTOCOL_PROTOBUF. - */ - public static final byte PROTOCOL_PROTOBUF = 11; + /** The constant PROTOCOL_PROTOBUF. */ + public static final byte PROTOCOL_PROTOBUF = 11; - @Override - public boolean serializeHeader(T request, InvokeContext invokeContext) { - return false; - } + @Override + public boolean serializeHeader( + T request, InvokeContext invokeContext) { + return false; + } - @Override - public boolean serializeHeader(T response) { - return false; - } + @Override + public boolean serializeHeader(T response) { + return false; + } - @Override - public boolean deserializeHeader(T request) { - return false; - } + @Override + public boolean deserializeHeader(T request) { + return false; + } - @Override - public boolean deserializeHeader(T response, - InvokeContext invokeContext) { - return false; - } + @Override + public boolean deserializeHeader( + T response, InvokeContext invokeContext) { + return false; + } - @Override - public boolean serializeContent(T request, - InvokeContext invokeContext) { - if (request instanceof RpcRequestCommand) { - try { - RpcRequestCommand requestCommand = (RpcRequestCommand) request; - Object requestObject = requestCommand.getRequestObject(); - request.setContent(ProtobufSerializer.getInstance().serialize(requestObject)); - return true; - } catch (CodecException e) { - LOGGER.error("[bolt] encode request error, {}", request, e); - } - } - return false; + @Override + public boolean serializeContent( + T request, InvokeContext invokeContext) { + if (request instanceof RpcRequestCommand) { + try { + RpcRequestCommand requestCommand = (RpcRequestCommand) request; + Object requestObject = requestCommand.getRequestObject(); + request.setContent(ProtobufSerializer.getInstance().serialize(requestObject)); + return true; + } catch (CodecException e) { + LOGGER.error("[bolt] encode request error, {}", request, e); + } } + return false; + } - @Override - public boolean serializeContent(T response) { - if (response instanceof RpcResponseCommand) { - if (response.getSerializer() == PROTOCOL_PROTOBUF) { - try { - Object appResponse = ((RpcResponseCommand) response).getResponseObject(); - if (appResponse instanceof Throwable) { - // 业务异常序列化的是错误字符串 - response.setContent(ProtobufSerializer.getInstance().serialize( - ((Throwable) appResponse).getMessage())); - return false; - } else { - response - .setContent(ProtobufSerializer.getInstance().serialize(appResponse)); - return true; - } - } catch (CodecException e) { - LOGGER.error("[bolt] encode response error, {}", response, e); - } - } + @Override + public boolean serializeContent(T response) { + if (response instanceof RpcResponseCommand) { + if (response.getSerializer() == PROTOCOL_PROTOBUF) { + try { + Object appResponse = ((RpcResponseCommand) response).getResponseObject(); + if (appResponse instanceof Throwable) { + // 业务异常序列化的是错误字符串 + response.setContent( + ProtobufSerializer.getInstance().serialize(((Throwable) appResponse).getMessage())); + return false; + } else { + response.setContent(ProtobufSerializer.getInstance().serialize(appResponse)); + return true; + } + } catch (CodecException e) { + LOGGER.error("[bolt] encode response error, {}", response, e); } - - return false; + } } - @Override - public boolean deserializeContent(T request) - throws DeserializationException { - if (request instanceof RpcRequestCommand) { - RpcRequestCommand requestCommand = (RpcRequestCommand) request; - if (requestCommand.getSerializer() == PROTOCOL_PROTOBUF) { - try { - Object pbReq = null; - byte[] content = requestCommand.getContent(); - if (content != null && content.length != 0) { - pbReq = ProtobufSerializer.getInstance().deserialize(content, - requestCommand.getRequestClass()); - } - requestCommand.setRequestObject(pbReq); - return true; - } catch (DeserializationException e) { - throw e; - } catch (Exception e) { - throw new DeserializationException(e.getMessage(), e); - } - } + return false; + } + + @Override + public boolean deserializeContent(T request) + throws DeserializationException { + if (request instanceof RpcRequestCommand) { + RpcRequestCommand requestCommand = (RpcRequestCommand) request; + if (requestCommand.getSerializer() == PROTOCOL_PROTOBUF) { + try { + Object pbReq = null; + byte[] content = requestCommand.getContent(); + if (content != null && content.length != 0) { + pbReq = + ProtobufSerializer.getInstance() + .deserialize(content, requestCommand.getRequestClass()); + } + requestCommand.setRequestObject(pbReq); + return true; + } catch (DeserializationException e) { + throw e; + } catch (Exception e) { + throw new DeserializationException(e.getMessage(), e); } - return false; + } } + return false; + } - @Override - public boolean deserializeContent(T response, - InvokeContext invokeContext) - throws DeserializationException { - if (response instanceof RpcResponseCommand) { - RpcResponseCommand responseCommand = (RpcResponseCommand) response; - if (response.getSerializer() == PROTOCOL_PROTOBUF) { - try { - Object pbReq = null; + @Override + public boolean deserializeContent( + T response, InvokeContext invokeContext) throws DeserializationException { + if (response instanceof RpcResponseCommand) { + RpcResponseCommand responseCommand = (RpcResponseCommand) response; + if (response.getSerializer() == PROTOCOL_PROTOBUF) { + try { + Object pbReq = null; - byte[] content = responseCommand.getContent(); - if (content != null && content.length != 0) { - pbReq = ProtobufSerializer.getInstance().deserialize(content, - ((RpcResponseCommand) response).getResponseClass()); - } - responseCommand.setResponseObject(pbReq); - return true; - } catch (DeserializationException e) { - throw e; - } catch (Exception e) { - throw new DeserializationException(e.getMessage(), e); - } - } + byte[] content = responseCommand.getContent(); + if (content != null && content.length != 0) { + pbReq = + ProtobufSerializer.getInstance() + .deserialize(content, ((RpcResponseCommand) response).getResponseClass()); + } + responseCommand.setResponseObject(pbReq); + return true; + } catch (DeserializationException e) { + throw e; + } catch (Exception e) { + throw new DeserializationException(e.getMessage(), e); } - - return false; + } } -} \ No newline at end of file + + return false; + } +} diff --git a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/ProtobufSerializer.java b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/ProtobufSerializer.java index c68416972..8ed1f660a 100644 --- a/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/ProtobufSerializer.java +++ b/server/remoting/bolt/src/main/java/com/alipay/sofa/registry/remoting/bolt/serializer/ProtobufSerializer.java @@ -21,7 +21,6 @@ import com.alipay.remoting.exception.SerializationException; import com.alipay.remoting.serialization.Serializer; import com.google.protobuf.MessageLite; - import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.charset.StandardCharsets; @@ -29,152 +28,156 @@ /** * Created by zhanggeng on 2017/2/23. + * * @author zhanggeng * @version $Id : ProtobufSerializer.java, v 0.1 2018-05-05 23:43 zhanggeng Exp $$ */ public class ProtobufSerializer implements Serializer { - public static final byte PROTOCOL_PROTOBUF = 11; + public static final byte PROTOCOL_PROTOBUF = 11; - /** cache parse method */ - private final ConcurrentHashMap parseMethodMap = new ConcurrentHashMap<>(); + /** cache parse method */ + private final ConcurrentHashMap parseMethodMap = new ConcurrentHashMap<>(); - /** cache toByteArray method */ - private final ConcurrentHashMap toByteArrayMethodMap = new ConcurrentHashMap<>(); + /** cache toByteArray method */ + private final ConcurrentHashMap toByteArrayMethodMap = new ConcurrentHashMap<>(); - private final static ProtobufSerializer instance = new ProtobufSerializer(); + private static final ProtobufSerializer instance = new ProtobufSerializer(); - private ProtobufSerializer() { + private ProtobufSerializer() {} - } - - public static ProtobufSerializer getInstance() { - return instance; - } + public static ProtobufSerializer getInstance() { + return instance; + } - @Override - public byte[] serialize(Object object) throws CodecException { - if (object == null) { - throw new SerializationException("Unsupported null message"); - } else if (isProtoBufMessageLite(object)) { - Class clazz = object.getClass(); - Method method = toByteArrayMethodMap.get(clazz); - if (method == null) { - try { - method = clazz.getMethod("toByteArray"); - method.setAccessible(true); - toByteArrayMethodMap.put(clazz, method); - } catch (Exception e) { - throw new SerializationException( - "Cannot found method " + clazz.getName() - + ".toByteArray(), please check the generated code"); - } - } - try { - return (byte[]) method.invoke(object); - } catch (Exception e) { - throw new SerializationException( - "Cannot found method " + clazz.getName() - + ".toByteArray(), please check the generated code"); - } - - } else if (object instanceof String) { - return ((String) object).getBytes(StandardCharsets.UTF_8); - } else { - throw new SerializationException("Unsupported class:" + object.getClass().getName() - + ", only support protobuf message"); - } - } - - @Override - public T deserialize(byte[] data, String classOfT) throws CodecException { + @Override + public byte[] serialize(Object object) throws CodecException { + if (object == null) { + throw new SerializationException("Unsupported null message"); + } else if (isProtoBufMessageLite(object)) { + Class clazz = object.getClass(); + Method method = toByteArrayMethodMap.get(clazz); + if (method == null) { try { - Class requestClass = Class.forName(classOfT); - return (T) decode(data, requestClass); - } catch (ClassNotFoundException e) { - throw new SerializationException("Cannot found class " + classOfT, e); + method = clazz.getMethod("toByteArray"); + method.setAccessible(true); + toByteArrayMethodMap.put(clazz, method); + } catch (Exception e) { + throw new SerializationException( + "Cannot found method " + + clazz.getName() + + ".toByteArray(), please check the generated code"); } + } + try { + return (byte[]) method.invoke(object); + } catch (Exception e) { + throw new SerializationException( + "Cannot found method " + + clazz.getName() + + ".toByteArray(), please check the generated code"); + } + + } else if (object instanceof String) { + return ((String) object).getBytes(StandardCharsets.UTF_8); + } else { + throw new SerializationException( + "Unsupported class:" + object.getClass().getName() + ", only support protobuf message"); } - - public Object decode(byte[] bytes, Class clazz) throws DeserializationException { - if (isProtoBufMessageLite(clazz)) { - try { - Method method = parseMethodMap.get(clazz); - if (method == null) { - method = clazz.getMethod("parseFrom", byte[].class); - if (!Modifier.isStatic(method.getModifiers())) { - throw new CodecException( - "Cannot found method " + clazz.getName() - + ".parseFrom(byte[]), please check the generated code"); - } - method.setAccessible(true); - parseMethodMap.put(clazz, method); - } - return method.invoke(null, bytes); - } catch (DeserializationException e) { - throw e; - } catch (Exception e) { - throw new DeserializationException( - "Cannot found method " + clazz.getName() - + ".parseFrom(byte[]), please check the generated code", e); - } - } else if (clazz == String.class) { - return new String(bytes, StandardCharsets.UTF_8); - } else { - throw new DeserializationException("Unsupported class:" + clazz.getName() - + ", only support protobuf message"); + } + + @Override + public T deserialize(byte[] data, String classOfT) throws CodecException { + try { + Class requestClass = Class.forName(classOfT); + return (T) decode(data, requestClass); + } catch (ClassNotFoundException e) { + throw new SerializationException("Cannot found class " + classOfT, e); + } + } + + public Object decode(byte[] bytes, Class clazz) throws DeserializationException { + if (isProtoBufMessageLite(clazz)) { + try { + Method method = parseMethodMap.get(clazz); + if (method == null) { + method = clazz.getMethod("parseFrom", byte[].class); + if (!Modifier.isStatic(method.getModifiers())) { + throw new CodecException( + "Cannot found method " + + clazz.getName() + + ".parseFrom(byte[]), please check the generated code"); + } + method.setAccessible(true); + parseMethodMap.put(clazz, method); } + return method.invoke(null, bytes); + } catch (DeserializationException e) { + throw e; + } catch (Exception e) { + throw new DeserializationException( + "Cannot found method " + + clazz.getName() + + ".parseFrom(byte[]), please check the generated code", + e); + } + } else if (clazz == String.class) { + return new String(bytes, StandardCharsets.UTF_8); + } else { + throw new DeserializationException( + "Unsupported class:" + clazz.getName() + ", only support protobuf message"); } + } - public static boolean isProtoBufMessageLite(Object object) { - Class clzz = object == null ? null : object.getClass(); - return isProtoBufMessageLite(clzz); - } + public static boolean isProtoBufMessageLite(Object object) { + Class clzz = object == null ? null : object.getClass(); + return isProtoBufMessageLite(clzz); + } - private static boolean isProtoBufMessageLite(Class clzz) { - if (clzz != null) { - return isSpecificationInterface(clzz, MessageLite.class.getCanonicalName()); - } - return false; + private static boolean isProtoBufMessageLite(Class clzz) { + if (clzz != null) { + return isSpecificationInterface(clzz, MessageLite.class.getCanonicalName()); } - - /** - * whether clazz has a interface named interfaceName - * - * @param clazz - * @param interfaceName - * @return - */ - private static boolean isSpecificationInterface(Class clazz, String interfaceName) { - - boolean find = false; - - // First, get all direct interface - Class[] interfaces = clazz.getInterfaces(); - if (interfaces.length > 0) { - for (Class interfaze : interfaces) { - find = interfaceName.equalsIgnoreCase(interfaze.getCanonicalName()); - if (find) { - break; - } - } + return false; + } + + /** + * whether clazz has a interface named interfaceName + * + * @param clazz + * @param interfaceName + * @return + */ + private static boolean isSpecificationInterface(Class clazz, String interfaceName) { + + boolean find = false; + + // First, get all direct interface + Class[] interfaces = clazz.getInterfaces(); + if (interfaces.length > 0) { + for (Class interfaze : interfaces) { + find = interfaceName.equalsIgnoreCase(interfaze.getCanonicalName()); + if (find) { + break; } - while (!Object.class.getCanonicalName().equals(clazz.getCanonicalName()) && !find) { - // Add the super class - Class superClass = clazz.getSuperclass(); - - // Interfaces does not have java,lang.Object as superclass, they have null, so break the cycle and return - if (superClass == null) { - break; - } - - // Now inspect the superclass - clazz = superClass; + } + } + while (!Object.class.getCanonicalName().equals(clazz.getCanonicalName()) && !find) { + // Add the super class + Class superClass = clazz.getSuperclass(); - find = isSpecificationInterface(clazz, interfaceName); + // Interfaces does not have java,lang.Object as superclass, they have null, so break the cycle + // and return + if (superClass == null) { + break; + } - } + // Now inspect the superclass + clazz = superClass; - return find; + find = isSpecificationInterface(clazz, interfaceName); } + + return find; + } } diff --git a/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/BoltChannelUtilTest.java b/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/BoltChannelUtilTest.java index d091f4190..33bd56a9b 100644 --- a/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/BoltChannelUtilTest.java +++ b/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/BoltChannelUtilTest.java @@ -20,34 +20,34 @@ import com.alipay.remoting.DefaultBizContext; import com.alipay.remoting.InvokeContext; import com.alipay.remoting.RemotingContext; +import java.util.concurrent.ConcurrentHashMap; import org.junit.Assert; import org.junit.Test; -import java.util.concurrent.ConcurrentHashMap; - /** * @author xuanbei * @since 2019/3/26 */ public class BoltChannelUtilTest { - @Test - public void testGetBoltCustomSerializer() { - Assert.assertNull(BoltChannelUtil.getBoltCustomSerializer(new MockChannel())); - BoltChannel boltChannel = new BoltChannel(); - InvokeContext invokeContext = new InvokeContext(); - invokeContext.put(InvokeContext.BOLT_CUSTOM_SERIALIZER, new Object()); - RemotingContext remotingContext = new RemotingContext(new MockChannelHandlerContext(), - invokeContext, false, new ConcurrentHashMap<>()); - BizContext bizContext = new DefaultBizContext(remotingContext); - boltChannel.setBizContext(bizContext); - boolean isException = false; - try { - BoltChannelUtil.getBoltCustomSerializer(boltChannel); - } catch (Throwable r) { - isException = true; - } - Assert.assertTrue(isException); - invokeContext.put(InvokeContext.BOLT_CUSTOM_SERIALIZER, new Byte("3")); - Assert.assertEquals(new Byte("3"), BoltChannelUtil.getBoltCustomSerializer(boltChannel)); + @Test + public void testGetBoltCustomSerializer() { + Assert.assertNull(BoltChannelUtil.getBoltCustomSerializer(new MockChannel())); + BoltChannel boltChannel = new BoltChannel(); + InvokeContext invokeContext = new InvokeContext(); + invokeContext.put(InvokeContext.BOLT_CUSTOM_SERIALIZER, new Object()); + RemotingContext remotingContext = + new RemotingContext( + new MockChannelHandlerContext(), invokeContext, false, new ConcurrentHashMap<>()); + BizContext bizContext = new DefaultBizContext(remotingContext); + boltChannel.setBizContext(bizContext); + boolean isException = false; + try { + BoltChannelUtil.getBoltCustomSerializer(boltChannel); + } catch (Throwable r) { + isException = true; } + Assert.assertTrue(isException); + invokeContext.put(InvokeContext.BOLT_CUSTOM_SERIALIZER, new Byte("3")); + Assert.assertEquals(new Byte("3"), BoltChannelUtil.getBoltCustomSerializer(boltChannel)); + } } diff --git a/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/BoltServerTest.java b/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/BoltServerTest.java index 9b7246467..beb8741db 100644 --- a/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/BoltServerTest.java +++ b/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/BoltServerTest.java @@ -16,71 +16,64 @@ */ package com.alipay.sofa.registry.remoting.bolt; +import com.alipay.sofa.registry.common.model.store.URL; +import com.alipay.sofa.registry.remoting.Channel; import java.net.InetSocketAddress; - import javax.ws.rs.client.WebTarget; - -import com.alipay.sofa.registry.common.model.store.URL; import org.junit.Assert; import org.junit.Test; -import com.alipay.sofa.registry.remoting.Channel; - /** - * * @author shangyu.wh * @version $Id: BoltServerTest.java, v 0.1 2018-05-14 19:34 shangyu.wh Exp $ */ public class BoltServerTest { - @Test - public void testGetChannel() { - BoltServer sessionServer = new BoltServer(new URL(), null); - for (int i = 0; i < 30; i++) { - - int finalI = i; - sessionServer.addChannel(new Channel() { - @Override - public InetSocketAddress getRemoteAddress() { - return new InetSocketAddress("192.168.1." + finalI, 9000); - } - - @Override - public InetSocketAddress getLocalAddress() { - return null; - } - - @Override - public boolean isConnected() { - return finalI % 2 == 0; - } - - @Override - public Object getAttribute(String key) { - return null; - } - - @Override - public void setAttribute(String key, Object value) { - - } - - @Override - public WebTarget getWebTarget() { - return null; - } - - @Override - public void close() { - - } - }); - } - sessionServer.getChannels(); - Channel channel = sessionServer.getChannel(new InetSocketAddress("192.168.1.1", 9000)); - Assert.assertNull(channel); - - channel = sessionServer.getChannel(new InetSocketAddress("192.168.1.18", 9000)); - Assert.assertNotNull(channel); + @Test + public void testGetChannel() { + BoltServer sessionServer = new BoltServer(new URL(), null); + for (int i = 0; i < 30; i++) { + + int finalI = i; + sessionServer.addChannel( + new Channel() { + @Override + public InetSocketAddress getRemoteAddress() { + return new InetSocketAddress("192.168.1." + finalI, 9000); + } + + @Override + public InetSocketAddress getLocalAddress() { + return null; + } + + @Override + public boolean isConnected() { + return finalI % 2 == 0; + } + + @Override + public Object getAttribute(String key) { + return null; + } + + @Override + public void setAttribute(String key, Object value) {} + + @Override + public WebTarget getWebTarget() { + return null; + } + + @Override + public void close() {} + }); } -} \ No newline at end of file + sessionServer.getChannels(); + Channel channel = sessionServer.getChannel(new InetSocketAddress("192.168.1.1", 9000)); + Assert.assertNull(channel); + + channel = sessionServer.getChannel(new InetSocketAddress("192.168.1.18", 9000)); + Assert.assertNotNull(channel); + } +} diff --git a/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/MockChannel.java b/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/MockChannel.java index d00c5d5b9..2fd85db83 100644 --- a/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/MockChannel.java +++ b/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/MockChannel.java @@ -16,49 +16,43 @@ */ package com.alipay.sofa.registry.remoting.bolt; +import com.alipay.sofa.registry.remoting.Channel; import java.net.InetSocketAddress; - import javax.ws.rs.client.WebTarget; -import com.alipay.sofa.registry.remoting.Channel; - /** * @author xuanbei * @since 2019/3/26 */ public class MockChannel implements Channel { - @Override - public InetSocketAddress getRemoteAddress() { - return null; - } - - @Override - public InetSocketAddress getLocalAddress() { - return null; - } - - @Override - public boolean isConnected() { - return false; - } - - @Override - public Object getAttribute(String key) { - return null; - } - - @Override - public void setAttribute(String key, Object value) { - - } - - @Override - public WebTarget getWebTarget() { - return null; - } - - @Override - public void close() { - - } + @Override + public InetSocketAddress getRemoteAddress() { + return null; + } + + @Override + public InetSocketAddress getLocalAddress() { + return null; + } + + @Override + public boolean isConnected() { + return false; + } + + @Override + public Object getAttribute(String key) { + return null; + } + + @Override + public void setAttribute(String key, Object value) {} + + @Override + public WebTarget getWebTarget() { + return null; + } + + @Override + public void close() {} } diff --git a/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/MockChannelHandlerContext.java b/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/MockChannelHandlerContext.java index 40befa716..ce857e9be 100644 --- a/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/MockChannelHandlerContext.java +++ b/server/remoting/bolt/src/test/java/com/alipay/sofa/registry/remoting/bolt/MockChannelHandlerContext.java @@ -27,7 +27,6 @@ import io.netty.util.Attribute; import io.netty.util.AttributeKey; import io.netty.util.concurrent.EventExecutor; - import java.net.SocketAddress; /** @@ -35,209 +34,209 @@ * @since 2019/3/27 */ public class MockChannelHandlerContext implements ChannelHandlerContext { - @Override - public Channel channel() { - return null; - } - - @Override - public EventExecutor executor() { - return null; - } - - @Override - public String name() { - return null; - } - - @Override - public ChannelHandler handler() { - return null; - } - - @Override - public boolean isRemoved() { - return false; - } - - @Override - public ChannelHandlerContext fireChannelRegistered() { - return null; - } - - @Override - public ChannelHandlerContext fireChannelUnregistered() { - return null; - } - - @Override - public ChannelHandlerContext fireChannelActive() { - return null; - } - - @Override - public ChannelHandlerContext fireChannelInactive() { - return null; - } - - @Override - public ChannelHandlerContext fireExceptionCaught(Throwable cause) { - return null; - } - - @Override - public ChannelHandlerContext fireUserEventTriggered(Object evt) { - return null; - } - - @Override - public ChannelHandlerContext fireChannelRead(Object msg) { - return null; - } - - @Override - public ChannelHandlerContext fireChannelReadComplete() { - return null; - } - - @Override - public ChannelHandlerContext fireChannelWritabilityChanged() { - return null; - } - - @Override - public ChannelFuture bind(SocketAddress localAddress) { - return null; - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress) { - return null; - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { - return null; - } - - @Override - public ChannelFuture disconnect() { - return null; - } - - @Override - public ChannelFuture close() { - return null; - } - - @Override - public ChannelFuture deregister() { - return null; - } - - @Override - public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { - return null; - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { - return null; - } - - @Override - public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, - ChannelPromise promise) { - return null; - } - - @Override - public ChannelFuture disconnect(ChannelPromise promise) { - return null; - } - - @Override - public ChannelFuture close(ChannelPromise promise) { - return null; - } - - @Override - public ChannelFuture deregister(ChannelPromise promise) { - return null; - } - - @Override - public ChannelHandlerContext read() { - return null; - } - - @Override - public ChannelFuture write(Object msg) { - return null; - } - - @Override - public ChannelFuture write(Object msg, ChannelPromise promise) { - return null; - } - - @Override - public ChannelHandlerContext flush() { - return null; - } - - @Override - public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { - return null; - } - - @Override - public ChannelFuture writeAndFlush(Object msg) { - return null; - } - - @Override - public ChannelPromise newPromise() { - return null; - } - - @Override - public ChannelProgressivePromise newProgressivePromise() { - return null; - } - - @Override - public ChannelFuture newSucceededFuture() { - return null; - } - - @Override - public ChannelFuture newFailedFuture(Throwable cause) { - return null; - } - - @Override - public ChannelPromise voidPromise() { - return null; - } - - @Override - public ChannelPipeline pipeline() { - return null; - } - - @Override - public ByteBufAllocator alloc() { - return null; - } - - @Override - public Attribute attr(AttributeKey key) { - return null; - } - - @Override - public boolean hasAttr(AttributeKey key) { - return false; - } + @Override + public Channel channel() { + return null; + } + + @Override + public EventExecutor executor() { + return null; + } + + @Override + public String name() { + return null; + } + + @Override + public ChannelHandler handler() { + return null; + } + + @Override + public boolean isRemoved() { + return false; + } + + @Override + public ChannelHandlerContext fireChannelRegistered() { + return null; + } + + @Override + public ChannelHandlerContext fireChannelUnregistered() { + return null; + } + + @Override + public ChannelHandlerContext fireChannelActive() { + return null; + } + + @Override + public ChannelHandlerContext fireChannelInactive() { + return null; + } + + @Override + public ChannelHandlerContext fireExceptionCaught(Throwable cause) { + return null; + } + + @Override + public ChannelHandlerContext fireUserEventTriggered(Object evt) { + return null; + } + + @Override + public ChannelHandlerContext fireChannelRead(Object msg) { + return null; + } + + @Override + public ChannelHandlerContext fireChannelReadComplete() { + return null; + } + + @Override + public ChannelHandlerContext fireChannelWritabilityChanged() { + return null; + } + + @Override + public ChannelFuture bind(SocketAddress localAddress) { + return null; + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress) { + return null; + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { + return null; + } + + @Override + public ChannelFuture disconnect() { + return null; + } + + @Override + public ChannelFuture close() { + return null; + } + + @Override + public ChannelFuture deregister() { + return null; + } + + @Override + public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { + return null; + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { + return null; + } + + @Override + public ChannelFuture connect( + SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { + return null; + } + + @Override + public ChannelFuture disconnect(ChannelPromise promise) { + return null; + } + + @Override + public ChannelFuture close(ChannelPromise promise) { + return null; + } + + @Override + public ChannelFuture deregister(ChannelPromise promise) { + return null; + } + + @Override + public ChannelHandlerContext read() { + return null; + } + + @Override + public ChannelFuture write(Object msg) { + return null; + } + + @Override + public ChannelFuture write(Object msg, ChannelPromise promise) { + return null; + } + + @Override + public ChannelHandlerContext flush() { + return null; + } + + @Override + public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { + return null; + } + + @Override + public ChannelFuture writeAndFlush(Object msg) { + return null; + } + + @Override + public ChannelPromise newPromise() { + return null; + } + + @Override + public ChannelProgressivePromise newProgressivePromise() { + return null; + } + + @Override + public ChannelFuture newSucceededFuture() { + return null; + } + + @Override + public ChannelFuture newFailedFuture(Throwable cause) { + return null; + } + + @Override + public ChannelPromise voidPromise() { + return null; + } + + @Override + public ChannelPipeline pipeline() { + return null; + } + + @Override + public ByteBufAllocator alloc() { + return null; + } + + @Override + public Attribute attr(AttributeKey key) { + return null; + } + + @Override + public boolean hasAttr(AttributeKey key) { + return false; + } } diff --git a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyChannel.java b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyChannel.java index 5a061273a..0084c8893 100644 --- a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyChannel.java +++ b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyChannel.java @@ -16,88 +16,83 @@ */ package com.alipay.sofa.registry.remoting.jersey; +import com.alipay.sofa.registry.net.NetUtil; +import com.alipay.sofa.registry.remoting.Channel; import java.net.InetSocketAddress; import java.net.URI; - import javax.ws.rs.client.Client; import javax.ws.rs.client.WebTarget; -import com.alipay.sofa.registry.net.NetUtil; -import com.alipay.sofa.registry.remoting.Channel; - /** - * * @author shangyu.wh * @version $Id: JerseyChannel.java, v 0.1 2018-02-01 11:35 shangyu.wh Exp $ */ public class JerseyChannel implements Channel { - private WebTarget webTarget; - - private Client client; - - @Override - public InetSocketAddress getRemoteAddress() { - if (webTarget != null) { - URI uri = webTarget.getUri(); - return new InetSocketAddress(uri.getHost(), uri.getPort()); - } - return null; - } + private WebTarget webTarget; - @Override - public InetSocketAddress getLocalAddress() { - return NetUtil.getLocalSocketAddress(); - } + private Client client; - @Override - public boolean isConnected() { - if (client instanceof org.glassfish.jersey.client.JerseyClient) { - return !((org.glassfish.jersey.client.JerseyClient) client).isClosed(); - } - return false; + @Override + public InetSocketAddress getRemoteAddress() { + if (webTarget != null) { + URI uri = webTarget.getUri(); + return new InetSocketAddress(uri.getHost(), uri.getPort()); } - - @Override - public Object getAttribute(String key) { - return null; - } - - @Override - public void setAttribute(String key, Object value) { - - } - - /** - * Getter method for property webTarget. - * - * @return property value of webTarget - */ - @Override - public WebTarget getWebTarget() { - return webTarget; - } - - @Override - public void close() { - client.close(); - } - - /** - * Setter method for property webTarget. - * - * @param webTarget value to be assigned to property webTarget - */ - public void setWebTarget(WebTarget webTarget) { - this.webTarget = webTarget; - } - - /** - * Setter method for property client. - * - * @param client value to be assigned to property client - */ - public void setClient(Client client) { - this.client = client; + return null; + } + + @Override + public InetSocketAddress getLocalAddress() { + return NetUtil.getLocalSocketAddress(); + } + + @Override + public boolean isConnected() { + if (client instanceof org.glassfish.jersey.client.JerseyClient) { + return !((org.glassfish.jersey.client.JerseyClient) client).isClosed(); } -} \ No newline at end of file + return false; + } + + @Override + public Object getAttribute(String key) { + return null; + } + + @Override + public void setAttribute(String key, Object value) {} + + /** + * Getter method for property webTarget. + * + * @return property value of webTarget + */ + @Override + public WebTarget getWebTarget() { + return webTarget; + } + + @Override + public void close() { + client.close(); + } + + /** + * Setter method for property webTarget. + * + * @param webTarget value to be assigned to property webTarget + */ + public void setWebTarget(WebTarget webTarget) { + this.webTarget = webTarget; + } + + /** + * Setter method for property client. + * + * @param client value to be assigned to property client + */ + public void setClient(Client client) { + this.client = client; + } +} diff --git a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyClient.java b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyClient.java index d3d1a56fd..30c5957d8 100644 --- a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyClient.java +++ b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyClient.java @@ -16,154 +16,145 @@ */ package com.alipay.sofa.registry.remoting.jersey; +import com.alipay.sofa.registry.common.model.store.URL; +import com.alipay.sofa.registry.log.Logger; +import com.alipay.sofa.registry.log.LoggerFactory; +import com.alipay.sofa.registry.net.NetUtil; +import com.alipay.sofa.registry.remoting.CallbackHandler; +import com.alipay.sofa.registry.remoting.Channel; +import com.alipay.sofa.registry.remoting.Client; import java.net.InetSocketAddress; import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; - import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.UriBuilder; - import org.glassfish.jersey.client.ClientConfig; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.client.HttpUrlConnectorProvider; import org.glassfish.jersey.jackson.JacksonFeature; -import com.alipay.sofa.registry.common.model.store.URL; -import com.alipay.sofa.registry.log.Logger; -import com.alipay.sofa.registry.log.LoggerFactory; -import com.alipay.sofa.registry.net.NetUtil; -import com.alipay.sofa.registry.remoting.CallbackHandler; -import com.alipay.sofa.registry.remoting.Channel; -import com.alipay.sofa.registry.remoting.Client; - /** - * * @author shangyu.wh * @version $Id: JerseyClient.java, v 0.1 2018-01-30 11:13 shangyu.wh Exp $ */ public class JerseyClient implements Client { - private static final Logger LOGGER = LoggerFactory - .getLogger(JerseyClient.class); - private static final JerseyClient instance = new JerseyClient(); - - private final AtomicReference client = new AtomicReference<>(null); - - private Map channels = new HashMap<>(); - - /** - * constructor - */ - public JerseyClient() { - setClient(getClient(null)); - } - - /** - * get instance of jerseyClient - * @return - */ - public static JerseyClient getInstance() { - return instance; + private static final Logger LOGGER = LoggerFactory.getLogger(JerseyClient.class); + private static final JerseyClient instance = new JerseyClient(); + + private final AtomicReference client = new AtomicReference<>(null); + + private Map channels = new HashMap<>(); + + /** constructor */ + public JerseyClient() { + setClient(getClient(null)); + } + + /** + * get instance of jerseyClient + * + * @return + */ + public static JerseyClient getInstance() { + return instance; + } + + @Override + public Channel connect(URL url) { + try { + + JerseyChannel channel = new JerseyChannel(); + channel.setWebTarget(getTarget(url)); + channel.setClient(getClient()); + channels.put(url.getAddressString(), channel); + return channel; + } catch (Exception e) { + LOGGER.error("Create jersey connect:" + url + " error!", e); + throw new RuntimeException("Create jersey connect:" + url + " error!", e); } - - @Override - public Channel connect(URL url) { - try { - - JerseyChannel channel = new JerseyChannel(); - channel.setWebTarget(getTarget(url)); - channel.setClient(getClient()); - channels.put(url.getAddressString(), channel); - return channel; - } catch (Exception e) { - LOGGER.error("Create jersey connect:" + url + " error!", e); - throw new RuntimeException("Create jersey connect:" + url + " error!", e); - } - } - - @Override - public Object sendSync(URL url, Object message, int timeoutMillis) { - return null; - } - - @Override - public Object sendSync(Channel channel, Object message, int timeoutMillis) { - return null; - } - - @Override - public void sendCallback(URL url, Object message, CallbackHandler callbackHandler, - int timeoutMillis) { - + } + + @Override + public Object sendSync(URL url, Object message, int timeoutMillis) { + return null; + } + + @Override + public Object sendSync(Channel channel, Object message, int timeoutMillis) { + return null; + } + + @Override + public void sendCallback( + URL url, Object message, CallbackHandler callbackHandler, int timeoutMillis) {} + + private WebTarget getTarget(URL targetUrl) { + return getClient().target(getBaseUri(targetUrl)); + } + + private javax.ws.rs.client.Client getClient(ClientConfig clientConfig) { + if (clientConfig == null) { + clientConfig = new ClientConfig(); + clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 3000); + clientConfig.property(ClientProperties.READ_TIMEOUT, 5000); } - private WebTarget getTarget(URL targetUrl) { - return getClient().target(getBaseUri(targetUrl)); - } + clientConfig.connectorProvider(new HttpUrlConnectorProvider()); - private javax.ws.rs.client.Client getClient(ClientConfig clientConfig) { - if (clientConfig == null) { - clientConfig = new ClientConfig(); - clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 3000); - clientConfig.property(ClientProperties.READ_TIMEOUT, 5000); - } + clientConfig.register(JacksonFeature.class); - clientConfig.connectorProvider(new HttpUrlConnectorProvider()); + return ClientBuilder.newClient(clientConfig); + } - clientConfig.register(JacksonFeature.class); + public javax.ws.rs.client.Client getClient() { + return client.get(); + } - return ClientBuilder.newClient(clientConfig); - } + public void setClient(final javax.ws.rs.client.Client clientIn) { + client.getAndSet(clientIn); + } - public javax.ws.rs.client.Client getClient() { - return client.get(); + public URI getBaseUri(URL targetUrl) { + URI uri; + try { + uri = + UriBuilder.fromUri("http://" + targetUrl.getIpAddress() + "/") + .port(targetUrl.getPort()) + .build(); + } catch (Exception e) { + LOGGER.error("get server URI error!", e); + throw new RuntimeException("get server URI error!", e); } - - public void setClient(final javax.ws.rs.client.Client clientIn) { - client.getAndSet(clientIn); + return uri; + } + + @Override + public Channel getChannel(URL url) { + Channel c = channels.get(url.getAddressString()); + if (c == null) { + return null; + } else { + if (!c.isConnected()) { + connect(url); + } } - - public URI getBaseUri(URL targetUrl) { - URI uri; - try { - uri = UriBuilder.fromUri("http://" + targetUrl.getIpAddress() + "/") - .port(targetUrl.getPort()).build(); - } catch (Exception e) { - LOGGER.error("get server URI error!", e); - throw new RuntimeException("get server URI error!", e); - } - return uri; - } - - @Override - public Channel getChannel(URL url) { - Channel c = channels.get(url.getAddressString()); - if (c == null) { - return null; - } else { - if (!c.isConnected()) { - connect(url); - } - } - return c; - } - - @Override - public InetSocketAddress getLocalAddress() { - return NetUtil.getLocalSocketAddress(); - } - - @Override - public void close() { - - } - - @Override - public boolean isClosed() { - return false; - } - -} \ No newline at end of file + return c; + } + + @Override + public InetSocketAddress getLocalAddress() { + return NetUtil.getLocalSocketAddress(); + } + + @Override + public void close() {} + + @Override + public boolean isClosed() { + return false; + } +} diff --git a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyJettyServer.java b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyJettyServer.java index 0e08653fa..d091e2678 100644 --- a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyJettyServer.java +++ b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/JerseyJettyServer.java @@ -16,14 +16,19 @@ */ package com.alipay.sofa.registry.remoting.jersey; +import com.alipay.sofa.registry.common.model.store.URL; +import com.alipay.sofa.registry.log.Logger; +import com.alipay.sofa.registry.log.LoggerFactory; +import com.alipay.sofa.registry.remoting.CallbackHandler; +import com.alipay.sofa.registry.remoting.Channel; +import com.alipay.sofa.registry.remoting.Server; +import com.alipay.sofa.registry.remoting.jersey.jetty.server.HttpConnectionCustomFactory; import java.net.InetSocketAddress; import java.net.URI; import java.util.Collection; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; - import javax.ws.rs.ProcessingException; - import org.eclipse.jetty.server.Connector; import org.eclipse.jetty.server.ServerConnector; import org.eclipse.jetty.util.thread.QueuedThreadPool; @@ -35,188 +40,171 @@ import org.glassfish.jersey.server.ResourceConfig; import org.glassfish.jersey.server.spi.Container; -import com.alipay.sofa.registry.common.model.store.URL; -import com.alipay.sofa.registry.log.Logger; -import com.alipay.sofa.registry.log.LoggerFactory; -import com.alipay.sofa.registry.remoting.CallbackHandler; -import com.alipay.sofa.registry.remoting.Channel; -import com.alipay.sofa.registry.remoting.Server; -import com.alipay.sofa.registry.remoting.jersey.jetty.server.HttpConnectionCustomFactory; - /** - * * @author shangyu.wh * @version $Id: Jersey.java, v 0.1 2018-01-29 17:57 shangyu.wh Exp $ */ public class JerseyJettyServer implements Server { - private static final Logger LOGGER = LoggerFactory - .getLogger(JerseyJettyServer.class); - - private final ResourceConfig resourceConfig; - - private final URI baseUri; - - private org.eclipse.jetty.server.Server server; - /** - * started status - */ - private AtomicBoolean isStarted = new AtomicBoolean(false); - - /** - * constructor - * @param resourceConfig - * @param baseUri - */ - public JerseyJettyServer(ResourceConfig resourceConfig, URI baseUri) { - this.resourceConfig = resourceConfig; - this.baseUri = baseUri; - } - - /** - * start jersey server - */ - public void startServer() { - if (isStarted.compareAndSet(false, true)) { - try { - - server = createServer(getBaseUri(), resourceConfig, true); - - } catch (Exception e) { - isStarted.set(false); - LOGGER.error("Start Jetty jersey server error!", e); - throw new RuntimeException("Start Jetty jersey server error!", e); - } - } - } - - public static org.eclipse.jetty.server.Server createServer(final URI uri, - final ResourceConfig resourceConfig, - final boolean start) { - if (uri == null) { - throw new IllegalArgumentException(LocalizationMessages.URI_CANNOT_BE_NULL()); - } + private static final Logger LOGGER = LoggerFactory.getLogger(JerseyJettyServer.class); - JettyHttpContainer handler = ContainerFactory.createContainer(JettyHttpContainer.class, - resourceConfig); + private final ResourceConfig resourceConfig; - int defaultPort = Container.DEFAULT_HTTP_PORT; + private final URI baseUri; - final int port = (uri.getPort() == -1) ? defaultPort : uri.getPort(); + private org.eclipse.jetty.server.Server server; + /** started status */ + private AtomicBoolean isStarted = new AtomicBoolean(false); - final org.eclipse.jetty.server.Server server = new org.eclipse.jetty.server.Server( - new JettyConnectorThreadPool()); + /** + * constructor + * + * @param resourceConfig + * @param baseUri + */ + public JerseyJettyServer(ResourceConfig resourceConfig, URI baseUri) { + this.resourceConfig = resourceConfig; + this.baseUri = baseUri; + } - final ServerConnector http = new ServerConnector(server, new HttpConnectionCustomFactory()); - http.setPort(port); - server.setConnectors(new Connector[] { http }); + /** start jersey server */ + public void startServer() { + if (isStarted.compareAndSet(false, true)) { + try { - if (handler != null) { - server.setHandler(handler); - } + server = createServer(getBaseUri(), resourceConfig, true); - if (start) { - try { - // Start the server. - server.start(); - } catch (final Exception e) { - throw new ProcessingException(LocalizationMessages.ERROR_WHEN_CREATING_SERVER(), e); - } - } - return server; + } catch (Exception e) { + isStarted.set(false); + LOGGER.error("Start Jetty jersey server error!", e); + throw new RuntimeException("Start Jetty jersey server error!", e); + } } + } - private static final class JettyConnectorThreadPool extends QueuedThreadPool { - private final ThreadFactory threadFactory = new ThreadFactoryBuilder() - .setNameFormat("jetty-http-server-%d") - .setUncaughtExceptionHandler( - new JerseyProcessingUncaughtExceptionHandler()) - .build(); - - @Override - protected Thread newThread(Runnable runnable) { - return threadFactory.newThread(runnable); - } + public static org.eclipse.jetty.server.Server createServer( + final URI uri, final ResourceConfig resourceConfig, final boolean start) { + if (uri == null) { + throw new IllegalArgumentException(LocalizationMessages.URI_CANNOT_BE_NULL()); } - @Override - public boolean isOpen() { - if (server != null) { - return server.isStarted(); - } - return false; - } + JettyHttpContainer handler = + ContainerFactory.createContainer(JettyHttpContainer.class, resourceConfig); - @Override - public Collection getChannels() { - return null; - } + int defaultPort = Container.DEFAULT_HTTP_PORT; - @Override - public Channel getChannel(InetSocketAddress remoteAddress) { - return null; - } + final int port = (uri.getPort() == -1) ? defaultPort : uri.getPort(); - @Override - public Channel getChannel(URL url) { - return null; - } + final org.eclipse.jetty.server.Server server = + new org.eclipse.jetty.server.Server(new JettyConnectorThreadPool()); - @Override - public void close(Channel channel) { - throw new UnsupportedOperationException("Jersey Server don't support close Channel."); - } + final ServerConnector http = new ServerConnector(server, new HttpConnectionCustomFactory()); + http.setPort(port); + server.setConnectors(new Connector[] {http}); - @Override - public InetSocketAddress getLocalAddress() { - return new InetSocketAddress(getBaseUri().getPort()); + if (handler != null) { + server.setHandler(handler); } - @Override - public void close() { - if (server != null) { - try { - server.stop(); - } catch (Exception e) { - LOGGER.error("Jersey Jetty Server stop error!", e); - throw new RuntimeException("Jersey Jetty Server stop error!", e); - } - return; - } - throw new RuntimeException("Jersey Server has not started!Server Channel has not created!"); + if (start) { + try { + // Start the server. + server.start(); + } catch (final Exception e) { + throw new ProcessingException(LocalizationMessages.ERROR_WHEN_CREATING_SERVER(), e); + } } + return server; + } - @Override - public boolean isClosed() { - if (server != null) { - return server.isStopped(); - } - return true; - } - - @Override - public Object sendSync(Channel channel, Object message, int timeoutMillis) { - return null; - } - - @Override - public void sendCallback(Channel channel, Object message, CallbackHandler callbackHandler, - int timeoutMillis) { - - } - - /** - * Getter method for property baseUri. - * - * @return property value of baseUri - */ - public URI getBaseUri() { - return baseUri; - } + private static final class JettyConnectorThreadPool extends QueuedThreadPool { + private final ThreadFactory threadFactory = + new ThreadFactoryBuilder() + .setNameFormat("jetty-http-server-%d") + .setUncaughtExceptionHandler(new JerseyProcessingUncaughtExceptionHandler()) + .build(); @Override - public int getChannelCount() { - return 0; - } - -} \ No newline at end of file + protected Thread newThread(Runnable runnable) { + return threadFactory.newThread(runnable); + } + } + + @Override + public boolean isOpen() { + if (server != null) { + return server.isStarted(); + } + return false; + } + + @Override + public Collection getChannels() { + return null; + } + + @Override + public Channel getChannel(InetSocketAddress remoteAddress) { + return null; + } + + @Override + public Channel getChannel(URL url) { + return null; + } + + @Override + public void close(Channel channel) { + throw new UnsupportedOperationException("Jersey Server don't support close Channel."); + } + + @Override + public InetSocketAddress getLocalAddress() { + return new InetSocketAddress(getBaseUri().getPort()); + } + + @Override + public void close() { + if (server != null) { + try { + server.stop(); + } catch (Exception e) { + LOGGER.error("Jersey Jetty Server stop error!", e); + throw new RuntimeException("Jersey Jetty Server stop error!", e); + } + return; + } + throw new RuntimeException("Jersey Server has not started!Server Channel has not created!"); + } + + @Override + public boolean isClosed() { + if (server != null) { + return server.isStopped(); + } + return true; + } + + @Override + public Object sendSync(Channel channel, Object message, int timeoutMillis) { + return null; + } + + @Override + public void sendCallback( + Channel channel, Object message, CallbackHandler callbackHandler, int timeoutMillis) {} + + /** + * Getter method for property baseUri. + * + * @return property value of baseUri + */ + public URI getBaseUri() { + return baseUri; + } + + @Override + public int getChannelCount() { + return 0; + } +} diff --git a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/exchange/JerseyExchange.java b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/exchange/JerseyExchange.java index f73c8b05f..aca967db1 100644 --- a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/exchange/JerseyExchange.java +++ b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/exchange/JerseyExchange.java @@ -16,13 +16,6 @@ */ package com.alipay.sofa.registry.remoting.jersey.exchange; -import java.net.URI; -import java.util.concurrent.ConcurrentHashMap; - -import javax.ws.rs.core.UriBuilder; - -import org.glassfish.jersey.server.ResourceConfig; - import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; @@ -31,85 +24,87 @@ import com.alipay.sofa.registry.remoting.exchange.Exchange; import com.alipay.sofa.registry.remoting.jersey.JerseyClient; import com.alipay.sofa.registry.remoting.jersey.JerseyJettyServer; +import java.net.URI; +import java.util.concurrent.ConcurrentHashMap; +import javax.ws.rs.core.UriBuilder; +import org.glassfish.jersey.server.ResourceConfig; /** - * * @author shangyu.wh * @version $Id: JerseyExchange.java, v 0.1 2018-01-29 19:49 shangyu.wh Exp $ */ public class JerseyExchange implements Exchange { - private static final Logger LOGGER = LoggerFactory - .getLogger(JerseyExchange.class); + private static final Logger LOGGER = LoggerFactory.getLogger(JerseyExchange.class); - private ConcurrentHashMap serverMap = new ConcurrentHashMap<>(); + private ConcurrentHashMap serverMap = new ConcurrentHashMap<>(); - private Client client; + private Client client; - @Override - public Client connect(String serverType, URL serverUrl, ResourceConfig... channelHandlers) { - JerseyClient jerseyClient = JerseyClient.getInstance(); - setClient(jerseyClient); - return jerseyClient; - } - - @Override - public Client connect(String serverType, int connNum, URL serverUrl, - ResourceConfig... channelHandlers) { - throw new UnsupportedOperationException(); - } + @Override + public Client connect(String serverType, URL serverUrl, ResourceConfig... channelHandlers) { + JerseyClient jerseyClient = JerseyClient.getInstance(); + setClient(jerseyClient); + return jerseyClient; + } - @Override - public Server open(URL url, ResourceConfig... resources) { + @Override + public Client connect( + String serverType, int connNum, URL serverUrl, ResourceConfig... channelHandlers) { + throw new UnsupportedOperationException(); + } - URI uri; - try { - uri = UriBuilder.fromUri("http://" + url.getIpAddress() + "/").port(url.getPort()) - .build(); - } catch (Exception e) { - LOGGER.error("get server URI error!", e); - throw new RuntimeException("get server URI error!", e); - } - JerseyJettyServer jerseyServer = new JerseyJettyServer(resources[0], uri); - setServer(jerseyServer, url); - jerseyServer.startServer(); + @Override + public Server open(URL url, ResourceConfig... resources) { - return jerseyServer; + URI uri; + try { + uri = UriBuilder.fromUri("http://" + url.getIpAddress() + "/").port(url.getPort()).build(); + } catch (Exception e) { + LOGGER.error("get server URI error!", e); + throw new RuntimeException("get server URI error!", e); } + JerseyJettyServer jerseyServer = new JerseyJettyServer(resources[0], uri); + setServer(jerseyServer, url); + jerseyServer.startServer(); + + return jerseyServer; + } - @Override - public Client getClient(String serverType) { + @Override + public Client getClient(String serverType) { + if (null == client) { + synchronized (JerseyExchange.class) { if (null == client) { - synchronized (JerseyExchange.class) { - if (null == client) { - JerseyClient jerseyClient = JerseyClient.getInstance(); - setClient(jerseyClient); - } - } + JerseyClient jerseyClient = JerseyClient.getInstance(); + setClient(jerseyClient); } - return client; - } - - /** - * Setter method for property client. - * - * @param client value to be assigned to property client - */ - public void setClient(Client client) { - this.client = client; - } - - @Override - public Server getServer(Integer port) { - return serverMap.get(port); - } - - /** - * add server into serverMap - * @param server - * @param url - */ - public void setServer(Server server, URL url) { - serverMap.putIfAbsent(url.getPort(), server); + } } -} \ No newline at end of file + return client; + } + + /** + * Setter method for property client. + * + * @param client value to be assigned to property client + */ + public void setClient(Client client) { + this.client = client; + } + + @Override + public Server getServer(Integer port) { + return serverMap.get(port); + } + + /** + * add server into serverMap + * + * @param server + * @param url + */ + public void setServer(Server server, URL url) { + serverMap.putIfAbsent(url.getPort(), server); + } +} diff --git a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpChannelOverHttpCustom.java b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpChannelOverHttpCustom.java index c45bf7c4c..941f280ab 100644 --- a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpChannelOverHttpCustom.java +++ b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpChannelOverHttpCustom.java @@ -25,32 +25,34 @@ import org.eclipse.jetty.server.HttpTransport; /** - * * @author shangyu.wh * @version $Id: HttpChannelOverHttpHack.java, v 0.1 2018-09-26 17:00 shangyu.wh Exp $ */ public class HttpChannelOverHttpCustom extends HttpChannelOverHttp { - private static final char QUESTION_MARK = '?'; + private static final char QUESTION_MARK = '?'; - public HttpChannelOverHttpCustom(HttpConnection httpConnection, Connector connector, - HttpConfiguration config, EndPoint endPoint, - HttpTransport transport) { - super(httpConnection, connector, config, endPoint, transport); - } + public HttpChannelOverHttpCustom( + HttpConnection httpConnection, + Connector connector, + HttpConfiguration config, + EndPoint endPoint, + HttpTransport transport) { + super(httpConnection, connector, config, endPoint, transport); + } - @Override - public boolean startRequest(String method, String uri, HttpVersion version) { + @Override + public boolean startRequest(String method, String uri, HttpVersion version) { - if (uri != null && !uri.isEmpty() && uri.charAt(0) == QUESTION_MARK) { - /* HTTP/1.1 spec says in 5.1.2. about Request-URI: - * "Note that the absolute path cannot be empty; if - * none is present in the original URI, it MUST be - * given as "/" (the server root)." So if the file - * name here has only a query string, the path is - * empty and we also have to add a "/". - */ - uri = "/" + uri; - } - return super.startRequest(method, uri, version); + if (uri != null && !uri.isEmpty() && uri.charAt(0) == QUESTION_MARK) { + /* HTTP/1.1 spec says in 5.1.2. about Request-URI: + * "Note that the absolute path cannot be empty; if + * none is present in the original URI, it MUST be + * given as "/" (the server root)." So if the file + * name here has only a query string, the path is + * empty and we also have to add a "/". + */ + uri = "/" + uri; } -} \ No newline at end of file + return super.startRequest(method, uri, version); + } +} diff --git a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpConnectionCustom.java b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpConnectionCustom.java index e6cc4b0e0..7fa121c67 100644 --- a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpConnectionCustom.java +++ b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpConnectionCustom.java @@ -24,20 +24,23 @@ import org.eclipse.jetty.server.HttpConnection; /** - * * @author shangyu.wh * @version $Id: HttpConnectionOver.java, v 0.1 2018-09-26 16:46 shangyu.wh Exp $ */ public class HttpConnectionCustom extends HttpConnection { - public HttpConnectionCustom(HttpConfiguration config, Connector connector, EndPoint endPoint, - HttpCompliance compliance, boolean recordComplianceViolations) { - super(config, connector, endPoint, compliance, recordComplianceViolations); - } + public HttpConnectionCustom( + HttpConfiguration config, + Connector connector, + EndPoint endPoint, + HttpCompliance compliance, + boolean recordComplianceViolations) { + super(config, connector, endPoint, compliance, recordComplianceViolations); + } - @Override - protected HttpChannelOverHttp newHttpChannel() { - return new HttpChannelOverHttpCustom(this, getConnector(), getHttpConfiguration(), - getEndPoint(), this); - } -} \ No newline at end of file + @Override + protected HttpChannelOverHttp newHttpChannel() { + return new HttpChannelOverHttpCustom( + this, getConnector(), getHttpConfiguration(), getEndPoint(), this); + } +} diff --git a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpConnectionCustomFactory.java b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpConnectionCustomFactory.java index bdc0e8e8b..93740e2e4 100644 --- a/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpConnectionCustomFactory.java +++ b/server/remoting/http/src/main/java/com/alipay/sofa/registry/remoting/jersey/jetty/server/HttpConnectionCustomFactory.java @@ -23,21 +23,24 @@ import org.eclipse.jetty.server.HttpConnectionFactory; /** - * * @author shangyu.wh * @version $Id: HttpConnectionOverFactory.java, v 0.1 2018-09-26 16:40 shangyu.wh Exp $ */ public class HttpConnectionCustomFactory extends HttpConnectionFactory { - public HttpConnectionCustomFactory() { - super(new HttpConfiguration()); - } - - @Override - public Connection newConnection(Connector connector, EndPoint endPoint) { - HttpConnectionCustom conn = new HttpConnectionCustom(getHttpConfiguration(), connector, - endPoint, getHttpCompliance(), isRecordHttpComplianceViolations()); - return configure(conn, connector, endPoint); - } + public HttpConnectionCustomFactory() { + super(new HttpConfiguration()); + } -} \ No newline at end of file + @Override + public Connection newConnection(Connector connector, EndPoint endPoint) { + HttpConnectionCustom conn = + new HttpConnectionCustom( + getHttpConfiguration(), + connector, + endPoint, + getHttpCompliance(), + isRecordHttpComplianceViolations()); + return configure(conn, connector, endPoint); + } +} diff --git a/server/remoting/http/src/test/java/com/alipay/sofa/registry/remoting/jersey/JerseyExchangeTest.java b/server/remoting/http/src/test/java/com/alipay/sofa/registry/remoting/jersey/JerseyExchangeTest.java index ee005fc98..5bc5219de 100644 --- a/server/remoting/http/src/test/java/com/alipay/sofa/registry/remoting/jersey/JerseyExchangeTest.java +++ b/server/remoting/http/src/test/java/com/alipay/sofa/registry/remoting/jersey/JerseyExchangeTest.java @@ -18,99 +18,98 @@ import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import com.alipay.sofa.registry.common.model.store.URL; +import com.alipay.sofa.registry.net.NetUtil; +import com.alipay.sofa.registry.remoting.CallbackHandler; +import com.alipay.sofa.registry.remoting.Channel; +import com.alipay.sofa.registry.remoting.jersey.exchange.JerseyExchange; import java.net.InetSocketAddress; import java.util.concurrent.Executor; - import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ResourceConfig; import org.junit.Assert; import org.junit.Test; -import com.alipay.sofa.registry.common.model.store.URL; -import com.alipay.sofa.registry.net.NetUtil; -import com.alipay.sofa.registry.remoting.CallbackHandler; -import com.alipay.sofa.registry.remoting.Channel; -import com.alipay.sofa.registry.remoting.jersey.exchange.JerseyExchange; - /** * @author xuanbei * @since 2019/3/27 */ public class JerseyExchangeTest { - private static final int JERSEY_TEST_PORT = 9662; - - @Test - public void doTest() { - ResourceConfig resourceConfig = new ResourceConfig(); - resourceConfig.register(JacksonFeature.class); - resourceConfig.registerInstances(new TestHttpResource()); - - CallbackHandler callbackHandler = new CallbackHandler() { - @Override - public void onCallback(Channel channel, Object message) { - } - - @Override - public void onException(Channel channel, Throwable exception) { - } - - @Override - public Executor getExecutor() { - return null; - } + private static final int JERSEY_TEST_PORT = 9662; + + @Test + public void doTest() { + ResourceConfig resourceConfig = new ResourceConfig(); + resourceConfig.register(JacksonFeature.class); + resourceConfig.registerInstances(new TestHttpResource()); + + CallbackHandler callbackHandler = + new CallbackHandler() { + @Override + public void onCallback(Channel channel, Object message) {} + + @Override + public void onException(Channel channel, Throwable exception) {} + + @Override + public Executor getExecutor() { + return null; + } }; - JerseyExchange jerseyExchange = new JerseyExchange(); - URL url = new URL(NetUtil.getLocalAddress().getHostAddress(), JERSEY_TEST_PORT); - JerseyJettyServer jerseyJettyServer = (JerseyJettyServer) jerseyExchange.open(url, - new ResourceConfig[] { resourceConfig }); - testJerseyJettyServer(url, jerseyJettyServer, jerseyExchange, callbackHandler); - - JerseyClient jerseyClient1 = (JerseyClient) jerseyExchange.getClient("jersey"); - JerseyClient jerseyClient2 = (JerseyClient) jerseyExchange.connect("jersey", url); - Assert.assertEquals(jerseyClient1, jerseyClient2); - testJerseyClient(url, jerseyClient1, callbackHandler); - - JerseyChannel jerseyChannel = (JerseyChannel) jerseyClient1.connect(url); - testJerseyChannel(jerseyChannel); - String result = jerseyChannel.getWebTarget().path("test").request(APPLICATION_JSON) - .get(String.class); - Assert.assertEquals("TestResource", result); - jerseyJettyServer.close(); - } - - private void testJerseyJettyServer(URL url, JerseyJettyServer jerseyJettyServer, - JerseyExchange jerseyExchange, - CallbackHandler callbackHandler) { - Assert.assertEquals(jerseyJettyServer, jerseyExchange.getServer(JERSEY_TEST_PORT)); - Assert.assertTrue(jerseyJettyServer.isOpen()); - Assert.assertNull(jerseyJettyServer.getChannels()); - Assert.assertNull(jerseyJettyServer.getChannel(new InetSocketAddress(9663))); - Assert.assertNull(jerseyJettyServer.getChannel(url)); - Assert.assertEquals(new InetSocketAddress(JERSEY_TEST_PORT), - jerseyJettyServer.getLocalAddress()); - Assert.assertFalse(jerseyJettyServer.isClosed()); - - jerseyJettyServer.sendCallback(new JerseyChannel(), new Object(), callbackHandler, 1000); - Assert.assertNull(jerseyJettyServer.sendSync(new JerseyChannel(), new Object(), 1000)); - } - - private void testJerseyClient(URL url, JerseyClient jerseyClient, - CallbackHandler callbackHandler) { - Assert.assertEquals(NetUtil.getLocalSocketAddress(), jerseyClient.getLocalAddress()); - Assert.assertFalse(jerseyClient.isClosed()); - Assert.assertNull(jerseyClient.getChannel(url)); - Assert.assertNull(jerseyClient.sendSync(new URL(), new Object(), 1000)); - jerseyClient.close(); - jerseyClient.sendCallback(new URL(), new Object(), callbackHandler, 1000); - } - - private void testJerseyChannel(JerseyChannel jerseyChannel) { - Assert.assertEquals(new InetSocketAddress(NetUtil.getLocalAddress(), 9662), - jerseyChannel.getRemoteAddress()); - Assert.assertEquals(NetUtil.getLocalSocketAddress(), jerseyChannel.getLocalAddress()); - Assert.assertTrue(jerseyChannel.isConnected()); - jerseyChannel.setAttribute("key", "value"); - Assert.assertNull(jerseyChannel.getAttribute("key")); - } + JerseyExchange jerseyExchange = new JerseyExchange(); + URL url = new URL(NetUtil.getLocalAddress().getHostAddress(), JERSEY_TEST_PORT); + JerseyJettyServer jerseyJettyServer = + (JerseyJettyServer) jerseyExchange.open(url, new ResourceConfig[] {resourceConfig}); + testJerseyJettyServer(url, jerseyJettyServer, jerseyExchange, callbackHandler); + + JerseyClient jerseyClient1 = (JerseyClient) jerseyExchange.getClient("jersey"); + JerseyClient jerseyClient2 = (JerseyClient) jerseyExchange.connect("jersey", url); + Assert.assertEquals(jerseyClient1, jerseyClient2); + testJerseyClient(url, jerseyClient1, callbackHandler); + + JerseyChannel jerseyChannel = (JerseyChannel) jerseyClient1.connect(url); + testJerseyChannel(jerseyChannel); + String result = + jerseyChannel.getWebTarget().path("test").request(APPLICATION_JSON).get(String.class); + Assert.assertEquals("TestResource", result); + jerseyJettyServer.close(); + } + + private void testJerseyJettyServer( + URL url, + JerseyJettyServer jerseyJettyServer, + JerseyExchange jerseyExchange, + CallbackHandler callbackHandler) { + Assert.assertEquals(jerseyJettyServer, jerseyExchange.getServer(JERSEY_TEST_PORT)); + Assert.assertTrue(jerseyJettyServer.isOpen()); + Assert.assertNull(jerseyJettyServer.getChannels()); + Assert.assertNull(jerseyJettyServer.getChannel(new InetSocketAddress(9663))); + Assert.assertNull(jerseyJettyServer.getChannel(url)); + Assert.assertEquals( + new InetSocketAddress(JERSEY_TEST_PORT), jerseyJettyServer.getLocalAddress()); + Assert.assertFalse(jerseyJettyServer.isClosed()); + + jerseyJettyServer.sendCallback(new JerseyChannel(), new Object(), callbackHandler, 1000); + Assert.assertNull(jerseyJettyServer.sendSync(new JerseyChannel(), new Object(), 1000)); + } + + private void testJerseyClient( + URL url, JerseyClient jerseyClient, CallbackHandler callbackHandler) { + Assert.assertEquals(NetUtil.getLocalSocketAddress(), jerseyClient.getLocalAddress()); + Assert.assertFalse(jerseyClient.isClosed()); + Assert.assertNull(jerseyClient.getChannel(url)); + Assert.assertNull(jerseyClient.sendSync(new URL(), new Object(), 1000)); + jerseyClient.close(); + jerseyClient.sendCallback(new URL(), new Object(), callbackHandler, 1000); + } + + private void testJerseyChannel(JerseyChannel jerseyChannel) { + Assert.assertEquals( + new InetSocketAddress(NetUtil.getLocalAddress(), 9662), jerseyChannel.getRemoteAddress()); + Assert.assertEquals(NetUtil.getLocalSocketAddress(), jerseyChannel.getLocalAddress()); + Assert.assertTrue(jerseyChannel.isConnected()); + jerseyChannel.setAttribute("key", "value"); + Assert.assertNull(jerseyChannel.getAttribute("key")); + } } diff --git a/server/remoting/http/src/test/java/com/alipay/sofa/registry/remoting/jersey/TestHttpResource.java b/server/remoting/http/src/test/java/com/alipay/sofa/registry/remoting/jersey/TestHttpResource.java index 89e02a09e..f5baafe89 100644 --- a/server/remoting/http/src/test/java/com/alipay/sofa/registry/remoting/jersey/TestHttpResource.java +++ b/server/remoting/http/src/test/java/com/alipay/sofa/registry/remoting/jersey/TestHttpResource.java @@ -27,9 +27,9 @@ */ @Path("test") public class TestHttpResource { - @GET - @Produces(MediaType.APPLICATION_JSON) - public String test() { - return "TestResource"; - } + @GET + @Produces(MediaType.APPLICATION_JSON) + public String test() { + return "TestResource"; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/DataApplication.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/DataApplication.java index 8df601bf7..a8efa1882 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/DataApplication.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/DataApplication.java @@ -24,21 +24,22 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; /** - * * @author zhuoyu.sjw * @version $Id: DataApplication.java, v 0.1 2017-11-13 19:04 zhuoyu.sjw Exp $$ */ @EnableDataServer -@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class DataApplication { - private static final Logger LOGGER = LoggerFactory.getLogger(DataApplication.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DataApplication.class); - public static void main(String[] args) { - // setup DefaultUncaughtExceptionHandler - Thread.setDefaultUncaughtExceptionHandler((t, e) -> { - LOGGER.error(String.format("UncaughtException in Thread(%s): %s", t.getName(), e.getMessage()), e); + public static void main(String[] args) { + // setup DefaultUncaughtExceptionHandler + Thread.setDefaultUncaughtExceptionHandler( + (t, e) -> { + LOGGER.error( + String.format("UncaughtException in Thread(%s): %s", t.getName(), e.getMessage()), e); }); - SpringApplication.run(DataApplication.class, args); - } + SpringApplication.run(DataApplication.class, args); + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/CommonConfig.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/CommonConfig.java index 385f1fd8c..b2db101f7 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/CommonConfig.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/CommonConfig.java @@ -16,71 +16,68 @@ */ package com.alipay.sofa.registry.server.data.bootstrap; +import java.util.Collection; +import java.util.Map; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.springframework.beans.factory.annotation.Value; -import java.util.Collection; -import java.util.Map; - /** - * * @author shangyu.wh * @version $Id: CommonConfig.java, v 0.1 2018-05-05 15:16 shangyu.wh Exp $ */ public class CommonConfig { - /** - * server local data center, get from System Property - * example: nodes.localDataCenter=DefaultDataCenter - */ - @Value("${nodes.localDataCenter}") - private String localDataCenter; + /** + * server local data center, get from System Property example: + * nodes.localDataCenter=DefaultDataCenter + */ + @Value("${nodes.localDataCenter}") + private String localDataCenter; - public static final String LOCAL_REGION = System - .getProperty("nodes.localRegion"); + public static final String LOCAL_REGION = System.getProperty("nodes.localRegion"); - @Value("#{PropertySplitter.mapOfList('${nodes.metaNode}')}") - private Map> metaNode; + @Value("#{PropertySplitter.mapOfList('${nodes.metaNode}')}") + private Map> metaNode; - /** - * Getter method for property metaNode. - * - * @return property value of metaNode - */ - public Map> getMetaNode() { - return metaNode; - } + /** + * Getter method for property metaNode. + * + * @return property value of metaNode + */ + public Map> getMetaNode() { + return metaNode; + } - /** - * Setter method for property metaNode. - * - * @param metaNode value to be assigned to property metaNode - */ - public void setMetaNode(Map> metaNode) { - this.metaNode = metaNode; - } + /** + * Setter method for property metaNode. + * + * @param metaNode value to be assigned to property metaNode + */ + public void setMetaNode(Map> metaNode) { + this.metaNode = metaNode; + } - /** - * Getter method for property localDataCenter. - * - * @return property value of localDataCenter - */ - public String getLocalDataCenter() { - return localDataCenter; - } + /** + * Getter method for property localDataCenter. + * + * @return property value of localDataCenter + */ + public String getLocalDataCenter() { + return localDataCenter; + } - /** - * Getter method for property localRegion. - * - * @return property value of localRegion - */ - public String getLocalRegion() { - return LOCAL_REGION; - } + /** + * Getter method for property localRegion. + * + * @return property value of localRegion + */ + public String getLocalRegion() { + return LOCAL_REGION; + } - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } -} \ No newline at end of file + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerBeanConfiguration.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerBeanConfiguration.java index 6fb3215f1..efcdb2145 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerBeanConfiguration.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerBeanConfiguration.java @@ -55,6 +55,11 @@ import com.alipay.sofa.registry.task.MetricsableThreadPoolExecutor; import com.alipay.sofa.registry.util.NamedThreadFactory; import com.alipay.sofa.registry.util.PropertySplitter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -63,14 +68,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import java.util.ArrayList; -import java.util.Collection; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - /** - * * @author qian.lqlq * @version $Id: DataServerBeanConfiguration.java, v 0.1 2018-01-11 15:08 qian.lqlq Exp $ */ @@ -79,282 +77,285 @@ @EnableConfigurationProperties public class DataServerBeanConfiguration { + @Bean + @ConditionalOnMissingBean + public DataServerBootstrap dataServerBootstrap() { + return new DataServerBootstrap(); + } + + @Configuration + protected static class DataServerBootstrapConfigConfiguration { + + @Bean + public CommonConfig commonConfig() { + return new CommonConfig(); + } + + @Bean + @ConditionalOnMissingBean + public DataServerConfig dataServerConfig(CommonConfig commonConfig) { + return new DataServerConfig(commonConfig); + } + + @Bean(name = "PropertySplitter") + public PropertySplitter propertySplitter() { + return new PropertySplitter(); + } + } + + @Configuration + public static class DataServerStorageConfiguration { + + @Bean + @ConditionalOnMissingBean + public DatumCache datumCache() { + return new DatumCache(); + } + + @Bean + @ConditionalOnMissingBean + public DatumStorage localDatumStorage() { + return new LocalDatumStorage(); + } + + @Bean + @ConditionalOnMissingBean + public SlotManager slotManager() { + return new SlotManagerImpl(); + } + + @Bean + @ConditionalOnMissingBean + public SessionLeaseManager sessionLeaseManager() { + return new SessionLeaseManager(); + } + } + + @Configuration + public static class LogTaskConfigConfiguration { + + @Bean + public CacheDigestTask cacheDigestTask() { + return new CacheDigestTask(); + } + + @Bean + public CacheCountTask cacheCountTask() { + return new CacheCountTask(); + } + } + + @Configuration + public static class SessionRemotingConfiguration { + + @Bean + public Exchange jerseyExchange() { + return new JerseyExchange(); + } + + @Bean + public Exchange boltExchange() { + return new BoltExchange(); + } + + @Bean + public DataNodeExchanger dataNodeExchanger() { + return new DataNodeExchanger(); + } + + @Bean + public SessionNodeExchanger sessionNodeExchanger() { + return new SessionNodeExchanger(); + } + + @Bean + public SessionServerConnectionFactory sessionServerConnectionFactory() { + return new SessionServerConnectionFactory(); + } + + @Bean(name = "serverHandlers") + public Collection serverHandlers() { + Collection list = new ArrayList<>(); + list.add(getDataHandler()); + list.add(batchPutDataHandler()); + list.add(getDataVersionsHandler()); + list.add(dataServerConnectionHandler()); + return list; + } + + @Bean(name = "serverSyncHandlers") + public Collection serverSyncHandlers() { + Collection list = new ArrayList<>(); + list.add(slotFollowerDiffDataInfoIdRequestHandler()); + list.add(slotFollowerDiffPublisherRequestHandler()); + return list; + } + + @Bean(name = "metaClientHandlers") + public Collection metaClientHandlers() { + Collection list = new ArrayList<>(); + list.add(notifyProvideDataChangeHandler()); + list.add(slotTableChangeEventHandler()); + return list; + } + + @Bean + public AbstractServerHandler dataServerConnectionHandler() { + return new DataServerConnectionHandler(); + } + + @Bean + public AbstractServerHandler getDataHandler() { + return new GetDataHandler(); + } + + @Bean + public AbstractServerHandler slotFollowerDiffDataInfoIdRequestHandler() { + return new SlotFollowerDiffDigestRequestHandler(); + } + + @Bean + public AbstractServerHandler slotFollowerDiffPublisherRequestHandler() { + return new SlotFollowerDiffPublisherRequestHandler(); + } + + @Bean + public AbstractServerHandler getDataVersionsHandler() { + return new GetDataVersionsHandler(); + } + + @Bean + public AbstractServerHandler batchPutDataHandler() { + return new BatchPutDataHandler(); + } + + @Bean + public NotifyProvideDataChangeHandler notifyProvideDataChangeHandler() { + return new NotifyProvideDataChangeHandler(); + } + + @Bean + public SlotTableChangeEventHandler slotTableChangeEventHandler() { + return new SlotTableChangeEventHandler(); + } + } + + @Configuration + public static class DataServerEventBeanConfiguration { + + @Bean + public DataChangeEventCenter dataChangeEventCenter() { + return new DataChangeEventCenter(); + } + } + + @Configuration + public static class DataServerRemotingBeanConfiguration { + + @Bean + public MetaServerManager metaServerManager() { + return new DataMetaServerManager(); + } + + @Bean + public MetaServerServiceImpl metaServerService() { + return new MetaServerServiceImpl(); + } + } + + @Configuration + public static class ResourceConfiguration { + + @Bean + public ResourceConfig jerseyResourceConfig() { + ResourceConfig resourceConfig = new ResourceConfig(); + resourceConfig.register(JacksonFeature.class); + return resourceConfig; + } + + @Bean + public HealthResource healthResource() { + return new HealthResource(); + } + + @Bean + public DatumApiResource datumApiResource() { + return new DatumApiResource(); + } + @Bean @ConditionalOnMissingBean - public DataServerBootstrap dataServerBootstrap() { - return new DataServerBootstrap(); + public DataDigestResource dataDigestResource() { + return new DataDigestResource(); } - @Configuration - protected static class DataServerBootstrapConfigConfiguration { - - @Bean - public CommonConfig commonConfig() { - return new CommonConfig(); - } - - @Bean - @ConditionalOnMissingBean - public DataServerConfig dataServerConfig(CommonConfig commonConfig) { - return new DataServerConfig(commonConfig); - } - - @Bean(name = "PropertySplitter") - public PropertySplitter propertySplitter() { - return new PropertySplitter(); - } - - } - - @Configuration - public static class DataServerStorageConfiguration { - - @Bean - @ConditionalOnMissingBean - public DatumCache datumCache() { - return new DatumCache(); - } - - @Bean - @ConditionalOnMissingBean - public DatumStorage localDatumStorage() { - return new LocalDatumStorage(); - } - - @Bean - @ConditionalOnMissingBean - public SlotManager slotManager() { - return new SlotManagerImpl(); - } - - @Bean - @ConditionalOnMissingBean - public SessionLeaseManager sessionLeaseManager() { - return new SessionLeaseManager(); - } - } - - @Configuration - public static class LogTaskConfigConfiguration { - - @Bean - public CacheDigestTask cacheDigestTask() { - return new CacheDigestTask(); - } - - @Bean - public CacheCountTask cacheCountTask() { - return new CacheCountTask(); - } - - } - - @Configuration - public static class SessionRemotingConfiguration { - - @Bean - public Exchange jerseyExchange() { - return new JerseyExchange(); - } - - @Bean - public Exchange boltExchange() { - return new BoltExchange(); - } - - @Bean - public DataNodeExchanger dataNodeExchanger() { - return new DataNodeExchanger(); - } - - @Bean - public SessionNodeExchanger sessionNodeExchanger() { - return new SessionNodeExchanger(); - } - - @Bean - public SessionServerConnectionFactory sessionServerConnectionFactory() { - return new SessionServerConnectionFactory(); - } - - @Bean(name = "serverHandlers") - public Collection serverHandlers() { - Collection list = new ArrayList<>(); - list.add(getDataHandler()); - list.add(batchPutDataHandler()); - list.add(getDataVersionsHandler()); - list.add(dataServerConnectionHandler()); - return list; - } - - @Bean(name = "serverSyncHandlers") - public Collection serverSyncHandlers() { - Collection list = new ArrayList<>(); - list.add(slotFollowerDiffDataInfoIdRequestHandler()); - list.add(slotFollowerDiffPublisherRequestHandler()); - return list; - } - - @Bean(name = "metaClientHandlers") - public Collection metaClientHandlers() { - Collection list = new ArrayList<>(); - list.add(notifyProvideDataChangeHandler()); - list.add(slotTableChangeEventHandler()); - return list; - } - - @Bean - public AbstractServerHandler dataServerConnectionHandler() { - return new DataServerConnectionHandler(); - } - - @Bean - public AbstractServerHandler getDataHandler() { - return new GetDataHandler(); - } - - @Bean - public AbstractServerHandler slotFollowerDiffDataInfoIdRequestHandler() { - return new SlotFollowerDiffDigestRequestHandler(); - } - - @Bean - public AbstractServerHandler slotFollowerDiffPublisherRequestHandler() { - return new SlotFollowerDiffPublisherRequestHandler(); - } - - @Bean - public AbstractServerHandler getDataVersionsHandler() { - return new GetDataVersionsHandler(); - } - - @Bean - public AbstractServerHandler batchPutDataHandler() { - return new BatchPutDataHandler(); - } - - @Bean - public NotifyProvideDataChangeHandler notifyProvideDataChangeHandler() { - return new NotifyProvideDataChangeHandler(); - } - - @Bean - public SlotTableChangeEventHandler slotTableChangeEventHandler() { - return new SlotTableChangeEventHandler(); - } - } - - @Configuration - public static class DataServerEventBeanConfiguration { - - @Bean - public DataChangeEventCenter dataChangeEventCenter() { - return new DataChangeEventCenter(); - } - - } - - @Configuration - public static class DataServerRemotingBeanConfiguration { - - @Bean - public MetaServerManager metaServerManager() { - return new DataMetaServerManager(); - } - - @Bean - public MetaServerServiceImpl metaServerService() { - return new MetaServerServiceImpl(); - } - } - - @Configuration - public static class ResourceConfiguration { - - @Bean - public ResourceConfig jerseyResourceConfig() { - ResourceConfig resourceConfig = new ResourceConfig(); - resourceConfig.register(JacksonFeature.class); - return resourceConfig; - } - - @Bean - public HealthResource healthResource() { - return new HealthResource(); - } - - @Bean - public DatumApiResource datumApiResource() { - return new DatumApiResource(); - } - - @Bean - @ConditionalOnMissingBean - public DataDigestResource dataDigestResource() { - return new DataDigestResource(); - } - - @Bean - public SlotGenericResource slotGenericResource() { - return new SlotGenericResource(); - } - - @Bean - public MetricsResource metricsResource() { - return new MetricsResource(); - } - - } - - @Configuration - public static class ExecutorConfiguration { - - @Bean(name = "publishProcessorExecutor") - public ThreadPoolExecutor publishProcessorExecutor(DataServerConfig dataServerConfig) { - return new MetricsableThreadPoolExecutor("PublishProcessorExecutor", - dataServerConfig.getPublishExecutorMinPoolSize(), - dataServerConfig.getPublishExecutorMaxPoolSize(), 300, TimeUnit.SECONDS, - new ArrayBlockingQueue<>(dataServerConfig.getPublishExecutorQueueSize()), - new NamedThreadFactory("PutExecutor", true)); - } + @Bean + public SlotGenericResource slotGenericResource() { + return new SlotGenericResource(); + } - @Bean(name = "getDataProcessorExecutor") - public ThreadPoolExecutor getDataProcessorExecutor(DataServerConfig dataServerConfig) { - return new MetricsableThreadPoolExecutor("GetDataProcessorExecutor", - dataServerConfig.getGetDataExecutorMinPoolSize(), - dataServerConfig.getGetDataExecutorMaxPoolSize(), - dataServerConfig.getGetDataExecutorKeepAliveTime(), TimeUnit.SECONDS, - new ArrayBlockingQueue<>(dataServerConfig.getGetDataExecutorQueueSize()), - new NamedThreadFactory("GetExecutor", true)); - } + @Bean + public MetricsResource metricsResource() { + return new MetricsResource(); + } + } + + @Configuration + public static class ExecutorConfiguration { + + @Bean(name = "publishProcessorExecutor") + public ThreadPoolExecutor publishProcessorExecutor(DataServerConfig dataServerConfig) { + return new MetricsableThreadPoolExecutor( + "PublishProcessorExecutor", + dataServerConfig.getPublishExecutorMinPoolSize(), + dataServerConfig.getPublishExecutorMaxPoolSize(), + 300, + TimeUnit.SECONDS, + new ArrayBlockingQueue<>(dataServerConfig.getPublishExecutorQueueSize()), + new NamedThreadFactory("PutExecutor", true)); + } - @Bean(name = "slotSyncRequestProcessorExecutor") - public ThreadPoolExecutor slotSyncRequestProcessorExecutor(DataServerConfig dataServerConfig) { - return new MetricsableThreadPoolExecutor("SlotSyncRequestProcessorExecutor", - dataServerConfig.getSlotSyncRequestExecutorMinPoolSize(), - dataServerConfig.getSlotSyncRequestExecutorMaxPoolSize(), 300, TimeUnit.SECONDS, - new ArrayBlockingQueue<>(dataServerConfig.getSlotSyncRequestExecutorQueueSize()), - new NamedThreadFactory("SyncExecutor", true)); - } + @Bean(name = "getDataProcessorExecutor") + public ThreadPoolExecutor getDataProcessorExecutor(DataServerConfig dataServerConfig) { + return new MetricsableThreadPoolExecutor( + "GetDataProcessorExecutor", + dataServerConfig.getGetDataExecutorMinPoolSize(), + dataServerConfig.getGetDataExecutorMaxPoolSize(), + dataServerConfig.getGetDataExecutorKeepAliveTime(), + TimeUnit.SECONDS, + new ArrayBlockingQueue<>(dataServerConfig.getGetDataExecutorQueueSize()), + new NamedThreadFactory("GetExecutor", true)); + } + @Bean(name = "slotSyncRequestProcessorExecutor") + public ThreadPoolExecutor slotSyncRequestProcessorExecutor(DataServerConfig dataServerConfig) { + return new MetricsableThreadPoolExecutor( + "SlotSyncRequestProcessorExecutor", + dataServerConfig.getSlotSyncRequestExecutorMinPoolSize(), + dataServerConfig.getSlotSyncRequestExecutorMaxPoolSize(), + 300, + TimeUnit.SECONDS, + new ArrayBlockingQueue<>(dataServerConfig.getSlotSyncRequestExecutorQueueSize()), + new NamedThreadFactory("SyncExecutor", true)); } + } - @Configuration - public static class DataProvideDataConfiguration { + @Configuration + public static class DataProvideDataConfiguration { - @Bean - public ProvideDataProcessor provideDataProcessorManager() { - return new ProvideDataProcessorManager(); - } + @Bean + public ProvideDataProcessor provideDataProcessorManager() { + return new ProvideDataProcessorManager(); + } - @Bean - public ProvideDataProcessor sessionLeaseProvideDataProcessor(ProvideDataProcessor provideDataProcessorManager) { - ProvideDataProcessor sessionLeaseProvideDataProcessor = new SessionLeaseProvideDataProcessor(); - ((ProvideDataProcessorManager) provideDataProcessorManager) - .addProvideDataProcessor(sessionLeaseProvideDataProcessor); - return sessionLeaseProvideDataProcessor; - } - - } - -} \ No newline at end of file + @Bean + public ProvideDataProcessor sessionLeaseProvideDataProcessor( + ProvideDataProcessor provideDataProcessorManager) { + ProvideDataProcessor sessionLeaseProvideDataProcessor = + new SessionLeaseProvideDataProcessor(); + ((ProvideDataProcessorManager) provideDataProcessorManager) + .addProvideDataProcessor(sessionLeaseProvideDataProcessor); + return sessionLeaseProvideDataProcessor; + } + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerBootstrap.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerBootstrap.java index bc51087e3..21e146b4f 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerBootstrap.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerBootstrap.java @@ -35,20 +35,19 @@ import com.github.rholder.retry.StopStrategies; import com.github.rholder.retry.WaitStrategies; import com.google.common.base.Predicate; -import org.glassfish.jersey.server.ResourceConfig; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.ApplicationContext; - -import javax.annotation.Resource; -import javax.ws.rs.Path; -import javax.ws.rs.ext.Provider; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import javax.annotation.Resource; +import javax.ws.rs.Path; +import javax.ws.rs.ext.Provider; +import org.glassfish.jersey.server.ResourceConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.ApplicationContext; /** * @author qian.lqlq @@ -56,242 +55,227 @@ */ @EnableConfigurationProperties public class DataServerBootstrap { - private static final Logger LOGGER = LoggerFactory - .getLogger(DataServerBootstrap.class); - - @Autowired - private DataServerConfig dataServerConfig; + private static final Logger LOGGER = LoggerFactory.getLogger(DataServerBootstrap.class); - @Autowired - private MetaServerService metaServerService; + @Autowired private DataServerConfig dataServerConfig; - @Autowired - private ApplicationContext applicationContext; + @Autowired private MetaServerService metaServerService; - @Autowired - private ResourceConfig jerseyResourceConfig; + @Autowired private ApplicationContext applicationContext; - @Autowired - private SlotManager slotManager; + @Autowired private ResourceConfig jerseyResourceConfig; - @Autowired - private Exchange jerseyExchange; + @Autowired private SlotManager slotManager; - @Autowired - private Exchange boltExchange; + @Autowired private Exchange jerseyExchange; - @Resource(name = "serverHandlers") - private Collection serverHandlers; + @Autowired private Exchange boltExchange; - @Resource(name = "serverSyncHandlers") - private Collection serverSyncHandlers; + @Resource(name = "serverHandlers") + private Collection serverHandlers; - private Server server; + @Resource(name = "serverSyncHandlers") + private Collection serverSyncHandlers; - private Server dataSyncServer; + private Server server; - private Server httpServer; + private Server dataSyncServer; - private final AtomicBoolean httpServerStarted = new AtomicBoolean(false); + private Server httpServer; - private final AtomicBoolean schedulerStarted = new AtomicBoolean(false); + private final AtomicBoolean httpServerStarted = new AtomicBoolean(false); - private final AtomicBoolean serverForSessionStarted = new AtomicBoolean(false); + private final AtomicBoolean schedulerStarted = new AtomicBoolean(false); - private final AtomicBoolean serverForDataSyncStarted = new AtomicBoolean(false); + private final AtomicBoolean serverForSessionStarted = new AtomicBoolean(false); - private final Retryer retryer = RetryerBuilder - . newBuilder() - .retryIfException() - .retryIfResult(new Predicate() { - @Override - public boolean apply(Boolean input) { - return !input; - } - }) - .withWaitStrategy( - WaitStrategies - .exponentialWait( - 1000, - 10000, - TimeUnit.MILLISECONDS)) - .withStopStrategy( - StopStrategies - .stopAfterAttempt(10)) - .build(); + private final AtomicBoolean serverForDataSyncStarted = new AtomicBoolean(false); - /** - * start dataserver - */ - public void start() { - try { - LOGGER.info("begin start server"); + private final Retryer retryer = + RetryerBuilder.newBuilder() + .retryIfException() + .retryIfResult( + new Predicate() { + @Override + public boolean apply(Boolean input) { + return !input; + } + }) + .withWaitStrategy(WaitStrategies.exponentialWait(1000, 10000, TimeUnit.MILLISECONDS)) + .withStopStrategy(StopStrategies.stopAfterAttempt(10)) + .build(); - LOGGER.info("the configuration items are as follows: " + dataServerConfig.toString()); + /** start dataserver */ + public void start() { + try { + LOGGER.info("begin start server"); - ReporterUtils.enablePrometheusDefaultExports(); + LOGGER.info("the configuration items are as follows: " + dataServerConfig.toString()); - openDataServer(); + ReporterUtils.enablePrometheusDefaultExports(); - openDataSyncServer(); + openDataServer(); - openHttpServer(); + openDataSyncServer(); - renewNode(); - fetchProviderData(); + openHttpServer(); - // wait until slot table is get - retryer.call(() -> { - return slotManager.getSlotTableEpoch() != SlotTable.INIT.getEpoch(); - }); + renewNode(); + fetchProviderData(); - startScheduler(); + // wait until slot table is get + retryer.call( + () -> { + return slotManager.getSlotTableEpoch() != SlotTable.INIT.getEpoch(); + }); + startScheduler(); - Runtime.getRuntime().addShutdownHook(new Thread(this::doStop)); + Runtime.getRuntime().addShutdownHook(new Thread(this::doStop)); - LOGGER.info("start server success"); - } catch (Exception e) { - throw new RuntimeException("start server error", e); - } + LOGGER.info("start server success"); + } catch (Exception e) { + throw new RuntimeException("start server error", e); } - - private void openDataServer() { - try { - if (serverForSessionStarted.compareAndSet(false, true)) { - server = boltExchange.open(new URL(NetUtil.getLocalAddress().getHostAddress(), - dataServerConfig.getPort()), serverHandlers - .toArray(new ChannelHandler[serverHandlers.size()])); - LOGGER.info("Data server for session started! port:{}", dataServerConfig.getPort()); - } - } catch (Exception e) { - serverForSessionStarted.set(false); - LOGGER.error("Data server start error! port:{}", dataServerConfig.getPort(), e); - throw new RuntimeException("Data server start error!", e); - } + } + + private void openDataServer() { + try { + if (serverForSessionStarted.compareAndSet(false, true)) { + server = + boltExchange.open( + new URL(NetUtil.getLocalAddress().getHostAddress(), dataServerConfig.getPort()), + serverHandlers.toArray(new ChannelHandler[serverHandlers.size()])); + LOGGER.info("Data server for session started! port:{}", dataServerConfig.getPort()); + } + } catch (Exception e) { + serverForSessionStarted.set(false); + LOGGER.error("Data server start error! port:{}", dataServerConfig.getPort(), e); + throw new RuntimeException("Data server start error!", e); } - - private void openDataSyncServer() { - try { - if (serverForDataSyncStarted.compareAndSet(false, true)) { - dataSyncServer = boltExchange.open(new URL(NetUtil.getLocalAddress() - .getHostAddress(), dataServerConfig.getSyncDataPort()), serverSyncHandlers - .toArray(new ChannelHandler[serverSyncHandlers.size()])); - LOGGER.info("Data server for sync started! port:{}", - dataServerConfig.getSyncDataPort()); - } - } catch (Exception e) { - serverForDataSyncStarted.set(false); - LOGGER.error("Data sync server start error! port:{}", - dataServerConfig.getSyncDataPort(), e); - throw new RuntimeException("Data sync server start error!", e); - } + } + + private void openDataSyncServer() { + try { + if (serverForDataSyncStarted.compareAndSet(false, true)) { + dataSyncServer = + boltExchange.open( + new URL( + NetUtil.getLocalAddress().getHostAddress(), dataServerConfig.getSyncDataPort()), + serverSyncHandlers.toArray(new ChannelHandler[serverSyncHandlers.size()])); + LOGGER.info("Data server for sync started! port:{}", dataServerConfig.getSyncDataPort()); + } + } catch (Exception e) { + serverForDataSyncStarted.set(false); + LOGGER.error("Data sync server start error! port:{}", dataServerConfig.getSyncDataPort(), e); + throw new RuntimeException("Data sync server start error!", e); } - - private void openHttpServer() { - try { - if (httpServerStarted.compareAndSet(false, true)) { - bindResourceConfig(); - httpServer = jerseyExchange.open( - new URL(NetUtil.getLocalAddress().getHostAddress(), dataServerConfig - .getHttpServerPort()), new ResourceConfig[] { jerseyResourceConfig }); - LOGGER.info("Open http server port {} success!", - dataServerConfig.getHttpServerPort()); - } - } catch (Exception e) { - httpServerStarted.set(false); - LOGGER - .error("Open http server port {} error!", dataServerConfig.getHttpServerPort(), e); - throw new RuntimeException("Open http server error!", e); - } + } + + private void openHttpServer() { + try { + if (httpServerStarted.compareAndSet(false, true)) { + bindResourceConfig(); + httpServer = + jerseyExchange.open( + new URL( + NetUtil.getLocalAddress().getHostAddress(), + dataServerConfig.getHttpServerPort()), + new ResourceConfig[] {jerseyResourceConfig}); + LOGGER.info("Open http server port {} success!", dataServerConfig.getHttpServerPort()); + } + } catch (Exception e) { + httpServerStarted.set(false); + LOGGER.error("Open http server port {} error!", dataServerConfig.getHttpServerPort(), e); + throw new RuntimeException("Open http server error!", e); } - - private void renewNode() { - metaServerService.renewNode(); - metaServerService.startRenewer(dataServerConfig.getSchedulerHeartbeatIntervalSecs() * 1000); - + } + + private void renewNode() { + metaServerService.renewNode(); + metaServerService.startRenewer(dataServerConfig.getSchedulerHeartbeatIntervalSecs() * 1000); + } + + private void fetchProviderData() { + ProvideData provideData = metaServerService.fetchData(ValueConstants.DATA_SESSION_LEASE_SEC); + Integer expireSec = ProvideData.toInteger(provideData); + if (expireSec != null) { + dataServerConfig.setSessionLeaseSecs(expireSec); + LOGGER.info( + "Fetch {}={}, update current config", ValueConstants.DATA_SESSION_LEASE_SEC, expireSec); } - private void fetchProviderData() { - ProvideData provideData = metaServerService - .fetchData(ValueConstants.DATA_SESSION_LEASE_SEC); - Integer expireSec = ProvideData.toInteger(provideData); - if (expireSec != null) { - dataServerConfig.setSessionLeaseSecs(expireSec); - LOGGER.info("Fetch {}={}, update current config", - ValueConstants.DATA_SESSION_LEASE_SEC, expireSec); - } - - provideData = metaServerService - .fetchData(ValueConstants.DATA_DATUM_SYNC_SESSION_INTERVAL_SEC); - Integer syncSessionIntervalSec = ProvideData.toInteger(provideData); - if (syncSessionIntervalSec != null) { - dataServerConfig.setSlotLeaderSyncSessionIntervalSecs(syncSessionIntervalSec); - LOGGER.info("Fetch {}={}, update current config", - ValueConstants.DATA_DATUM_SYNC_SESSION_INTERVAL_SEC, syncSessionIntervalSec); - } + provideData = metaServerService.fetchData(ValueConstants.DATA_DATUM_SYNC_SESSION_INTERVAL_SEC); + Integer syncSessionIntervalSec = ProvideData.toInteger(provideData); + if (syncSessionIntervalSec != null) { + dataServerConfig.setSlotLeaderSyncSessionIntervalSecs(syncSessionIntervalSec); + LOGGER.info( + "Fetch {}={}, update current config", + ValueConstants.DATA_DATUM_SYNC_SESSION_INTERVAL_SEC, + syncSessionIntervalSec); } - - private void startScheduler() { - try { - schedulerStarted.compareAndSet(false, true); - } catch (Exception e) { - schedulerStarted.set(false); - LOGGER.error("Data Scheduler start error!", e); - throw new RuntimeException("Data Scheduler start error!", e); - } + } + + private void startScheduler() { + try { + schedulerStarted.compareAndSet(false, true); + } catch (Exception e) { + schedulerStarted.set(false); + LOGGER.error("Data Scheduler start error!", e); + throw new RuntimeException("Data Scheduler start error!", e); } + } - public void destroy() { - doStop(); - } + public void destroy() { + doStop(); + } - private void doStop() { - try { - LOGGER.info("{} Shutting down Data Server..", new Date().toString()); - - if (httpServer != null && httpServer.isOpen()) { - httpServer.close(); - } - - if (server != null && server.isOpen()) { - server.close(); - } - - if (dataSyncServer != null && dataSyncServer.isOpen()) { - dataSyncServer.close(); - } - } catch (Throwable e) { - LOGGER.error("Shutting down Data Server error!", e); - } - LOGGER.info("{} Data server is now shutdown...", new Date().toString()); - } + private void doStop() { + try { + LOGGER.info("{} Shutting down Data Server..", new Date().toString()); - private void bindResourceConfig() { - registerInstances(Path.class); - registerInstances(Provider.class); - } + if (httpServer != null && httpServer.isOpen()) { + httpServer.close(); + } - private void registerInstances(Class annotationType) { - Map beans = applicationContext.getBeansWithAnnotation(annotationType); - if (beans != null && !beans.isEmpty()) { - beans.forEach((beanName, bean) -> jerseyResourceConfig.registerInstances(bean)); - } - } + if (server != null && server.isOpen()) { + server.close(); + } - public boolean getHttpServerStarted() { - return httpServerStarted.get(); + if (dataSyncServer != null && dataSyncServer.isOpen()) { + dataSyncServer.close(); + } + } catch (Throwable e) { + LOGGER.error("Shutting down Data Server error!", e); } - - public boolean getSchedulerStarted() { - return schedulerStarted.get(); + LOGGER.info("{} Data server is now shutdown...", new Date().toString()); + } + + private void bindResourceConfig() { + registerInstances(Path.class); + registerInstances(Provider.class); + } + + private void registerInstances(Class annotationType) { + Map beans = applicationContext.getBeansWithAnnotation(annotationType); + if (beans != null && !beans.isEmpty()) { + beans.forEach((beanName, bean) -> jerseyResourceConfig.registerInstances(bean)); } + } - public boolean getServerForSessionStarted() { - return serverForSessionStarted.get(); - } + public boolean getHttpServerStarted() { + return httpServerStarted.get(); + } - public boolean getServerForDataSyncStarted() { - return serverForDataSyncStarted.get(); - } + public boolean getSchedulerStarted() { + return schedulerStarted.get(); + } + + public boolean getServerForSessionStarted() { + return serverForSessionStarted.get(); + } + + public boolean getServerForDataSyncStarted() { + return serverForDataSyncStarted.get(); + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerConfig.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerConfig.java index 378b762ee..24ea54478 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerConfig.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerConfig.java @@ -18,12 +18,11 @@ import com.alipay.sofa.registry.server.shared.env.ServerEnv; import com.alipay.sofa.registry.util.OsUtils; +import java.util.Collection; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.springframework.boot.context.properties.ConfigurationProperties; -import java.util.Collection; - /** * @author qian.lqlq * @version $Id: DataServerBootstrapConfig.java, v 0.1 2017-12-06 20:50 qian.lqlq Exp $ @@ -31,742 +30,747 @@ @ConfigurationProperties(prefix = DataServerConfig.PRE_FIX) public class DataServerConfig { - public static final String PRE_FIX = "data.server"; - - private int port = 9620; - - private int syncDataPort = 9621; - private int syncSessionPort = 9602; - - private int metaServerPort = 9611; - - private int httpServerPort = 9622; - - private int notifyExecutorPoolSize = OsUtils - .getCpuCount() * 3; - - private int notifyExecutorQueueSize = 10000; - - private int notifyRetryQueueSize = 10000; - - private int notifyMaxItems = 300; + public static final String PRE_FIX = "data.server"; - private int notifyIntervalMillis = 1000; + private int port = 9620; - private int notifyRetryTimes = 3; + private int syncDataPort = 9621; + private int syncSessionPort = 9602; - private int notifyRetryBackoffMillis = 500; + private int metaServerPort = 9611; - private int notifyTempExecutorPoolSize = OsUtils - .getCpuCount() * 3; + private int httpServerPort = 9622; - private int notifyTempExecutorQueueSize = 4000; - private int notifyTempDataIntervalMillis = 500; + private int notifyExecutorPoolSize = OsUtils.getCpuCount() * 3; - private int rpcTimeoutMillis = 3000; + private int notifyExecutorQueueSize = 10000; - private CommonConfig commonConfig; + private int notifyRetryQueueSize = 10000; - private volatile Collection metaAddresses = null; + private int notifyMaxItems = 300; - private int getDataExecutorMinPoolSize = OsUtils - .getCpuCount() * 5; + private int notifyIntervalMillis = 1000; - private int getDataExecutorMaxPoolSize = OsUtils - .getCpuCount() * 10; + private int notifyRetryTimes = 3; - private int getDataExecutorQueueSize = 20000; + private int notifyRetryBackoffMillis = 500; - private long getDataExecutorKeepAliveTime = 60; + private int notifyTempExecutorPoolSize = OsUtils.getCpuCount() * 3; - private int publishExecutorMinPoolSize = OsUtils - .getCpuCount() * 5; + private int notifyTempExecutorQueueSize = 4000; + private int notifyTempDataIntervalMillis = 500; - private int publishExecutorMaxPoolSize = OsUtils - .getCpuCount() * 10; + private int rpcTimeoutMillis = 3000; - private int publishExecutorQueueSize = 10000; + private CommonConfig commonConfig; - private volatile int sessionLeaseSecs = 30; + private volatile Collection metaAddresses = null; - private int datumCompactDelaySecs = 60 * 3; + private int getDataExecutorMinPoolSize = OsUtils.getCpuCount() * 5; - private int slotLeaderSyncSessionExecutorThreadSize = OsUtils - .getCpuCount() * 3; - private int slotLeaderSyncSessionExecutorQueueSize = 40000; - private volatile int slotLeaderSyncSessionIntervalSecs = 6; + private int getDataExecutorMaxPoolSize = OsUtils.getCpuCount() * 10; - private int slotFollowerSyncLeaderExecutorThreadSize = OsUtils - .getCpuCount(); - private int slotFollowerSyncLeaderExecutorQueueSize = 10000; - private volatile int slotFollowerSyncLeaderIntervalSecs = 60; + private int getDataExecutorQueueSize = 20000; - // the publisher.digest if len(registerId/uuid+long+long), 50bytes - private volatile int slotSyncPublisherDigestMaxNum = 4000; + private long getDataExecutorKeepAliveTime = 60; - private volatile int slotSyncPublisherMaxNum = 512; + private int publishExecutorMinPoolSize = OsUtils.getCpuCount() * 5; - private int slotSyncRequestExecutorMinPoolSize = OsUtils - .getCpuCount() * 3; + private int publishExecutorMaxPoolSize = OsUtils.getCpuCount() * 10; - private int slotSyncRequestExecutorMaxPoolSize = OsUtils - .getCpuCount() * 3; + private int publishExecutorQueueSize = 10000; - private int slotSyncRequestExecutorQueueSize = 1000; + private volatile int sessionLeaseSecs = 30; - private int schedulerHeartbeatIntervalSecs = 1; + private int datumCompactDelaySecs = 60 * 3; - private boolean enableTestApi = false; + private int slotLeaderSyncSessionExecutorThreadSize = OsUtils.getCpuCount() * 3; + private int slotLeaderSyncSessionExecutorQueueSize = 40000; + private volatile int slotLeaderSyncSessionIntervalSecs = 6; - private int cacheDigestIntervalMinutes = 15; + private int slotFollowerSyncLeaderExecutorThreadSize = OsUtils.getCpuCount(); + private int slotFollowerSyncLeaderExecutorQueueSize = 10000; + private volatile int slotFollowerSyncLeaderIntervalSecs = 60; - private int cacheCountIntervalSecs = 30; + // the publisher.digest if len(registerId/uuid+long+long), 50bytes + private volatile int slotSyncPublisherDigestMaxNum = 4000; - /** - * constructor - * - * @param commonConfig - */ - public DataServerConfig(CommonConfig commonConfig) { - this.commonConfig = commonConfig; - } + private volatile int slotSyncPublisherMaxNum = 512; - public boolean isLocalDataCenter(String dataCenter) { - return commonConfig.getLocalDataCenter().equals(dataCenter); - } + private int slotSyncRequestExecutorMinPoolSize = OsUtils.getCpuCount() * 3; - public String getLocalDataCenter() { - return commonConfig.getLocalDataCenter(); - } + private int slotSyncRequestExecutorMaxPoolSize = OsUtils.getCpuCount() * 3; - /** - * Getter method for property port. - * - * @return property value of port - */ - public int getPort() { - return port; - } + private int slotSyncRequestExecutorQueueSize = 1000; - /** - * Setter method for property port. - * - * @param port value to be assigned to property port - */ - public void setPort(int port) { - this.port = port; - } + private int schedulerHeartbeatIntervalSecs = 1; - /** - * Getter method for property syncDataPort. - * - * @return property value of syncDataPort - */ - public int getSyncDataPort() { - return syncDataPort; - } + private boolean enableTestApi = false; - /** - * Setter method for property syncDataPort. - * - * @param syncDataPort value to be assigned to property syncDataPort - */ - public void setSyncDataPort(int syncDataPort) { - this.syncDataPort = syncDataPort; - } + private int cacheDigestIntervalMinutes = 15; - /** - * Getter method for property metaServerPort. - * - * @return property value of metaServerPort - */ - public int getMetaServerPort() { - return metaServerPort; - } + private int cacheCountIntervalSecs = 30; - /** - * Setter method for property metaServerPort. - * - * @param metaServerPort value to be assigned to property metaServerPort - */ - public void setMetaServerPort(int metaServerPort) { - this.metaServerPort = metaServerPort; - } + /** + * constructor + * + * @param commonConfig + */ + public DataServerConfig(CommonConfig commonConfig) { + this.commonConfig = commonConfig; + } - /** - * Getter method for property httpServerPort. - * - * @return property value of httpServerPort - */ - public int getHttpServerPort() { - return httpServerPort; - } + public boolean isLocalDataCenter(String dataCenter) { + return commonConfig.getLocalDataCenter().equals(dataCenter); + } - /** - * Setter method for property httpServerPort. - * - * @param httpServerPort value to be assigned to property httpServerPort - */ - public void setHttpServerPort(int httpServerPort) { - this.httpServerPort = httpServerPort; - } + public String getLocalDataCenter() { + return commonConfig.getLocalDataCenter(); + } - /** - * Getter method for property notifyIntervalMs. - * - * @return property value of notifyIntervalMs - */ - public int getNotifyIntervalMillis() { - return notifyIntervalMillis; - } - - /** - * Setter method for property notifyIntervalMs. - * - * @param notifyIntervalMillis value to be assigned to property notifyIntervalMs - */ - public void setNotifyIntervalMillis(int notifyIntervalMillis) { - this.notifyIntervalMillis = notifyIntervalMillis; - } - - /** - * Getter method for property notifyTempDataIntervalMs. - * - * @return property value of notifyTempDataIntervalMs - */ - public int getNotifyTempDataIntervalMillis() { - return notifyTempDataIntervalMillis; - } - - /** - * Setter method for property notifyTempDataIntervalMs. - * - * @param notifyTempDataIntervalMillis value to be assigned to property notifyTempDataIntervalMs - */ - public void setNotifyTempDataIntervalMillis(int notifyTempDataIntervalMillis) { - this.notifyTempDataIntervalMillis = notifyTempDataIntervalMillis; - } - - /** - * Getter method for property rpcTimeout. - * - * @return property value of rpcTimeout - */ - public int getRpcTimeoutMillis() { - return rpcTimeoutMillis; - } - - /** - * Setter method for property rpcTimeout. - * - * @param rpcTimeoutMillis value to be assigned to property rpcTimeout - */ - public void setRpcTimeoutMillis(int rpcTimeoutMillis) { - this.rpcTimeoutMillis = rpcTimeoutMillis; - } - - /** - * Getter method for property getDataExecutorMinPoolSize. - * - * @return property value of getDataExecutorMinPoolSize - */ - public int getGetDataExecutorMinPoolSize() { - return getDataExecutorMinPoolSize; - } - - /** - * Getter method for property getDataExecutorMaxPoolSize. - * - * @return property value of getDataExecutorMaxPoolSize - */ - public int getGetDataExecutorMaxPoolSize() { - return getDataExecutorMaxPoolSize; - } - - /** - * Getter method for property getDataExecutorQueueSize. - * - * @return property value of getDataExecutorQueueSize - */ - public int getGetDataExecutorQueueSize() { - return getDataExecutorQueueSize; - } - - /** - * Getter method for property getDataExecutorKeepAliveTime. - * - * @return property value of getDataExecutorKeepAliveTime - */ - public long getGetDataExecutorKeepAliveTime() { - return getDataExecutorKeepAliveTime; - } - - /** - * Setter method for property getDataExecutorMinPoolSize. - * - * @param getDataExecutorMinPoolSize value to be assigned to property getDataExecutorMinPoolSize - */ - public void setGetDataExecutorMinPoolSize(int getDataExecutorMinPoolSize) { - this.getDataExecutorMinPoolSize = getDataExecutorMinPoolSize; - } - - /** - * Setter method for property getDataExecutorMaxPoolSize. - * - * @param getDataExecutorMaxPoolSize value to be assigned to property getDataExecutorMaxPoolSize - */ - public void setGetDataExecutorMaxPoolSize(int getDataExecutorMaxPoolSize) { - this.getDataExecutorMaxPoolSize = getDataExecutorMaxPoolSize; - } - - /** - * Setter method for property getDataExecutorQueueSize. - * - * @param getDataExecutorQueueSize value to be assigned to property getDataExecutorQueueSize - */ - public void setGetDataExecutorQueueSize(int getDataExecutorQueueSize) { - this.getDataExecutorQueueSize = getDataExecutorQueueSize; - } - - /** - * Setter method for property getDataExecutorKeepAliveTime. - * - * @param getDataExecutorKeepAliveTime value to be assigned to property getDataExecutorKeepAliveTime - */ - public void setGetDataExecutorKeepAliveTime(long getDataExecutorKeepAliveTime) { - this.getDataExecutorKeepAliveTime = getDataExecutorKeepAliveTime; - } - - /** - * Getter method for property publishExecutorMinPoolSize. - * - * @return property value of publishExecutorMinPoolSize - */ - public int getPublishExecutorMinPoolSize() { - return publishExecutorMinPoolSize; - } - - /** - * Setter method for property publishExecutorMinPoolSize. - * - * @param publishExecutorMinPoolSize value to be assigned to property publishExecutorMinPoolSize - */ - public void setPublishExecutorMinPoolSize(int publishExecutorMinPoolSize) { - this.publishExecutorMinPoolSize = publishExecutorMinPoolSize; - } - - /** - * Getter method for property publishExecutorMaxPoolSize. - * - * @return property value of publishExecutorMaxPoolSize - */ - public int getPublishExecutorMaxPoolSize() { - return publishExecutorMaxPoolSize; - } - - /** - * Setter method for property publishExecutorMaxPoolSize. - * - * @param publishExecutorMaxPoolSize value to be assigned to property publishExecutorMaxPoolSize - */ - public void setPublishExecutorMaxPoolSize(int publishExecutorMaxPoolSize) { - this.publishExecutorMaxPoolSize = publishExecutorMaxPoolSize; - } - - /** - * Getter method for property publishExecutorQueueSize. - * - * @return property value of publishExecutorQueueSize - */ - public int getPublishExecutorQueueSize() { - return publishExecutorQueueSize; - } - - /** - * Setter method for property publishExecutorQueueSize. - * - * @param publishExecutorQueueSize value to be assigned to property publishExecutorQueueSize - */ - public void setPublishExecutorQueueSize(int publishExecutorQueueSize) { - this.publishExecutorQueueSize = publishExecutorQueueSize; - } - - /** - * Getter method for property metaServerIpAddress. - * - * @return property value of metaServerIpAddress - */ - public Collection getMetaServerAddresses() { - final Collection addresses = metaAddresses; - if (addresses != null) { - return addresses; - } - metaAddresses = ServerEnv.getMetaAddresses(commonConfig.getMetaNode(), - commonConfig.getLocalDataCenter()); - return metaAddresses; - } - - /** - * Getter method for property sessionLeaseSec. - * - * @return property value of sessionLeaseSec - */ - public int getSessionLeaseSecs() { - return sessionLeaseSecs; - } - - /** - * Setter method for property sessionLeaseSec. - * - * @param sessionLeaseSecs value to be assigned to property sessionLeaseSec - */ - public void setSessionLeaseSecs(int sessionLeaseSecs) { - this.sessionLeaseSecs = sessionLeaseSecs; - } - - /** - * Getter method for property datumCompactDelaySecs. - * - * @return property value of datumCompactDelaySecs - */ - public int getDatumCompactDelaySecs() { - return datumCompactDelaySecs; - } - - /** - * Setter method for property datumCompactDelaySecs. - * - * @param datumCompactDelaySecs value to be assigned to property datumCompactDelaySecs - */ - public void setDatumCompactDelaySecs(int datumCompactDelaySecs) { - this.datumCompactDelaySecs = datumCompactDelaySecs; - } - - /** - * Getter method for property slotSyncPublisherDigestMaxNum. - * - * @return property value of slotSyncPublisherDigestMaxNum - */ - public int getSlotSyncPublisherDigestMaxNum() { - return slotSyncPublisherDigestMaxNum; - } - - /** - * Setter method for property slotSyncPublisherDigestMaxNum. - * - * @param slotSyncPublisherDigestMaxNum value to be assigned to property slotSyncPublisherDigestMaxNum - */ - public void setSlotSyncPublisherDigestMaxNum(int slotSyncPublisherDigestMaxNum) { - this.slotSyncPublisherDigestMaxNum = slotSyncPublisherDigestMaxNum; - } - - /** - * Getter method for property slotSyncPublisherMaxNum. - * - * @return property value of slotSyncPublisherMaxNum - */ - public int getSlotSyncPublisherMaxNum() { - return slotSyncPublisherMaxNum; - } - - /** - * Setter method for property slotSyncPublisherMaxNum. - * - * @param slotSyncPublisherMaxNum value to be assigned to property slotSyncPublisherMaxNum - */ - public void setSlotSyncPublisherMaxNum(int slotSyncPublisherMaxNum) { - this.slotSyncPublisherMaxNum = slotSyncPublisherMaxNum; - } - - /** - * Getter method for property slotLeaderSyncSessionExecutorThreadSize. - * - * @return property value of slotLeaderSyncSessionExecutorThreadSize - */ - public int getSlotLeaderSyncSessionExecutorThreadSize() { - return slotLeaderSyncSessionExecutorThreadSize; - } - - /** - * Setter method for property slotLeaderSyncSessionExecutorThreadSize. - * - * @param slotLeaderSyncSessionExecutorThreadSize value to be assigned to property slotLeaderSyncSessionExecutorThreadSize - */ - public void setSlotLeaderSyncSessionExecutorThreadSize(int slotLeaderSyncSessionExecutorThreadSize) { - this.slotLeaderSyncSessionExecutorThreadSize = slotLeaderSyncSessionExecutorThreadSize; - } - - /** - * Getter method for property slotLeaderSyncSessionIntervalMs. - * - * @return property value of slotLeaderSyncSessionIntervalMs - */ - public int getSlotLeaderSyncSessionIntervalSecs() { - return slotLeaderSyncSessionIntervalSecs; - } - - /** - * Setter method for property slotLeaderSyncSessionIntervalSec. - * - * @param slotLeaderSyncSessionIntervalSecs value to be assigned to property slotLeaderSyncSessionIntervalSec - */ - public void setSlotLeaderSyncSessionIntervalSecs(int slotLeaderSyncSessionIntervalSecs) { - this.slotLeaderSyncSessionIntervalSecs = slotLeaderSyncSessionIntervalSecs; - } - - /** - * Getter method for property slotFollowerSyncLeaderExecutorThreadSize. - * - * @return property value of slotFollowerSyncLeaderExecutorThreadSize - */ - public int getSlotFollowerSyncLeaderExecutorThreadSize() { - return slotFollowerSyncLeaderExecutorThreadSize; - } - - /** - * Setter method for property slotFollowerSyncLeaderExecutorThreadSize. - * - * @param slotFollowerSyncLeaderExecutorThreadSize value to be assigned to property slotFollowerSyncLeaderExecutorThreadSize - */ - public void setSlotFollowerSyncLeaderExecutorThreadSize(int slotFollowerSyncLeaderExecutorThreadSize) { - this.slotFollowerSyncLeaderExecutorThreadSize = slotFollowerSyncLeaderExecutorThreadSize; - } - - /** - * Getter method for property slotFollowerSyncLeaderIntervalSec. - * - * @return property value of slotFollowerSyncLeaderIntervalSec - */ - public int getSlotFollowerSyncLeaderIntervalSecs() { - return slotFollowerSyncLeaderIntervalSecs; - } - - /** - * Setter method for property slotFollowerSyncLeaderIntervalSec. - * - * @param slotFollowerSyncLeaderIntervalSecs value to be assigned to property slotFollowerSyncLeaderIntervalSec - */ - public void setSlotFollowerSyncLeaderIntervalSecs(int slotFollowerSyncLeaderIntervalSecs) { - this.slotFollowerSyncLeaderIntervalSecs = slotFollowerSyncLeaderIntervalSecs; - } - - /** - * Getter method for property slotLeaderSyncSessionExecutorQueueSize. - * - * @return property value of slotLeaderSyncSessionExecutorQueueSize - */ - public int getSlotLeaderSyncSessionExecutorQueueSize() { - return slotLeaderSyncSessionExecutorQueueSize; - } - - /** - * Setter method for property slotLeaderSyncSessionExecutorQueueSize. - * - * @param slotLeaderSyncSessionExecutorQueueSize value to be assigned to property slotLeaderSyncSessionExecutorQueueSize - */ - public void setSlotLeaderSyncSessionExecutorQueueSize(int slotLeaderSyncSessionExecutorQueueSize) { - this.slotLeaderSyncSessionExecutorQueueSize = slotLeaderSyncSessionExecutorQueueSize; - } - - /** - * Getter method for property slotFollowerSyncLeaderExecutorQueueSize. - * - * @return property value of slotFollowerSyncLeaderExecutorQueueSize - */ - public int getSlotFollowerSyncLeaderExecutorQueueSize() { - return slotFollowerSyncLeaderExecutorQueueSize; - } - - /** - * Setter method for property slotFollowerSyncLeaderExecutorQueueSize. - * - * @param slotFollowerSyncLeaderExecutorQueueSize value to be assigned to property slotFollowerSyncLeaderExecutorQueueSize - */ - public void setSlotFollowerSyncLeaderExecutorQueueSize(int slotFollowerSyncLeaderExecutorQueueSize) { - this.slotFollowerSyncLeaderExecutorQueueSize = slotFollowerSyncLeaderExecutorQueueSize; - } - - /** - * Getter method for property slotSyncRequestExecutorMinPoolSize. - * - * @return property value of slotSyncRequestExecutorMinPoolSize - */ - public int getSlotSyncRequestExecutorMinPoolSize() { - return slotSyncRequestExecutorMinPoolSize; - } - - /** - * Setter method for property slotSyncRequestExecutorMinPoolSize. - * - * @param slotSyncRequestExecutorMinPoolSize value to be assigned to property slotSyncRequestExecutorMinPoolSize - */ - public void setSlotSyncRequestExecutorMinPoolSize(int slotSyncRequestExecutorMinPoolSize) { - this.slotSyncRequestExecutorMinPoolSize = slotSyncRequestExecutorMinPoolSize; - } - - /** - * Getter method for property slotSyncRequestExecutorMaxPoolSize. - * - * @return property value of slotSyncRequestExecutorMaxPoolSize - */ - public int getSlotSyncRequestExecutorMaxPoolSize() { - return slotSyncRequestExecutorMaxPoolSize; - } - - /** - * Setter method for property slotSyncRequestExecutorMaxPoolSize. - * - * @param slotSyncRequestExecutorMaxPoolSize value to be assigned to property slotSyncRequestExecutorMaxPoolSize - */ - public void setSlotSyncRequestExecutorMaxPoolSize(int slotSyncRequestExecutorMaxPoolSize) { - this.slotSyncRequestExecutorMaxPoolSize = slotSyncRequestExecutorMaxPoolSize; - } - - /** - * Getter method for property slotSyncRequestExecutorQueueSize. - * - * @return property value of slotSyncRequestExecutorQueueSize - */ - public int getSlotSyncRequestExecutorQueueSize() { - return slotSyncRequestExecutorQueueSize; - } - - /** - * Setter method for property slotSyncRequestExecutorQueueSize. - * - * @param slotSyncRequestExecutorQueueSize value to be assigned to property slotSyncRequestExecutorQueueSize - */ - public void setSlotSyncRequestExecutorQueueSize(int slotSyncRequestExecutorQueueSize) { - this.slotSyncRequestExecutorQueueSize = slotSyncRequestExecutorQueueSize; - } - - /** - * Getter method for property schedulerHeartbeatIntervalSec. - * - * @return property value of schedulerHeartbeatIntervalSec - */ - public int getSchedulerHeartbeatIntervalSecs() { - return schedulerHeartbeatIntervalSecs; - } - - /** - * Setter method for property schedulerHeartbeatIntervalSec. - * - * @param schedulerHeartbeatIntervalSecs value to be assigned to property schedulerHeartbeatIntervalSec - */ - public void setSchedulerHeartbeatIntervalSecs(int schedulerHeartbeatIntervalSecs) { - this.schedulerHeartbeatIntervalSecs = schedulerHeartbeatIntervalSecs; - } - - /** - * Getter method for property syncSessionPort. - * - * @return property value of syncSessionPort - */ - public int getSyncSessionPort() { - return syncSessionPort; - } - - /** - * Setter method for property syncSessionPort. - * - * @param syncSessionPort value to be assigned to property syncSessionPort - */ - public void setSyncSessionPort(int syncSessionPort) { - this.syncSessionPort = syncSessionPort; - } - - public boolean isEnableTestApi() { - return enableTestApi; - } - - public void setEnableTestApi(boolean enableTestApi) { - this.enableTestApi = enableTestApi; - } - - public int getNotifyMaxItems() { - return notifyMaxItems; - } - - public void setNotifyMaxItems(int notifyMaxItems) { - this.notifyMaxItems = notifyMaxItems; - } - - public int getNotifyExecutorPoolSize() { - return notifyExecutorPoolSize; - } - - public void setNotifyExecutorPoolSize(int notifyExecutorPoolSize) { - this.notifyExecutorPoolSize = notifyExecutorPoolSize; - } - - public int getNotifyExecutorQueueSize() { - return notifyExecutorQueueSize; - } - - public void setNotifyExecutorQueueSize(int notifyExecutorQueueSize) { - this.notifyExecutorQueueSize = notifyExecutorQueueSize; - } - - public int getNotifyTempExecutorPoolSize() { - return notifyTempExecutorPoolSize; - } - - public void setNotifyTempExecutorPoolSize(int notifyTempExecutorPoolSize) { - this.notifyTempExecutorPoolSize = notifyTempExecutorPoolSize; - } - - public int getNotifyTempExecutorQueueSize() { - return notifyTempExecutorQueueSize; - } - - public void setNotifyTempExecutorQueueSize(int notifyTempExecutorQueueSize) { - this.notifyTempExecutorQueueSize = notifyTempExecutorQueueSize; - } - - public int getNotifyRetryQueueSize() { - return notifyRetryQueueSize; - } - - public void setNotifyRetryQueueSize(int notifyRetryQueueSize) { - this.notifyRetryQueueSize = notifyRetryQueueSize; - } - - public int getNotifyRetryTimes() { - return notifyRetryTimes; - } - - public void setNotifyRetryTimes(int notifyRetryTimes) { - this.notifyRetryTimes = notifyRetryTimes; - } - - public int getCacheDigestIntervalMinutes() { - return cacheDigestIntervalMinutes; - } - - public void setCacheDigestIntervalMinutes(int cacheDigestIntervalMinutes) { - this.cacheDigestIntervalMinutes = cacheDigestIntervalMinutes; - } - - public int getCacheCountIntervalSecs() { - return cacheCountIntervalSecs; - } - - public void setCacheCountIntervalSecs(int cacheCountIntervalSecs) { - this.cacheCountIntervalSecs = cacheCountIntervalSecs; - } - - public int getNotifyRetryBackoffMillis() { - return notifyRetryBackoffMillis; - } - - public void setNotifyRetryBackoffMillis(int notifyRetryBackoffMillis) { - this.notifyRetryBackoffMillis = notifyRetryBackoffMillis; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } + /** + * Getter method for property port. + * + * @return property value of port + */ + public int getPort() { + return port; + } + /** + * Setter method for property port. + * + * @param port value to be assigned to property port + */ + public void setPort(int port) { + this.port = port; + } + + /** + * Getter method for property syncDataPort. + * + * @return property value of syncDataPort + */ + public int getSyncDataPort() { + return syncDataPort; + } + + /** + * Setter method for property syncDataPort. + * + * @param syncDataPort value to be assigned to property syncDataPort + */ + public void setSyncDataPort(int syncDataPort) { + this.syncDataPort = syncDataPort; + } + + /** + * Getter method for property metaServerPort. + * + * @return property value of metaServerPort + */ + public int getMetaServerPort() { + return metaServerPort; + } + + /** + * Setter method for property metaServerPort. + * + * @param metaServerPort value to be assigned to property metaServerPort + */ + public void setMetaServerPort(int metaServerPort) { + this.metaServerPort = metaServerPort; + } + + /** + * Getter method for property httpServerPort. + * + * @return property value of httpServerPort + */ + public int getHttpServerPort() { + return httpServerPort; + } + + /** + * Setter method for property httpServerPort. + * + * @param httpServerPort value to be assigned to property httpServerPort + */ + public void setHttpServerPort(int httpServerPort) { + this.httpServerPort = httpServerPort; + } + + /** + * Getter method for property notifyIntervalMs. + * + * @return property value of notifyIntervalMs + */ + public int getNotifyIntervalMillis() { + return notifyIntervalMillis; + } + + /** + * Setter method for property notifyIntervalMs. + * + * @param notifyIntervalMillis value to be assigned to property notifyIntervalMs + */ + public void setNotifyIntervalMillis(int notifyIntervalMillis) { + this.notifyIntervalMillis = notifyIntervalMillis; + } + + /** + * Getter method for property notifyTempDataIntervalMs. + * + * @return property value of notifyTempDataIntervalMs + */ + public int getNotifyTempDataIntervalMillis() { + return notifyTempDataIntervalMillis; + } + + /** + * Setter method for property notifyTempDataIntervalMs. + * + * @param notifyTempDataIntervalMillis value to be assigned to property notifyTempDataIntervalMs + */ + public void setNotifyTempDataIntervalMillis(int notifyTempDataIntervalMillis) { + this.notifyTempDataIntervalMillis = notifyTempDataIntervalMillis; + } + + /** + * Getter method for property rpcTimeout. + * + * @return property value of rpcTimeout + */ + public int getRpcTimeoutMillis() { + return rpcTimeoutMillis; + } + + /** + * Setter method for property rpcTimeout. + * + * @param rpcTimeoutMillis value to be assigned to property rpcTimeout + */ + public void setRpcTimeoutMillis(int rpcTimeoutMillis) { + this.rpcTimeoutMillis = rpcTimeoutMillis; + } + + /** + * Getter method for property getDataExecutorMinPoolSize. + * + * @return property value of getDataExecutorMinPoolSize + */ + public int getGetDataExecutorMinPoolSize() { + return getDataExecutorMinPoolSize; + } + + /** + * Getter method for property getDataExecutorMaxPoolSize. + * + * @return property value of getDataExecutorMaxPoolSize + */ + public int getGetDataExecutorMaxPoolSize() { + return getDataExecutorMaxPoolSize; + } + + /** + * Getter method for property getDataExecutorQueueSize. + * + * @return property value of getDataExecutorQueueSize + */ + public int getGetDataExecutorQueueSize() { + return getDataExecutorQueueSize; + } + + /** + * Getter method for property getDataExecutorKeepAliveTime. + * + * @return property value of getDataExecutorKeepAliveTime + */ + public long getGetDataExecutorKeepAliveTime() { + return getDataExecutorKeepAliveTime; + } + + /** + * Setter method for property getDataExecutorMinPoolSize. + * + * @param getDataExecutorMinPoolSize value to be assigned to property getDataExecutorMinPoolSize + */ + public void setGetDataExecutorMinPoolSize(int getDataExecutorMinPoolSize) { + this.getDataExecutorMinPoolSize = getDataExecutorMinPoolSize; + } + + /** + * Setter method for property getDataExecutorMaxPoolSize. + * + * @param getDataExecutorMaxPoolSize value to be assigned to property getDataExecutorMaxPoolSize + */ + public void setGetDataExecutorMaxPoolSize(int getDataExecutorMaxPoolSize) { + this.getDataExecutorMaxPoolSize = getDataExecutorMaxPoolSize; + } + + /** + * Setter method for property getDataExecutorQueueSize. + * + * @param getDataExecutorQueueSize value to be assigned to property getDataExecutorQueueSize + */ + public void setGetDataExecutorQueueSize(int getDataExecutorQueueSize) { + this.getDataExecutorQueueSize = getDataExecutorQueueSize; + } + + /** + * Setter method for property getDataExecutorKeepAliveTime. + * + * @param getDataExecutorKeepAliveTime value to be assigned to property + * getDataExecutorKeepAliveTime + */ + public void setGetDataExecutorKeepAliveTime(long getDataExecutorKeepAliveTime) { + this.getDataExecutorKeepAliveTime = getDataExecutorKeepAliveTime; + } + + /** + * Getter method for property publishExecutorMinPoolSize. + * + * @return property value of publishExecutorMinPoolSize + */ + public int getPublishExecutorMinPoolSize() { + return publishExecutorMinPoolSize; + } + + /** + * Setter method for property publishExecutorMinPoolSize. + * + * @param publishExecutorMinPoolSize value to be assigned to property publishExecutorMinPoolSize + */ + public void setPublishExecutorMinPoolSize(int publishExecutorMinPoolSize) { + this.publishExecutorMinPoolSize = publishExecutorMinPoolSize; + } + + /** + * Getter method for property publishExecutorMaxPoolSize. + * + * @return property value of publishExecutorMaxPoolSize + */ + public int getPublishExecutorMaxPoolSize() { + return publishExecutorMaxPoolSize; + } + + /** + * Setter method for property publishExecutorMaxPoolSize. + * + * @param publishExecutorMaxPoolSize value to be assigned to property publishExecutorMaxPoolSize + */ + public void setPublishExecutorMaxPoolSize(int publishExecutorMaxPoolSize) { + this.publishExecutorMaxPoolSize = publishExecutorMaxPoolSize; + } + + /** + * Getter method for property publishExecutorQueueSize. + * + * @return property value of publishExecutorQueueSize + */ + public int getPublishExecutorQueueSize() { + return publishExecutorQueueSize; + } + + /** + * Setter method for property publishExecutorQueueSize. + * + * @param publishExecutorQueueSize value to be assigned to property publishExecutorQueueSize + */ + public void setPublishExecutorQueueSize(int publishExecutorQueueSize) { + this.publishExecutorQueueSize = publishExecutorQueueSize; + } + + /** + * Getter method for property metaServerIpAddress. + * + * @return property value of metaServerIpAddress + */ + public Collection getMetaServerAddresses() { + final Collection addresses = metaAddresses; + if (addresses != null) { + return addresses; + } + metaAddresses = + ServerEnv.getMetaAddresses(commonConfig.getMetaNode(), commonConfig.getLocalDataCenter()); + return metaAddresses; + } + + /** + * Getter method for property sessionLeaseSec. + * + * @return property value of sessionLeaseSec + */ + public int getSessionLeaseSecs() { + return sessionLeaseSecs; + } + + /** + * Setter method for property sessionLeaseSec. + * + * @param sessionLeaseSecs value to be assigned to property sessionLeaseSec + */ + public void setSessionLeaseSecs(int sessionLeaseSecs) { + this.sessionLeaseSecs = sessionLeaseSecs; + } + + /** + * Getter method for property datumCompactDelaySecs. + * + * @return property value of datumCompactDelaySecs + */ + public int getDatumCompactDelaySecs() { + return datumCompactDelaySecs; + } + + /** + * Setter method for property datumCompactDelaySecs. + * + * @param datumCompactDelaySecs value to be assigned to property datumCompactDelaySecs + */ + public void setDatumCompactDelaySecs(int datumCompactDelaySecs) { + this.datumCompactDelaySecs = datumCompactDelaySecs; + } + + /** + * Getter method for property slotSyncPublisherDigestMaxNum. + * + * @return property value of slotSyncPublisherDigestMaxNum + */ + public int getSlotSyncPublisherDigestMaxNum() { + return slotSyncPublisherDigestMaxNum; + } + + /** + * Setter method for property slotSyncPublisherDigestMaxNum. + * + * @param slotSyncPublisherDigestMaxNum value to be assigned to property + * slotSyncPublisherDigestMaxNum + */ + public void setSlotSyncPublisherDigestMaxNum(int slotSyncPublisherDigestMaxNum) { + this.slotSyncPublisherDigestMaxNum = slotSyncPublisherDigestMaxNum; + } + + /** + * Getter method for property slotSyncPublisherMaxNum. + * + * @return property value of slotSyncPublisherMaxNum + */ + public int getSlotSyncPublisherMaxNum() { + return slotSyncPublisherMaxNum; + } + + /** + * Setter method for property slotSyncPublisherMaxNum. + * + * @param slotSyncPublisherMaxNum value to be assigned to property slotSyncPublisherMaxNum + */ + public void setSlotSyncPublisherMaxNum(int slotSyncPublisherMaxNum) { + this.slotSyncPublisherMaxNum = slotSyncPublisherMaxNum; + } + + /** + * Getter method for property slotLeaderSyncSessionExecutorThreadSize. + * + * @return property value of slotLeaderSyncSessionExecutorThreadSize + */ + public int getSlotLeaderSyncSessionExecutorThreadSize() { + return slotLeaderSyncSessionExecutorThreadSize; + } + + /** + * Setter method for property slotLeaderSyncSessionExecutorThreadSize. + * + * @param slotLeaderSyncSessionExecutorThreadSize value to be assigned to property + * slotLeaderSyncSessionExecutorThreadSize + */ + public void setSlotLeaderSyncSessionExecutorThreadSize( + int slotLeaderSyncSessionExecutorThreadSize) { + this.slotLeaderSyncSessionExecutorThreadSize = slotLeaderSyncSessionExecutorThreadSize; + } + + /** + * Getter method for property slotLeaderSyncSessionIntervalMs. + * + * @return property value of slotLeaderSyncSessionIntervalMs + */ + public int getSlotLeaderSyncSessionIntervalSecs() { + return slotLeaderSyncSessionIntervalSecs; + } + + /** + * Setter method for property slotLeaderSyncSessionIntervalSec. + * + * @param slotLeaderSyncSessionIntervalSecs value to be assigned to property + * slotLeaderSyncSessionIntervalSec + */ + public void setSlotLeaderSyncSessionIntervalSecs(int slotLeaderSyncSessionIntervalSecs) { + this.slotLeaderSyncSessionIntervalSecs = slotLeaderSyncSessionIntervalSecs; + } + + /** + * Getter method for property slotFollowerSyncLeaderExecutorThreadSize. + * + * @return property value of slotFollowerSyncLeaderExecutorThreadSize + */ + public int getSlotFollowerSyncLeaderExecutorThreadSize() { + return slotFollowerSyncLeaderExecutorThreadSize; + } + + /** + * Setter method for property slotFollowerSyncLeaderExecutorThreadSize. + * + * @param slotFollowerSyncLeaderExecutorThreadSize value to be assigned to property + * slotFollowerSyncLeaderExecutorThreadSize + */ + public void setSlotFollowerSyncLeaderExecutorThreadSize( + int slotFollowerSyncLeaderExecutorThreadSize) { + this.slotFollowerSyncLeaderExecutorThreadSize = slotFollowerSyncLeaderExecutorThreadSize; + } + + /** + * Getter method for property slotFollowerSyncLeaderIntervalSec. + * + * @return property value of slotFollowerSyncLeaderIntervalSec + */ + public int getSlotFollowerSyncLeaderIntervalSecs() { + return slotFollowerSyncLeaderIntervalSecs; + } + + /** + * Setter method for property slotFollowerSyncLeaderIntervalSec. + * + * @param slotFollowerSyncLeaderIntervalSecs value to be assigned to property + * slotFollowerSyncLeaderIntervalSec + */ + public void setSlotFollowerSyncLeaderIntervalSecs(int slotFollowerSyncLeaderIntervalSecs) { + this.slotFollowerSyncLeaderIntervalSecs = slotFollowerSyncLeaderIntervalSecs; + } + + /** + * Getter method for property slotLeaderSyncSessionExecutorQueueSize. + * + * @return property value of slotLeaderSyncSessionExecutorQueueSize + */ + public int getSlotLeaderSyncSessionExecutorQueueSize() { + return slotLeaderSyncSessionExecutorQueueSize; + } + + /** + * Setter method for property slotLeaderSyncSessionExecutorQueueSize. + * + * @param slotLeaderSyncSessionExecutorQueueSize value to be assigned to property + * slotLeaderSyncSessionExecutorQueueSize + */ + public void setSlotLeaderSyncSessionExecutorQueueSize( + int slotLeaderSyncSessionExecutorQueueSize) { + this.slotLeaderSyncSessionExecutorQueueSize = slotLeaderSyncSessionExecutorQueueSize; + } + + /** + * Getter method for property slotFollowerSyncLeaderExecutorQueueSize. + * + * @return property value of slotFollowerSyncLeaderExecutorQueueSize + */ + public int getSlotFollowerSyncLeaderExecutorQueueSize() { + return slotFollowerSyncLeaderExecutorQueueSize; + } + + /** + * Setter method for property slotFollowerSyncLeaderExecutorQueueSize. + * + * @param slotFollowerSyncLeaderExecutorQueueSize value to be assigned to property + * slotFollowerSyncLeaderExecutorQueueSize + */ + public void setSlotFollowerSyncLeaderExecutorQueueSize( + int slotFollowerSyncLeaderExecutorQueueSize) { + this.slotFollowerSyncLeaderExecutorQueueSize = slotFollowerSyncLeaderExecutorQueueSize; + } + + /** + * Getter method for property slotSyncRequestExecutorMinPoolSize. + * + * @return property value of slotSyncRequestExecutorMinPoolSize + */ + public int getSlotSyncRequestExecutorMinPoolSize() { + return slotSyncRequestExecutorMinPoolSize; + } + + /** + * Setter method for property slotSyncRequestExecutorMinPoolSize. + * + * @param slotSyncRequestExecutorMinPoolSize value to be assigned to property + * slotSyncRequestExecutorMinPoolSize + */ + public void setSlotSyncRequestExecutorMinPoolSize(int slotSyncRequestExecutorMinPoolSize) { + this.slotSyncRequestExecutorMinPoolSize = slotSyncRequestExecutorMinPoolSize; + } + + /** + * Getter method for property slotSyncRequestExecutorMaxPoolSize. + * + * @return property value of slotSyncRequestExecutorMaxPoolSize + */ + public int getSlotSyncRequestExecutorMaxPoolSize() { + return slotSyncRequestExecutorMaxPoolSize; + } + + /** + * Setter method for property slotSyncRequestExecutorMaxPoolSize. + * + * @param slotSyncRequestExecutorMaxPoolSize value to be assigned to property + * slotSyncRequestExecutorMaxPoolSize + */ + public void setSlotSyncRequestExecutorMaxPoolSize(int slotSyncRequestExecutorMaxPoolSize) { + this.slotSyncRequestExecutorMaxPoolSize = slotSyncRequestExecutorMaxPoolSize; + } + + /** + * Getter method for property slotSyncRequestExecutorQueueSize. + * + * @return property value of slotSyncRequestExecutorQueueSize + */ + public int getSlotSyncRequestExecutorQueueSize() { + return slotSyncRequestExecutorQueueSize; + } + + /** + * Setter method for property slotSyncRequestExecutorQueueSize. + * + * @param slotSyncRequestExecutorQueueSize value to be assigned to property + * slotSyncRequestExecutorQueueSize + */ + public void setSlotSyncRequestExecutorQueueSize(int slotSyncRequestExecutorQueueSize) { + this.slotSyncRequestExecutorQueueSize = slotSyncRequestExecutorQueueSize; + } + + /** + * Getter method for property schedulerHeartbeatIntervalSec. + * + * @return property value of schedulerHeartbeatIntervalSec + */ + public int getSchedulerHeartbeatIntervalSecs() { + return schedulerHeartbeatIntervalSecs; + } + + /** + * Setter method for property schedulerHeartbeatIntervalSec. + * + * @param schedulerHeartbeatIntervalSecs value to be assigned to property + * schedulerHeartbeatIntervalSec + */ + public void setSchedulerHeartbeatIntervalSecs(int schedulerHeartbeatIntervalSecs) { + this.schedulerHeartbeatIntervalSecs = schedulerHeartbeatIntervalSecs; + } + + /** + * Getter method for property syncSessionPort. + * + * @return property value of syncSessionPort + */ + public int getSyncSessionPort() { + return syncSessionPort; + } + + /** + * Setter method for property syncSessionPort. + * + * @param syncSessionPort value to be assigned to property syncSessionPort + */ + public void setSyncSessionPort(int syncSessionPort) { + this.syncSessionPort = syncSessionPort; + } + + public boolean isEnableTestApi() { + return enableTestApi; + } + + public void setEnableTestApi(boolean enableTestApi) { + this.enableTestApi = enableTestApi; + } + + public int getNotifyMaxItems() { + return notifyMaxItems; + } + + public void setNotifyMaxItems(int notifyMaxItems) { + this.notifyMaxItems = notifyMaxItems; + } + + public int getNotifyExecutorPoolSize() { + return notifyExecutorPoolSize; + } + + public void setNotifyExecutorPoolSize(int notifyExecutorPoolSize) { + this.notifyExecutorPoolSize = notifyExecutorPoolSize; + } + + public int getNotifyExecutorQueueSize() { + return notifyExecutorQueueSize; + } + + public void setNotifyExecutorQueueSize(int notifyExecutorQueueSize) { + this.notifyExecutorQueueSize = notifyExecutorQueueSize; + } + + public int getNotifyTempExecutorPoolSize() { + return notifyTempExecutorPoolSize; + } + + public void setNotifyTempExecutorPoolSize(int notifyTempExecutorPoolSize) { + this.notifyTempExecutorPoolSize = notifyTempExecutorPoolSize; + } + + public int getNotifyTempExecutorQueueSize() { + return notifyTempExecutorQueueSize; + } + + public void setNotifyTempExecutorQueueSize(int notifyTempExecutorQueueSize) { + this.notifyTempExecutorQueueSize = notifyTempExecutorQueueSize; + } + + public int getNotifyRetryQueueSize() { + return notifyRetryQueueSize; + } + + public void setNotifyRetryQueueSize(int notifyRetryQueueSize) { + this.notifyRetryQueueSize = notifyRetryQueueSize; + } + + public int getNotifyRetryTimes() { + return notifyRetryTimes; + } + + public void setNotifyRetryTimes(int notifyRetryTimes) { + this.notifyRetryTimes = notifyRetryTimes; + } + + public int getCacheDigestIntervalMinutes() { + return cacheDigestIntervalMinutes; + } + + public void setCacheDigestIntervalMinutes(int cacheDigestIntervalMinutes) { + this.cacheDigestIntervalMinutes = cacheDigestIntervalMinutes; + } + + public int getCacheCountIntervalSecs() { + return cacheCountIntervalSecs; + } + + public void setCacheCountIntervalSecs(int cacheCountIntervalSecs) { + this.cacheCountIntervalSecs = cacheCountIntervalSecs; + } + + public int getNotifyRetryBackoffMillis() { + return notifyRetryBackoffMillis; + } + + public void setNotifyRetryBackoffMillis(int notifyRetryBackoffMillis) { + this.notifyRetryBackoffMillis = notifyRetryBackoffMillis; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerInitializer.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerInitializer.java index 322d5c0d4..34175c7a3 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerInitializer.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/DataServerInitializer.java @@ -26,48 +26,47 @@ * @version $Id: DataServerInitializer.java, v 0.1 2018年01月04日 11:08 qian.lqlq Exp $ */ public class DataServerInitializer implements SmartLifecycle { - private static final Logger LOGGER = LoggerFactory.getLogger(DataServerInitializer.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DataServerInitializer.class); - @Autowired - private DataServerBootstrap dataServerBootstrap; + @Autowired private DataServerBootstrap dataServerBootstrap; - private volatile boolean isRunning; + private volatile boolean isRunning; - @Override - public boolean isAutoStartup() { - return true; - } + @Override + public boolean isAutoStartup() { + return true; + } - @Override - public void stop(Runnable runnable) { - runnable.run(); - this.isRunning = false; - } + @Override + public void stop(Runnable runnable) { + runnable.run(); + this.isRunning = false; + } - @Override - public void start() { - try { - dataServerBootstrap.start(); - this.isRunning = true; - } catch (Throwable ex) { - this.isRunning = false; - LOGGER.error("Could not initalized Data server", ex); - System.exit(-1); - } + @Override + public void start() { + try { + dataServerBootstrap.start(); + this.isRunning = true; + } catch (Throwable ex) { + this.isRunning = false; + LOGGER.error("Could not initalized Data server", ex); + System.exit(-1); } + } - @Override - public void stop() { - this.isRunning = false; - } + @Override + public void stop() { + this.isRunning = false; + } - @Override - public boolean isRunning() { - return this.isRunning; - } + @Override + public boolean isRunning() { + return this.isRunning; + } - @Override - public int getPhase() { - return 0; - } -} \ No newline at end of file + @Override + public int getPhase() { + return 0; + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/EnableDataServer.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/EnableDataServer.java index d42b85691..ff5419f51 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/EnableDataServer.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/bootstrap/EnableDataServer.java @@ -16,16 +16,14 @@ */ package com.alipay.sofa.registry.server.data.bootstrap; -import org.springframework.context.annotation.Import; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.context.annotation.Import; /** - * * @author shangyu.wh * @version $Id: EnableSessionServer.java, v 0.1 2017-11-14 11:38 synex Exp $ */ @@ -33,5 +31,4 @@ @Retention(RetentionPolicy.RUNTIME) @Documented @Import(DataServerBeanConfiguration.class) -public @interface EnableDataServer { -} \ No newline at end of file +public @interface EnableDataServer {} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DatumCache.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DatumCache.java index c4c1c42e3..31d9341a3 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DatumCache.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DatumCache.java @@ -22,9 +22,8 @@ import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.server.data.bootstrap.DataServerConfig; import com.google.common.annotations.VisibleForTesting; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.*; +import org.springframework.beans.factory.annotation.Autowired; /** * cache of datum, providing query function to the upper module @@ -34,76 +33,74 @@ * @version $Id: DatumCache.java, v 0.1 2017-12-06 20:50 qian.lqlq Exp $ */ public class DatumCache { - @Autowired - private DatumStorage localDatumStorage; + @Autowired private DatumStorage localDatumStorage; - @Autowired - private DataServerConfig dataServerConfig; + @Autowired private DataServerConfig dataServerConfig; - /** - * get datum by specific dataCenter and dataInfoId - * - * @param dataCenter - * @param dataInfoId - * @return - */ - public Datum get(String dataCenter, String dataInfoId) { - return localDatumStorage.get(dataInfoId); - } + /** + * get datum by specific dataCenter and dataInfoId + * + * @param dataCenter + * @param dataInfoId + * @return + */ + public Datum get(String dataCenter, String dataInfoId) { + return localDatumStorage.get(dataInfoId); + } - public void clean(String dataCenter, String dataInfoId) { - localDatumStorage.remove(dataInfoId, null); - } + public void clean(String dataCenter, String dataInfoId) { + localDatumStorage.remove(dataInfoId, null); + } - public DatumVersion getVersion(String dataCenter, String dataInfoId) { - //TODO only get local datacenter - DatumVersion version = localDatumStorage.getVersion(dataInfoId); - return version; - } + public DatumVersion getVersion(String dataCenter, String dataInfoId) { + // TODO only get local datacenter + DatumVersion version = localDatumStorage.getVersion(dataInfoId); + return version; + } - public Map getVersions(String dataCenter, int slotId, - Collection targetDataInfoIds) { - //local - return localDatumStorage.getVersions(slotId, targetDataInfoIds); - } + public Map getVersions( + String dataCenter, int slotId, Collection targetDataInfoIds) { + // local + return localDatumStorage.getVersions(slotId, targetDataInfoIds); + } - public DatumVersion updateVersion(String dataCenter, String dataInfoId) { - return localDatumStorage.updateVersion(dataInfoId); - } + public DatumVersion updateVersion(String dataCenter, String dataInfoId) { + return localDatumStorage.updateVersion(dataInfoId); + } - /** - * get all datum - * - * @return - */ - public Map> getAll() { - Map> datumMap = new HashMap<>(); - datumMap.put(dataServerConfig.getLocalDataCenter(), localDatumStorage.getAll()); - return datumMap; - } + /** + * get all datum + * + * @return + */ + public Map> getAll() { + Map> datumMap = new HashMap<>(); + datumMap.put(dataServerConfig.getLocalDataCenter(), localDatumStorage.getAll()); + return datumMap; + } - // get without datum.version, it's more efficient than getDatum - public Map>> getAllPublisher() { - Map>> datumMap = new HashMap<>(); - datumMap.put(dataServerConfig.getLocalDataCenter(), localDatumStorage.getAllPublisher()); - return datumMap; - } + // get without datum.version, it's more efficient than getDatum + public Map>> getAllPublisher() { + Map>> datumMap = new HashMap<>(); + datumMap.put(dataServerConfig.getLocalDataCenter(), localDatumStorage.getAllPublisher()); + return datumMap; + } - public Map getByConnectId(ConnectId connectId) { - return localDatumStorage.getByConnectId(connectId); - } + public Map getByConnectId(ConnectId connectId) { + return localDatumStorage.getByConnectId(connectId); + } - @VisibleForTesting - public void setLocalDatumStorage(DatumStorage localDatumStorage) { - this.localDatumStorage = localDatumStorage; - } + @VisibleForTesting + public void setLocalDatumStorage(DatumStorage localDatumStorage) { + this.localDatumStorage = localDatumStorage; + } - @VisibleForTesting - public void setDataServerConfig(DataServerConfig dataServerConfig) { - this.dataServerConfig = dataServerConfig; - } + @VisibleForTesting + public void setDataServerConfig(DataServerConfig dataServerConfig) { + this.dataServerConfig = dataServerConfig; + } - public DatumStorage getLocalDatumStorage() { - return localDatumStorage; - } -} \ No newline at end of file + public DatumStorage getLocalDatumStorage() { + return localDatumStorage; + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DatumStorage.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DatumStorage.java index be726b2a6..273fc6536 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DatumStorage.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DatumStorage.java @@ -24,68 +24,67 @@ import com.alipay.sofa.registry.common.model.dataserver.DatumVersion; import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.server.data.slot.SlotChangeListener; - import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-02 19:52 yuzhi.lyz Exp $ */ public interface DatumStorage { - /** - * get datum by specific dataInfoId - * - * @param dataInfoId - * @return - */ - Datum get(String dataInfoId); - - DatumVersion getVersion(String dataInfoId); + /** + * get datum by specific dataInfoId + * + * @param dataInfoId + * @return + */ + Datum get(String dataInfoId); - Map getVersions(int slotId, Collection targetDatInfoIds); + DatumVersion getVersion(String dataInfoId); - Map getByConnectId(ConnectId connectId); + Map getVersions(int slotId, Collection targetDatInfoIds); - Map> getPublishers(int slot); + Map getByConnectId(ConnectId connectId); - /** - * get all datum - * - * @return - */ - Map getAll(); + Map> getPublishers(int slot); - Map> getAllPublisher(); + /** + * get all datum + * + * @return + */ + Map getAll(); - DatumVersion put(Publisher publisher); + Map> getAllPublisher(); - DatumVersion createEmptyDatumIfAbsent(String dataInfoId, String dataCenter); + DatumVersion put(Publisher publisher); - Map clean(ProcessId sessionProcessId); + DatumVersion createEmptyDatumIfAbsent(String dataInfoId, String dataCenter); - DatumVersion remove(String dataInfoId, ProcessId sessionProcessId); + Map clean(ProcessId sessionProcessId); - DatumVersion remove(String dataInfoId, ProcessId sessionProcessId, - Map removedPublishers); + DatumVersion remove(String dataInfoId, ProcessId sessionProcessId); - DatumVersion put(String dataInfoId, List updatedPublishers); + DatumVersion remove( + String dataInfoId, + ProcessId sessionProcessId, + Map removedPublishers); - Map getDatumSummary(int slotId, String sessionIpAddress); + DatumVersion put(String dataInfoId, List updatedPublishers); - SlotChangeListener getSlotChangeListener(); + Map getDatumSummary(int slotId, String sessionIpAddress); - Set getSessionProcessIds(); + SlotChangeListener getSlotChangeListener(); - Map compact(long tombstoneTimestamp); + Set getSessionProcessIds(); - int tombstoneNum(); + Map compact(long tombstoneTimestamp); - boolean updateVersion(int slotId); + int tombstoneNum(); - DatumVersion updateVersion(String dataInfoId); + boolean updateVersion(int slotId); + DatumVersion updateVersion(String dataInfoId); } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/LocalDatumStorage.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/LocalDatumStorage.java index 24a69fd38..660bfffaf 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/LocalDatumStorage.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/LocalDatumStorage.java @@ -34,213 +34,214 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.*; +import org.springframework.beans.factory.annotation.Autowired; /** * @author yuzhi.lyz * @version v 0.1 2020-12-02 19:40 yuzhi.lyz Exp $ */ public final class LocalDatumStorage implements DatumStorage { - private static final Logger LOGGER = LoggerFactory - .getLogger(LocalDatumStorage.class); - - private final SlotFunction slotFunction = SlotFunctionRegistry.getFunc(); - private final Map publisherGroupsMap = Maps.newConcurrentMap(); - - @Autowired - private DataServerConfig dataServerConfig; - - private PublisherGroups getPublisherGroups(String dataInfoId) { - final Integer slotId = slotFunction.slotOf(dataInfoId); - PublisherGroups groups = publisherGroupsMap.get(slotId); - if (groups == null) { - LOGGER.warn("[nullGroups] {}, {}", slotId, dataInfoId); - - } - return groups; - } - - private PublisherGroups getPublisherGroups(int slotId) { - PublisherGroups groups = publisherGroupsMap.get(slotId); - if (groups == null) { - LOGGER.warn("[nullGroups] {}", slotId); - - } - return groups; - } - - @Override - public Datum get(String dataInfoId) { - final PublisherGroups groups = getPublisherGroups(dataInfoId); - return groups == null ? null : groups.getDatum(dataInfoId); - } - - @Override - public DatumVersion getVersion(String dataInfoId) { - PublisherGroups groups = getPublisherGroups(dataInfoId); - return groups == null ? null : groups.getVersion(dataInfoId); - } - - @Override - public Map getVersions(int slotId, Collection targetDataInfoIds) { - PublisherGroups groups = getPublisherGroups(slotId); - return groups == null ? Collections.emptyMap() : groups.getVersions(targetDataInfoIds); - } - - @Override - public Map getAll() { - Map m = Maps.newHashMapWithExpectedSize(128); - publisherGroupsMap.values().forEach(g -> m.putAll(g.getAllDatum())); - return m; - } - - @Override - public Map> getAllPublisher() { - Map> m = Maps.newHashMapWithExpectedSize(128); - publisherGroupsMap.values().forEach(g -> m.putAll(g.getAllPublisher())); - return m; - } - - @Override - public Map getByConnectId(ConnectId connectId) { - Map m = Maps.newHashMapWithExpectedSize(64); - publisherGroupsMap.values().forEach(g -> m.putAll(g.getByConnectId(connectId))); - return m; - } - - @Override - public Map> getPublishers(int slotId) { - PublisherGroups groups = getPublisherGroups(slotId); - if (groups == null) { - return Collections.emptyMap(); - } - Map> map = Maps.newHashMap(); - Map datumMap = groups.getAllDatum(); - datumMap.values().forEach(d -> map.put(d.getDataInfoId(), d.getPubMap())); - return map; - } - - @Override - public DatumVersion createEmptyDatumIfAbsent(String dataInfoId, String dataCenter) { - PublisherGroups groups = getPublisherGroups(dataInfoId); - return groups == null ? null : groups.createGroupIfAbsent(dataInfoId).getVersion(); - } - - @Override - public Map clean(ProcessId sessionProcessId) { - // clean by sessionProcessId, the sessionProcessId could not be null - ParaCheckUtil.checkNotNull(sessionProcessId, "sessionProcessId"); - Map versionMap = Maps.newHashMapWithExpectedSize(32); - publisherGroupsMap.values().forEach(g -> versionMap.putAll(g.clean(sessionProcessId))); - return versionMap; - } - - // only for http testapi - @Override - public DatumVersion remove(String dataInfoId, ProcessId sessionProcessId) { - // the sessionProcessId is null when the call from sync leader - PublisherGroups groups = getPublisherGroups(dataInfoId); - return groups == null ? null : groups.remove(dataInfoId, sessionProcessId); - } - - @Override - public DatumVersion put(String dataInfoId, List publishers) { - PublisherGroups groups = getPublisherGroups(dataInfoId); - return groups == null ? null : groups.put(dataInfoId, publishers); - } - - @Override - public DatumVersion put(Publisher publisher) { - return put(publisher.getDataInfoId(), Collections.singletonList(publisher)); - } - - @Override - public DatumVersion remove(String dataInfoId, ProcessId sessionProcessId, - Map removedPublishers) { - // the sessionProcessId is null when the call from sync leader - PublisherGroups groups = getPublisherGroups(dataInfoId); - return groups == null ? null : groups.remove(dataInfoId, sessionProcessId, - removedPublishers); - } - - @Override - public Map getDatumSummary(int slotId, String sessionIpAddress) { - final PublisherGroups groups = publisherGroupsMap.get(slotId); - return groups != null ? groups.getSummary(sessionIpAddress) : Collections.emptyMap(); - } - - @Override - public SlotChangeListener getSlotChangeListener() { - return new SlotListener(); - } - - @Override - public Set getSessionProcessIds() { - Set ids = Sets.newHashSet(); - publisherGroupsMap.values().forEach(g -> ids.addAll(g.getSessionProcessIds())); - return ids; - } - - @Override - public Map compact(long tombstoneTimestamp) { - Map compacts = Maps.newHashMap(); - publisherGroupsMap.values().forEach(g -> compacts.putAll(g.compact(tombstoneTimestamp))); - return compacts; - } - - @Override - public int tombstoneNum() { - int count = 0; - for (PublisherGroups groups : publisherGroupsMap.values()) { - count += groups.tombstoneNum(); - } - return count; - } - - @Override - public boolean updateVersion(int slotId) { - PublisherGroups groups = publisherGroupsMap.get(slotId); - if (groups == null) { - return false; - } - groups.updateVersion(); - return true; - } - - @Override - public DatumVersion updateVersion(String dataInfoId) { - PublisherGroups groups = getPublisherGroups(dataInfoId); - return groups == null ? null : groups.updateVersion(dataInfoId); - } - - private final class SlotListener implements SlotChangeListener { - - @Override - public void onSlotAdd(int slotId, Slot.Role role) { - publisherGroupsMap.computeIfAbsent(slotId, k -> { - PublisherGroups groups = new PublisherGroups(dataServerConfig.getLocalDataCenter()); - LOGGER.info("{} add publisherGroup {}", dataServerConfig.getLocalDataCenter(), slotId); - return groups; - }); - } - - @Override - public void onSlotRemove(int slotId, Slot.Role role) { - boolean removed = publisherGroupsMap.remove(slotId) != null; - LOGGER.info("{}, remove publisherGroup {}, removed={}", - dataServerConfig.getLocalDataCenter(), slotId, removed); - } - } - - @VisibleForTesting - public void setDataServerConfig(DataServerConfig dataServerConfig) { - this.dataServerConfig = dataServerConfig; - } - - @VisibleForTesting - public DataServerConfig getDataServerConfig() { - return dataServerConfig; - } + private static final Logger LOGGER = LoggerFactory.getLogger(LocalDatumStorage.class); + + private final SlotFunction slotFunction = SlotFunctionRegistry.getFunc(); + private final Map publisherGroupsMap = Maps.newConcurrentMap(); + + @Autowired private DataServerConfig dataServerConfig; + + private PublisherGroups getPublisherGroups(String dataInfoId) { + final Integer slotId = slotFunction.slotOf(dataInfoId); + PublisherGroups groups = publisherGroupsMap.get(slotId); + if (groups == null) { + LOGGER.warn("[nullGroups] {}, {}", slotId, dataInfoId); + } + return groups; + } + + private PublisherGroups getPublisherGroups(int slotId) { + PublisherGroups groups = publisherGroupsMap.get(slotId); + if (groups == null) { + LOGGER.warn("[nullGroups] {}", slotId); + } + return groups; + } + + @Override + public Datum get(String dataInfoId) { + final PublisherGroups groups = getPublisherGroups(dataInfoId); + return groups == null ? null : groups.getDatum(dataInfoId); + } + + @Override + public DatumVersion getVersion(String dataInfoId) { + PublisherGroups groups = getPublisherGroups(dataInfoId); + return groups == null ? null : groups.getVersion(dataInfoId); + } + + @Override + public Map getVersions(int slotId, Collection targetDataInfoIds) { + PublisherGroups groups = getPublisherGroups(slotId); + return groups == null ? Collections.emptyMap() : groups.getVersions(targetDataInfoIds); + } + + @Override + public Map getAll() { + Map m = Maps.newHashMapWithExpectedSize(128); + publisherGroupsMap.values().forEach(g -> m.putAll(g.getAllDatum())); + return m; + } + + @Override + public Map> getAllPublisher() { + Map> m = Maps.newHashMapWithExpectedSize(128); + publisherGroupsMap.values().forEach(g -> m.putAll(g.getAllPublisher())); + return m; + } + + @Override + public Map getByConnectId(ConnectId connectId) { + Map m = Maps.newHashMapWithExpectedSize(64); + publisherGroupsMap.values().forEach(g -> m.putAll(g.getByConnectId(connectId))); + return m; + } + + @Override + public Map> getPublishers(int slotId) { + PublisherGroups groups = getPublisherGroups(slotId); + if (groups == null) { + return Collections.emptyMap(); + } + Map> map = Maps.newHashMap(); + Map datumMap = groups.getAllDatum(); + datumMap.values().forEach(d -> map.put(d.getDataInfoId(), d.getPubMap())); + return map; + } + + @Override + public DatumVersion createEmptyDatumIfAbsent(String dataInfoId, String dataCenter) { + PublisherGroups groups = getPublisherGroups(dataInfoId); + return groups == null ? null : groups.createGroupIfAbsent(dataInfoId).getVersion(); + } + + @Override + public Map clean(ProcessId sessionProcessId) { + // clean by sessionProcessId, the sessionProcessId could not be null + ParaCheckUtil.checkNotNull(sessionProcessId, "sessionProcessId"); + Map versionMap = Maps.newHashMapWithExpectedSize(32); + publisherGroupsMap.values().forEach(g -> versionMap.putAll(g.clean(sessionProcessId))); + return versionMap; + } + + // only for http testapi + @Override + public DatumVersion remove(String dataInfoId, ProcessId sessionProcessId) { + // the sessionProcessId is null when the call from sync leader + PublisherGroups groups = getPublisherGroups(dataInfoId); + return groups == null ? null : groups.remove(dataInfoId, sessionProcessId); + } + + @Override + public DatumVersion put(String dataInfoId, List publishers) { + PublisherGroups groups = getPublisherGroups(dataInfoId); + return groups == null ? null : groups.put(dataInfoId, publishers); + } + + @Override + public DatumVersion put(Publisher publisher) { + return put(publisher.getDataInfoId(), Collections.singletonList(publisher)); + } + + @Override + public DatumVersion remove( + String dataInfoId, + ProcessId sessionProcessId, + Map removedPublishers) { + // the sessionProcessId is null when the call from sync leader + PublisherGroups groups = getPublisherGroups(dataInfoId); + return groups == null ? null : groups.remove(dataInfoId, sessionProcessId, removedPublishers); + } + + @Override + public Map getDatumSummary(int slotId, String sessionIpAddress) { + final PublisherGroups groups = publisherGroupsMap.get(slotId); + return groups != null ? groups.getSummary(sessionIpAddress) : Collections.emptyMap(); + } + + @Override + public SlotChangeListener getSlotChangeListener() { + return new SlotListener(); + } + + @Override + public Set getSessionProcessIds() { + Set ids = Sets.newHashSet(); + publisherGroupsMap.values().forEach(g -> ids.addAll(g.getSessionProcessIds())); + return ids; + } + + @Override + public Map compact(long tombstoneTimestamp) { + Map compacts = Maps.newHashMap(); + publisherGroupsMap.values().forEach(g -> compacts.putAll(g.compact(tombstoneTimestamp))); + return compacts; + } + + @Override + public int tombstoneNum() { + int count = 0; + for (PublisherGroups groups : publisherGroupsMap.values()) { + count += groups.tombstoneNum(); + } + return count; + } + + @Override + public boolean updateVersion(int slotId) { + PublisherGroups groups = publisherGroupsMap.get(slotId); + if (groups == null) { + return false; + } + groups.updateVersion(); + return true; + } + + @Override + public DatumVersion updateVersion(String dataInfoId) { + PublisherGroups groups = getPublisherGroups(dataInfoId); + return groups == null ? null : groups.updateVersion(dataInfoId); + } + + private final class SlotListener implements SlotChangeListener { + + @Override + public void onSlotAdd(int slotId, Slot.Role role) { + publisherGroupsMap.computeIfAbsent( + slotId, + k -> { + PublisherGroups groups = new PublisherGroups(dataServerConfig.getLocalDataCenter()); + LOGGER.info("{} add publisherGroup {}", dataServerConfig.getLocalDataCenter(), slotId); + return groups; + }); + } + + @Override + public void onSlotRemove(int slotId, Slot.Role role) { + boolean removed = publisherGroupsMap.remove(slotId) != null; + LOGGER.info( + "{}, remove publisherGroup {}, removed={}", + dataServerConfig.getLocalDataCenter(), + slotId, + removed); + } + } + + @VisibleForTesting + public void setDataServerConfig(DataServerConfig dataServerConfig) { + this.dataServerConfig = dataServerConfig; + } + + @VisibleForTesting + public DataServerConfig getDataServerConfig() { + return dataServerConfig; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherEnvelope.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherEnvelope.java index 5527afcf7..0dbe86d33 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherEnvelope.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherEnvelope.java @@ -24,67 +24,76 @@ import com.alipay.sofa.registry.util.ParaCheckUtil; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-02 19:47 yuzhi.lyz Exp $ */ public final class PublisherEnvelope { - final Publisher publisher; - final ProcessId sessionProcessId; - final RegisterVersion registerVersion; - final long tombstoneTimestamp; + final Publisher publisher; + final ProcessId sessionProcessId; + final RegisterVersion registerVersion; + final long tombstoneTimestamp; - private PublisherEnvelope(Publisher publisher, ProcessId sessionProcessId, - RegisterVersion registerVersion, long tombstoneTimestamp) { - this.publisher = publisher; - this.sessionProcessId = sessionProcessId; - this.registerVersion = registerVersion; - this.tombstoneTimestamp = tombstoneTimestamp; - } + private PublisherEnvelope( + Publisher publisher, + ProcessId sessionProcessId, + RegisterVersion registerVersion, + long tombstoneTimestamp) { + this.publisher = publisher; + this.sessionProcessId = sessionProcessId; + this.registerVersion = registerVersion; + this.tombstoneTimestamp = tombstoneTimestamp; + } - static PublisherEnvelope of(Publisher publisher) { - ParaCheckUtil.checkNotNull(publisher.getSessionProcessId(), "publisher.sessionProcessId"); - switch (publisher.getDataType()) { - case PUBLISHER: - return pubOf(publisher, publisher.getSessionProcessId()); - case UN_PUBLISHER: - return unpubOf(publisher.registerVersion(), publisher.getSessionProcessId()); - default: - throw new IllegalArgumentException("not accept Publisher Type:" - + publisher.getDataType()); - } + static PublisherEnvelope of(Publisher publisher) { + ParaCheckUtil.checkNotNull(publisher.getSessionProcessId(), "publisher.sessionProcessId"); + switch (publisher.getDataType()) { + case PUBLISHER: + return pubOf(publisher, publisher.getSessionProcessId()); + case UN_PUBLISHER: + return unpubOf(publisher.registerVersion(), publisher.getSessionProcessId()); + default: + throw new IllegalArgumentException("not accept Publisher Type:" + publisher.getDataType()); } + } - static PublisherEnvelope pubOf(Publisher publisher, ProcessId sessionProcessId) { - ParaCheckUtil.checkEquals(publisher.getDataType(), StoreData.DataType.PUBLISHER, - "Publisher.dataType"); - return new PublisherEnvelope(publisher, sessionProcessId, publisher.registerVersion(), + static PublisherEnvelope pubOf(Publisher publisher, ProcessId sessionProcessId) { + ParaCheckUtil.checkEquals( + publisher.getDataType(), StoreData.DataType.PUBLISHER, "Publisher.dataType"); + return new PublisherEnvelope( + publisher, + sessionProcessId, + publisher.registerVersion(), // Long.max means pub never compact - Long.MAX_VALUE); - } + Long.MAX_VALUE); + } - static PublisherEnvelope unpubOf(RegisterVersion version, ProcessId sessionProcessId) { - return new PublisherEnvelope(null, sessionProcessId, version, System.currentTimeMillis()); - } + static PublisherEnvelope unpubOf(RegisterVersion version, ProcessId sessionProcessId) { + return new PublisherEnvelope(null, sessionProcessId, version, System.currentTimeMillis()); + } - boolean isPub() { - return publisher != null; - } + boolean isPub() { + return publisher != null; + } - RegisterVersion getVersionIfPub() { - return isPub() ? registerVersion : null; - } + RegisterVersion getVersionIfPub() { + return isPub() ? registerVersion : null; + } - boolean isConnectId(ConnectId connectId) { - return isPub() && publisher.connectId().equals(connectId); - } + boolean isConnectId(ConnectId connectId) { + return isPub() && publisher.connectId().equals(connectId); + } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(128); - sb.append("pub=").append(isPub()).append(", connectId=") - .append(publisher != null ? publisher.connectId() : "null").append(", ver=") - .append(registerVersion).append(", ts=").append(tombstoneTimestamp); - return sb.toString(); - } + @Override + public String toString() { + StringBuilder sb = new StringBuilder(128); + sb.append("pub=") + .append(isPub()) + .append(", connectId=") + .append(publisher != null ? publisher.connectId() : "null") + .append(", ver=") + .append(registerVersion) + .append(", ts=") + .append(tombstoneTimestamp); + return sb.toString(); + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherGroup.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherGroup.java index 0a4d91ffb..a300be4a0 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherGroup.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherGroup.java @@ -34,290 +34,308 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.apache.commons.collections.MapUtils; - import java.util.*; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; +import org.apache.commons.collections.MapUtils; /** * @author yuzhi.lyz * @version v 0.1 2020-12-02 20:26 yuzhi.lyz Exp $ */ public final class PublisherGroup { - private static final Logger LOGGER = LoggerFactory - .getLogger(PublisherGroup.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PublisherGroup.class); - private final ReadWriteLock lock = new ReentrantReadWriteLock(); + private final ReadWriteLock lock = new ReentrantReadWriteLock(); - final String dataInfoId; + final String dataInfoId; - final String dataCenter; + final String dataCenter; - final String dataId; + final String dataId; - final String instanceId; + final String instanceId; - final String group; + final String group; - // if the delete publisher from session, mark unpub - final Map pubMap = Maps.newConcurrentMap(); + // if the delete publisher from session, mark unpub + final Map pubMap = Maps.newConcurrentMap(); - private volatile long version; + private volatile long version; - PublisherGroup(String dataInfoId, String dataCenter) { - DataInfo dataInfo = DataInfo.valueOf(dataInfoId); - this.dataInfoId = WordCache.getWordCache(dataInfoId); - this.dataCenter = WordCache.getWordCache(dataCenter); - this.dataId = WordCache.getWordCache(dataInfo.getDataId()); - this.instanceId = WordCache.getWordCache(dataInfo.getInstanceId()); - this.group = WordCache.getWordCache(dataInfo.getGroup()); - this.version = DatumVersionUtil.nextId(); - } + PublisherGroup(String dataInfoId, String dataCenter) { + DataInfo dataInfo = DataInfo.valueOf(dataInfoId); + this.dataInfoId = WordCache.getWordCache(dataInfoId); + this.dataCenter = WordCache.getWordCache(dataCenter); + this.dataId = WordCache.getWordCache(dataInfo.getDataId()); + this.instanceId = WordCache.getWordCache(dataInfo.getInstanceId()); + this.group = WordCache.getWordCache(dataInfo.getGroup()); + this.version = DatumVersionUtil.nextId(); + } - DatumVersion getVersion() { - return new DatumVersion(version); - } + DatumVersion getVersion() { + return new DatumVersion(version); + } - Datum toDatum() { - Datum datum = new Datum(); - datum.setDataCenter(dataCenter); - datum.setDataId(dataId); - datum.setDataInfoId(dataInfoId); - datum.setGroup(group); - datum.setInstanceId(instanceId); - long ver; - List list = new ArrayList<>(pubMap.size()); - lock.readLock().lock(); - try { - ver = this.version; - for (PublisherEnvelope envelope : pubMap.values()) { - if (envelope.isPub()) { - list.add(envelope.publisher); - } - } - } finally { - lock.readLock().unlock(); + Datum toDatum() { + Datum datum = new Datum(); + datum.setDataCenter(dataCenter); + datum.setDataId(dataId); + datum.setDataInfoId(dataInfoId); + datum.setGroup(group); + datum.setInstanceId(instanceId); + long ver; + List list = new ArrayList<>(pubMap.size()); + lock.readLock().lock(); + try { + ver = this.version; + for (PublisherEnvelope envelope : pubMap.values()) { + if (envelope.isPub()) { + list.add(envelope.publisher); } - datum.setVersion(ver); - list.forEach(p -> datum.addPublisher(p)); - return datum; + } + } finally { + lock.readLock().unlock(); } + datum.setVersion(ver); + list.forEach(p -> datum.addPublisher(p)); + return datum; + } - List getPublishers() { - List list = new ArrayList<>(pubMap.size()); - for (PublisherEnvelope envelope : Lists.newArrayList(pubMap.values())) { - if (envelope.isPub()) { - list.add(envelope.publisher); - } - } - return list; + List getPublishers() { + List list = new ArrayList<>(pubMap.size()); + for (PublisherEnvelope envelope : Lists.newArrayList(pubMap.values())) { + if (envelope.isPub()) { + list.add(envelope.publisher); + } } + return list; + } - Map getByConnectId(ConnectId connectId) { - Map map = Maps.newHashMap(); - pubMap.values().forEach(p -> { - if (p.isConnectId(connectId)) { + Map getByConnectId(ConnectId connectId) { + Map map = Maps.newHashMap(); + pubMap + .values() + .forEach( + p -> { + if (p.isConnectId(connectId)) { map.put(p.publisher.getRegisterId(), p.publisher); - } - }); - return map; - } + } + }); + return map; + } - DatumVersion updateVersion() { - this.version = DatumVersionUtil.nextId(); - return new DatumVersion(version); - } + DatumVersion updateVersion() { + this.version = DatumVersionUtil.nextId(); + return new DatumVersion(version); + } - private boolean tryAddPublisher(Publisher publisher) { - PublisherEnvelope exist = pubMap.get(publisher.getRegisterId()); - final RegisterVersion registerVersion = publisher.registerVersion(); - if (exist != null) { - if (exist.registerVersion.equals(registerVersion)) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("[AddSameVer] {}, {}, exist={}, add={}", - publisher.getDataInfoId(), publisher.getRegisterId(), - exist.registerVersion, publisher.registerVersion()); - } - return false; - } - if (!exist.registerVersion.orderThan(registerVersion)) { - LOGGER.warn("[AddOlderVer] {}, {}, exist={}, add={}", publisher.getDataInfoId(), - publisher.getRegisterId(), exist.registerVersion, publisher.registerVersion()); - return false; - } + private boolean tryAddPublisher(Publisher publisher) { + PublisherEnvelope exist = pubMap.get(publisher.getRegisterId()); + final RegisterVersion registerVersion = publisher.registerVersion(); + if (exist != null) { + if (exist.registerVersion.equals(registerVersion)) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "[AddSameVer] {}, {}, exist={}, add={}", + publisher.getDataInfoId(), + publisher.getRegisterId(), + exist.registerVersion, + publisher.registerVersion()); } - pubMap.put(publisher.getRegisterId(), PublisherEnvelope.of(publisher)); - return true; + return false; + } + if (!exist.registerVersion.orderThan(registerVersion)) { + LOGGER.warn( + "[AddOlderVer] {}, {}, exist={}, add={}", + publisher.getDataInfoId(), + publisher.getRegisterId(), + exist.registerVersion, + publisher.registerVersion()); + return false; + } } + pubMap.put(publisher.getRegisterId(), PublisherEnvelope.of(publisher)); + return true; + } - DatumVersion addPublisher(Publisher publisher) { - publisher.setSessionProcessId(ProcessIdCache.cache(publisher.getSessionProcessId())); - lock.writeLock().lock(); - try { - if (tryAddPublisher(publisher)) { - return updateVersion(); - } - return null; - } finally { - lock.writeLock().unlock(); - } + DatumVersion addPublisher(Publisher publisher) { + publisher.setSessionProcessId(ProcessIdCache.cache(publisher.getSessionProcessId())); + lock.writeLock().lock(); + try { + if (tryAddPublisher(publisher)) { + return updateVersion(); + } + return null; + } finally { + lock.writeLock().unlock(); } + } - DatumVersion clean(ProcessId sessionProcessId) { - sessionProcessId = ProcessIdCache.cache(sessionProcessId); - lock.writeLock().lock(); - try { - boolean modified = false; - if (sessionProcessId == null) { - modified = !pubMap.isEmpty(); - pubMap.clear(); - } else { - // clean by session processId, could not increase the pub version - // the publisher from the session maybe sync again after clean, could not reject that - Iterator> it = pubMap.entrySet().iterator(); - while (it.hasNext()) { - PublisherEnvelope envelope = it.next().getValue(); - if (envelope.isPub() && envelope.sessionProcessId.equals(sessionProcessId)) { - it.remove(); - modified = true; - } - } - } - return modified ? updateVersion() : null; - } finally { - lock.writeLock().unlock(); + DatumVersion clean(ProcessId sessionProcessId) { + sessionProcessId = ProcessIdCache.cache(sessionProcessId); + lock.writeLock().lock(); + try { + boolean modified = false; + if (sessionProcessId == null) { + modified = !pubMap.isEmpty(); + pubMap.clear(); + } else { + // clean by session processId, could not increase the pub version + // the publisher from the session maybe sync again after clean, could not reject that + Iterator> it = pubMap.entrySet().iterator(); + while (it.hasNext()) { + PublisherEnvelope envelope = it.next().getValue(); + if (envelope.isPub() && envelope.sessionProcessId.equals(sessionProcessId)) { + it.remove(); + modified = true; + } } + } + return modified ? updateVersion() : null; + } finally { + lock.writeLock().unlock(); } + } - DatumVersion remove(ProcessId sessionProcessId, Map removedPublishers) { - sessionProcessId = ProcessIdCache.cache(sessionProcessId); - if (MapUtils.isEmpty(removedPublishers)) { - return null; - } - lock.writeLock().lock(); - try { - boolean modified = false; - for (Map.Entry e : removedPublishers.entrySet()) { - final String registerId = e.getKey(); - final RegisterVersion removedVer = e.getValue(); - - final PublisherEnvelope existing = pubMap.get(registerId); - if (existing == null || !existing.isPub()) { - // the removedPublishers is from pubMap, but now notExist/unpub/pubByOtherSession - continue; - } - if (existing.registerVersion.equals(removedVer)) { - // sync from leader - if (sessionProcessId == null) { - pubMap.remove(registerId); - modified = true; - continue; - } - if (sessionProcessId.equals(existing.sessionProcessId)) { - // syn from session, mark unpub with higher registerTimestamp - pubMap.put(registerId, PublisherEnvelope.unpubOf( - removedVer.incrRegisterTimestamp(), sessionProcessId)); - modified = true; - } else { - LOGGER.warn("[RemovePidModified] {}, {}, exist={}/{}, expect={}/{}", - dataInfoId, registerId, existing.registerVersion, - existing.sessionProcessId, removedVer, sessionProcessId); - } - } else { - // the item has modified after diff, ignored - LOGGER.warn("[RemoveVerModified] {}, {}, exist={}, expect={}", dataInfoId, - registerId, existing.registerVersion, removedVer); - } - } - return modified ? updateVersion() : null; - } finally { - lock.writeLock().unlock(); - } + DatumVersion remove(ProcessId sessionProcessId, Map removedPublishers) { + sessionProcessId = ProcessIdCache.cache(sessionProcessId); + if (MapUtils.isEmpty(removedPublishers)) { + return null; } + lock.writeLock().lock(); + try { + boolean modified = false; + for (Map.Entry e : removedPublishers.entrySet()) { + final String registerId = e.getKey(); + final RegisterVersion removedVer = e.getValue(); - DatumVersion put(List puts) { - for (Publisher p : puts) { - ParaCheckUtil.checkNotNull(p.getSessionProcessId(), "publisher.sessionProcessId"); - ParaCheckUtil.checkEquals(p.getDataInfoId(), dataInfoId, "publisher.dataInfoId"); - p.setSessionProcessId(ProcessIdCache.cache(p.getSessionProcessId())); + final PublisherEnvelope existing = pubMap.get(registerId); + if (existing == null || !existing.isPub()) { + // the removedPublishers is from pubMap, but now notExist/unpub/pubByOtherSession + continue; } - lock.writeLock().lock(); - try { - boolean modified = false; - for (Publisher publisher : puts) { - if (tryAddPublisher(publisher)) { - modified = true; - } - } - if (modified) { - return updateVersion(); - } - return null; - } finally { - lock.writeLock().unlock(); + if (existing.registerVersion.equals(removedVer)) { + // sync from leader + if (sessionProcessId == null) { + pubMap.remove(registerId); + modified = true; + continue; + } + if (sessionProcessId.equals(existing.sessionProcessId)) { + // syn from session, mark unpub with higher registerTimestamp + pubMap.put( + registerId, + PublisherEnvelope.unpubOf(removedVer.incrRegisterTimestamp(), sessionProcessId)); + modified = true; + } else { + LOGGER.warn( + "[RemovePidModified] {}, {}, exist={}/{}, expect={}/{}", + dataInfoId, + registerId, + existing.registerVersion, + existing.sessionProcessId, + removedVer, + sessionProcessId); + } + } else { + // the item has modified after diff, ignored + LOGGER.warn( + "[RemoveVerModified] {}, {}, exist={}, expect={}", + dataInfoId, + registerId, + existing.registerVersion, + removedVer); } + } + return modified ? updateVersion() : null; + } finally { + lock.writeLock().unlock(); } + } - DatumSummary getSummary(String sessionIpAddress) { - Map publisherVersions = Maps - .newHashMapWithExpectedSize(64); - for (Map.Entry e : pubMap.entrySet()) { - PublisherEnvelope envelope = e.getValue(); - RegisterVersion v = envelope.getVersionIfPub(); - if (v == null) { - continue; - } - if (sessionIpAddress == null - || sessionIpAddress.equals(envelope.sessionProcessId.getHostAddress())) { - publisherVersions.put(e.getKey(), v); - } + DatumVersion put(List puts) { + for (Publisher p : puts) { + ParaCheckUtil.checkNotNull(p.getSessionProcessId(), "publisher.sessionProcessId"); + ParaCheckUtil.checkEquals(p.getDataInfoId(), dataInfoId, "publisher.dataInfoId"); + p.setSessionProcessId(ProcessIdCache.cache(p.getSessionProcessId())); + } + lock.writeLock().lock(); + try { + boolean modified = false; + for (Publisher publisher : puts) { + if (tryAddPublisher(publisher)) { + modified = true; } - return new DatumSummary(dataInfoId, publisherVersions); + } + if (modified) { + return updateVersion(); + } + return null; + } finally { + lock.writeLock().unlock(); } + } - Collection getSessionProcessIds() { - Set set = Sets.newHashSet(); - for (PublisherEnvelope e : pubMap.values()) { - if (e.isPub()) { - set.add(e.sessionProcessId); - } - } - return set; + DatumSummary getSummary(String sessionIpAddress) { + Map publisherVersions = + Maps.newHashMapWithExpectedSize(64); + for (Map.Entry e : pubMap.entrySet()) { + PublisherEnvelope envelope = e.getValue(); + RegisterVersion v = envelope.getVersionIfPub(); + if (v == null) { + continue; + } + if (sessionIpAddress == null + || sessionIpAddress.equals(envelope.sessionProcessId.getHostAddress())) { + publisherVersions.put(e.getKey(), v); + } } + return new DatumSummary(dataInfoId, publisherVersions); + } - int compact(long tombstoneTimestamp) { - // compact not modify the version, no need to lock - int count = 0; - Map compacts = Maps.newHashMap(); - for (Map.Entry e : pubMap.entrySet()) { - final PublisherEnvelope envelope = e.getValue(); - if (!envelope.isPub() && envelope.tombstoneTimestamp <= tombstoneTimestamp) { - compacts.put(e.getKey(), envelope); - } - } + Collection getSessionProcessIds() { + Set set = Sets.newHashSet(); + for (PublisherEnvelope e : pubMap.values()) { + if (e.isPub()) { + set.add(e.sessionProcessId); + } + } + return set; + } - for (Map.Entry compact : compacts.entrySet()) { - if (pubMap.remove(compact.getKey(), compact.getValue())) { - count++; - } - } - return count; + int compact(long tombstoneTimestamp) { + // compact not modify the version, no need to lock + int count = 0; + Map compacts = Maps.newHashMap(); + for (Map.Entry e : pubMap.entrySet()) { + final PublisherEnvelope envelope = e.getValue(); + if (!envelope.isPub() && envelope.tombstoneTimestamp <= tombstoneTimestamp) { + compacts.put(e.getKey(), envelope); + } } - int tombstoneNum() { - int count = 0; - for (PublisherEnvelope envelope : pubMap.values()) { - if (!envelope.isPub()) { - count++; - } - } - return count; + for (Map.Entry compact : compacts.entrySet()) { + if (pubMap.remove(compact.getKey(), compact.getValue())) { + count++; + } } + return count; + } - @Override - public String toString() { - return StringFormatter.format("PubGroup{{},size={},ver={}}", dataInfoId, pubMap.size(), - version); + int tombstoneNum() { + int count = 0; + for (PublisherEnvelope envelope : pubMap.values()) { + if (!envelope.isPub()) { + count++; + } } -} \ No newline at end of file + return count; + } + + @Override + public String toString() { + return StringFormatter.format( + "PubGroup{{},size={},ver={}}", dataInfoId, pubMap.size(), version); + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherGroups.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherGroups.java index 74acc699c..7a181641f 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherGroups.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/PublisherGroups.java @@ -25,161 +25,170 @@ import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.util.StringFormatter; import com.google.common.collect.Maps; -import org.apache.commons.collections.CollectionUtils; -import org.glassfish.jersey.internal.guava.Sets; - import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; +import org.apache.commons.collections.CollectionUtils; +import org.glassfish.jersey.internal.guava.Sets; /** * @author yuzhi.lyz * @version v 0.1 2020-12-02 21:52 yuzhi.lyz Exp $ */ public final class PublisherGroups { - private final Map publisherGroupMap = Maps.newConcurrentMap(); - private final String dataCenter; - - PublisherGroups(String dataCenter) { - this.dataCenter = dataCenter; - } - - Datum getDatum(String dataInfoId) { - PublisherGroup group = publisherGroupMap.get(dataInfoId); - return group == null ? null : group.toDatum(); - } - - DatumVersion getVersion(String dataInfoId) { - PublisherGroup group = publisherGroupMap.get(dataInfoId); - return group == null ? null : group.getVersion(); - } - - Map getVersions(Collection targetDataInfoIds) { - if (CollectionUtils.isEmpty(targetDataInfoIds)) { - final Map ret = Maps.newHashMapWithExpectedSize(publisherGroupMap.size()); - publisherGroupMap.forEach((k, v) -> ret.put(k, v.getVersion())); - return ret; - } - final Map ret = Maps.newHashMapWithExpectedSize(targetDataInfoIds.size()); - for (String dataInfoId : targetDataInfoIds) { - PublisherGroup group = publisherGroupMap.get(dataInfoId); - if (group != null) { - ret.put(dataInfoId, group.getVersion()); - } - } - return ret; - } - - Map getAllDatum() { - Map map = Maps.newHashMapWithExpectedSize(publisherGroupMap.size()); - publisherGroupMap.forEach((k, v) -> { - map.put(k, v.toDatum()); + private final Map publisherGroupMap = Maps.newConcurrentMap(); + private final String dataCenter; + + PublisherGroups(String dataCenter) { + this.dataCenter = dataCenter; + } + + Datum getDatum(String dataInfoId) { + PublisherGroup group = publisherGroupMap.get(dataInfoId); + return group == null ? null : group.toDatum(); + } + + DatumVersion getVersion(String dataInfoId) { + PublisherGroup group = publisherGroupMap.get(dataInfoId); + return group == null ? null : group.getVersion(); + } + + Map getVersions(Collection targetDataInfoIds) { + if (CollectionUtils.isEmpty(targetDataInfoIds)) { + final Map ret = + Maps.newHashMapWithExpectedSize(publisherGroupMap.size()); + publisherGroupMap.forEach((k, v) -> ret.put(k, v.getVersion())); + return ret; + } + final Map ret = Maps.newHashMapWithExpectedSize(targetDataInfoIds.size()); + for (String dataInfoId : targetDataInfoIds) { + PublisherGroup group = publisherGroupMap.get(dataInfoId); + if (group != null) { + ret.put(dataInfoId, group.getVersion()); + } + } + return ret; + } + + Map getAllDatum() { + Map map = Maps.newHashMapWithExpectedSize(publisherGroupMap.size()); + publisherGroupMap.forEach( + (k, v) -> { + map.put(k, v.toDatum()); }); - return map; - } - - Map> getAllPublisher() { - Map> map = Maps.newHashMapWithExpectedSize(publisherGroupMap.size()); - publisherGroupMap.forEach((k, v) -> { - map.put(k, v.getPublishers()); + return map; + } + + Map> getAllPublisher() { + Map> map = Maps.newHashMapWithExpectedSize(publisherGroupMap.size()); + publisherGroupMap.forEach( + (k, v) -> { + map.put(k, v.getPublishers()); }); - return map; - } - - Map getByConnectId(ConnectId connectId) { - Map map = Maps.newHashMapWithExpectedSize(64); - publisherGroupMap.values().forEach(v -> map.putAll(v.getByConnectId(connectId))); - return map; - } - - PublisherGroup createGroupIfAbsent(String dataInfoId) { - return publisherGroupMap - .computeIfAbsent(dataInfoId, - k -> new PublisherGroup(dataInfoId, dataCenter)); - } - - Map clean(ProcessId sessionProcessId) { - Map versionMap = Maps.newHashMapWithExpectedSize(64); - publisherGroupMap.values().forEach(g -> { - DatumVersion ver = g.clean(sessionProcessId); - if (ver != null) { + return map; + } + + Map getByConnectId(ConnectId connectId) { + Map map = Maps.newHashMapWithExpectedSize(64); + publisherGroupMap.values().forEach(v -> map.putAll(v.getByConnectId(connectId))); + return map; + } + + PublisherGroup createGroupIfAbsent(String dataInfoId) { + return publisherGroupMap.computeIfAbsent( + dataInfoId, k -> new PublisherGroup(dataInfoId, dataCenter)); + } + + Map clean(ProcessId sessionProcessId) { + Map versionMap = Maps.newHashMapWithExpectedSize(64); + publisherGroupMap + .values() + .forEach( + g -> { + DatumVersion ver = g.clean(sessionProcessId); + if (ver != null) { versionMap.put(g.dataInfoId, ver); - } + } + }); + return versionMap; + } + + DatumVersion remove(String dataInfoId, ProcessId sessionProcessId) { + PublisherGroup group = publisherGroupMap.get(dataInfoId); + return group == null ? null : group.clean(sessionProcessId); + } + + DatumVersion put(String dataInfoId, List publishers) { + if (CollectionUtils.isEmpty(publishers)) { + return null; + } + PublisherGroup group = createGroupIfAbsent(dataInfoId); + return group.put(publishers); + } + + DatumVersion remove( + String dataInfoId, + ProcessId sessionProcessId, + Map removedPublishers) { + PublisherGroup group = publisherGroupMap.get(dataInfoId); + return group == null ? null : group.remove(sessionProcessId, removedPublishers); + } + + Map getSummary(String sessionIpAddress) { + Map summaries = Maps.newHashMap(); + publisherGroupMap.forEach( + (k, g) -> { + DatumSummary summary = g.getSummary(sessionIpAddress); + if (!summary.isEmpty()) { + summaries.put(k, summary); + } }); - return versionMap; - } - - DatumVersion remove(String dataInfoId, ProcessId sessionProcessId) { - PublisherGroup group = publisherGroupMap.get(dataInfoId); - return group == null ? null : group.clean(sessionProcessId); - } - - DatumVersion put(String dataInfoId, List publishers) { - if (CollectionUtils.isEmpty(publishers)) { - return null; - } - PublisherGroup group = createGroupIfAbsent(dataInfoId); - return group.put(publishers); - } - - DatumVersion remove(String dataInfoId, ProcessId sessionProcessId, - Map removedPublishers) { - PublisherGroup group = publisherGroupMap.get(dataInfoId); - return group == null ? null : group.remove(sessionProcessId, removedPublishers); - } - - Map getSummary(String sessionIpAddress) { - Map summaries = Maps.newHashMap(); - publisherGroupMap.forEach((k, g) -> { - DatumSummary summary = g.getSummary(sessionIpAddress); - if (!summary.isEmpty()) { - summaries.put(k, summary); - } - }); - return summaries; - } - - Set getSessionProcessIds() { - Set ids = Sets.newHashSet(); - publisherGroupMap.values().forEach(g -> ids.addAll(g.getSessionProcessIds())); - return ids; - } - - Map compact(long tombstoneTimestamp) { - Map compacts = Maps.newHashMap(); - publisherGroupMap.values().forEach(g -> { - int count = g.compact(tombstoneTimestamp); - if (count != 0) { + return summaries; + } + + Set getSessionProcessIds() { + Set ids = Sets.newHashSet(); + publisherGroupMap.values().forEach(g -> ids.addAll(g.getSessionProcessIds())); + return ids; + } + + Map compact(long tombstoneTimestamp) { + Map compacts = Maps.newHashMap(); + publisherGroupMap + .values() + .forEach( + g -> { + int count = g.compact(tombstoneTimestamp); + if (count != 0) { compacts.put(g.dataInfoId, count); - } - }); - return compacts; - } - - int tombstoneNum() { - int count = 0; - for (PublisherGroup group : publisherGroupMap.values()) { - count += group.tombstoneNum(); - } - return count; - } - - void updateVersion() { - publisherGroupMap.values().forEach(g -> g.updateVersion()); - } - - DatumVersion updateVersion(String dataInfoId) { - PublisherGroup group = publisherGroupMap.get(dataInfoId); - if (group == null) { - return null; - } - return group.updateVersion(); - } - - @Override - public String toString() { - return StringFormatter - .format("PubGroups{{},size={}}", dataCenter, publisherGroupMap.size()); - } + } + }); + return compacts; + } + + int tombstoneNum() { + int count = 0; + for (PublisherGroup group : publisherGroupMap.values()) { + count += group.tombstoneNum(); + } + return count; + } + + void updateVersion() { + publisherGroupMap.values().forEach(g -> g.updateVersion()); + } + + DatumVersion updateVersion(String dataInfoId) { + PublisherGroup group = publisherGroupMap.get(dataInfoId); + if (group == null) { + return null; + } + return group.updateVersion(); + } + + @Override + public String toString() { + return StringFormatter.format("PubGroups{{},size={}}", dataCenter, publisherGroupMap.size()); + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/ChangeMetrics.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/ChangeMetrics.java index 4c1eb2f64..97f5f6198 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/ChangeMetrics.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/ChangeMetrics.java @@ -19,38 +19,38 @@ import io.prometheus.client.Counter; public final class ChangeMetrics { - private ChangeMetrics() { - } + private ChangeMetrics() {} - private static final Counter CHANGE_COUNTER_ = Counter.build() - .namespace("data").subsystem("change").name("notify_total") - .help("notify session").labelNames("type").register(); + private static final Counter CHANGE_COUNTER_ = + Counter.build() + .namespace("data") + .subsystem("change") + .name("notify_total") + .help("notify session") + .labelNames("type") + .register(); - static final Counter.Child CHANGE_COMMIT_COUNTER = CHANGE_COUNTER_ - .labels("commit"); - // retry change - static final Counter.Child CHANGE_RETRY_COUNTER = CHANGE_COUNTER_ - .labels("retry"); - // skip change - static final Counter.Child CHANGE_SKIP_COUNTER = CHANGE_COUNTER_ - .labels("skip"); + static final Counter.Child CHANGE_COMMIT_COUNTER = CHANGE_COUNTER_.labels("commit"); + // retry change + static final Counter.Child CHANGE_RETRY_COUNTER = CHANGE_COUNTER_.labels("retry"); + // skip change + static final Counter.Child CHANGE_SKIP_COUNTER = CHANGE_COUNTER_.labels("skip"); - static final Counter.Child CHANGE_FAIL_COUNTER = CHANGE_COUNTER_ - .labels("fail"); - static final Counter.Child CHANGE_SUCCESS_COUNTER = CHANGE_COUNTER_ - .labels("success"); + static final Counter.Child CHANGE_FAIL_COUNTER = CHANGE_COUNTER_.labels("fail"); + static final Counter.Child CHANGE_SUCCESS_COUNTER = CHANGE_COUNTER_.labels("success"); - // should not use - private static final Counter CHANGE_TEMP_COUNTER_ = Counter.build() - .namespace("data").subsystem("change").name("notify_temp_total") - .help("notify temp session").labelNames("type").register(); + // should not use + private static final Counter CHANGE_TEMP_COUNTER_ = + Counter.build() + .namespace("data") + .subsystem("change") + .name("notify_temp_total") + .help("notify temp session") + .labelNames("type") + .register(); - static final Counter.Child CHANGETEMP_SKIP_COUNTER = CHANGE_TEMP_COUNTER_ - .labels("skip"); - static final Counter.Child CHANGETEMP_COMMIT_COUNTER = CHANGE_TEMP_COUNTER_ - .labels("commit"); - static final Counter.Child CHANGETEMP_SUCCESS_COUNTER = CHANGE_TEMP_COUNTER_ - .labels("success"); - static final Counter.Child CHANGETEMP_FAIL_COUNTER = CHANGE_TEMP_COUNTER_ - .labels("fail"); + static final Counter.Child CHANGETEMP_SKIP_COUNTER = CHANGE_TEMP_COUNTER_.labels("skip"); + static final Counter.Child CHANGETEMP_COMMIT_COUNTER = CHANGE_TEMP_COUNTER_.labels("commit"); + static final Counter.Child CHANGETEMP_SUCCESS_COUNTER = CHANGE_TEMP_COUNTER_.labels("success"); + static final Counter.Child CHANGETEMP_FAIL_COUNTER = CHANGE_TEMP_COUNTER_.labels("fail"); } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeEvent.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeEvent.java index 012b8b3da..f6b110fc0 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeEvent.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeEvent.java @@ -17,7 +17,6 @@ package com.alipay.sofa.registry.server.data.change; import com.google.common.collect.Lists; - import java.util.Collections; import java.util.List; @@ -28,29 +27,36 @@ * @version $Id: DataChangeEvent.java, v 0.1 2017-12-07 18:44 qian.lqlq Exp $ */ public class DataChangeEvent implements IDataChangeEvent { - private final String dataCenter; - private final List dataInfoIds; + private final String dataCenter; + private final List dataInfoIds; - public DataChangeEvent(String dataCenter, List dataInfoIds) { - this.dataCenter = dataCenter; - this.dataInfoIds = Collections.unmodifiableList(Lists.newArrayList(dataInfoIds)); - } + public DataChangeEvent(String dataCenter, List dataInfoIds) { + this.dataCenter = dataCenter; + this.dataInfoIds = Collections.unmodifiableList(Lists.newArrayList(dataInfoIds)); + } - /** - * Getter method for property dataCenter. - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } - public List getDataInfoIds() { - return dataInfoIds; - } + public List getDataInfoIds() { + return dataInfoIds; + } - @Override - public String toString() { - return "DataChangeEvent{" + "dataCenter='" + dataCenter + '\'' + ", dataInfoIds='" - + dataInfoIds + '\'' + '}'; - } -} \ No newline at end of file + @Override + public String toString() { + return "DataChangeEvent{" + + "dataCenter='" + + dataCenter + + '\'' + + ", dataInfoIds='" + + dataInfoIds + + '\'' + + '}'; + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeEventCenter.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeEventCenter.java index ebc933b34..44fd98296 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeEventCenter.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeEventCenter.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.data.change; +import static com.alipay.sofa.registry.server.data.change.ChangeMetrics.*; + import com.alipay.remoting.Connection; import com.alipay.sofa.registry.common.model.Tuple; import com.alipay.sofa.registry.common.model.dataserver.Datum; @@ -33,368 +35,372 @@ import com.alipay.sofa.registry.task.KeyedThreadPoolExecutor; import com.alipay.sofa.registry.util.ConcurrentUtils; import com.alipay.sofa.registry.util.LoopRunnable; - -import static com.alipay.sofa.registry.server.data.change.ChangeMetrics.*; - import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; - -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.util.*; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; /** * @author qian.lqlq * @version $Id: DataChangeEventCenter.java, v 0.1 2018-03-09 14:25 qian.lqlq Exp $ */ public final class DataChangeEventCenter { - private static final Logger LOGGER = LoggerFactory - .getLogger(DataChangeEventCenter.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DataChangeEventCenter.class); - @Autowired - private DataServerConfig dataServerConfig; + @Autowired private DataServerConfig dataServerConfig; - @Autowired - private DatumCache datumCache; + @Autowired private DatumCache datumCache; - @Autowired - private SessionServerConnectionFactory sessionServerConnectionFactory; + @Autowired private SessionServerConnectionFactory sessionServerConnectionFactory; - @Autowired - private Exchange boltExchange; + @Autowired private Exchange boltExchange; - private final Map> dataCenter2Changes = Maps.newConcurrentMap(); - private final ReadWriteLock lock = new ReentrantReadWriteLock(); - private final LinkedList retryNotifiers = Lists.newLinkedList(); + private final Map> dataCenter2Changes = Maps.newConcurrentMap(); + private final ReadWriteLock lock = new ReentrantReadWriteLock(); + private final LinkedList retryNotifiers = Lists.newLinkedList(); - private final Map> dataCenter2TempChanges = Maps.newConcurrentMap(); - private final ReadWriteLock tempLock = new ReentrantReadWriteLock(); + private final Map> dataCenter2TempChanges = Maps.newConcurrentMap(); + private final ReadWriteLock tempLock = new ReentrantReadWriteLock(); - private TempChangeMerger tempChangeMerger; - private ChangeMerger changeMerger; + private TempChangeMerger tempChangeMerger; + private ChangeMerger changeMerger; - private KeyedThreadPoolExecutor notifyExecutor; - private KeyedThreadPoolExecutor notifyTempExecutor; + private KeyedThreadPoolExecutor notifyExecutor; + private KeyedThreadPoolExecutor notifyTempExecutor; - @PostConstruct - public void init() { - this.notifyExecutor = new KeyedThreadPoolExecutor("notify", + @PostConstruct + public void init() { + this.notifyExecutor = + new KeyedThreadPoolExecutor( + "notify", dataServerConfig.getNotifyExecutorPoolSize(), dataServerConfig.getNotifyExecutorQueueSize()); - this.notifyTempExecutor = new KeyedThreadPoolExecutor("notifyTemp", + this.notifyTempExecutor = + new KeyedThreadPoolExecutor( + "notifyTemp", dataServerConfig.getNotifyTempExecutorPoolSize(), dataServerConfig.getNotifyExecutorQueueSize()); - this.changeMerger = new ChangeMerger(); - this.tempChangeMerger = new TempChangeMerger(); - - ConcurrentUtils.createDaemonThread("changeMerger", changeMerger).start(); - ConcurrentUtils.createDaemonThread("tempChangeMerger", tempChangeMerger).start(); - - LOGGER.info("start DataChange NotifyIntervalMs={}", - dataServerConfig.getNotifyIntervalMillis()); - } - - public void onTempPubChange(Publisher publisher, String dataCenter) { - Map changes = dataCenter2TempChanges - .computeIfAbsent(dataCenter, k -> Maps.newConcurrentMap()); - tempLock.readLock().lock(); - try { - Datum existing = changes - .computeIfAbsent(publisher.getDataInfoId(), k -> new Datum(publisher, dataCenter)); - existing.addPublisher(publisher); - } finally { - tempLock.readLock().unlock(); - } + this.changeMerger = new ChangeMerger(); + this.tempChangeMerger = new TempChangeMerger(); + + ConcurrentUtils.createDaemonThread("changeMerger", changeMerger).start(); + ConcurrentUtils.createDaemonThread("tempChangeMerger", tempChangeMerger).start(); + + LOGGER.info("start DataChange NotifyIntervalMs={}", dataServerConfig.getNotifyIntervalMillis()); + } + + public void onTempPubChange(Publisher publisher, String dataCenter) { + Map changes = + dataCenter2TempChanges.computeIfAbsent(dataCenter, k -> Maps.newConcurrentMap()); + tempLock.readLock().lock(); + try { + Datum existing = + changes.computeIfAbsent(publisher.getDataInfoId(), k -> new Datum(publisher, dataCenter)); + existing.addPublisher(publisher); + } finally { + tempLock.readLock().unlock(); } - - public void onChange(Collection dataInfoIds, String dataCenter) { - Set changes = dataCenter2Changes.computeIfAbsent(dataCenter, k -> Sets.newConcurrentHashSet()); - lock.readLock().lock(); - try { - changes.addAll(dataInfoIds); - } finally { - lock.readLock().unlock(); - } + } + + public void onChange(Collection dataInfoIds, String dataCenter) { + Set changes = + dataCenter2Changes.computeIfAbsent(dataCenter, k -> Sets.newConcurrentHashSet()); + lock.readLock().lock(); + try { + changes.addAll(dataInfoIds); + } finally { + lock.readLock().unlock(); } + } - private final class TempNotifier implements Runnable { - final Connection connection; - final Datum datum; - - TempNotifier(Connection connection, Datum datum) { - this.connection = connection; - this.datum = datum; - } + private final class TempNotifier implements Runnable { + final Connection connection; + final Datum datum; - @Override - public void run() { - try { - if (!connection.isFine()) { - CHANGETEMP_FAIL_COUNTER.inc(); - LOGGER.info("temp change notify failed, conn is closed, {}", - connection.getRemoteAddress()); - return; - } - notifyTempPub(connection, datum); - CHANGETEMP_SUCCESS_COUNTER.inc(); - } catch (Throwable e) { - CHANGETEMP_FAIL_COUNTER.inc(); - LOGGER.error("failed to notify temp {}, {}", connection.getRemoteAddress(), datum, - e); - } - } + TempNotifier(Connection connection, Datum datum) { + this.connection = connection; + this.datum = datum; } - private final class ChangeNotifierRetry { - final ChangeNotifier notifier; - final long expireTimestamp; - - ChangeNotifierRetry(ChangeNotifier notifier, long expireTimestamp) { - this.notifier = notifier; - this.expireTimestamp = expireTimestamp; + @Override + public void run() { + try { + if (!connection.isFine()) { + CHANGETEMP_FAIL_COUNTER.inc(); + LOGGER.info( + "temp change notify failed, conn is closed, {}", connection.getRemoteAddress()); + return; } + notifyTempPub(connection, datum); + CHANGETEMP_SUCCESS_COUNTER.inc(); + } catch (Throwable e) { + CHANGETEMP_FAIL_COUNTER.inc(); + LOGGER.error("failed to notify temp {}, {}", connection.getRemoteAddress(), datum, e); + } } + } - private final class ChangeNotifier implements Runnable { - final Connection connection; - final String dataCenter; - final Map dataInfoIds; - volatile int retryCount; - - public ChangeNotifier(Connection connection, String dataCenter, - Map dataInfoIds) { - this.dataCenter = dataCenter; - this.connection = connection; - this.dataInfoIds = dataInfoIds; - } - - @Override - public void run() { - try { - if (!connection.isFine()) { - CHANGE_FAIL_COUNTER.inc(); - LOGGER.info("change notify failed, conn is closed, {}", - connection.getRemoteAddress()); - return; - } - DataChangeRequest request = new DataChangeRequest(dataCenter, dataInfoIds); - doNotify(request, connection); - CHANGE_SUCCESS_COUNTER.inc(); - } catch (Throwable e) { - CHANGE_FAIL_COUNTER.inc(); - LOGGER.error("failed to notify {}", this, e); - retry(this); - } - } + private final class ChangeNotifierRetry { + final ChangeNotifier notifier; + final long expireTimestamp; - @Override - public String toString() { - return "ChangeNotifier{" + "connection=" + connection + ", dataCenter='" + dataCenter - + '\'' + ", dataInfoIds=" + dataInfoIds.size() + ", retryCount=" + retryCount - + '}'; - } + ChangeNotifierRetry(ChangeNotifier notifier, long expireTimestamp) { + this.notifier = notifier; + this.expireTimestamp = expireTimestamp; } - - private void retry(ChangeNotifier notifier) { - notifier.retryCount++; - if (notifier.retryCount < dataServerConfig.getNotifyRetryTimes()) { - if (commitRetry(notifier)) { - CHANGE_RETRY_COUNTER.inc(); - return; - } - } - CHANGE_SKIP_COUNTER.inc(); - LOGGER.warn("skip retry of full, {}", notifier); + } + + private final class ChangeNotifier implements Runnable { + final Connection connection; + final String dataCenter; + final Map dataInfoIds; + volatile int retryCount; + + public ChangeNotifier( + Connection connection, String dataCenter, Map dataInfoIds) { + this.dataCenter = dataCenter; + this.connection = connection; + this.dataInfoIds = dataInfoIds; } - private boolean commitRetry(ChangeNotifier retry) { - final int maxSize = dataServerConfig.getNotifyRetryQueueSize(); - final long expireTimestamp = System.currentTimeMillis() - + dataServerConfig.getNotifyRetryBackoffMillis(); - synchronized (retryNotifiers) { - if (retryNotifiers.size() >= maxSize) { - // remove first - retryNotifiers.removeFirst(); - } - retryNotifiers.add(new ChangeNotifierRetry(retry, expireTimestamp)); + @Override + public void run() { + try { + if (!connection.isFine()) { + CHANGE_FAIL_COUNTER.inc(); + LOGGER.info("change notify failed, conn is closed, {}", connection.getRemoteAddress()); + return; } - return true; + DataChangeRequest request = new DataChangeRequest(dataCenter, dataInfoIds); + doNotify(request, connection); + CHANGE_SUCCESS_COUNTER.inc(); + } catch (Throwable e) { + CHANGE_FAIL_COUNTER.inc(); + LOGGER.error("failed to notify {}", this, e); + retry(this); + } } - private List getExpires() { - final List expires = Lists.newLinkedList(); - final long now = System.currentTimeMillis(); - synchronized (retryNotifiers) { - final Iterator it = retryNotifiers.iterator(); - while (it.hasNext()) { - ChangeNotifierRetry retry = it.next(); - if (retry.expireTimestamp <= now) { - expires.add(retry.notifier); - it.remove(); - } - } + @Override + public String toString() { + return "ChangeNotifier{" + + "connection=" + + connection + + ", dataCenter='" + + dataCenter + + '\'' + + ", dataInfoIds=" + + dataInfoIds.size() + + ", retryCount=" + + retryCount + + '}'; + } + } + + private void retry(ChangeNotifier notifier) { + notifier.retryCount++; + if (notifier.retryCount < dataServerConfig.getNotifyRetryTimes()) { + if (commitRetry(notifier)) { + CHANGE_RETRY_COUNTER.inc(); + return; + } + } + CHANGE_SKIP_COUNTER.inc(); + LOGGER.warn("skip retry of full, {}", notifier); + } + + private boolean commitRetry(ChangeNotifier retry) { + final int maxSize = dataServerConfig.getNotifyRetryQueueSize(); + final long expireTimestamp = + System.currentTimeMillis() + dataServerConfig.getNotifyRetryBackoffMillis(); + synchronized (retryNotifiers) { + if (retryNotifiers.size() >= maxSize) { + // remove first + retryNotifiers.removeFirst(); + } + retryNotifiers.add(new ChangeNotifierRetry(retry, expireTimestamp)); + } + return true; + } + + private List getExpires() { + final List expires = Lists.newLinkedList(); + final long now = System.currentTimeMillis(); + synchronized (retryNotifiers) { + final Iterator it = retryNotifiers.iterator(); + while (it.hasNext()) { + ChangeNotifierRetry retry = it.next(); + if (retry.expireTimestamp <= now) { + expires.add(retry.notifier); + it.remove(); } - return expires; + } } - - private void notifyTempPub(Connection connection, Datum datum) { - // has temp pub, need to update the datum.version, we use the cache.datum.version as push.version - final DatumVersion v = datumCache.updateVersion(datum.getDataCenter(), - datum.getDataInfoId()); - if (v == null) { - LOGGER.warn("not owns the DataInfoId when temp pub,{}", datum.getDataInfoId()); - return; + return expires; + } + + private void notifyTempPub(Connection connection, Datum datum) { + // has temp pub, need to update the datum.version, we use the cache.datum.version as + // push.version + final DatumVersion v = datumCache.updateVersion(datum.getDataCenter(), datum.getDataInfoId()); + if (v == null) { + LOGGER.warn("not owns the DataInfoId when temp pub,{}", datum.getDataInfoId()); + return; + } + Datum existDatum = datumCache.get(datum.getDataCenter(), datum.getDataInfoId()); + if (existDatum != null) { + datum.addPublishers(existDatum.getPubMap()); + } + datum.setVersion(v.getValue()); + DataPushRequest request = new DataPushRequest(datum); + LOGGER.info("temp pub, {}", datum); + doNotify(request, connection); + } + + private void doNotify(Object request, Connection connection) { + Server sessionServer = boltExchange.getServer(dataServerConfig.getPort()); + sessionServer.sendSync( + sessionServer.getChannel(connection.getRemoteAddress()), + request, + dataServerConfig.getRpcTimeoutMillis()); + } + + private final class TempChangeMerger extends LoopRunnable { + + @Override + public void runUnthrowable() { + final List events = Lists.newArrayList(); + tempLock.writeLock().lock(); + try { + for (Map change : dataCenter2TempChanges.values()) { + change + .values() + .forEach( + d -> { + events.add(new DataTempChangeEvent(d)); + }); + change.clear(); } - Datum existDatum = datumCache.get(datum.getDataCenter(), datum.getDataInfoId()); - if (existDatum != null) { - datum.addPublishers(existDatum.getPubMap()); + } finally { + tempLock.writeLock().unlock(); + } + if (events.isEmpty()) { + return; + } + final List connections = sessionServerConnectionFactory.getSessionConnections(); + if (connections.isEmpty()) { + LOGGER.warn("session conn is empty when temp change"); + return; + } + for (Connection connection : connections) { + for (DataTempChangeEvent event : events) { + Datum datum = event.getDatum(); + try { + // group by connect && dataInfoId + notifyTempExecutor.execute( + Tuple.of(datum.getDataInfoId(), connection.getRemoteAddress()), + new TempNotifier(connection, datum)); + CHANGETEMP_COMMIT_COUNTER.inc(); + } catch (RejectedExecutionException e) { + CHANGETEMP_SKIP_COUNTER.inc(); + LOGGER.warn("commit notify temp full, {}, {}", datum, e.getMessage()); + } catch (Throwable e) { + CHANGETEMP_SKIP_COUNTER.inc(); + LOGGER.error("commit notify temp failed, {}", datum, e); + } } - datum.setVersion(v.getValue()); - DataPushRequest request = new DataPushRequest(datum); - LOGGER.info("temp pub, {}", datum); - doNotify(request, connection); + } } - private void doNotify(Object request, Connection connection) { - Server sessionServer = boltExchange.getServer(dataServerConfig.getPort()); - sessionServer.sendSync(sessionServer.getChannel(connection.getRemoteAddress()), request, - dataServerConfig.getRpcTimeoutMillis()); + @Override + public void waitingUnthrowable() { + ConcurrentUtils.sleepUninterruptibly( + dataServerConfig.getNotifyTempDataIntervalMillis(), TimeUnit.MILLISECONDS); } - - private final class TempChangeMerger extends LoopRunnable { - - @Override - public void runUnthrowable() { - final List events = Lists.newArrayList(); - tempLock.writeLock().lock(); - try { - for (Map change : dataCenter2TempChanges.values()) { - change.values().forEach(d -> { - events.add(new DataTempChangeEvent(d)); - }); - change.clear(); - } - } finally { - tempLock.writeLock().unlock(); - } - if (events.isEmpty()) { - return; - } - final List connections = sessionServerConnectionFactory.getSessionConnections(); - if (connections.isEmpty()) { - LOGGER.warn("session conn is empty when temp change"); - return; - } - for (Connection connection : connections) { - for (DataTempChangeEvent event : events) { - Datum datum = event.getDatum(); - try { - // group by connect && dataInfoId - notifyTempExecutor.execute(Tuple.of(datum.getDataInfoId(), connection.getRemoteAddress()), - new TempNotifier(connection, datum)); - CHANGETEMP_COMMIT_COUNTER.inc(); - } catch (RejectedExecutionException e) { - CHANGETEMP_SKIP_COUNTER.inc(); - LOGGER.warn("commit notify temp full, {}, {}", datum, e.getMessage()); - } catch (Throwable e) { - CHANGETEMP_SKIP_COUNTER.inc(); - LOGGER.error("commit notify temp failed, {}", datum, e); - } - } - } + } + + private final class ChangeMerger extends LoopRunnable { + + @Override + public void runUnthrowable() { + final List events = Lists.newArrayList(); + final int maxItems = dataServerConfig.getNotifyMaxItems(); + lock.writeLock().lock(); + try { + for (Map.Entry> change : dataCenter2Changes.entrySet()) { + final String dataCenter = change.getKey(); + List dataInfoIds = Lists.newArrayList(change.getValue()); + change.getValue().clear(); + List> parts = Lists.partition(dataInfoIds, maxItems); + for (int i = 0; i < parts.size(); i++) { + events.add(new DataChangeEvent(dataCenter, parts.get(i))); + } } - - @Override - public void waitingUnthrowable() { - ConcurrentUtils.sleepUninterruptibly( - dataServerConfig.getNotifyTempDataIntervalMillis(), TimeUnit.MILLISECONDS); + } finally { + lock.writeLock().unlock(); + } + + if (!events.isEmpty()) { + final List connections = sessionServerConnectionFactory.getSessionConnections(); + if (connections.isEmpty()) { + LOGGER.error("session conn is empty when change"); + return; } - } - - private final class ChangeMerger extends LoopRunnable { - - @Override - public void runUnthrowable() { - final List events = Lists.newArrayList(); - final int maxItems = dataServerConfig.getNotifyMaxItems(); - lock.writeLock().lock(); - try { - for (Map.Entry> change : dataCenter2Changes.entrySet()) { - final String dataCenter = change.getKey(); - List dataInfoIds = Lists.newArrayList(change.getValue()); - change.getValue().clear(); - List> parts = Lists.partition(dataInfoIds, maxItems); - for (int i = 0; i < parts.size(); i++) { - events.add(new DataChangeEvent(dataCenter, parts.get(i))); - } - } - } finally { - lock.writeLock().unlock(); - } - - if (!events.isEmpty()) { - final List connections = sessionServerConnectionFactory - .getSessionConnections(); - if (connections.isEmpty()) { - LOGGER.error("session conn is empty when change"); - return; - } - for (DataChangeEvent event : events) { - final Map changes = new HashMap<>(events.size()); - final String dataCenter = event.getDataCenter(); - for (String dataInfoId : event.getDataInfoIds()) { - DatumVersion datumVersion = datumCache.getVersion(dataCenter, dataInfoId); - if (datumVersion != null) { - changes.put(dataInfoId, datumVersion); - } - } - if (changes.isEmpty()) { - continue; - } - for (Connection connection : connections) { - // group by connection - try { - notifyExecutor.execute(connection.getRemoteAddress(), - new ChangeNotifier(connection, event.getDataCenter(), changes)); - CHANGE_COMMIT_COUNTER.inc(); - } catch (RejectedExecutionException e) { - CHANGE_SKIP_COUNTER.inc(); - LOGGER.warn("commit notify full, {}, {}", connection, changes.size(), - e.getMessage()); - } catch (Throwable e) { - CHANGE_SKIP_COUNTER.inc(); - LOGGER.error("commit notify failed, {}, {}", connection, - changes.size(), e); - } - } - } + for (DataChangeEvent event : events) { + final Map changes = new HashMap<>(events.size()); + final String dataCenter = event.getDataCenter(); + for (String dataInfoId : event.getDataInfoIds()) { + DatumVersion datumVersion = datumCache.getVersion(dataCenter, dataInfoId); + if (datumVersion != null) { + changes.put(dataInfoId, datumVersion); } - - final List retries = getExpires(); - // commit retry - for (ChangeNotifier retry : retries) { - notifyExecutor.execute(retry.connection.getRemoteAddress(), retry); + } + if (changes.isEmpty()) { + continue; + } + for (Connection connection : connections) { + // group by connection + try { + notifyExecutor.execute( + connection.getRemoteAddress(), + new ChangeNotifier(connection, event.getDataCenter(), changes)); + CHANGE_COMMIT_COUNTER.inc(); + } catch (RejectedExecutionException e) { + CHANGE_SKIP_COUNTER.inc(); + LOGGER.warn("commit notify full, {}, {}", connection, changes.size(), e.getMessage()); + } catch (Throwable e) { + CHANGE_SKIP_COUNTER.inc(); + LOGGER.error("commit notify failed, {}, {}", connection, changes.size(), e); } + } } + } - @Override - public void waitingUnthrowable() { - ConcurrentUtils.sleepUninterruptibly(dataServerConfig.getNotifyIntervalMillis(), - TimeUnit.MILLISECONDS); - } + final List retries = getExpires(); + // commit retry + for (ChangeNotifier retry : retries) { + notifyExecutor.execute(retry.connection.getRemoteAddress(), retry); + } } - @VisibleForTesting - public Set getOnChanges(String dataCenter) { - Set changes = dataCenter2Changes.get(dataCenter); - return changes == null ? Collections.emptySet() : Sets.newHashSet(changes); + @Override + public void waitingUnthrowable() { + ConcurrentUtils.sleepUninterruptibly( + dataServerConfig.getNotifyIntervalMillis(), TimeUnit.MILLISECONDS); } -} \ No newline at end of file + } + + @VisibleForTesting + public Set getOnChanges(String dataCenter) { + Set changes = dataCenter2Changes.get(dataCenter); + return changes == null ? Collections.emptySet() : Sets.newHashSet(changes); + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataTempChangeEvent.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataTempChangeEvent.java index 880e5487f..f217fbd3f 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataTempChangeEvent.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataTempChangeEvent.java @@ -19,27 +19,27 @@ import com.alipay.sofa.registry.common.model.dataserver.Datum; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-08 19:54 yuzhi.lyz Exp $ */ public final class DataTempChangeEvent implements IDataChangeEvent { - private final Datum datum; + private final Datum datum; - public DataTempChangeEvent(Datum datum) { - this.datum = datum; - } + public DataTempChangeEvent(Datum datum) { + this.datum = datum; + } - /** - * Getter method for property datum. - * @return property value of datum - */ - public Datum getDatum() { - return datum; - } + /** + * Getter method for property datum. + * + * @return property value of datum + */ + public Datum getDatum() { + return datum; + } - @Override - public String toString() { - return "DataTempChangeEvent{" + "datum=" + datum + '}'; - } + @Override + public String toString() { + return "DataTempChangeEvent{" + "datum=" + datum + '}'; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/IDataChangeEvent.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/IDataChangeEvent.java index a1472d733..48e1ba93c 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/IDataChangeEvent.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/IDataChangeEvent.java @@ -17,10 +17,7 @@ package com.alipay.sofa.registry.server.data.change; /** - * * @author qian.lqlq * @version $Id: IDataChangeEvent.java, v 0.1 2018-05-10 17:11 qian.lqlq Exp $ */ -public interface IDataChangeEvent { - -} \ No newline at end of file +public interface IDataChangeEvent {} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/executor/ExecutorFactory.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/executor/ExecutorFactory.java index 21bf0f077..6806555ca 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/executor/ExecutorFactory.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/executor/ExecutorFactory.java @@ -16,6 +16,7 @@ */ package com.alipay.sofa.registry.server.data.executor; +import com.alipay.sofa.registry.util.NamedThreadFactory; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ScheduledExecutorService; @@ -23,48 +24,49 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; -import com.alipay.sofa.registry.util.NamedThreadFactory; - /** * the factory to create executor - * + * * @author qian.lqlq * @version $Id: ExecutorFactory.java, v 0.1 2018-03-08 14:50 qian.lqlq Exp $ */ public class ExecutorFactory { - /** - * new thread pool - * - * @param size - * @param name - * @return - */ - public static Executor newFixedThreadPool(int size, String name) { - return new ThreadPoolExecutor(size, size, 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue<>(), new NamedThreadFactory(name)); - } - /** - * new scheduled thread pool - * - * @param size - * @param name - * @return - */ - public static ScheduledExecutorService newScheduledThreadPool(int size, - String name) { - return new ScheduledThreadPoolExecutor(size, new NamedThreadFactory( - name)); - } + /** + * new thread pool + * + * @param size + * @param name + * @return + */ + public static Executor newFixedThreadPool(int size, String name) { + return new ThreadPoolExecutor( + size, + size, + 0L, + TimeUnit.MILLISECONDS, + new LinkedBlockingQueue<>(), + new NamedThreadFactory(name)); + } + /** + * new scheduled thread pool + * + * @param size + * @param name + * @return + */ + public static ScheduledExecutorService newScheduledThreadPool(int size, String name) { + return new ScheduledThreadPoolExecutor(size, new NamedThreadFactory(name)); + } - /** - * new single thread executor - * - * @param name - * @return - */ - public static Executor newSingleThreadExecutor(String name) { - return new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), - new NamedThreadFactory(name)); - } -} \ No newline at end of file + /** + * new single thread executor + * + * @param name + * @return + */ + public static Executor newSingleThreadExecutor(String name) { + return new ThreadPoolExecutor( + 1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(), new NamedThreadFactory(name)); + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/lease/SessionLeaseManager.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/lease/SessionLeaseManager.java index 062021797..600a90f6b 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/lease/SessionLeaseManager.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/lease/SessionLeaseManager.java @@ -29,139 +29,135 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; /** * @author yuzhi.lyz * @version v 0.1 2020-11-30 10:30 yuzhi.lyz Exp $ */ public final class SessionLeaseManager { - private static final Logger LOGGER = LoggerFactory - .getLogger(SessionLeaseManager.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SessionLeaseManager.class); - private static final Logger COMPACT_LOGGER = LoggerFactory - .getLogger("COMPACT"); + private static final Logger COMPACT_LOGGER = LoggerFactory.getLogger("COMPACT"); - private static final int MIN_LEASE_SEC = 5; + private static final int MIN_LEASE_SEC = 5; - @Autowired - private DataServerConfig dataServerConfig; - @Autowired - private DatumStorage localDatumStorage; - @Autowired - private SessionServerConnectionFactory sessionServerConnectionFactory; - - private final Map connectIdRenewTimestampMap = new ConcurrentHashMap<>(); - - @PostConstruct - public void init() { - validateSessionLeaseSec(dataServerConfig.getSessionLeaseSecs()); - ConcurrentUtils.createDaemonThread("session-lease-cleaner", new LeaseCleaner()).start(); - } - - public static void validateSessionLeaseSec(int sec) { - if (sec < MIN_LEASE_SEC) { - throw new IllegalArgumentException(String.format("min sessionLeaseSec(%d): %d", - MIN_LEASE_SEC, sec)); - } - } + @Autowired private DataServerConfig dataServerConfig; + @Autowired private DatumStorage localDatumStorage; + @Autowired private SessionServerConnectionFactory sessionServerConnectionFactory; - public void renewSession(ProcessId sessionProcessId) { - sessionProcessId = ProcessIdCache.cache(sessionProcessId); - connectIdRenewTimestampMap.put(sessionProcessId, System.currentTimeMillis()); - } + private final Map connectIdRenewTimestampMap = new ConcurrentHashMap<>(); - boolean contains(ProcessId sessionProcessId) { - return connectIdRenewTimestampMap.containsKey(sessionProcessId); - } + @PostConstruct + public void init() { + validateSessionLeaseSec(dataServerConfig.getSessionLeaseSecs()); + ConcurrentUtils.createDaemonThread("session-lease-cleaner", new LeaseCleaner()).start(); + } - private Map getExpireProcessId(int leaseMs) { - Map expires = Maps.newHashMap(); - final long lastRenew = System.currentTimeMillis() - leaseMs; - for (Map.Entry e : connectIdRenewTimestampMap.entrySet()) { - if (e.getValue() < lastRenew) { - expires.put(e.getKey(), new Date(e.getValue())); - } - } - return expires; + public static void validateSessionLeaseSec(int sec) { + if (sec < MIN_LEASE_SEC) { + throw new IllegalArgumentException( + String.format("min sessionLeaseSec(%d): %d", MIN_LEASE_SEC, sec)); } - - private List cleanExpire(Collection expires) { - List cleans = Lists.newArrayList(); - for (ProcessId p : expires) { - if (sessionServerConnectionFactory.containsConnection(p)) { - LOGGER.warn("expire session has conn, {}", p); - continue; - } - connectIdRenewTimestampMap.remove(p); - cleans.add(p); - } - return cleans; + } + + public void renewSession(ProcessId sessionProcessId) { + sessionProcessId = ProcessIdCache.cache(sessionProcessId); + connectIdRenewTimestampMap.put(sessionProcessId, System.currentTimeMillis()); + } + + boolean contains(ProcessId sessionProcessId) { + return connectIdRenewTimestampMap.containsKey(sessionProcessId); + } + + private Map getExpireProcessId(int leaseMs) { + Map expires = Maps.newHashMap(); + final long lastRenew = System.currentTimeMillis() - leaseMs; + for (Map.Entry e : connectIdRenewTimestampMap.entrySet()) { + if (e.getValue() < lastRenew) { + expires.put(e.getKey(), new Date(e.getValue())); + } } - - private void cleanStorage() { - // make sure the existing processId be clean - Set stores = localDatumStorage.getSessionProcessIds(); - for (ProcessId p : stores) { - if (!connectIdRenewTimestampMap.containsKey(p)) { - Map versionMap = localDatumStorage.clean(p); - LOGGER.info("expire session correct, {}, datums={}", p, versionMap.size()); - } - } + return expires; + } + + private List cleanExpire(Collection expires) { + List cleans = Lists.newArrayList(); + for (ProcessId p : expires) { + if (sessionServerConnectionFactory.containsConnection(p)) { + LOGGER.warn("expire session has conn, {}", p); + continue; + } + connectIdRenewTimestampMap.remove(p); + cleans.add(p); } - - private void renewByConnection() { - sessionServerConnectionFactory.getProcessIds().forEach(p -> renewSession(p)); + return cleans; + } + + private void cleanStorage() { + // make sure the existing processId be clean + Set stores = localDatumStorage.getSessionProcessIds(); + for (ProcessId p : stores) { + if (!connectIdRenewTimestampMap.containsKey(p)) { + Map versionMap = localDatumStorage.clean(p); + LOGGER.info("expire session correct, {}, datums={}", p, versionMap.size()); + } } + } - private final class LeaseCleaner extends LoopRunnable { - @Override - public void runUnthrowable() { - clean(); - } + private void renewByConnection() { + sessionServerConnectionFactory.getProcessIds().forEach(p -> renewSession(p)); + } - @Override - public void waitingUnthrowable() { - ConcurrentUtils.sleepUninterruptibly(1, TimeUnit.SECONDS); - } + private final class LeaseCleaner extends LoopRunnable { + @Override + public void runUnthrowable() { + clean(); } - void clean() { - renewByConnection(); - Map expires = getExpireProcessId(dataServerConfig.getSessionLeaseSecs() * 1000); - LOGGER.info("lease expire sessions, {}", expires); - - if (!expires.isEmpty()) { - List cleans = cleanExpire(expires.keySet()); - LOGGER.info("expire sessions clean, {}", cleans); - } - - cleanStorage(); - - // compact the unpub - long tombstoneTimestamp = System.currentTimeMillis() - - dataServerConfig.getDatumCompactDelaySecs() * 1000; - Map compacted = localDatumStorage.compact(tombstoneTimestamp); - COMPACT_LOGGER.info("compact datum, {}", compacted); + @Override + public void waitingUnthrowable() { + ConcurrentUtils.sleepUninterruptibly(1, TimeUnit.SECONDS); } + } - @VisibleForTesting - void setDataServerConfig(DataServerConfig dataServerConfig) { - this.dataServerConfig = dataServerConfig; - } + void clean() { + renewByConnection(); + Map expires = + getExpireProcessId(dataServerConfig.getSessionLeaseSecs() * 1000); + LOGGER.info("lease expire sessions, {}", expires); - @VisibleForTesting - void setLocalDatumStorage(DatumStorage localDatumStorage) { - this.localDatumStorage = localDatumStorage; + if (!expires.isEmpty()) { + List cleans = cleanExpire(expires.keySet()); + LOGGER.info("expire sessions clean, {}", cleans); } - @VisibleForTesting - void setSessionServerConnectionFactory(SessionServerConnectionFactory sessionServerConnectionFactory) { - this.sessionServerConnectionFactory = sessionServerConnectionFactory; - } + cleanStorage(); + + // compact the unpub + long tombstoneTimestamp = + System.currentTimeMillis() - dataServerConfig.getDatumCompactDelaySecs() * 1000; + Map compacted = localDatumStorage.compact(tombstoneTimestamp); + COMPACT_LOGGER.info("compact datum, {}", compacted); + } + + @VisibleForTesting + void setDataServerConfig(DataServerConfig dataServerConfig) { + this.dataServerConfig = dataServerConfig; + } + + @VisibleForTesting + void setLocalDatumStorage(DatumStorage localDatumStorage) { + this.localDatumStorage = localDatumStorage; + } + + @VisibleForTesting + void setSessionServerConnectionFactory( + SessionServerConnectionFactory sessionServerConnectionFactory) { + this.sessionServerConnectionFactory = sessionServerConnectionFactory; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/DataMetaServerManager.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/DataMetaServerManager.java index 40a39b0de..1802ebcfc 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/DataMetaServerManager.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/DataMetaServerManager.java @@ -18,32 +18,29 @@ import com.alipay.sofa.registry.server.data.bootstrap.DataServerConfig; import com.alipay.sofa.registry.server.shared.meta.AbstractMetaServerManager; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Collection; +import org.springframework.beans.factory.annotation.Autowired; /** * @author chen.zhu - *

- * Mar 15, 2021 + *

Mar 15, 2021 */ public class DataMetaServerManager extends AbstractMetaServerManager { - @Autowired - private DataServerConfig dataServerConfig; + @Autowired private DataServerConfig dataServerConfig; - @Override - protected Collection getConfiguredMetaServerDomains() { - return dataServerConfig.getMetaServerAddresses(); - } + @Override + protected Collection getConfiguredMetaServerDomains() { + return dataServerConfig.getMetaServerAddresses(); + } - @Override - public int getRpcTimeoutMillis() { - return dataServerConfig.getRpcTimeoutMillis(); - } + @Override + public int getRpcTimeoutMillis() { + return dataServerConfig.getRpcTimeoutMillis(); + } - @Override - public int getServerPort() { - return dataServerConfig.getMetaServerPort(); - } + @Override + public int getServerPort() { + return dataServerConfig.getMetaServerPort(); + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/DataNodeExchanger.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/DataNodeExchanger.java index f5049dbac..d07d9d0b0 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/DataNodeExchanger.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/DataNodeExchanger.java @@ -20,10 +20,9 @@ import com.alipay.sofa.registry.remoting.exchange.Exchange; import com.alipay.sofa.registry.server.data.bootstrap.DataServerConfig; import com.alipay.sofa.registry.server.shared.remoting.ClientSideExchanger; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Collection; import java.util.Collections; +import org.springframework.beans.factory.annotation.Autowired; /** * @author xuanbei @@ -31,31 +30,30 @@ */ public class DataNodeExchanger extends ClientSideExchanger { - @Autowired - private DataServerConfig dataServerConfig; - - public DataNodeExchanger() { - super(Exchange.DATA_SERVER_TYPE); - } - - @Override - public int getRpcTimeoutMillis() { - return dataServerConfig.getRpcTimeoutMillis(); - } - - @Override - public int getServerPort() { - // the Exchanger only for sync data - return dataServerConfig.getSyncDataPort(); - } - - @Override - public int getConnNum() { - return 3; - } - - @Override - protected Collection getClientHandlers() { - return Collections.emptyList(); - } + @Autowired private DataServerConfig dataServerConfig; + + public DataNodeExchanger() { + super(Exchange.DATA_SERVER_TYPE); + } + + @Override + public int getRpcTimeoutMillis() { + return dataServerConfig.getRpcTimeoutMillis(); + } + + @Override + public int getServerPort() { + // the Exchanger only for sync data + return dataServerConfig.getSyncDataPort(); + } + + @Override + public int getConnNum() { + return 3; + } + + @Override + protected Collection getClientHandlers() { + return Collections.emptyList(); + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/SessionNodeExchanger.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/SessionNodeExchanger.java index 049502e4f..e42e93ec4 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/SessionNodeExchanger.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/SessionNodeExchanger.java @@ -20,42 +20,39 @@ import com.alipay.sofa.registry.remoting.exchange.Exchange; import com.alipay.sofa.registry.server.data.bootstrap.DataServerConfig; import com.alipay.sofa.registry.server.shared.remoting.ClientSideExchanger; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Collection; import java.util.Collections; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-30 21:28 yuzhi.lyz Exp $ */ public class SessionNodeExchanger extends ClientSideExchanger { - @Autowired - private DataServerConfig dataServerConfig; - - public SessionNodeExchanger() { - super(Exchange.SESSION_SERVER_TYPE); - } - - @Override - public int getRpcTimeoutMillis() { - return dataServerConfig.getRpcTimeoutMillis(); - } - - @Override - public int getServerPort() { - // the Exchanger only for sync session - return dataServerConfig.getSyncSessionPort(); - } - - @Override - public int getConnNum() { - return 5; - } - - @Override - protected Collection getClientHandlers() { - return Collections.emptyList(); - } + @Autowired private DataServerConfig dataServerConfig; + + public SessionNodeExchanger() { + super(Exchange.SESSION_SERVER_TYPE); + } + + @Override + public int getRpcTimeoutMillis() { + return dataServerConfig.getRpcTimeoutMillis(); + } + + @Override + public int getServerPort() { + // the Exchanger only for sync session + return dataServerConfig.getSyncSessionPort(); + } + + @Override + public int getConnNum() { + return 5; + } + + @Override + protected Collection getClientHandlers() { + return Collections.emptyList(); + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/SlotFollowerDiffDigestRequestHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/SlotFollowerDiffDigestRequestHandler.java index 8ac42360d..6f463f90e 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/SlotFollowerDiffDigestRequestHandler.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/SlotFollowerDiffDigestRequestHandler.java @@ -30,81 +30,80 @@ import com.alipay.sofa.registry.server.data.slot.SlotManager; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; import com.alipay.sofa.registry.util.ParaCheckUtil; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-06 15:41 yuzhi.lyz Exp $ */ -public class SlotFollowerDiffDigestRequestHandler extends - AbstractServerHandler { - private static final Logger LOGGER = LoggerFactory - .getLogger(SlotFollowerDiffDigestRequestHandler.class); +public class SlotFollowerDiffDigestRequestHandler + extends AbstractServerHandler { + private static final Logger LOGGER = + LoggerFactory.getLogger(SlotFollowerDiffDigestRequestHandler.class); - @Autowired - private ThreadPoolExecutor slotSyncRequestProcessorExecutor; + @Autowired private ThreadPoolExecutor slotSyncRequestProcessorExecutor; - @Autowired - private DatumStorage localDatumStorage; + @Autowired private DatumStorage localDatumStorage; - @Autowired - private SlotManager slotManager; + @Autowired private SlotManager slotManager; - @Override - public Object doHandle(Channel channel, DataSlotDiffDigestRequest request) { - try { - slotManager.triggerUpdateSlotTable(request.getSlotTableEpoch()); - final int slotId = request.getSlotId(); - if (!slotManager.isLeader(slotId)) { - LOGGER.warn("not leader of {}", slotId); - return new GenericResponse().fillFailed("not leader of " + slotId); - } - DataSlotDiffDigestResult result = calcDiffResult(slotId, request.getDatumDigest(), - localDatumStorage.getPublishers(request.getSlotId())); - result.setSlotTableEpoch(slotManager.getSlotTableEpoch()); - return new GenericResponse().fillSucceed(result); - } catch (Throwable e) { - LOGGER.error("DiffSync dataInfoIds Request error for slot {}", request.getSlotId(), e); - throw new RuntimeException("DiffSync Request error!", e); - } + @Override + public Object doHandle(Channel channel, DataSlotDiffDigestRequest request) { + try { + slotManager.triggerUpdateSlotTable(request.getSlotTableEpoch()); + final int slotId = request.getSlotId(); + if (!slotManager.isLeader(slotId)) { + LOGGER.warn("not leader of {}", slotId); + return new GenericResponse().fillFailed("not leader of " + slotId); + } + DataSlotDiffDigestResult result = + calcDiffResult( + slotId, + request.getDatumDigest(), + localDatumStorage.getPublishers(request.getSlotId())); + result.setSlotTableEpoch(slotManager.getSlotTableEpoch()); + return new GenericResponse().fillSucceed(result); + } catch (Throwable e) { + LOGGER.error("DiffSync dataInfoIds Request error for slot {}", request.getSlotId(), e); + throw new RuntimeException("DiffSync Request error!", e); } + } - private DataSlotDiffDigestResult calcDiffResult(int targetSlot, - Map targetDigestMap, - Map> existingPublishers) { - DataSlotDiffDigestResult result = DataSlotDiffUtils.diffDigestPublishers(targetDigestMap, - existingPublishers); - DataSlotDiffUtils.logDiffResult(result, targetSlot); - return result; - } + private DataSlotDiffDigestResult calcDiffResult( + int targetSlot, + Map targetDigestMap, + Map> existingPublishers) { + DataSlotDiffDigestResult result = + DataSlotDiffUtils.diffDigestPublishers(targetDigestMap, existingPublishers); + DataSlotDiffUtils.logDiffResult(result, targetSlot); + return result; + } - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.DATA; - } + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.DATA; + } - @Override - public Class interest() { - return DataSlotDiffDigestRequest.class; - } + @Override + public Class interest() { + return DataSlotDiffDigestRequest.class; + } - @Override - public void checkParam(DataSlotDiffDigestRequest request) throws RuntimeException { - ParaCheckUtil.checkNonNegative(request.getSlotId(), "request.slotId"); - } + @Override + public void checkParam(DataSlotDiffDigestRequest request) throws RuntimeException { + ParaCheckUtil.checkNonNegative(request.getSlotId(), "request.slotId"); + } - @Override - public Object buildFailedResponse(String msg) { - return new GenericResponse().fillFailed(msg); - } + @Override + public Object buildFailedResponse(String msg) { + return new GenericResponse().fillFailed(msg); + } - @Override - public Executor getExecutor() { - return slotSyncRequestProcessorExecutor; - } + @Override + public Executor getExecutor() { + return slotSyncRequestProcessorExecutor; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/SlotFollowerDiffPublisherRequestHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/SlotFollowerDiffPublisherRequestHandler.java index 3c305c865..2e10a5c6e 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/SlotFollowerDiffPublisherRequestHandler.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/SlotFollowerDiffPublisherRequestHandler.java @@ -31,87 +31,85 @@ import com.alipay.sofa.registry.server.data.slot.SlotManager; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; import com.alipay.sofa.registry.util.ParaCheckUtil; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.List; import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-06 15:41 yuzhi.lyz Exp $ */ public class SlotFollowerDiffPublisherRequestHandler - extends - AbstractServerHandler { + extends AbstractServerHandler { - private static final Logger LOGGER = LoggerFactory - .getLogger(SlotFollowerDiffPublisherRequestHandler.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(SlotFollowerDiffPublisherRequestHandler.class); - @Autowired - private ThreadPoolExecutor slotSyncRequestProcessorExecutor; + @Autowired private ThreadPoolExecutor slotSyncRequestProcessorExecutor; - @Autowired - private DataServerConfig dataServerConfig; + @Autowired private DataServerConfig dataServerConfig; - @Autowired - private DatumStorage localDatumStorage; + @Autowired private DatumStorage localDatumStorage; - @Autowired - private SlotManager slotManager; + @Autowired private SlotManager slotManager; - @Override - public void checkParam(DataSlotDiffPublisherRequest request) throws RuntimeException { - ParaCheckUtil.checkNonNegative(request.getSlotId(), "request.slotId"); - } + @Override + public void checkParam(DataSlotDiffPublisherRequest request) throws RuntimeException { + ParaCheckUtil.checkNonNegative(request.getSlotId(), "request.slotId"); + } - @Override - public Object doHandle(Channel channel, DataSlotDiffPublisherRequest request) { - try { - slotManager.triggerUpdateSlotTable(request.getSlotTableEpoch()); - final int slotId = request.getSlotId(); - if (!slotManager.isLeader(slotId)) { - LOGGER.warn("not leader of {}", slotId); - return new GenericResponse().fillFailed("not leader of " + slotId); - } - DataSlotDiffPublisherResult result = calcDiffResult(slotId, - request.getDatumSummaries(), localDatumStorage.getPublishers(request.getSlotId())); - result.setSlotTableEpoch(slotManager.getSlotTableEpoch()); - return new GenericResponse().fillSucceed(result); - } catch (Throwable e) { - LOGGER.error("DiffSync publisher Request error for slot {}", request.getSlotId(), e); - throw new RuntimeException("DiffSync Request error!", e); - } + @Override + public Object doHandle(Channel channel, DataSlotDiffPublisherRequest request) { + try { + slotManager.triggerUpdateSlotTable(request.getSlotTableEpoch()); + final int slotId = request.getSlotId(); + if (!slotManager.isLeader(slotId)) { + LOGGER.warn("not leader of {}", slotId); + return new GenericResponse().fillFailed("not leader of " + slotId); + } + DataSlotDiffPublisherResult result = + calcDiffResult( + slotId, + request.getDatumSummaries(), + localDatumStorage.getPublishers(request.getSlotId())); + result.setSlotTableEpoch(slotManager.getSlotTableEpoch()); + return new GenericResponse().fillSucceed(result); + } catch (Throwable e) { + LOGGER.error("DiffSync publisher Request error for slot {}", request.getSlotId(), e); + throw new RuntimeException("DiffSync Request error!", e); } + } - private DataSlotDiffPublisherResult calcDiffResult(int targetSlot, - List datumSummaries, - Map> existingPublishers) { - DataSlotDiffPublisherResult result = DataSlotDiffUtils.diffPublishersResult(datumSummaries, - existingPublishers, dataServerConfig.getSlotSyncPublisherMaxNum()); - DataSlotDiffUtils.logDiffResult(result, targetSlot); - return result; - } + private DataSlotDiffPublisherResult calcDiffResult( + int targetSlot, + List datumSummaries, + Map> existingPublishers) { + DataSlotDiffPublisherResult result = + DataSlotDiffUtils.diffPublishersResult( + datumSummaries, existingPublishers, dataServerConfig.getSlotSyncPublisherMaxNum()); + DataSlotDiffUtils.logDiffResult(result, targetSlot); + return result; + } - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.DATA; - } + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.DATA; + } - @Override - public Class interest() { - return DataSlotDiffPublisherRequest.class; - } + @Override + public Class interest() { + return DataSlotDiffPublisherRequest.class; + } - @Override - public Object buildFailedResponse(String msg) { - return new GenericResponse().fillFailed(msg); - } + @Override + public Object buildFailedResponse(String msg) { + return new GenericResponse().fillFailed(msg); + } - @Override - public Executor getExecutor() { - return slotSyncRequestProcessorExecutor; - } + @Override + public Executor getExecutor() { + return slotSyncRequestProcessorExecutor; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/MetaServerServiceImpl.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/MetaServerServiceImpl.java index 7127d1d29..f6294137d 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/MetaServerServiceImpl.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/MetaServerServiceImpl.java @@ -29,74 +29,71 @@ import com.alipay.sofa.registry.server.data.slot.SlotManager; import com.alipay.sofa.registry.server.shared.env.ServerEnv; import com.alipay.sofa.registry.server.shared.meta.AbstractMetaServerService; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.List; import java.util.Set; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author qian.lqlq * @version $Id: MetaServiceImpl.java, v 0.1 2018-03-07 20:41 qian.lqlq Exp $ */ public class MetaServerServiceImpl extends AbstractMetaServerService { - @Autowired - private SlotManager slotManager; + @Autowired private SlotManager slotManager; - @Autowired - private DataNodeExchanger dataNodeExchanger; + @Autowired private DataNodeExchanger dataNodeExchanger; - @Autowired - private SessionNodeExchanger sessionNodeExchanger; + @Autowired private SessionNodeExchanger sessionNodeExchanger; - @Autowired - private DataServerConfig dataServerConfig; + @Autowired private DataServerConfig dataServerConfig; - @Override - protected long getCurrentSlotTableEpoch() { - return slotManager.getSlotTableEpoch(); - } + @Override + protected long getCurrentSlotTableEpoch() { + return slotManager.getSlotTableEpoch(); + } - @Override - protected void handleRenewResult(DataHeartBeatResponse result) { + @Override + protected void handleRenewResult(DataHeartBeatResponse result) { - Set dataServerList = getDataServerList(); - if (dataServerList != null && !dataServerList.isEmpty()) { - dataNodeExchanger.setServerIps(dataServerList); - dataNodeExchanger.notifyConnectServerAsync(); - } - Set sessionServerList = getDataServerList(); - if (sessionServerList != null && !sessionServerList.isEmpty()) { - sessionNodeExchanger.setServerIps(result.getSessionNodesMap().keySet()); - sessionNodeExchanger.notifyConnectServerAsync(); - } - if (result.getSlotTable() != null && result.getSlotTable() != SlotTable.INIT) { - slotManager.updateSlotTable(result.getSlotTable()); - } else { - LOGGER.warn("[handleRenewResult] not slot table result"); - } + Set dataServerList = getDataServerList(); + if (dataServerList != null && !dataServerList.isEmpty()) { + dataNodeExchanger.setServerIps(dataServerList); + dataNodeExchanger.notifyConnectServerAsync(); } - - @Override - protected HeartbeatRequest createRequest() { - long slotTableEpoch = -1L; - List slotStatuses; - try { - slotManager.readLock().lock(); - slotTableEpoch = slotManager.getSlotTableEpoch(); - slotStatuses = slotManager.getSlotStatuses(); - } finally { - slotManager.readLock().unlock(); - } - return new HeartbeatRequest<>(createNode(), slotTableEpoch, - dataServerConfig.getLocalDataCenter(), System.currentTimeMillis(), - new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, - SlotConfig.FUNC), slotStatuses); + Set sessionServerList = getDataServerList(); + if (sessionServerList != null && !sessionServerList.isEmpty()) { + sessionNodeExchanger.setServerIps(result.getSessionNodesMap().keySet()); + sessionNodeExchanger.notifyConnectServerAsync(); + } + if (result.getSlotTable() != null && result.getSlotTable() != SlotTable.INIT) { + slotManager.updateSlotTable(result.getSlotTable()); + } else { + LOGGER.warn("[handleRenewResult] not slot table result"); } + } - private DataNode createNode() { - return new DataNode(new URL(ServerEnv.IP), dataServerConfig.getLocalDataCenter()); + @Override + protected HeartbeatRequest createRequest() { + long slotTableEpoch = -1L; + List slotStatuses; + try { + slotManager.readLock().lock(); + slotTableEpoch = slotManager.getSlotTableEpoch(); + slotStatuses = slotManager.getSlotStatuses(); + } finally { + slotManager.readLock().unlock(); } + return new HeartbeatRequest<>( + createNode(), + slotTableEpoch, + dataServerConfig.getLocalDataCenter(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), + slotStatuses); + } -} \ No newline at end of file + private DataNode createNode() { + return new DataNode(new URL(ServerEnv.IP), dataServerConfig.getLocalDataCenter()); + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/handler/NotifyProvideDataChangeHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/handler/NotifyProvideDataChangeHandler.java index 3651d9dfb..5f6526251 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/handler/NotifyProvideDataChangeHandler.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/handler/NotifyProvideDataChangeHandler.java @@ -28,41 +28,37 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: DataChangeRequestHandler.java, v 0.1 2017-12-12 15:09 shangyu.wh Exp $ */ public class NotifyProvideDataChangeHandler extends AbstractClientHandler { - @Autowired - private MetaServerService metaServerService; + @Autowired private MetaServerService metaServerService; - @Autowired - private ProvideDataProcessor provideDataProcessorManager; + @Autowired private ProvideDataProcessor provideDataProcessorManager; - @Override - protected NodeType getConnectNodeType() { - return NodeType.META; - } + @Override + protected NodeType getConnectNodeType() { + return NodeType.META; + } - @Override - public Object doHandle(Channel channel, ProvideDataChangeEvent request) { - String dataInfoId = request.getDataInfoId(); - if (request.getDataOperator() != DataOperator.REMOVE) { - ProvideData provideData = metaServerService.fetchData(dataInfoId); - provideDataProcessorManager.changeDataProcess(provideData); - } - return null; + @Override + public Object doHandle(Channel channel, ProvideDataChangeEvent request) { + String dataInfoId = request.getDataInfoId(); + if (request.getDataOperator() != DataOperator.REMOVE) { + ProvideData provideData = metaServerService.fetchData(dataInfoId); + provideDataProcessorManager.changeDataProcess(provideData); } + return null; + } - @Override - public Class interest() { - return ProvideDataChangeEvent.class; - } - - @Override - public CommonResponse buildFailedResponse(String msg) { - return CommonResponse.buildFailedResponse(msg); - } + @Override + public Class interest() { + return ProvideDataChangeEvent.class; + } -} \ No newline at end of file + @Override + public CommonResponse buildFailedResponse(String msg) { + return CommonResponse.buildFailedResponse(msg); + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/ProvideDataProcessor.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/ProvideDataProcessor.java index e10f8c5b4..ecb4cedbc 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/ProvideDataProcessor.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/ProvideDataProcessor.java @@ -19,14 +19,12 @@ import com.alipay.sofa.registry.common.model.metaserver.ProvideData; /** - * * @author kezhu.wukz - * @version 1.0: ProvideDataProcessor.java, v 0.1 2019-12-25 17:26 kezhu.wukz - * Exp $ + * @version 1.0: ProvideDataProcessor.java, v 0.1 2019-12-25 17:26 kezhu.wukz Exp $ */ public interface ProvideDataProcessor { - void changeDataProcess(ProvideData provideData); + void changeDataProcess(ProvideData provideData); - boolean support(ProvideData provideData); -} \ No newline at end of file + boolean support(ProvideData provideData); +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/ProvideDataProcessorManager.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/ProvideDataProcessorManager.java index 24346f4d9..3f42a8c35 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/ProvideDataProcessorManager.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/ProvideDataProcessorManager.java @@ -16,35 +16,33 @@ */ package com.alipay.sofa.registry.server.data.remoting.metaserver.provideData; +import com.alipay.sofa.registry.common.model.metaserver.ProvideData; import java.util.ArrayList; import java.util.Collection; -import com.alipay.sofa.registry.common.model.metaserver.ProvideData; - /** - * * @author kezhu.wukz * @version 1.0: ProvideDataProcessorManager.java, v 0.1 2019-12-25 17:39 kezhu.wukz Exp $ */ public class ProvideDataProcessorManager implements ProvideDataProcessor { - private Collection provideDataProcessors = new ArrayList<>(); + private Collection provideDataProcessors = new ArrayList<>(); - public void addProvideDataProcessor(ProvideDataProcessor provideDataProcessor) { - provideDataProcessors.add(provideDataProcessor); - } + public void addProvideDataProcessor(ProvideDataProcessor provideDataProcessor) { + provideDataProcessors.add(provideDataProcessor); + } - @Override - public void changeDataProcess(ProvideData provideData) { - for (ProvideDataProcessor provideDataProcessor : provideDataProcessors) { - if (provideDataProcessor.support(provideData)) { - provideDataProcessor.changeDataProcess(provideData); - } - } + @Override + public void changeDataProcess(ProvideData provideData) { + for (ProvideDataProcessor provideDataProcessor : provideDataProcessors) { + if (provideDataProcessor.support(provideData)) { + provideDataProcessor.changeDataProcess(provideData); + } } + } - @Override - public boolean support(ProvideData provideData) { - return false; - } -} \ No newline at end of file + @Override + public boolean support(ProvideData provideData) { + return false; + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/processor/SessionLeaseProvideDataProcessor.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/processor/SessionLeaseProvideDataProcessor.java index b325617e1..3713cce57 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/processor/SessionLeaseProvideDataProcessor.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/metaserver/provideData/processor/SessionLeaseProvideDataProcessor.java @@ -26,37 +26,35 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author kezhu.wukz * @version 1.0: DatumExpireProvideDataProcessor.java, v 0.1 2019-12-26 20:30 kezhu.wukz Exp $ */ public class SessionLeaseProvideDataProcessor implements ProvideDataProcessor { - private static final Logger LOGGER = LoggerFactory - .getLogger(SessionLeaseProvideDataProcessor.class); - - @Autowired - private DataServerConfig dataServerConfig; - - @Override - public void changeDataProcess(ProvideData provideData) { - if (provideData == null) { - LOGGER.info("Fetch data sessionLease null"); - return; - } + private static final Logger LOGGER = + LoggerFactory.getLogger(SessionLeaseProvideDataProcessor.class); - final Integer data = ProvideData.toInteger(provideData); - if (data == null) { - LOGGER.info("Fetch data sessionLease content null"); - return; - } + @Autowired private DataServerConfig dataServerConfig; - LOGGER.info("Fetch sessionLeaseSec {}", data); - SessionLeaseManager.validateSessionLeaseSec(data); - dataServerConfig.setSessionLeaseSecs(data); + @Override + public void changeDataProcess(ProvideData provideData) { + if (provideData == null) { + LOGGER.info("Fetch data sessionLease null"); + return; } - @Override - public boolean support(ProvideData provideData) { - return ValueConstants.DATA_SESSION_LEASE_SEC.equals(provideData.getDataInfoId()); + final Integer data = ProvideData.toInteger(provideData); + if (data == null) { + LOGGER.info("Fetch data sessionLease content null"); + return; } -} \ No newline at end of file + + LOGGER.info("Fetch sessionLeaseSec {}", data); + SessionLeaseManager.validateSessionLeaseSec(data); + dataServerConfig.setSessionLeaseSecs(data); + } + + @Override + public boolean support(ProvideData provideData) { + return ValueConstants.DATA_SESSION_LEASE_SEC.equals(provideData.getDataInfoId()); + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/SessionServerConnectionFactory.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/SessionServerConnectionFactory.java index 1960520de..8bf04be96 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/SessionServerConnectionFactory.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/SessionServerConnectionFactory.java @@ -27,7 +27,6 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; - import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.ConcurrentHashMap; @@ -42,159 +41,160 @@ * @version $Id: SessionServerConnectionFactory.java, v 0.1 2017-12-06 15:48 qian.lqlq Exp $ */ public class SessionServerConnectionFactory { - private static final Logger LOGGER = LoggerFactory - .getLogger(SessionServerConnectionFactory.class); - - private final Map session2Connections = new ConcurrentHashMap<>(); - - public boolean registerSession(ProcessId processId, Channel channel) { - if (channel == null) { - LOGGER.warn("registerSession with null channel, {}", processId); - return false; - } - final InetSocketAddress remoteAddress = channel.getRemoteAddress(); - final Connection conn = ((BoltChannel) channel).getConnection(); - if (remoteAddress == null || conn == null) { - LOGGER.warn("registerSession with null channel.connection, {}", processId); - return false; - } + private static final Logger LOGGER = + LoggerFactory.getLogger(SessionServerConnectionFactory.class); - Channels channels = session2Connections - .computeIfAbsent(remoteAddress.getAddress().getHostAddress(), k -> new Channels()); - Tuple exist = channels.channels.get(remoteAddress); - if (exist != null) { - if (exist.o1.equals(processId)) { - // the same - return false; - } - LOGGER.warn("registerSession channel {} has conflict processId, exist={}, register={}", - channel, exist.o1, processId); - } - processId = ProcessIdCache.cache(processId); - // maybe register happens after disconnect or parallely, at that time, connection is not fine - // synchronized avoid the case: isFine=true->disconnect.remove->register.put - synchronized (this) { - if (!channel.isConnected()) { - LOGGER.warn("registerSession with unconnected channel, {}, {}", processId, remoteAddress); - return false; - } - channels.channels.put(remoteAddress, new Tuple<>(processId, conn)); - } + private final Map session2Connections = new ConcurrentHashMap<>(); - LOGGER.info("registerSession {}, processId={}, channelSize={}", channel, processId, channels.channels.size()); - return true; + public boolean registerSession(ProcessId processId, Channel channel) { + if (channel == null) { + LOGGER.warn("registerSession with null channel, {}", processId); + return false; } - - /** - * session disconnected, The SessionServerDisconnectEvent is triggered only when the last connections is removed - */ - public void sessionDisconnected(Channel channel) { - final InetSocketAddress remoteAddress = channel.getRemoteAddress(); - if (remoteAddress == null) { - LOGGER.warn("sessionDisconnected with null channel.connection"); - return; - } - final Channels channels = session2Connections.get(remoteAddress.getAddress() - .getHostAddress()); - if (channels == null) { - LOGGER.warn("sessionDisconnected not found channels {}", remoteAddress); - return; - } - Tuple tuple = null; - synchronized (this) { - tuple = channels.channels.remove(remoteAddress); - } - LOGGER.info("sessionDisconnected, removed={}, processId={}, channelSize={}", channel, - tuple != null ? tuple.o1 : null, channels.channels.size()); - } - - /** - * get the map of sessionIp -> connection - */ - public Map getSessionConnectionMap() { - Map map = Maps.newHashMapWithExpectedSize(session2Connections.size()); - for (Map.Entry e : session2Connections.entrySet()) { - Channels channels = e.getValue(); - Connection conn = channels.chooseConnection(); - if (conn != null) { - map.put(e.getKey(), conn); - } - } - return map; + final InetSocketAddress remoteAddress = channel.getRemoteAddress(); + final Connection conn = ((BoltChannel) channel).getConnection(); + if (remoteAddress == null || conn == null) { + LOGGER.warn("registerSession with null channel.connection, {}", processId); + return false; } - public Map> getAllSessionConnections() { - Map> map = Maps.newHashMapWithExpectedSize(session2Connections - .size()); - for (Map.Entry e : session2Connections.entrySet()) { - Channels channels = e.getValue(); - List conns = new ArrayList<>(channels.channels.size()); - for (Tuple t : channels.channels.values()) { - conns.add(t.o2); - } - map.put(e.getKey(), conns); - } - return map; + Channels channels = + session2Connections.computeIfAbsent( + remoteAddress.getAddress().getHostAddress(), k -> new Channels()); + Tuple exist = channels.channels.get(remoteAddress); + if (exist != null) { + if (exist.o1.equals(processId)) { + // the same + return false; + } + LOGGER.warn( + "registerSession channel {} has conflict processId, exist={}, register={}", + channel, + exist.o1, + processId); } - - public boolean containsConnection(ProcessId sessionProcessId) { - for (Channels p : session2Connections.values()) { - if (p.contains(sessionProcessId)) { - return true; - } - } + processId = ProcessIdCache.cache(processId); + // maybe register happens after disconnect or parallely, at that time, connection is not fine + // synchronized avoid the case: isFine=true->disconnect.remove->register.put + synchronized (this) { + if (!channel.isConnected()) { + LOGGER.warn("registerSession with unconnected channel, {}, {}", processId, remoteAddress); return false; + } + channels.channels.put(remoteAddress, new Tuple<>(processId, conn)); } - /** - * get connections of SessionServer ( Randomly select a connection for each session ) - */ - public List getSessionConnections() { - return new ArrayList<>(getSessionConnectionMap().values()); + LOGGER.info( + "registerSession {}, processId={}, channelSize={}", + channel, + processId, + channels.channels.size()); + return true; + } + + /** + * session disconnected, The SessionServerDisconnectEvent is triggered only when the last + * connections is removed + */ + public void sessionDisconnected(Channel channel) { + final InetSocketAddress remoteAddress = channel.getRemoteAddress(); + if (remoteAddress == null) { + LOGGER.warn("sessionDisconnected with null channel.connection"); + return; } - - public Set getProcessIds() { - Set set = Sets.newHashSet(); - session2Connections.values().forEach(c -> set.addAll(c.getProcessIds())); - return set; + final Channels channels = session2Connections.get(remoteAddress.getAddress().getHostAddress()); + if (channels == null) { + LOGGER.warn("sessionDisconnected not found channels {}", remoteAddress); + return; } + Tuple tuple = null; + synchronized (this) { + tuple = channels.channels.remove(remoteAddress); + } + LOGGER.info( + "sessionDisconnected, removed={}, processId={}, channelSize={}", + channel, + tuple != null ? tuple.o1 : null, + channels.channels.size()); + } + + /** get the map of sessionIp -> connection */ + public Map getSessionConnectionMap() { + Map map = Maps.newHashMapWithExpectedSize(session2Connections.size()); + for (Map.Entry e : session2Connections.entrySet()) { + Channels channels = e.getValue(); + Connection conn = channels.chooseConnection(); + if (conn != null) { + map.put(e.getKey(), conn); + } + } + return map; + } + + public Map> getAllSessionConnections() { + Map> map = Maps.newHashMapWithExpectedSize(session2Connections.size()); + for (Map.Entry e : session2Connections.entrySet()) { + Channels channels = e.getValue(); + List conns = new ArrayList<>(channels.channels.size()); + for (Tuple t : channels.channels.values()) { + conns.add(t.o2); + } + map.put(e.getKey(), conns); + } + return map; + } - /** - * convenient class to store sessionConnAddress and connection - */ - private static final class Channels { - final AtomicInteger roundRobin = new AtomicInteger( - -1); - // remoteAddress as key - final Map> channels = Maps - .newConcurrentMap(); - - Connection chooseConnection() { - List> list = Lists.newArrayList(channels.values()); - if (list.isEmpty()) { - return null; - } - int n = roundRobin.incrementAndGet(); - if (n < 0) { - roundRobin.compareAndSet(n, 0); - n = (n == Integer.MIN_VALUE) ? 0 : Math.abs(n); - } - n = n % list.size(); - return list.get(n).o2; - } - - boolean contains(ProcessId processId) { - for (Tuple t : channels.values()) { - if (t.o1.equals(processId)) { - return true; - } - } - return false; - } + public boolean containsConnection(ProcessId sessionProcessId) { + for (Channels p : session2Connections.values()) { + if (p.contains(sessionProcessId)) { + return true; + } + } + return false; + } + + /** get connections of SessionServer ( Randomly select a connection for each session ) */ + public List getSessionConnections() { + return new ArrayList<>(getSessionConnectionMap().values()); + } + + public Set getProcessIds() { + Set set = Sets.newHashSet(); + session2Connections.values().forEach(c -> set.addAll(c.getProcessIds())); + return set; + } + + /** convenient class to store sessionConnAddress and connection */ + private static final class Channels { + final AtomicInteger roundRobin = new AtomicInteger(-1); + // remoteAddress as key + final Map> channels = Maps.newConcurrentMap(); + + Connection chooseConnection() { + List> list = Lists.newArrayList(channels.values()); + if (list.isEmpty()) { + return null; + } + int n = roundRobin.incrementAndGet(); + if (n < 0) { + roundRobin.compareAndSet(n, 0); + n = (n == Integer.MIN_VALUE) ? 0 : Math.abs(n); + } + n = n % list.size(); + return list.get(n).o2; + } - Set getProcessIds() { - return channels.values().stream().map(t -> t.o1).collect(Collectors.toSet()); + boolean contains(ProcessId processId) { + for (Tuple t : channels.values()) { + if (t.o1.equals(processId)) { + return true; } + } + return false; } + Set getProcessIds() { + return channels.values().stream().map(t -> t.o1).collect(Collectors.toSet()); + } + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/AbstractDataHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/AbstractDataHandler.java index 6c708d602..d644a6d28 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/AbstractDataHandler.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/AbstractDataHandler.java @@ -36,99 +36,94 @@ import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; import com.alipay.sofa.registry.util.ParaCheckUtil; import com.google.common.collect.Sets; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Collections; import java.util.Set; +import org.springframework.beans.factory.annotation.Autowired; /** * @author yuzhi.lyz * @version v 0.1 2020-12-04 14:59 yuzhi.lyz Exp $ */ public abstract class AbstractDataHandler extends AbstractServerHandler { - private static final Logger LOGGER_SLOT_ACCESS = LoggerFactory - .getLogger("SLOT-ACCESS"); - - private final Set DATA_TYPES = Collections - .unmodifiableSet(Sets - .newHashSet( - StoreData.DataType.PUBLISHER, - StoreData.DataType.UN_PUBLISHER)); - - @Autowired - protected DataChangeEventCenter dataChangeEventCenter; - - @Autowired - protected DataServerConfig dataServerConfig; - - @Autowired - protected SlotManager slotManager; - - @Autowired - protected DatumStorage localDatumStorage; - - @Autowired - protected SessionLeaseManager sessionLeaseManager; - - @Autowired - protected SessionServerConnectionFactory sessionServerConnectionFactory; - - protected void checkPublisher(Publisher publisher) { - ParaCheckUtil.checkNotNull(publisher, "publisher"); - ParaCheckUtil.checkNotBlank(publisher.getDataId(), "publisher.dataId"); - ParaCheckUtil.checkNotBlank(publisher.getInstanceId(), "publisher.instanceId"); - ParaCheckUtil.checkNotBlank(publisher.getGroup(), "publisher.group"); - ParaCheckUtil.checkNotBlank(publisher.getDataInfoId(), "publisher.dataInfoId"); - ParaCheckUtil.checkNotNull(publisher.getVersion(), "publisher.version"); - ParaCheckUtil.checkNotBlank(publisher.getRegisterId(), "publisher.registerId"); - if (publisher.getPublishType() != PublishType.TEMPORARY - && publisher.getDataType() == StoreData.DataType.PUBLISHER) { - ParaCheckUtil.checkNotNull(publisher.getSourceAddress(), "publisher.sourceAddress"); - } - ParaCheckUtil.checkContains(DATA_TYPES, publisher.getDataType(), "publisher.dataType"); - } + private static final Logger LOGGER_SLOT_ACCESS = LoggerFactory.getLogger("SLOT-ACCESS"); - protected void checkSessionProcessId(ProcessId sessionProcessId) { - ParaCheckUtil.checkNotNull(sessionProcessId, "request.sessionProcessId"); - } + private final Set DATA_TYPES = + Collections.unmodifiableSet( + Sets.newHashSet(StoreData.DataType.PUBLISHER, StoreData.DataType.UN_PUBLISHER)); - protected SlotAccess checkAccess(String dataInfoId, long slotTableEpoch, long slotLeaderEpoch) { - final int slotId = slotManager.slotOf(dataInfoId); - return checkAccess(slotId, slotTableEpoch, slotLeaderEpoch); - } + @Autowired protected DataChangeEventCenter dataChangeEventCenter; - protected SlotAccess checkAccess(int slotId, long slotTableEpoch, long slotLeaderEpoch) { - final SlotAccess slotAccess = slotManager.checkSlotAccess(slotId, slotTableEpoch, - slotLeaderEpoch); - if (slotAccess.isMoved()) { - LOGGER_SLOT_ACCESS.warn("[moved]{}, leaderEpoch={}, tableEpoch={}", slotAccess, - slotLeaderEpoch, slotTableEpoch); - } - - if (slotAccess.isMigrating()) { - LOGGER_SLOT_ACCESS.warn("[migrating]{}, leaderEpoch={}, tableEpoch={}", slotAccess, - slotLeaderEpoch, slotTableEpoch); - } - if (slotAccess.isMisMatch()) { - LOGGER_SLOT_ACCESS.warn("[mismatch]{}, leaderEpoch={}, tableEpoch={}", slotAccess, - slotLeaderEpoch, slotTableEpoch); - } - return slotAccess; - } + @Autowired protected DataServerConfig dataServerConfig; - protected void processSessionProcessId(Channel channel, ProcessId sessionProcessId) { - sessionServerConnectionFactory.registerSession(sessionProcessId, channel); - sessionLeaseManager.renewSession(sessionProcessId); - } + @Autowired protected SlotManager slotManager; - @Override - public CommonResponse buildFailedResponse(String msg) { - return SlotAccessGenericResponse.failedResponse(msg); - } + @Autowired protected DatumStorage localDatumStorage; + + @Autowired protected SessionLeaseManager sessionLeaseManager; + + @Autowired protected SessionServerConnectionFactory sessionServerConnectionFactory; - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.SESSION; + protected void checkPublisher(Publisher publisher) { + ParaCheckUtil.checkNotNull(publisher, "publisher"); + ParaCheckUtil.checkNotBlank(publisher.getDataId(), "publisher.dataId"); + ParaCheckUtil.checkNotBlank(publisher.getInstanceId(), "publisher.instanceId"); + ParaCheckUtil.checkNotBlank(publisher.getGroup(), "publisher.group"); + ParaCheckUtil.checkNotBlank(publisher.getDataInfoId(), "publisher.dataInfoId"); + ParaCheckUtil.checkNotNull(publisher.getVersion(), "publisher.version"); + ParaCheckUtil.checkNotBlank(publisher.getRegisterId(), "publisher.registerId"); + if (publisher.getPublishType() != PublishType.TEMPORARY + && publisher.getDataType() == StoreData.DataType.PUBLISHER) { + ParaCheckUtil.checkNotNull(publisher.getSourceAddress(), "publisher.sourceAddress"); + } + ParaCheckUtil.checkContains(DATA_TYPES, publisher.getDataType(), "publisher.dataType"); + } + + protected void checkSessionProcessId(ProcessId sessionProcessId) { + ParaCheckUtil.checkNotNull(sessionProcessId, "request.sessionProcessId"); + } + + protected SlotAccess checkAccess(String dataInfoId, long slotTableEpoch, long slotLeaderEpoch) { + final int slotId = slotManager.slotOf(dataInfoId); + return checkAccess(slotId, slotTableEpoch, slotLeaderEpoch); + } + + protected SlotAccess checkAccess(int slotId, long slotTableEpoch, long slotLeaderEpoch) { + final SlotAccess slotAccess = + slotManager.checkSlotAccess(slotId, slotTableEpoch, slotLeaderEpoch); + if (slotAccess.isMoved()) { + LOGGER_SLOT_ACCESS.warn( + "[moved]{}, leaderEpoch={}, tableEpoch={}", slotAccess, slotLeaderEpoch, slotTableEpoch); } + if (slotAccess.isMigrating()) { + LOGGER_SLOT_ACCESS.warn( + "[migrating]{}, leaderEpoch={}, tableEpoch={}", + slotAccess, + slotLeaderEpoch, + slotTableEpoch); + } + if (slotAccess.isMisMatch()) { + LOGGER_SLOT_ACCESS.warn( + "[mismatch]{}, leaderEpoch={}, tableEpoch={}", + slotAccess, + slotLeaderEpoch, + slotTableEpoch); + } + return slotAccess; + } + + protected void processSessionProcessId(Channel channel, ProcessId sessionProcessId) { + sessionServerConnectionFactory.registerSession(sessionProcessId, channel); + sessionLeaseManager.renewSession(sessionProcessId); + } + + @Override + public CommonResponse buildFailedResponse(String msg) { + return SlotAccessGenericResponse.failedResponse(msg); + } + + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.SESSION; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/BatchPutDataHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/BatchPutDataHandler.java index c5f31c6cd..23732e322 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/BatchPutDataHandler.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/BatchPutDataHandler.java @@ -31,126 +31,134 @@ import com.alipay.sofa.registry.remoting.Channel; import com.alipay.sofa.registry.util.ParaCheckUtil; import com.google.common.collect.Sets; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; +import org.springframework.beans.factory.annotation.Autowired; public class BatchPutDataHandler extends AbstractDataHandler { - private static final Logger LOGGER = LoggerFactory.getLogger("PUT"); - @Autowired - private ThreadPoolExecutor publishProcessorExecutor; + private static final Logger LOGGER = LoggerFactory.getLogger("PUT"); + @Autowired private ThreadPoolExecutor publishProcessorExecutor; - @Override - public void checkParam(BatchRequest request) throws RuntimeException { - checkSessionProcessId(request.getSessionProcessId()); - for (Object req : request.getRequest()) { - if (req instanceof Publisher) { - checkPublisher((Publisher) req); - } else if (req instanceof ClientOffPublisher) { - ParaCheckUtil.checkNotNull(((ClientOffPublisher) req).getConnectId(), - "ClientOffPublisher.connectIds"); - ParaCheckUtil.checkNotNull(((ClientOffPublisher) req).getPublisherMap(), - "ClientOffPublisher.publisherMap"); - } else { - throw new IllegalArgumentException("unsupported item in batch:" + req); - } - } + @Override + public void checkParam(BatchRequest request) throws RuntimeException { + checkSessionProcessId(request.getSessionProcessId()); + for (Object req : request.getRequest()) { + if (req instanceof Publisher) { + checkPublisher((Publisher) req); + } else if (req instanceof ClientOffPublisher) { + ParaCheckUtil.checkNotNull( + ((ClientOffPublisher) req).getConnectId(), "ClientOffPublisher.connectIds"); + ParaCheckUtil.checkNotNull( + ((ClientOffPublisher) req).getPublisherMap(), "ClientOffPublisher.publisherMap"); + } else { + throw new IllegalArgumentException("unsupported item in batch:" + req); + } } + } - @Override - public Object doHandle(Channel channel, BatchRequest request) { - final ProcessId sessionProcessId = request.getSessionProcessId(); - processSessionProcessId(channel, sessionProcessId); - final SlotAccess slotAccess = checkAccess(request.getSlotId(), request.getSlotTableEpoch(), - request.getSlotLeaderEpoch()); - if (slotAccess.isMoved() || slotAccess.isMisMatch()) { - // only reject the when moved - return SlotAccessGenericResponse.failedResponse(slotAccess); - } - final String slotIdStr = String.valueOf(request.getSlotId()); - final Set changeDataInfoIds = Sets.newHashSetWithExpectedSize(128); - try { - for (Object req : request.getRequest()) { - // contains publisher and unPublisher - if (req instanceof Publisher) { - Publisher publisher = (Publisher) req; - changeDataInfoIds.addAll(doHandle(publisher)); - if (publisher instanceof UnPublisher) { - LOGGER.info("unpub,{},{},{},{},{}", slotIdStr, publisher.getDataInfoId(), - publisher.getRegisterId(), publisher.getVersion(), - publisher.getRegisterTimestamp()); - } else { - LOGGER.info("pub,{},{},{},{},{}", slotIdStr, publisher.getDataInfoId(), - publisher.getRegisterId(), publisher.getVersion(), - publisher.getRegisterTimestamp()); - } - } else if (req instanceof ClientOffPublisher) { - ClientOffPublisher clientOff = (ClientOffPublisher) req; - changeDataInfoIds.addAll(doHandle(clientOff, sessionProcessId)); - for (Map.Entry> e : clientOff - .getPublisherMap().entrySet()) { - final String dataInfoId = e.getKey(); - for (Map.Entry ver : e.getValue().entrySet()) { - RegisterVersion version = ver.getValue(); - LOGGER.info("off,{},{},{},{},{}", slotIdStr, dataInfoId, ver.getKey(), - version.getVersion(), version.getRegisterTimestamp()); - } - } - } else { - throw new IllegalArgumentException("unsupported item in batch:" + req); - } - } - } finally { - // if has exception, try to notify the req which was handled - if (!changeDataInfoIds.isEmpty()) { - dataChangeEventCenter.onChange(changeDataInfoIds, - dataServerConfig.getLocalDataCenter()); - } - } - - return SlotAccessGenericResponse.successResponse(slotAccess, null); + @Override + public Object doHandle(Channel channel, BatchRequest request) { + final ProcessId sessionProcessId = request.getSessionProcessId(); + processSessionProcessId(channel, sessionProcessId); + final SlotAccess slotAccess = + checkAccess(request.getSlotId(), request.getSlotTableEpoch(), request.getSlotLeaderEpoch()); + if (slotAccess.isMoved() || slotAccess.isMisMatch()) { + // only reject the when moved + return SlotAccessGenericResponse.failedResponse(slotAccess); } - - private List doHandle(Publisher publisher) { - publisher = Publisher.internPublisher(publisher); - if (publisher.getPublishType() == PublishType.TEMPORARY) { - // create datum for the temp publisher, we need the datum.version for check ver - localDatumStorage.createEmptyDatumIfAbsent(publisher.getDataInfoId(), - dataServerConfig.getLocalDataCenter()); - // temporary only notify session, not store - dataChangeEventCenter.onTempPubChange(publisher, dataServerConfig.getLocalDataCenter()); - } else { - DatumVersion version = localDatumStorage.put(publisher); - if (version != null) { - return Collections.singletonList(publisher.getDataInfoId()); + final String slotIdStr = String.valueOf(request.getSlotId()); + final Set changeDataInfoIds = Sets.newHashSetWithExpectedSize(128); + try { + for (Object req : request.getRequest()) { + // contains publisher and unPublisher + if (req instanceof Publisher) { + Publisher publisher = (Publisher) req; + changeDataInfoIds.addAll(doHandle(publisher)); + if (publisher instanceof UnPublisher) { + LOGGER.info( + "unpub,{},{},{},{},{}", + slotIdStr, + publisher.getDataInfoId(), + publisher.getRegisterId(), + publisher.getVersion(), + publisher.getRegisterTimestamp()); + } else { + LOGGER.info( + "pub,{},{},{},{},{}", + slotIdStr, + publisher.getDataInfoId(), + publisher.getRegisterId(), + publisher.getVersion(), + publisher.getRegisterTimestamp()); + } + } else if (req instanceof ClientOffPublisher) { + ClientOffPublisher clientOff = (ClientOffPublisher) req; + changeDataInfoIds.addAll(doHandle(clientOff, sessionProcessId)); + for (Map.Entry> e : + clientOff.getPublisherMap().entrySet()) { + final String dataInfoId = e.getKey(); + for (Map.Entry ver : e.getValue().entrySet()) { + RegisterVersion version = ver.getValue(); + LOGGER.info( + "off,{},{},{},{},{}", + slotIdStr, + dataInfoId, + ver.getKey(), + version.getVersion(), + version.getRegisterTimestamp()); } + } + } else { + throw new IllegalArgumentException("unsupported item in batch:" + req); } - return Collections.emptyList(); + } + } finally { + // if has exception, try to notify the req which was handled + if (!changeDataInfoIds.isEmpty()) { + dataChangeEventCenter.onChange(changeDataInfoIds, dataServerConfig.getLocalDataCenter()); + } } - public List doHandle(ClientOffPublisher request, ProcessId sessionProcessId) { - Map> publisherMap = request.getPublisherMap(); - List dataInfoIds = new ArrayList<>(publisherMap.size()); - for (Map.Entry> e : publisherMap.entrySet()) { - DatumVersion version = localDatumStorage.remove(e.getKey(), sessionProcessId, - e.getValue()); - if (version != null) { - dataInfoIds.add(e.getKey()); - } - } - return dataInfoIds; - } + return SlotAccessGenericResponse.successResponse(slotAccess, null); + } - @Override - public Class interest() { - return BatchRequest.class; + private List doHandle(Publisher publisher) { + publisher = Publisher.internPublisher(publisher); + if (publisher.getPublishType() == PublishType.TEMPORARY) { + // create datum for the temp publisher, we need the datum.version for check ver + localDatumStorage.createEmptyDatumIfAbsent( + publisher.getDataInfoId(), dataServerConfig.getLocalDataCenter()); + // temporary only notify session, not store + dataChangeEventCenter.onTempPubChange(publisher, dataServerConfig.getLocalDataCenter()); + } else { + DatumVersion version = localDatumStorage.put(publisher); + if (version != null) { + return Collections.singletonList(publisher.getDataInfoId()); + } } + return Collections.emptyList(); + } - @Override - public Executor getExecutor() { - return publishProcessorExecutor; + public List doHandle(ClientOffPublisher request, ProcessId sessionProcessId) { + Map> publisherMap = request.getPublisherMap(); + List dataInfoIds = new ArrayList<>(publisherMap.size()); + for (Map.Entry> e : publisherMap.entrySet()) { + DatumVersion version = localDatumStorage.remove(e.getKey(), sessionProcessId, e.getValue()); + if (version != null) { + dataInfoIds.add(e.getKey()); + } } + return dataInfoIds; + } + + @Override + public Class interest() { + return BatchRequest.class; + } + @Override + public Executor getExecutor() { + return publishProcessorExecutor; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/DataServerConnectionHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/DataServerConnectionHandler.java index 58a7eb7cf..d565afc93 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/DataServerConnectionHandler.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/DataServerConnectionHandler.java @@ -24,25 +24,24 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * Connection handler for session connect data server * - * fix shangyu.wh + *

fix shangyu.wh + * * @author xuanbei * @since 2019/2/15 */ public class DataServerConnectionHandler extends ListenServerChannelHandler { - @Autowired - private SessionServerConnectionFactory sessionServerConnectionFactory; + @Autowired private SessionServerConnectionFactory sessionServerConnectionFactory; - @Override - public void disconnected(Channel channel) { - super.disconnected(channel); - sessionServerConnectionFactory.sessionDisconnected(channel); - } + @Override + public void disconnected(Channel channel) { + super.disconnected(channel); + sessionServerConnectionFactory.sessionDisconnected(channel); + } - @Override - protected Node.NodeType getConnectNodeType() { - return NodeType.SESSION; - } + @Override + protected Node.NodeType getConnectNodeType() { + return NodeType.SESSION; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/GetDataHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/GetDataHandler.java index a9390b983..12b4f7790 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/GetDataHandler.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/GetDataHandler.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.data.remoting.sessionserver.handler; +import static com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.HandlerMetrics.GetData.*; + import com.alipay.sofa.registry.common.model.dataserver.Datum; import com.alipay.sofa.registry.common.model.dataserver.GetDataRequest; import com.alipay.sofa.registry.common.model.slot.SlotAccess; @@ -27,12 +29,9 @@ import com.alipay.sofa.registry.server.data.cache.DatumCache; import com.alipay.sofa.registry.server.shared.util.DatumUtils; import com.alipay.sofa.registry.util.ParaCheckUtil; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; - -import static com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.HandlerMetrics.GetData.*; +import org.springframework.beans.factory.annotation.Autowired; /** * processor to get specific data @@ -41,74 +40,77 @@ * @version $Id: GetDataProcessor.java, v 0.1 2017-12-01 15:48 qian.lqlq Exp $ */ public class GetDataHandler extends AbstractDataHandler { - private static final Logger LOGGER = LoggerFactory.getLogger("GET"); - @Autowired - private DatumCache datumCache; + private static final Logger LOGGER = LoggerFactory.getLogger("GET"); + @Autowired private DatumCache datumCache; - @Autowired - private ThreadPoolExecutor getDataProcessorExecutor; + @Autowired private ThreadPoolExecutor getDataProcessorExecutor; - @Override - public Executor getExecutor() { - return getDataProcessorExecutor; - } + @Override + public Executor getExecutor() { + return getDataProcessorExecutor; + } - @Override - public void checkParam(GetDataRequest request) throws RuntimeException { - ParaCheckUtil.checkNotBlank(request.getDataInfoId(), "GetDataRequest.dataInfoId"); - ParaCheckUtil.checkNotBlank(request.getDataCenter(), "GetDataRequest.dataCenter"); - checkSessionProcessId(request.getSessionProcessId()); - } - - @Override - public Object doHandle(Channel channel, GetDataRequest request) { - processSessionProcessId(channel, request.getSessionProcessId()); + @Override + public void checkParam(GetDataRequest request) throws RuntimeException { + ParaCheckUtil.checkNotBlank(request.getDataInfoId(), "GetDataRequest.dataInfoId"); + ParaCheckUtil.checkNotBlank(request.getDataCenter(), "GetDataRequest.dataCenter"); + checkSessionProcessId(request.getSessionProcessId()); + } - final String dataInfoId = request.getDataInfoId(); - final String dataCenter = request.getDataCenter(); - final SlotAccess slotAccessBefore = checkAccess(dataInfoId, request.getSlotTableEpoch(), - request.getSlotLeaderEpoch()); - if (!slotAccessBefore.isAccept()) { - GET_DATUM_N_COUNTER.inc(); - return SlotAccessGenericResponse.failedResponse(slotAccessBefore); - } - final Datum datum = datumCache.get(dataCenter, dataInfoId); - // important. double check the slot access. avoid the case: - // 1. the slot is leader, the first check pass - // 2. slot moved and data cleaned - // 3. get datum, but null after cleaned, dangerous!! - // 3.1. session get datum by change.version, ignored null datum, would not push - // 3.2. session get datum by subscriber.register, accept null datum(the pub may not exists) and push empty - // so, need a double check slot access, make sure the slot's leader not change in the getting - final SlotAccess slotAccessAfter = checkAccess(dataInfoId, request.getSlotTableEpoch(), - request.getSlotLeaderEpoch()); - if (slotAccessAfter.getSlotLeaderEpoch() != slotAccessBefore.getSlotLeaderEpoch()) { - // the slot's leader has change - GET_DATUM_N_COUNTER.inc(); - return SlotAccessGenericResponse.failedResponse(slotAccessAfter, - "slotLeaderEpoch has change, prev=" + slotAccessBefore); - } - // return SubDatum, it's serdeSize and memoryOverhead much smaller than Datum - final SubDatum subDatum = datum != null ? DatumUtils.of(datum) : null; - GET_DATUM_Y_COUNTER.inc(); - if (subDatum != null) { - LOGGER.info("getD,{},{},{},{}", dataInfoId, dataCenter, - subDatum.getPublishers().size(), subDatum.getVersion()); - GET_PUBLISHER_COUNTER.inc(subDatum.getPublishers().size()); - } else { - LOGGER.info("getNilD,{},{}", dataInfoId, dataCenter); - } + @Override + public Object doHandle(Channel channel, GetDataRequest request) { + processSessionProcessId(channel, request.getSessionProcessId()); - return SlotAccessGenericResponse.successResponse(slotAccessAfter, subDatum); + final String dataInfoId = request.getDataInfoId(); + final String dataCenter = request.getDataCenter(); + final SlotAccess slotAccessBefore = + checkAccess(dataInfoId, request.getSlotTableEpoch(), request.getSlotLeaderEpoch()); + if (!slotAccessBefore.isAccept()) { + GET_DATUM_N_COUNTER.inc(); + return SlotAccessGenericResponse.failedResponse(slotAccessBefore); } - - @Override - protected void logRequest(Channel channel, GetDataRequest request) { - // not log + final Datum datum = datumCache.get(dataCenter, dataInfoId); + // important. double check the slot access. avoid the case: + // 1. the slot is leader, the first check pass + // 2. slot moved and data cleaned + // 3. get datum, but null after cleaned, dangerous!! + // 3.1. session get datum by change.version, ignored null datum, would not push + // 3.2. session get datum by subscriber.register, accept null datum(the pub may not exists) and + // push empty + // so, need a double check slot access, make sure the slot's leader not change in the getting + final SlotAccess slotAccessAfter = + checkAccess(dataInfoId, request.getSlotTableEpoch(), request.getSlotLeaderEpoch()); + if (slotAccessAfter.getSlotLeaderEpoch() != slotAccessBefore.getSlotLeaderEpoch()) { + // the slot's leader has change + GET_DATUM_N_COUNTER.inc(); + return SlotAccessGenericResponse.failedResponse( + slotAccessAfter, "slotLeaderEpoch has change, prev=" + slotAccessBefore); } - - @Override - public Class interest() { - return GetDataRequest.class; + // return SubDatum, it's serdeSize and memoryOverhead much smaller than Datum + final SubDatum subDatum = datum != null ? DatumUtils.of(datum) : null; + GET_DATUM_Y_COUNTER.inc(); + if (subDatum != null) { + LOGGER.info( + "getD,{},{},{},{}", + dataInfoId, + dataCenter, + subDatum.getPublishers().size(), + subDatum.getVersion()); + GET_PUBLISHER_COUNTER.inc(subDatum.getPublishers().size()); + } else { + LOGGER.info("getNilD,{},{}", dataInfoId, dataCenter); } + + return SlotAccessGenericResponse.successResponse(slotAccessAfter, subDatum); + } + + @Override + protected void logRequest(Channel channel, GetDataRequest request) { + // not log + } + + @Override + public Class interest() { + return GetDataRequest.class; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/GetDataVersionsHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/GetDataVersionsHandler.java index ef1eaa777..7f9364a8d 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/GetDataVersionsHandler.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/handler/GetDataVersionsHandler.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.data.remoting.sessionserver.handler; +import static com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.HandlerMetrics.GetVersion.*; + import com.alipay.sofa.registry.common.model.dataserver.DatumVersion; import com.alipay.sofa.registry.common.model.dataserver.GetDataVersionRequest; import com.alipay.sofa.registry.common.model.slot.SlotAccess; @@ -26,15 +28,11 @@ import com.alipay.sofa.registry.server.data.cache.DatumCache; import com.alipay.sofa.registry.server.data.cache.DatumStorage; import com.alipay.sofa.registry.util.ParaCheckUtil; - -import static com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.HandlerMetrics.GetVersion.*; - import com.google.common.collect.Maps; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Map; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; +import org.springframework.beans.factory.annotation.Autowired; /** * processor to get versions of specific dataInfoIds @@ -43,99 +41,116 @@ * @version $Id: GetDataVersionsProcessor.java, v 0.1 2017-12-06 19:56 qian.lqlq Exp $ */ public class GetDataVersionsHandler extends AbstractDataHandler { - private static final Logger LOGGER = LoggerFactory.getLogger("GET"); - @Autowired - private DatumCache datumCache; + private static final Logger LOGGER = LoggerFactory.getLogger("GET"); + @Autowired private DatumCache datumCache; - @Autowired - private DatumStorage localDatumStorage; + @Autowired private DatumStorage localDatumStorage; - @Autowired - private ThreadPoolExecutor getDataProcessorExecutor; + @Autowired private ThreadPoolExecutor getDataProcessorExecutor; - @Override - public Executor getExecutor() { - return getDataProcessorExecutor; - } + @Override + public Executor getExecutor() { + return getDataProcessorExecutor; + } - @Override - public void checkParam(GetDataVersionRequest request) throws RuntimeException { - ParaCheckUtil.checkNonNegative(request.getSlotId(), "GetDataVersionRequest.slotId"); - ParaCheckUtil.checkNotBlank(request.getDataCenter(), "GetDataVersionRequest.dataCenter"); - checkSessionProcessId(request.getSessionProcessId()); - } + @Override + public void checkParam(GetDataVersionRequest request) throws RuntimeException { + ParaCheckUtil.checkNonNegative(request.getSlotId(), "GetDataVersionRequest.slotId"); + ParaCheckUtil.checkNotBlank(request.getDataCenter(), "GetDataVersionRequest.dataCenter"); + checkSessionProcessId(request.getSessionProcessId()); + } - @Override - public Object doHandle(Channel channel, GetDataVersionRequest request) { - processSessionProcessId(channel, request.getSessionProcessId()); - final int slotId = request.getSlotId(); - final String dataCenter = request.getDataCenter(); - final SlotAccess slotAccessBefore = checkAccess(slotId, request.getSlotTableEpoch(), - request.getSlotLeaderEpoch()); - if (!slotAccessBefore.isAccept()) { - return SlotAccessGenericResponse.failedResponse(slotAccessBefore); - } - final Map interests = request.getInterests(); - Map getVersions = datumCache.getVersions(dataCenter, - slotId, interests.keySet()); - // double check slot access, @see GetDataHandler - final SlotAccess slotAccessAfter = checkAccess(slotId, request.getSlotTableEpoch(), - request.getSlotLeaderEpoch()); - if (slotAccessAfter.getSlotLeaderEpoch() != slotAccessBefore.getSlotLeaderEpoch()) { - return SlotAccessGenericResponse.failedResponse(slotAccessAfter, - "slotLeaderEpoch has change, prev=" + slotAccessBefore); + @Override + public Object doHandle(Channel channel, GetDataVersionRequest request) { + processSessionProcessId(channel, request.getSessionProcessId()); + final int slotId = request.getSlotId(); + final String dataCenter = request.getDataCenter(); + final SlotAccess slotAccessBefore = + checkAccess(slotId, request.getSlotTableEpoch(), request.getSlotLeaderEpoch()); + if (!slotAccessBefore.isAccept()) { + return SlotAccessGenericResponse.failedResponse(slotAccessBefore); + } + final Map interests = request.getInterests(); + Map getVersions = + datumCache.getVersions(dataCenter, slotId, interests.keySet()); + // double check slot access, @see GetDataHandler + final SlotAccess slotAccessAfter = + checkAccess(slotId, request.getSlotTableEpoch(), request.getSlotLeaderEpoch()); + if (slotAccessAfter.getSlotLeaderEpoch() != slotAccessBefore.getSlotLeaderEpoch()) { + return SlotAccessGenericResponse.failedResponse( + slotAccessAfter, "slotLeaderEpoch has change, prev=" + slotAccessBefore); + } + final boolean localDataCenter = dataServerConfig.isLocalDataCenter(dataCenter); + Map ret = Maps.newHashMapWithExpectedSize(interests.size()); + for (Map.Entry e : interests.entrySet()) { + final String dataInfoId = e.getKey(); + final DatumVersion interestVer = e.getValue(); + final DatumVersion currentVer = getVersions.get(dataInfoId); + // contains the datum which is interested + if (currentVer != null) { + if (interestVer.getValue() < currentVer.getValue()) { + // need to notify session + ret.put(dataInfoId, currentVer); + } else if (interestVer.getValue() > currentVer.getValue()) { + // the session.push version is bigger than datum.version. this may happens: + // 1. slot-1 own by data-A, balance slot-1, migrating from data-A to data-B. + // this need a very short time window to broadcast the information. e.g. a heartbeat + // interval time + // 2.1. part of session/data has not updated the slotTable. [session-A, data-A] + // 2.2. another part of the session/data has updated the slotTable. [session-B, data-B] + // 3. data-B finish migrating and session-B put publisher-B to data-B gen a new + // datum.version=V1 + // 4. session-A put publisher-A to data-A, gen a new datum.version=V2(V1 ret = Maps.newHashMapWithExpectedSize(interests.size()); - for (Map.Entry e : interests.entrySet()) { - final String dataInfoId = e.getKey(); - final DatumVersion interestVer = e.getValue(); - final DatumVersion currentVer = getVersions.get(dataInfoId); - // contains the datum which is interested - if (currentVer != null) { - if (interestVer.getValue() < currentVer.getValue()) { - // need to notify session - ret.put(dataInfoId, currentVer); - } else if (interestVer.getValue() > currentVer.getValue()) { - // the session.push version is bigger than datum.version. this may happens: - // 1. slot-1 own by data-A, balance slot-1, migrating from data-A to data-B. - // this need a very short time window to broadcast the information. e.g. a heartbeat interval time - // 2.1. part of session/data has not updated the slotTable. [session-A, data-A] - // 2.2. another part of the session/data has updated the slotTable. [session-B, data-B] - // 3. data-B finish migrating and session-B put publisher-B to data-B gen a new datum.version=V1 - // 4. session-A put publisher-A to data-A, gen a new datum.version=V2(V1 getDatumByDataInfoId(@QueryParam("dataId") String dataId, - @QueryParam("group") String group, - @QueryParam("instanceId") String instanceId, - @QueryParam("dataCenter") String dataCenter) { - - ParaCheckUtil.checkNotBlank(dataId, "dataId"); - ParaCheckUtil.checkNotBlank(group, "group"); - ParaCheckUtil.checkNotBlank(instanceId, "instanceId"); - ParaCheckUtil.checkNotBlank(dataCenter, "dataCenter"); - String dataInfoId = DataInfo.toDataInfoId(dataId, instanceId, group); - Map retList = new HashMap<>(); - retList.put(dataCenter, datumCache.get(dataCenter, dataInfoId)); - return retList; - } - - @POST - @Path("connect/query") - @Produces(MediaType.APPLICATION_JSON) - public Map> getPublishersByConnectId(Map map) { - Map> ret = new HashMap<>(); - if (map != null && !map.isEmpty()) { - map.forEach((clientConnectId, sessionConnectId) -> { - ConnectId connectId = ConnectId.of(clientConnectId, sessionConnectId); - Map publisherMap = datumCache.getByConnectId(connectId); - if (publisherMap != null && !publisherMap.isEmpty()) { - ret.put(connectId.toString(), publisherMap); - } - }); - } - return ret; - } - - @GET - @Path("datum/count") - @Produces(MediaType.APPLICATION_JSON) - public String getDatumCount() { - return getLocalDatumCount(); - } - - protected String getLocalDatumCount() { - StringBuilder sb = new StringBuilder("CacheDigest"); - try { - - Map> allMap = datumCache.getAll(); - if (!allMap.isEmpty()) { - for (Entry> dataCenterEntry : allMap.entrySet()) { - String dataCenter = dataCenterEntry.getKey(); - Map datumMap = dataCenterEntry.getValue(); - sb.append(String.format(" [Datum] size of datum in %s is %s", dataCenter, datumMap.size())); - int pubCount = datumMap.values().stream().mapToInt(Datum::publisherSize).sum(); - sb.append(String.format(",[Publisher] size of publisher in %s is %s", dataCenter, pubCount)); - } - } else { - sb.append(" datum cache is empty"); + private static final String SESSION = "SESSION"; + + private static final String META = "META"; + + @Autowired private SessionServerConnectionFactory sessionServerConnectionFactory; + + @Autowired private MetaServerServiceImpl metaServerService; + + @Autowired private DataServerConfig dataServerConfig; + + @Autowired private DatumCache datumCache; + + @GET + @Path("datum/query") + @Produces(MediaType.APPLICATION_JSON) + public Map getDatumByDataInfoId( + @QueryParam("dataId") String dataId, + @QueryParam("group") String group, + @QueryParam("instanceId") String instanceId, + @QueryParam("dataCenter") String dataCenter) { + + ParaCheckUtil.checkNotBlank(dataId, "dataId"); + ParaCheckUtil.checkNotBlank(group, "group"); + ParaCheckUtil.checkNotBlank(instanceId, "instanceId"); + ParaCheckUtil.checkNotBlank(dataCenter, "dataCenter"); + String dataInfoId = DataInfo.toDataInfoId(dataId, instanceId, group); + Map retList = new HashMap<>(); + retList.put(dataCenter, datumCache.get(dataCenter, dataInfoId)); + return retList; + } + + @POST + @Path("connect/query") + @Produces(MediaType.APPLICATION_JSON) + public Map> getPublishersByConnectId(Map map) { + Map> ret = new HashMap<>(); + if (map != null && !map.isEmpty()) { + map.forEach( + (clientConnectId, sessionConnectId) -> { + ConnectId connectId = ConnectId.of(clientConnectId, sessionConnectId); + Map publisherMap = datumCache.getByConnectId(connectId); + if (publisherMap != null && !publisherMap.isEmpty()) { + ret.put(connectId.toString(), publisherMap); } - - } catch (Throwable t) { - sb.append(" cache digest error!"); - } - - return sb.toString(); + }); } - - @GET - @Path("{type}/serverList/query") - @Produces(MediaType.APPLICATION_JSON) - public Map> getServerListAll(@PathParam("type") String type) { - Map> map = new HashMap<>(); - if (type != null && !type.isEmpty()) { - String inputType = type.toUpperCase(); - - switch (inputType) { - case SESSION: - List sessionList = getSessionServerList(); - if (sessionList != null) { - map.put(dataServerConfig.getLocalDataCenter(), sessionList); - } - break; - case META: - List metaList = getMetaServerList(); - if (metaList != null) { - map.put(dataServerConfig.getLocalDataCenter(), metaList); - } - break; - default: - throw new IllegalArgumentException("unsupported server type:" + type); - } - + return ret; + } + + @GET + @Path("datum/count") + @Produces(MediaType.APPLICATION_JSON) + public String getDatumCount() { + return getLocalDatumCount(); + } + + protected String getLocalDatumCount() { + StringBuilder sb = new StringBuilder("CacheDigest"); + try { + + Map> allMap = datumCache.getAll(); + if (!allMap.isEmpty()) { + for (Entry> dataCenterEntry : allMap.entrySet()) { + String dataCenter = dataCenterEntry.getKey(); + Map datumMap = dataCenterEntry.getValue(); + sb.append( + String.format(" [Datum] size of datum in %s is %s", dataCenter, datumMap.size())); + int pubCount = datumMap.values().stream().mapToInt(Datum::publisherSize).sum(); + sb.append( + String.format(",[Publisher] size of publisher in %s is %s", dataCenter, pubCount)); } + } else { + sb.append(" datum cache is empty"); + } - return map; - } - - public List getSessionServerList() { - List connections = sessionServerConnectionFactory.getSessionConnections().stream() - .filter(connection -> connection != null && connection.isFine()) - .map(connection -> connection.getRemoteIP() + ":" + connection.getRemotePort()) - .collect(Collectors.toList()); - return connections; + } catch (Throwable t) { + sb.append(" cache digest error!"); } - public List getMetaServerList() { - return Lists.newArrayList(metaServerService.getMetaServerList()); + return sb.toString(); + } + + @GET + @Path("{type}/serverList/query") + @Produces(MediaType.APPLICATION_JSON) + public Map> getServerListAll(@PathParam("type") String type) { + Map> map = new HashMap<>(); + if (type != null && !type.isEmpty()) { + String inputType = type.toUpperCase(); + + switch (inputType) { + case SESSION: + List sessionList = getSessionServerList(); + if (sessionList != null) { + map.put(dataServerConfig.getLocalDataCenter(), sessionList); + } + break; + case META: + List metaList = getMetaServerList(); + if (metaList != null) { + map.put(dataServerConfig.getLocalDataCenter(), metaList); + } + break; + default: + throw new IllegalArgumentException("unsupported server type:" + type); + } } -} \ No newline at end of file + return map; + } + + public List getSessionServerList() { + List connections = + sessionServerConnectionFactory.getSessionConnections().stream() + .filter(connection -> connection != null && connection.isFine()) + .map(connection -> connection.getRemoteIP() + ":" + connection.getRemotePort()) + .collect(Collectors.toList()); + return connections; + } + + public List getMetaServerList() { + return Lists.newArrayList(metaServerService.getMetaServerList()); + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/DatumApiResource.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/DatumApiResource.java index 9a8cd21c7..9ace4db5d 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/DatumApiResource.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/DatumApiResource.java @@ -25,329 +25,337 @@ import com.alipay.sofa.registry.common.model.slot.Slot; import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.common.model.store.URL; +import com.alipay.sofa.registry.common.model.store.UnPublisher; import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.server.data.bootstrap.DataServerConfig; import com.alipay.sofa.registry.server.data.cache.DatumCache; import com.alipay.sofa.registry.server.data.cache.DatumStorage; -import com.alipay.sofa.registry.common.model.store.UnPublisher; import com.alipay.sofa.registry.server.data.slot.SlotManager; import com.alipay.sofa.registry.server.shared.env.ServerEnv; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; import com.alipay.sofa.registry.server.shared.util.DatumUtils; import com.google.common.collect.Lists; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.Validate; -import org.springframework.beans.factory.annotation.Autowired; - +import java.util.*; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import java.util.*; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author kezhu.wukz * @version $Id: DatumApiResource.java, v 0.1 2019-07-01 16:16 kezhu.wukz Exp $ */ @Path("datum/api") public class DatumApiResource { - private static final Logger LOGGER = LoggerFactory - .getLogger(DatumApiResource.class); - - private static final ProcessId TEMP_SESSION_PROCESSID = ServerEnv.PROCESS_ID; - - @Autowired - private DataServerConfig dataServerConfig; - - @Autowired - private DatumCache datumCache; + private static final Logger LOGGER = LoggerFactory.getLogger(DatumApiResource.class); - @Autowired - private DatumStorage localDatumStorage; + private static final ProcessId TEMP_SESSION_PROCESSID = ServerEnv.PROCESS_ID; - @Autowired - private AbstractServerHandler batchPutDataHandler; + @Autowired private DataServerConfig dataServerConfig; - @Autowired - private SlotManager slotManager; + @Autowired private DatumCache datumCache; - /** - * curl -i -d '{"dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP"}' -H "Content-Type: application/json" -X POST http://localhost:9622/datum/api/get - */ - @POST - @Path("/get") - @Produces(MediaType.APPLICATION_JSON) - public CommonResponse get(DatumParam datumParam) { - try { - validateAndCorrect(datumParam); - } catch (RuntimeException e) { - LOGGER.error(e.getMessage(), e); - return CommonResponse.buildFailedResponse(e.getMessage()); - } + @Autowired private DatumStorage localDatumStorage; - Datum datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); - if (datum == null) { - return getNotFoundResponse(datumParam); - } + @Autowired private AbstractServerHandler batchPutDataHandler; - return createResponse(datum); - } + @Autowired private SlotManager slotManager; - /** - * curl -i -d '{"dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP"}' -H "Content-Type: application/json" -X POST http://localhost:9622/datum/api/delete - */ - @POST - @Path("/delete") - @Produces(MediaType.APPLICATION_JSON) - public CommonResponse delete(DatumParam datumParam) { - try { - checkTestApiEnable(); - validateAndCorrect(datumParam); - } catch (RuntimeException e) { - LOGGER.error(e.getMessage(), e); - return CommonResponse.buildFailedResponse(e.getMessage()); - } - - Datum datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); - if (datum == null) { - return getNotFoundResponse(datumParam); - } - datumCache.clean(datumParam.getDataCenter(), datumParam.getDataInfoId()); - // get the newly datum - datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); - return createResponse(datum); + /** + * curl -i -d '{"dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP"}' -H + * "Content-Type: application/json" -X POST http://localhost:9622/datum/api/get + */ + @POST + @Path("/get") + @Produces(MediaType.APPLICATION_JSON) + public CommonResponse get(DatumParam datumParam) { + try { + validateAndCorrect(datumParam); + } catch (RuntimeException e) { + LOGGER.error(e.getMessage(), e); + return CommonResponse.buildFailedResponse(e.getMessage()); } - /** - * curl -i -d '{"dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP", "publisherDataBox":"1234", "publisherCell":"TestZone2", "publisherConnectId":"127.0.0.1:80"} ' -H "Content-Type: application/json" -X POST http://localhost:9622/datum/api/pub/add - * curl -i -d '{"dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP", "publisherDataBox":"1234", "publisherCell":"TestZone2"} ' -H "Content-Type: application/json" -X POST http://localhost:9622/datum/api/pub/add - * "publisherConnectId" can be unspecified. If not specified, the connectId of the first pub under the datum can be automatically selected (for testing purposes, it is generally not necessary to specify the connectId artificially). - */ - @POST - @Path("/pub/add") - @Produces(MediaType.APPLICATION_JSON) - public CommonResponse addPub(DatumParam datumParam) throws InterruptedException { - try { - checkTestApiEnable(); - validateAndCorrect(datumParam); - - //build pub - Datum datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); - if (datum == null) { - return getNotFoundResponse(datumParam); - } - Publisher publisher = buildPublisher(datum, datumParam); - - //build request and invoke - final int slotId = slotManager.slotOf(publisher.getDataInfoId()); - final Slot slot = slotManager.getSlot(slotId); - BatchRequest batchRequest = new BatchRequest(publisher.getSessionProcessId(), slotId, - Collections.singletonList(publisher)); - batchRequest.setSlotTableEpoch(slotManager.getSlotTableEpoch()); - batchRequest.setSlotLeaderEpoch(slot.getLeaderEpoch()); - batchPutDataHandler.doHandle(null, batchRequest); - // get the newly datum - datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); - return createResponse(datum); - } catch (RuntimeException e) { - LOGGER.error(e.getMessage(), e); - return CommonResponse.buildFailedResponse(e.getMessage()); - } + Datum datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); + if (datum == null) { + return getNotFoundResponse(datumParam); } - /** - * curl -i -d '{"dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP", "publisherRegisterId":"98de0e41-2a4d-44d7-b1f7-c520660657e8"} ' -H "Content-Type: application/json" -X POST http://localhost:9622/datum/api/pub/delete - */ - @POST - @Path("/pub/delete") - @Produces(MediaType.APPLICATION_JSON) - public CommonResponse deletePub(DatumParam datumParam) throws InterruptedException { - try { - checkTestApiEnable(); - validateAndCorrect(datumParam); - - //build pub - Datum datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); - if (datum == null) { - return getNotFoundResponse(datumParam); - } - UnPublisher publisher = buildUnPublisher(datum, datumParam); - - //build request and invoke - final int slotId = slotManager.slotOf(publisher.getDataInfoId()); - final Slot slot = slotManager.getSlot(slotId); - BatchRequest batchRequest = new BatchRequest(publisher.getSessionProcessId(), slotId, - Collections.singletonList(publisher)); - batchRequest.setSlotTableEpoch(slotManager.getSlotTableEpoch()); - batchRequest.setSlotLeaderEpoch(slot.getLeaderEpoch()); - batchPutDataHandler.doHandle(null, batchRequest); - // get the newly datum - datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); - return createResponse(datum); - } catch (RuntimeException e) { - LOGGER.error(e.getMessage(), e); - return CommonResponse.buildFailedResponse(e.getMessage()); - } + return createResponse(datum); + } + + /** + * curl -i -d '{"dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP"}' -H + * "Content-Type: application/json" -X POST http://localhost:9622/datum/api/delete + */ + @POST + @Path("/delete") + @Produces(MediaType.APPLICATION_JSON) + public CommonResponse delete(DatumParam datumParam) { + try { + checkTestApiEnable(); + validateAndCorrect(datumParam); + } catch (RuntimeException e) { + LOGGER.error(e.getMessage(), e); + return CommonResponse.buildFailedResponse(e.getMessage()); } - /** - * curl -d '{"dataCenter":"registry-cloud-test-b"}' -H "Content-Type: application/json" http://localhost:9622/datum/api/getDatumVersions - */ - @POST - @Path("/getDatumVersions") - @Produces(MediaType.APPLICATION_JSON) - public Object getDatumVersions(DatumParam datumParam) { - Map datumVersions = _getDatumVersions(datumParam); - - return datumVersions; + Datum datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); + if (datum == null) { + return getNotFoundResponse(datumParam); } - - private Map _getDatumVersions(DatumParam datumParam) { - Map datumVersions = new HashMap<>(); - if (dataServerConfig.isLocalDataCenter(datumParam.getDataCenter())) { - Map localDatums = localDatumStorage.getAll(); - return DatumUtils.getVersions(localDatums); - } else { - // TODO need support remote datecenter - LOGGER.error("unsupport remote datacenter, {}", datumParam.getDataCenter()); - } - return datumVersions; + datumCache.clean(datumParam.getDataCenter(), datumParam.getDataInfoId()); + // get the newly datum + datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); + return createResponse(datum); + } + + /** + * curl -i -d '{"dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP", + * "publisherDataBox":"1234", "publisherCell":"TestZone2", "publisherConnectId":"127.0.0.1:80"} ' + * -H "Content-Type: application/json" -X POST http://localhost:9622/datum/api/pub/add curl -i -d + * '{"dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP", "publisherDataBox":"1234", + * "publisherCell":"TestZone2"} ' -H "Content-Type: application/json" -X POST + * http://localhost:9622/datum/api/pub/add "publisherConnectId" can be unspecified. If not + * specified, the connectId of the first pub under the datum can be automatically selected (for + * testing purposes, it is generally not necessary to specify the connectId artificially). + */ + @POST + @Path("/pub/add") + @Produces(MediaType.APPLICATION_JSON) + public CommonResponse addPub(DatumParam datumParam) throws InterruptedException { + try { + checkTestApiEnable(); + validateAndCorrect(datumParam); + + // build pub + Datum datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); + if (datum == null) { + return getNotFoundResponse(datumParam); + } + Publisher publisher = buildPublisher(datum, datumParam); + + // build request and invoke + final int slotId = slotManager.slotOf(publisher.getDataInfoId()); + final Slot slot = slotManager.getSlot(slotId); + BatchRequest batchRequest = + new BatchRequest( + publisher.getSessionProcessId(), slotId, Collections.singletonList(publisher)); + batchRequest.setSlotTableEpoch(slotManager.getSlotTableEpoch()); + batchRequest.setSlotLeaderEpoch(slot.getLeaderEpoch()); + batchPutDataHandler.doHandle(null, batchRequest); + // get the newly datum + datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); + return createResponse(datum); + } catch (RuntimeException e) { + LOGGER.error(e.getMessage(), e); + return CommonResponse.buildFailedResponse(e.getMessage()); } - - /** - * curl -d '{"dataCenter":"registry-cloud-test-b"}' -H "Content-Type: application/json" http://localhost:9622/datum/api/getDatumVersions - */ - @POST - @Path("/getRemoteDatumVersions") - @Produces(MediaType.APPLICATION_JSON) - public Object getRemoteDatumVersions(DatumParam datumParam) { - throw new UnsupportedOperationException(); + } + + /** + * curl -i -d '{"dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP", + * "publisherRegisterId":"98de0e41-2a4d-44d7-b1f7-c520660657e8"} ' -H "Content-Type: + * application/json" -X POST http://localhost:9622/datum/api/pub/delete + */ + @POST + @Path("/pub/delete") + @Produces(MediaType.APPLICATION_JSON) + public CommonResponse deletePub(DatumParam datumParam) throws InterruptedException { + try { + checkTestApiEnable(); + validateAndCorrect(datumParam); + + // build pub + Datum datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); + if (datum == null) { + return getNotFoundResponse(datumParam); + } + UnPublisher publisher = buildUnPublisher(datum, datumParam); + + // build request and invoke + final int slotId = slotManager.slotOf(publisher.getDataInfoId()); + final Slot slot = slotManager.getSlot(slotId); + BatchRequest batchRequest = + new BatchRequest( + publisher.getSessionProcessId(), slotId, Collections.singletonList(publisher)); + batchRequest.setSlotTableEpoch(slotManager.getSlotTableEpoch()); + batchRequest.setSlotLeaderEpoch(slot.getLeaderEpoch()); + batchPutDataHandler.doHandle(null, batchRequest); + // get the newly datum + datum = datumCache.get(datumParam.getDataCenter(), datumParam.getDataInfoId()); + return createResponse(datum); + } catch (RuntimeException e) { + LOGGER.error(e.getMessage(), e); + return CommonResponse.buildFailedResponse(e.getMessage()); } - - /** - * curl -H "Content-Type: application/json" http://localhost:9622/datum/api/getDatumSizes - */ - @GET - @Path("/getDatumSizes") - @Produces(MediaType.APPLICATION_JSON) - public Object getDatumSizes() { - Map datumSizes = new HashMap<>(); - - Map localDatums = localDatumStorage.getAll(); - int localDatumSize = localDatums.size(); - datumSizes.put(dataServerConfig.getLocalDataCenter(), localDatumSize); - // TODO remote cluster - return datumSizes; + } + + /** + * curl -d '{"dataCenter":"registry-cloud-test-b"}' -H "Content-Type: application/json" + * http://localhost:9622/datum/api/getDatumVersions + */ + @POST + @Path("/getDatumVersions") + @Produces(MediaType.APPLICATION_JSON) + public Object getDatumVersions(DatumParam datumParam) { + Map datumVersions = _getDatumVersions(datumParam); + + return datumVersions; + } + + private Map _getDatumVersions(DatumParam datumParam) { + Map datumVersions = new HashMap<>(); + if (dataServerConfig.isLocalDataCenter(datumParam.getDataCenter())) { + Map localDatums = localDatumStorage.getAll(); + return DatumUtils.getVersions(localDatums); + } else { + // TODO need support remote datecenter + LOGGER.error("unsupport remote datacenter, {}", datumParam.getDataCenter()); } - - /** - * curl -d '{"dataCenter":"registry-cloud-test-b", "dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP"}' -H "Content-Type: application/json" http://localhost:9622/datum/api/getDatumVersion - */ - @POST - @Path("/getDatumVersion") - @Produces(MediaType.APPLICATION_JSON) - public Object getDatumVersion(DatumParam datumParam) { - String format = "dataCenter:%s, dataInfoId:%s, dataServer:%s, version:%s"; - String dataServer = null; - Long version = null; - if (dataServerConfig.isLocalDataCenter(datumParam.getDataCenter())) { - Map localDatums = localDatumStorage.getAll(); - Datum datum = localDatums.get(datumParam.getDataInfoId()); - if (datum != null) { - version = datum.getVersion(); - } - } else { - // TODO unsupport remote cluster - version = null; - } - - return String.format(format, datumParam.getDataCenter(), datumParam.getDataInfoId(), - dataServer, version); + return datumVersions; + } + + /** + * curl -d '{"dataCenter":"registry-cloud-test-b"}' -H "Content-Type: application/json" + * http://localhost:9622/datum/api/getDatumVersions + */ + @POST + @Path("/getRemoteDatumVersions") + @Produces(MediaType.APPLICATION_JSON) + public Object getRemoteDatumVersions(DatumParam datumParam) { + throw new UnsupportedOperationException(); + } + + /** curl -H "Content-Type: application/json" http://localhost:9622/datum/api/getDatumSizes */ + @GET + @Path("/getDatumSizes") + @Produces(MediaType.APPLICATION_JSON) + public Object getDatumSizes() { + Map datumSizes = new HashMap<>(); + + Map localDatums = localDatumStorage.getAll(); + int localDatumSize = localDatums.size(); + datumSizes.put(dataServerConfig.getLocalDataCenter(), localDatumSize); + // TODO remote cluster + return datumSizes; + } + + /** + * curl -d '{"dataCenter":"registry-cloud-test-b", + * "dataInfoId":"testDataId#@#DEFAULT_INSTANCE_ID#@#DEFAULT_GROUP"}' -H "Content-Type: + * application/json" http://localhost:9622/datum/api/getDatumVersion + */ + @POST + @Path("/getDatumVersion") + @Produces(MediaType.APPLICATION_JSON) + public Object getDatumVersion(DatumParam datumParam) { + String format = "dataCenter:%s, dataInfoId:%s, dataServer:%s, version:%s"; + String dataServer = null; + Long version = null; + if (dataServerConfig.isLocalDataCenter(datumParam.getDataCenter())) { + Map localDatums = localDatumStorage.getAll(); + Datum datum = localDatums.get(datumParam.getDataInfoId()); + if (datum != null) { + version = datum.getVersion(); + } + } else { + // TODO unsupport remote cluster + version = null; } - private CommonResponse getNotFoundResponse(DatumParam datumParam) { - return CommonResponse.buildFailedResponse(String.format( - "datum not found by dataCenter=%s, dataInfoId=%s", datumParam.getDataCenter(), - datumParam.getDataInfoId())); + return String.format( + format, datumParam.getDataCenter(), datumParam.getDataInfoId(), dataServer, version); + } + + private CommonResponse getNotFoundResponse(DatumParam datumParam) { + return CommonResponse.buildFailedResponse( + String.format( + "datum not found by dataCenter=%s, dataInfoId=%s", + datumParam.getDataCenter(), datumParam.getDataInfoId())); + } + + private void validateAndCorrect(DatumParam datumParam) { + Validate.notNull(datumParam, "datumParam is null"); + Validate.notEmpty(datumParam.getDataInfoId(), "datumParam.dataInfoId is empty"); + if (StringUtils.isBlank(datumParam.getDataCenter())) { + datumParam.setDataCenter(dataServerConfig.getLocalDataCenter()); } - - private void validateAndCorrect(DatumParam datumParam) { - Validate.notNull(datumParam, "datumParam is null"); - Validate.notEmpty(datumParam.getDataInfoId(), "datumParam.dataInfoId is empty"); - if (StringUtils.isBlank(datumParam.getDataCenter())) { - datumParam.setDataCenter(dataServerConfig.getLocalDataCenter()); - } + } + + private Publisher buildPublisher(Datum datum, DatumParam datumParam) { + Validate.notNull(datumParam.getPublisherRegisterId(), "datumParam.publisherRegisterId is null"); + Validate.notNull(datumParam.getPublisherCell(), "datumParam.publisherCell is null"); + Validate.notNull(datumParam.getPublisherDataBox(), "datumParam.publisherDataBox is null"); + + Publisher publisher = new Publisher(); + publisher.setSessionProcessId(TEMP_SESSION_PROCESSID); + publisher.setDataInfoId(datumParam.getDataInfoId()); + publisher.setRegisterId(datumParam.getPublisherRegisterId()); + publisher.setRegisterTimestamp(datumParam.getPublisherRegisterTimestamp()); + publisher.setVersion(datumParam.getPublisherVersion()); + if (datumParam.getPublisherConnectId() != null) { + String[] parts = datumParam.getPublisherConnectId().split(ValueConstants.CONNECT_ID_SPLIT); + if (parts.length < 2) { + throw new IllegalArgumentException( + "datumParam.publisherConnectId format invalid, should be clientIp:clientPort_sessionIp:sessionPort"); + } + publisher.setSourceAddress(URL.valueOf(parts[0])); + publisher.setTargetAddress(URL.valueOf(parts[1])); + } else { + Collection publishers = datum.getPubMap().values(); + if (publishers.size() == 0) { + throw new IllegalArgumentException( + "datumParam.publisherConnectId is null, and datum has no pubs"); + } + Publisher firstPub = publishers.iterator().next(); + publisher.setSourceAddress(firstPub.getSourceAddress()); + publisher.setTargetAddress(firstPub.getTargetAddress()); } - - private Publisher buildPublisher(Datum datum, DatumParam datumParam) { - Validate.notNull(datumParam.getPublisherRegisterId(), - "datumParam.publisherRegisterId is null"); - Validate.notNull(datumParam.getPublisherCell(), "datumParam.publisherCell is null"); - Validate.notNull(datumParam.getPublisherDataBox(), "datumParam.publisherDataBox is null"); - - Publisher publisher = new Publisher(); - publisher.setSessionProcessId(TEMP_SESSION_PROCESSID); - publisher.setDataInfoId(datumParam.getDataInfoId()); - publisher.setRegisterId(datumParam.getPublisherRegisterId()); - publisher.setRegisterTimestamp(datumParam.getPublisherRegisterTimestamp()); - publisher.setVersion(datumParam.getPublisherVersion()); - if (datumParam.getPublisherConnectId() != null) { - String[] parts = datumParam.getPublisherConnectId().split( - ValueConstants.CONNECT_ID_SPLIT); - if (parts.length < 2) { - throw new IllegalArgumentException( - "datumParam.publisherConnectId format invalid, should be clientIp:clientPort_sessionIp:sessionPort"); - } - publisher.setSourceAddress(URL.valueOf(parts[0])); - publisher.setTargetAddress(URL.valueOf(parts[1])); - } else { - Collection publishers = datum.getPubMap().values(); - if (publishers.size() == 0) { - throw new IllegalArgumentException( - "datumParam.publisherConnectId is null, and datum has no pubs"); - } - Publisher firstPub = publishers.iterator().next(); - publisher.setSourceAddress(firstPub.getSourceAddress()); - publisher.setTargetAddress(firstPub.getTargetAddress()); - } - publisher.setCell(datumParam.getPublisherCell()); - ServerDataBox dataBox = new ServerDataBox(datumParam.getPublisherDataBox()); - List dataList = Lists.newArrayList(dataBox); - publisher.setDataList(dataList); - return publisher; - } - - private UnPublisher buildUnPublisher(Datum datum, DatumParam datumParam) { - Validate.notNull(datumParam.getPublisherRegisterId(), - "datumParam.publisherRegisterId is null"); - Validate.notNull(datumParam.getPublisherRegisterTimestamp(), - "datumParam.publisherRegisterTimestamp is null"); - - UnPublisher publisher = new UnPublisher(datumParam.getDataInfoId(), TEMP_SESSION_PROCESSID, - datumParam.getPublisherRegisterId(), datumParam.getPublisherRegisterTimestamp(), + publisher.setCell(datumParam.getPublisherCell()); + ServerDataBox dataBox = new ServerDataBox(datumParam.getPublisherDataBox()); + List dataList = Lists.newArrayList(dataBox); + publisher.setDataList(dataList); + return publisher; + } + + private UnPublisher buildUnPublisher(Datum datum, DatumParam datumParam) { + Validate.notNull(datumParam.getPublisherRegisterId(), "datumParam.publisherRegisterId is null"); + Validate.notNull( + datumParam.getPublisherRegisterTimestamp(), + "datumParam.publisherRegisterTimestamp is null"); + + UnPublisher publisher = + new UnPublisher( + datumParam.getDataInfoId(), + TEMP_SESSION_PROCESSID, + datumParam.getPublisherRegisterId(), + datumParam.getPublisherRegisterTimestamp(), datumParam.getPublisherVersion()); - Publisher _publisher = datum.getPubMap().get(datumParam.getPublisherRegisterId()); - if (_publisher == null) { - throw new IllegalArgumentException(String.format("No pub of registerId(%s)", - datumParam.getPublisherRegisterId())); - } - publisher.setSourceAddress(_publisher.getSourceAddress()); - publisher.setTargetAddress(_publisher.getTargetAddress()); - - return publisher; + Publisher _publisher = datum.getPubMap().get(datumParam.getPublisherRegisterId()); + if (_publisher == null) { + throw new IllegalArgumentException( + String.format("No pub of registerId(%s)", datumParam.getPublisherRegisterId())); } + publisher.setSourceAddress(_publisher.getSourceAddress()); + publisher.setTargetAddress(_publisher.getTargetAddress()); - private void checkTestApiEnable() { - Validate.isTrue(dataServerConfig.isEnableTestApi(), "This api is disabled"); - } + return publisher; + } - private CommonResponse createResponse(Datum datum) { - return CommonResponse.buildSuccessResponse(String.format("datum=%s, publishers=%s", datum, - datum.getPubMap())); - } -} \ No newline at end of file + private void checkTestApiEnable() { + Validate.isTrue(dataServerConfig.isEnableTestApi(), "This api is disabled"); + } + + private CommonResponse createResponse(Datum datum) { + return CommonResponse.buildSuccessResponse( + String.format("datum=%s, publishers=%s", datum, datum.getPubMap())); + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/DatumParam.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/DatumParam.java index 6fb0fdc59..0f5c13b9a 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/DatumParam.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/DatumParam.java @@ -20,179 +20,170 @@ import java.util.UUID; /** - * * @author kezhu.wukz * @version $Id: DatumParam.java, v 0.1 2019-06-28 15:55 kezhu.wukz Exp $ */ public class DatumParam implements Serializable { - private static final long serialVersionUID = -3747877410102014868L; - - private String dataInfoId; - - private String dataCenter; - - private String publisherRegisterId = UUID.randomUUID().toString(); - - private long publisherVersion = System.currentTimeMillis(); - - private long publisherRegisterTimestamp = System.currentTimeMillis(); - - private String publisherDataBox; - - private String publisherConnectId; - - private String publisherCell; - - /** - * Getter method for property publisherCell. - * - * @return property value of publisherCell - */ - public String getPublisherCell() { - return publisherCell; - } - - /** - * Setter method for property publisherCell . - * - * @param publisherCell - * value to be assigned to property publisherCell - */ - public void setPublisherCell(String publisherCell) { - this.publisherCell = publisherCell; - } - - /** - * Getter method for property dataInfoId. - * - * @return property value of dataInfoId - */ - public String getDataInfoId() { - return dataInfoId; - } - - /** - * Setter method for property dataInfoId . - * - * @param dataInfoId - * value to be assigned to property dataInfoId - */ - public void setDataInfoId(String dataInfoId) { - this.dataInfoId = dataInfoId; - } - - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } - - /** - * Setter method for property dataCenter . - * - * @param dataCenter - * value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } - - /** - * Getter method for property publisherRegisterId. - * - * @return property value of publisherRegisterId - */ - public String getPublisherRegisterId() { - return publisherRegisterId; - } - - /** - * Setter method for property publisherRegisterId . - * - * @param publisherRegisterId - * value to be assigned to property publisherRegisterId - */ - public void setPublisherRegisterId(String publisherRegisterId) { - this.publisherRegisterId = publisherRegisterId; - } - - /** - * Getter method for property publisherVersion. - * - * @return property value of publisherVersion - */ - public long getPublisherVersion() { - return publisherVersion; - } - - /** - * Setter method for property publisherVersion . - * - * @param publisherVersion - * value to be assigned to property publisherVersion - */ - public void setPublisherVersion(long publisherVersion) { - this.publisherVersion = publisherVersion; - } - - /** - * Getter method for property publisherRegisterTimestamp. - * - * @return property value of publisherRegisterTimestamp - */ - public long getPublisherRegisterTimestamp() { - return publisherRegisterTimestamp; - } - - /** - * Setter method for property publisherRegisterTimestamp . - * - * @param publisherRegisterTimestamp - * value to be assigned to property publisherRegisterTimestamp - */ - public void setPublisherRegisterTimestamp(long publisherRegisterTimestamp) { - this.publisherRegisterTimestamp = publisherRegisterTimestamp; - } - - /** - * Getter method for property publisherDataBox. - * - * @return property value of publisherDataBox - */ - public String getPublisherDataBox() { - return publisherDataBox; - } - - /** - * Setter method for property publisherDataBox . - * - * @param publisherDataBox - * value to be assigned to property publisherDataBox - */ - public void setPublisherDataBox(String publisherDataBox) { - this.publisherDataBox = publisherDataBox; - } - - /** - * Getter method for property publisherConnectId. - * - * @return property value of publisherConnectId - */ - public String getPublisherConnectId() { - return publisherConnectId; - } - - /** - * Setter method for property publisherConnectId . - * - * @param publisherConnectId - * value to be assigned to property publisherConnectId - */ - public void setPublisherConnectId(String publisherConnectId) { - this.publisherConnectId = publisherConnectId; - } -} \ No newline at end of file + private static final long serialVersionUID = -3747877410102014868L; + + private String dataInfoId; + + private String dataCenter; + + private String publisherRegisterId = UUID.randomUUID().toString(); + + private long publisherVersion = System.currentTimeMillis(); + + private long publisherRegisterTimestamp = System.currentTimeMillis(); + + private String publisherDataBox; + + private String publisherConnectId; + + private String publisherCell; + + /** + * Getter method for property publisherCell. + * + * @return property value of publisherCell + */ + public String getPublisherCell() { + return publisherCell; + } + + /** + * Setter method for property publisherCell . + * + * @param publisherCell value to be assigned to property publisherCell + */ + public void setPublisherCell(String publisherCell) { + this.publisherCell = publisherCell; + } + + /** + * Getter method for property dataInfoId. + * + * @return property value of dataInfoId + */ + public String getDataInfoId() { + return dataInfoId; + } + + /** + * Setter method for property dataInfoId . + * + * @param dataInfoId value to be assigned to property dataInfoId + */ + public void setDataInfoId(String dataInfoId) { + this.dataInfoId = dataInfoId; + } + + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * Setter method for property dataCenter . + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } + + /** + * Getter method for property publisherRegisterId. + * + * @return property value of publisherRegisterId + */ + public String getPublisherRegisterId() { + return publisherRegisterId; + } + + /** + * Setter method for property publisherRegisterId . + * + * @param publisherRegisterId value to be assigned to property publisherRegisterId + */ + public void setPublisherRegisterId(String publisherRegisterId) { + this.publisherRegisterId = publisherRegisterId; + } + + /** + * Getter method for property publisherVersion. + * + * @return property value of publisherVersion + */ + public long getPublisherVersion() { + return publisherVersion; + } + + /** + * Setter method for property publisherVersion . + * + * @param publisherVersion value to be assigned to property publisherVersion + */ + public void setPublisherVersion(long publisherVersion) { + this.publisherVersion = publisherVersion; + } + + /** + * Getter method for property publisherRegisterTimestamp. + * + * @return property value of publisherRegisterTimestamp + */ + public long getPublisherRegisterTimestamp() { + return publisherRegisterTimestamp; + } + + /** + * Setter method for property publisherRegisterTimestamp . + * + * @param publisherRegisterTimestamp value to be assigned to property publisherRegisterTimestamp + */ + public void setPublisherRegisterTimestamp(long publisherRegisterTimestamp) { + this.publisherRegisterTimestamp = publisherRegisterTimestamp; + } + + /** + * Getter method for property publisherDataBox. + * + * @return property value of publisherDataBox + */ + public String getPublisherDataBox() { + return publisherDataBox; + } + + /** + * Setter method for property publisherDataBox . + * + * @param publisherDataBox value to be assigned to property publisherDataBox + */ + public void setPublisherDataBox(String publisherDataBox) { + this.publisherDataBox = publisherDataBox; + } + + /** + * Getter method for property publisherConnectId. + * + * @return property value of publisherConnectId + */ + public String getPublisherConnectId() { + return publisherConnectId; + } + + /** + * Setter method for property publisherConnectId . + * + * @param publisherConnectId value to be assigned to property publisherConnectId + */ + public void setPublisherConnectId(String publisherConnectId) { + this.publisherConnectId = publisherConnectId; + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/HealthResource.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/HealthResource.java index 235ec484e..3a08ca01c 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/HealthResource.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/resource/HealthResource.java @@ -16,6 +16,11 @@ */ package com.alipay.sofa.registry.server.data.resource; +import com.alipay.sofa.registry.common.model.CommonResponse; +import com.alipay.sofa.registry.metrics.ReporterUtils; +import com.alipay.sofa.registry.server.data.bootstrap.DataServerBootstrap; +import com.codahale.metrics.Gauge; +import com.codahale.metrics.MetricRegistry; import javax.annotation.PostConstruct; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -24,74 +29,65 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; - import org.springframework.beans.factory.annotation.Autowired; -import com.alipay.sofa.registry.common.model.CommonResponse; -import com.alipay.sofa.registry.metrics.ReporterUtils; -import com.alipay.sofa.registry.server.data.bootstrap.DataServerBootstrap; -import com.codahale.metrics.Gauge; -import com.codahale.metrics.MetricRegistry; - /** - * * @author shangyu.wh * @version $Id: HealthResource.java, v 0.1 2018-10-19 14:56 shangyu.wh Exp $ */ @Path("health") public class HealthResource { - @Autowired - private DataServerBootstrap dataServerBootstrap; - - @PostConstruct - public void init() { - MetricRegistry metrics = new MetricRegistry(); - metrics.register("healthCheck", (Gauge) () -> getHealthCheckResult()); - ReporterUtils.startSlf4jReporter(60, metrics); + @Autowired private DataServerBootstrap dataServerBootstrap; + + @PostConstruct + public void init() { + MetricRegistry metrics = new MetricRegistry(); + metrics.register("healthCheck", (Gauge) () -> getHealthCheckResult()); + ReporterUtils.startSlf4jReporter(60, metrics); + } + + @GET + @Path("check") + @Produces(MediaType.APPLICATION_JSON) + public Response checkHealth() { + + ResponseBuilder builder = Response.status(Response.Status.OK); + CommonResponse response = getHealthCheckResult(); + builder.entity(response); + if (!response.isSuccess()) { + builder.status(Status.INTERNAL_SERVER_ERROR); } - @GET - @Path("check") - @Produces(MediaType.APPLICATION_JSON) - public Response checkHealth() { - - ResponseBuilder builder = Response.status(Response.Status.OK); - CommonResponse response = getHealthCheckResult(); - builder.entity(response); - if (!response.isSuccess()) { - builder.status(Status.INTERNAL_SERVER_ERROR); - } - - return builder.build(); - } + return builder.build(); + } - private CommonResponse getHealthCheckResult() { - CommonResponse response; + private CommonResponse getHealthCheckResult() { + CommonResponse response; - StringBuilder sb = new StringBuilder("DataServerBoot "); + StringBuilder sb = new StringBuilder("DataServerBoot "); - boolean start = dataServerBootstrap.getServerForSessionStarted(); - boolean ret = start; - sb.append("severForSession:").append(start); + boolean start = dataServerBootstrap.getServerForSessionStarted(); + boolean ret = start; + sb.append("severForSession:").append(start); - start = dataServerBootstrap.getServerForDataSyncStarted(); - ret = ret && start; - sb.append(", severForDataSync:").append(start); + start = dataServerBootstrap.getServerForDataSyncStarted(); + ret = ret && start; + sb.append(", severForDataSync:").append(start); - start = dataServerBootstrap.getHttpServerStarted(); - ret = ret && start; - sb.append(", httpServer:").append(start); + start = dataServerBootstrap.getHttpServerStarted(); + ret = ret && start; + sb.append(", httpServer:").append(start); - start = dataServerBootstrap.getSchedulerStarted(); - ret = ret && start; - sb.append(", schedulerStarted:").append(start); + start = dataServerBootstrap.getSchedulerStarted(); + ret = ret && start; + sb.append(", schedulerStarted:").append(start); - if (ret) { - response = CommonResponse.buildSuccessResponse(sb.toString()); - } else { - response = CommonResponse.buildFailedResponse(sb.toString()); - } - return response; + if (ret) { + response = CommonResponse.buildSuccessResponse(sb.toString()); + } else { + response = CommonResponse.buildFailedResponse(sb.toString()); } -} \ No newline at end of file + return response; + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotChangeListener.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotChangeListener.java index 9f8ef448f..f97fa67ab 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotChangeListener.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotChangeListener.java @@ -23,7 +23,7 @@ * @version v 0.1 2020-10-30 10:46 yuzhi.lyz Exp $ */ public interface SlotChangeListener { - void onSlotAdd(int slotId, Slot.Role role); + void onSlotAdd(int slotId, Slot.Role role); - void onSlotRemove(int slotId, Slot.Role role); + void onSlotRemove(int slotId, Slot.Role role); } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotDiffSyncer.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotDiffSyncer.java index 6efb6bb39..608f171b9 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotDiffSyncer.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotDiffSyncer.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.data.slot; +import static com.alipay.sofa.registry.server.data.slot.SlotMetrics.*; + import com.alipay.sofa.registry.common.model.GenericResponse; import com.alipay.sofa.registry.common.model.ProcessId; import com.alipay.sofa.registry.common.model.PublisherDigestUtil; @@ -39,9 +41,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; import com.google.common.collect.Sets; - -import static com.alipay.sofa.registry.server.data.slot.SlotMetrics.*; - import java.util.*; /** @@ -49,249 +48,302 @@ * @version v 0.1 2020-11-20 13:56 yuzhi.lyz Exp $ */ public final class SlotDiffSyncer { - private static final Logger LOGGER = LoggerFactory.getLogger(SlotDiffSyncer.class); - private static final Logger DIFF_LOGGER = LoggerFactory.getLogger("SYNC-DIFF"); - private final DataServerConfig dataServerConfig; + private static final Logger LOGGER = LoggerFactory.getLogger(SlotDiffSyncer.class); + private static final Logger DIFF_LOGGER = LoggerFactory.getLogger("SYNC-DIFF"); + private final DataServerConfig dataServerConfig; - private final DatumStorage datumStorage; - private final DataChangeEventCenter dataChangeEventCenter; - private final SessionLeaseManager sessionLeaseManager; + private final DatumStorage datumStorage; + private final DataChangeEventCenter dataChangeEventCenter; + private final SessionLeaseManager sessionLeaseManager; - SlotDiffSyncer(DataServerConfig dataServerConfig, DatumStorage datumStorage, - DataChangeEventCenter dataChangeEventCenter, - SessionLeaseManager sessionLeaseManager) { - this.dataServerConfig = dataServerConfig; - this.datumStorage = datumStorage; - this.dataChangeEventCenter = dataChangeEventCenter; - this.sessionLeaseManager = sessionLeaseManager; - } + SlotDiffSyncer( + DataServerConfig dataServerConfig, + DatumStorage datumStorage, + DataChangeEventCenter dataChangeEventCenter, + SessionLeaseManager sessionLeaseManager) { + this.dataServerConfig = dataServerConfig; + this.datumStorage = datumStorage; + this.dataChangeEventCenter = dataChangeEventCenter; + this.sessionLeaseManager = sessionLeaseManager; + } - DataSlotDiffPublisherResult processSyncPublisherResp(int slotId, - GenericResponse resp, - String targetAddress, - Map summaryMap) { - if (resp == null || !resp.isSuccess()) { - LOGGER.error("DiffPublisherFailed, slotId={} from {}, resp={}", slotId, targetAddress, - resp); - return null; - } - DataSlotDiffPublisherResult result = resp.getData(); - - // sync from session - final ProcessId sessionProcessId = result.getSessionProcessId(); - if (sessionProcessId != null) { - sessionLeaseManager.renewSession(sessionProcessId); - } - - if (result.isEmpty()) { - DIFF_LOGGER.info("DiffPublisherEmpty, slotId={} from {}", slotId, targetAddress); - return result; - } - - final Set changeDataIds = Sets.newHashSet(); - for (Map.Entry> e : result.getUpdatedPublishers().entrySet()) { - final String dataInfoId = e.getKey(); - if (datumStorage.put(dataInfoId, e.getValue()) != null) { - changeDataIds.add(dataInfoId); - } - } - // for sync publishers - for (Map.Entry> e : result.getRemovedPublishers().entrySet()) { - final String dataInfoId = e.getKey(); - final List registerIds = e.getValue(); - final DatumSummary summary = summaryMap.get(dataInfoId); - if (summary == null) { - throw new IllegalArgumentException( - "sync publisher with not exist local DatumSummary:" + dataInfoId); - } - Map versionMap = summary.getPublisherVersions(registerIds); - if (datumStorage.remove(dataInfoId, sessionProcessId, versionMap) != null) { - changeDataIds.add(dataInfoId); - } - } - if (sessionProcessId != null && !changeDataIds.isEmpty()) { - // only trigger event when sync from session - dataChangeEventCenter.onChange(changeDataIds, dataServerConfig.getLocalDataCenter()); - } - DIFF_LOGGER.info("DiffPublisher, slotId={} from {}, updatedP {}:{}, removedP {}:{}", - slotId, targetAddress, result.getUpdatedPublishers().size(), result - .getUpdatedPublishersCount(), result.getRemovedPublishersCount(), result - .getRemovedPublishers().size()); - return result; + DataSlotDiffPublisherResult processSyncPublisherResp( + int slotId, + GenericResponse resp, + String targetAddress, + Map summaryMap) { + if (resp == null || !resp.isSuccess()) { + LOGGER.error("DiffPublisherFailed, slotId={} from {}, resp={}", slotId, targetAddress, resp); + return null; } + DataSlotDiffPublisherResult result = resp.getData(); - boolean syncPublishers(int slotId, String targetAddress, ClientSideExchanger exchanger, long slotTableEpoch, - Map summaryMap, int maxPublishers, - SyncContinues continues, boolean syncSession) { - // need the empty dataInfoId to add updatePublisher - Map round = pickSummaries(summaryMap, maxPublishers); - // sync for the existing dataInfoIds.publisher - while (!summaryMap.isEmpty()) { - if (!continues.continues()) { - LOGGER.info("syncing publishers break, slotId={} from {}", slotId, targetAddress); - return true; - } - // maybe to many publishers, spit round - if (syncSession) { - SyncSession.observeSyncSessionPub(slotId, DatumSummary.countPublisherSize(round.values())); - } else { - SyncLeader.observeSyncLeaderPub(slotId, DatumSummary.countPublisherSize(round.values())); - } - DataSlotDiffPublisherRequest request = new DataSlotDiffPublisherRequest(slotTableEpoch, slotId, round.values()); - - GenericResponse resp = (GenericResponse) exchanger - .requestRaw(targetAddress, request).getResult(); - DataSlotDiffPublisherResult result = processSyncPublisherResp(slotId, resp, targetAddress, round); - if (result == null) { - return false; - } - if (!result.isHasRemain()) { - // the sync round has finish, enter next round - round.keySet().forEach(d -> summaryMap.remove(d)); - round = pickSummaries(summaryMap, maxPublishers); - } else { - // has remain, remove the synced dataInfoIds, enter next round - Set synced = result.syncDataInfoIds(); - for (String dataInfoId : synced) { - round.remove(dataInfoId); - summaryMap.remove(dataInfoId); - } - } - } - return true; + // sync from session + final ProcessId sessionProcessId = result.getSessionProcessId(); + if (sessionProcessId != null) { + sessionLeaseManager.renewSession(sessionProcessId); } - boolean sync(int slotId, String targetAddress, ClientSideExchanger exchanger, - long slotTableEpoch, String summaryTargetIp, int maxPublishers, - SyncContinues continues) { - Map summaryMap = datumStorage - .getDatumSummary(slotId, summaryTargetIp); - final boolean syncSession = summaryTargetIp != null; - if (syncSession) { - SyncSession.observeSyncSessionId(slotId, summaryMap.size()); - } else { - SyncLeader.observeSyncLeaderId(slotId, summaryMap.size()); - } - Map digestMap = PublisherDigestUtil.digest(summaryMap); - DataSlotDiffDigestRequest request = new DataSlotDiffDigestRequest(slotTableEpoch, slotId, - digestMap); - Response exchangeResp = exchanger.requestRaw(targetAddress, request); - GenericResponse resp = (GenericResponse) exchangeResp - .getResult(); - DataSlotDiffDigestResult result = processSyncDigestResp(slotId, resp, targetAddress, - summaryMap); - if (result == null) { - return false; - } - if (result.getUpdateAndAddSize() == 0) { - // no change of update and add - return true; - } - final Map newSummaryMap = getSummaryForSyncPublishers(result, - summaryMap); - return syncPublishers(slotId, targetAddress, exchanger, slotTableEpoch, newSummaryMap, - maxPublishers, continues, syncSession); + if (result.isEmpty()) { + DIFF_LOGGER.info("DiffPublisherEmpty, slotId={} from {}", slotId, targetAddress); + return result; } - static Map getSummaryForSyncPublishers(DataSlotDiffDigestResult result, - Map digestSummaryMap) { - final Map newSummaryMap = Maps.newHashMapWithExpectedSize(result - .getUpdateAndAddSize()); - for (String add : result.getAddedDataInfoIds()) { - newSummaryMap.put(add, new DatumSummary(add)); - } - for (String update : result.getUpdatedDataInfoIds()) { - newSummaryMap.put(update, digestSummaryMap.get(update)); - } - return newSummaryMap; + final Set changeDataIds = Sets.newHashSet(); + for (Map.Entry> e : result.getUpdatedPublishers().entrySet()) { + final String dataInfoId = e.getKey(); + if (datumStorage.put(dataInfoId, e.getValue()) != null) { + changeDataIds.add(dataInfoId); + } + } + // for sync publishers + for (Map.Entry> e : result.getRemovedPublishers().entrySet()) { + final String dataInfoId = e.getKey(); + final List registerIds = e.getValue(); + final DatumSummary summary = summaryMap.get(dataInfoId); + if (summary == null) { + throw new IllegalArgumentException( + "sync publisher with not exist local DatumSummary:" + dataInfoId); + } + Map versionMap = summary.getPublisherVersions(registerIds); + if (datumStorage.remove(dataInfoId, sessionProcessId, versionMap) != null) { + changeDataIds.add(dataInfoId); + } } + if (sessionProcessId != null && !changeDataIds.isEmpty()) { + // only trigger event when sync from session + dataChangeEventCenter.onChange(changeDataIds, dataServerConfig.getLocalDataCenter()); + } + DIFF_LOGGER.info( + "DiffPublisher, slotId={} from {}, updatedP {}:{}, removedP {}:{}", + slotId, + targetAddress, + result.getUpdatedPublishers().size(), + result.getUpdatedPublishersCount(), + result.getRemovedPublishersCount(), + result.getRemovedPublishers().size()); + return result; + } - DataSlotDiffDigestResult processSyncDigestResp(int slotId, - GenericResponse resp, - String targetAddress, - Map summaryMap) { - if (resp == null || !resp.isSuccess()) { - LOGGER.error("DiffDigestFailed, slotId={} from {}, resp={}", slotId, targetAddress, - resp); - return null; - } - DataSlotDiffDigestResult result = resp.getData(); + boolean syncPublishers( + int slotId, + String targetAddress, + ClientSideExchanger exchanger, + long slotTableEpoch, + Map summaryMap, + int maxPublishers, + SyncContinues continues, + boolean syncSession) { + // need the empty dataInfoId to add updatePublisher + Map round = pickSummaries(summaryMap, maxPublishers); + // sync for the existing dataInfoIds.publisher + while (!summaryMap.isEmpty()) { + if (!continues.continues()) { + LOGGER.info("syncing publishers break, slotId={} from {}", slotId, targetAddress); + return true; + } + // maybe to many publishers, spit round + if (syncSession) { + SyncSession.observeSyncSessionPub(slotId, DatumSummary.countPublisherSize(round.values())); + } else { + SyncLeader.observeSyncLeaderPub(slotId, DatumSummary.countPublisherSize(round.values())); + } + DataSlotDiffPublisherRequest request = + new DataSlotDiffPublisherRequest(slotTableEpoch, slotId, round.values()); - // sync from session - final ProcessId sessionProcessId = result.getSessionProcessId(); - if (sessionProcessId != null) { - sessionLeaseManager.renewSession(sessionProcessId); + GenericResponse resp = + (GenericResponse) + exchanger.requestRaw(targetAddress, request).getResult(); + DataSlotDiffPublisherResult result = + processSyncPublisherResp(slotId, resp, targetAddress, round); + if (result == null) { + return false; + } + if (!result.isHasRemain()) { + // the sync round has finish, enter next round + round.keySet().forEach(d -> summaryMap.remove(d)); + round = pickSummaries(summaryMap, maxPublishers); + } else { + // has remain, remove the synced dataInfoIds, enter next round + Set synced = result.syncDataInfoIds(); + for (String dataInfoId : synced) { + round.remove(dataInfoId); + summaryMap.remove(dataInfoId); } + } + } + return true; + } - if (result.isEmpty()) { - DIFF_LOGGER.info("DiffDigestEmpty, slotId={} from {}", slotId, targetAddress); - return result; - } - // do nothing with added dataInfoId, the added publishers would sync and update by sync.publisher - // if we create a new empty datum when absent, it's dangerous. - // if some not expect error occurs when sync publisher and no publisher write to datum, - // it maybe trigger a empty push with bigger datum.version which created by new empty - final Set changeDataIds = Sets.newHashSet(); - for (String removeDataInfoId : result.getRemovedDataInfoIds()) { - if (datumStorage.remove(removeDataInfoId, sessionProcessId, - summaryMap.get(removeDataInfoId).getPublisherVersions()) != null) { - changeDataIds.add(removeDataInfoId); - } - } + boolean sync( + int slotId, + String targetAddress, + ClientSideExchanger exchanger, + long slotTableEpoch, + String summaryTargetIp, + int maxPublishers, + SyncContinues continues) { + Map summaryMap = datumStorage.getDatumSummary(slotId, summaryTargetIp); + final boolean syncSession = summaryTargetIp != null; + if (syncSession) { + SyncSession.observeSyncSessionId(slotId, summaryMap.size()); + } else { + SyncLeader.observeSyncLeaderId(slotId, summaryMap.size()); + } + Map digestMap = PublisherDigestUtil.digest(summaryMap); + DataSlotDiffDigestRequest request = + new DataSlotDiffDigestRequest(slotTableEpoch, slotId, digestMap); + Response exchangeResp = exchanger.requestRaw(targetAddress, request); + GenericResponse resp = + (GenericResponse) exchangeResp.getResult(); + DataSlotDiffDigestResult result = + processSyncDigestResp(slotId, resp, targetAddress, summaryMap); + if (result == null) { + return false; + } + if (result.getUpdateAndAddSize() == 0) { + // no change of update and add + return true; + } + final Map newSummaryMap = getSummaryForSyncPublishers(result, summaryMap); + return syncPublishers( + slotId, + targetAddress, + exchanger, + slotTableEpoch, + newSummaryMap, + maxPublishers, + continues, + syncSession); + } - if (sessionProcessId != null && !changeDataIds.isEmpty()) { - // only trigger event when sync from session - dataChangeEventCenter.onChange(changeDataIds, dataServerConfig.getLocalDataCenter()); - } - DIFF_LOGGER.info( - "DiffDigest, slotId={} from {}, update={}, add={}, remove={}, adds={}, removes={}", - slotId, targetAddress, result.getUpdatedDataInfoIds().size(), result - .getAddedDataInfoIds().size(), result.getRemovedDataInfoIds().size(), result - .getAddedDataInfoIds(), result.getRemovedDataInfoIds()); - return result; + static Map getSummaryForSyncPublishers( + DataSlotDiffDigestResult result, Map digestSummaryMap) { + final Map newSummaryMap = + Maps.newHashMapWithExpectedSize(result.getUpdateAndAddSize()); + for (String add : result.getAddedDataInfoIds()) { + newSummaryMap.put(add, new DatumSummary(add)); } + for (String update : result.getUpdatedDataInfoIds()) { + newSummaryMap.put(update, digestSummaryMap.get(update)); + } + return newSummaryMap; + } - public boolean syncSession(int slotId, String sessionIp, SessionNodeExchanger exchanger, - long slotTableEpoch, SyncContinues continues) - throws RequestException { - ParaCheckUtil.checkNotBlank(sessionIp, "sessionIp"); - return sync(slotId, sessionIp, exchanger, slotTableEpoch, sessionIp, - dataServerConfig.getSlotSyncPublisherDigestMaxNum(), continues); + DataSlotDiffDigestResult processSyncDigestResp( + int slotId, + GenericResponse resp, + String targetAddress, + Map summaryMap) { + if (resp == null || !resp.isSuccess()) { + LOGGER.error("DiffDigestFailed, slotId={} from {}, resp={}", slotId, targetAddress, resp); + return null; } + DataSlotDiffDigestResult result = resp.getData(); - public boolean syncSlotLeader(int slotId, String slotLeaderIp, DataNodeExchanger exchanger, - long slotTableEpoch, SyncContinues continues) - throws RequestException { - ParaCheckUtil.checkNotBlank(slotLeaderIp, "slotLeaderIp"); - return sync(slotId, slotLeaderIp, exchanger, slotTableEpoch, null, - dataServerConfig.getSlotSyncPublisherDigestMaxNum(), continues); + // sync from session + final ProcessId sessionProcessId = result.getSessionProcessId(); + if (sessionProcessId != null) { + sessionLeaseManager.renewSession(sessionProcessId); } - static Map pickSummaries(Map syncSummaries, int n) { - Map m = new HashMap<>(); - for (Map.Entry e : syncSummaries.entrySet()) { - // at least pick one - m.put(e.getKey(), e.getValue()); - int versionSize = e.getValue().getPublisherVersions().size(); - if (versionSize == 0) { - // is empty, budget=1 - versionSize = 1; - } - n -= versionSize; - if (n <= 0) { - break; - } - } - return m; + if (result.isEmpty()) { + DIFF_LOGGER.info("DiffDigestEmpty, slotId={} from {}", slotId, targetAddress); + return result; + } + // do nothing with added dataInfoId, the added publishers would sync and update by + // sync.publisher + // if we create a new empty datum when absent, it's dangerous. + // if some not expect error occurs when sync publisher and no publisher write to datum, + // it maybe trigger a empty push with bigger datum.version which created by new empty + final Set changeDataIds = Sets.newHashSet(); + for (String removeDataInfoId : result.getRemovedDataInfoIds()) { + if (datumStorage.remove( + removeDataInfoId, + sessionProcessId, + summaryMap.get(removeDataInfoId).getPublisherVersions()) + != null) { + changeDataIds.add(removeDataInfoId); + } } - @VisibleForTesting - DatumStorage getDatumStorage() { - return datumStorage; + if (sessionProcessId != null && !changeDataIds.isEmpty()) { + // only trigger event when sync from session + dataChangeEventCenter.onChange(changeDataIds, dataServerConfig.getLocalDataCenter()); } + DIFF_LOGGER.info( + "DiffDigest, slotId={} from {}, update={}, add={}, remove={}, adds={}, removes={}", + slotId, + targetAddress, + result.getUpdatedDataInfoIds().size(), + result.getAddedDataInfoIds().size(), + result.getRemovedDataInfoIds().size(), + result.getAddedDataInfoIds(), + result.getRemovedDataInfoIds()); + return result; + } + + public boolean syncSession( + int slotId, + String sessionIp, + SessionNodeExchanger exchanger, + long slotTableEpoch, + SyncContinues continues) + throws RequestException { + ParaCheckUtil.checkNotBlank(sessionIp, "sessionIp"); + return sync( + slotId, + sessionIp, + exchanger, + slotTableEpoch, + sessionIp, + dataServerConfig.getSlotSyncPublisherDigestMaxNum(), + continues); + } + + public boolean syncSlotLeader( + int slotId, + String slotLeaderIp, + DataNodeExchanger exchanger, + long slotTableEpoch, + SyncContinues continues) + throws RequestException { + ParaCheckUtil.checkNotBlank(slotLeaderIp, "slotLeaderIp"); + return sync( + slotId, + slotLeaderIp, + exchanger, + slotTableEpoch, + null, + dataServerConfig.getSlotSyncPublisherDigestMaxNum(), + continues); + } - @VisibleForTesting - DataServerConfig getDataServerConfig() { - return dataServerConfig; + static Map pickSummaries(Map syncSummaries, int n) { + Map m = new HashMap<>(); + for (Map.Entry e : syncSummaries.entrySet()) { + // at least pick one + m.put(e.getKey(), e.getValue()); + int versionSize = e.getValue().getPublisherVersions().size(); + if (versionSize == 0) { + // is empty, budget=1 + versionSize = 1; + } + n -= versionSize; + if (n <= 0) { + break; + } } + return m; + } + + @VisibleForTesting + DatumStorage getDatumStorage() { + return datumStorage; + } + + @VisibleForTesting + DataServerConfig getDataServerConfig() { + return dataServerConfig; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotManager.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotManager.java index 32c68b3f8..a37816ab2 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotManager.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotManager.java @@ -20,7 +20,6 @@ import com.alipay.sofa.registry.common.model.slot.Slot; import com.alipay.sofa.registry.common.model.slot.SlotAccess; import com.alipay.sofa.registry.common.model.slot.SlotTable; - import java.util.List; import java.util.concurrent.locks.ReadWriteLock; @@ -30,22 +29,21 @@ */ public interface SlotManager extends ReadWriteLock { - int slotOf(String dataInfoId); - - Slot getSlot(int slotId); + int slotOf(String dataInfoId); - SlotAccess checkSlotAccess(int slotId, long srcSlotEpoch, long srcLeaderEpoch); + Slot getSlot(int slotId); - List getSlotStatuses(); + SlotAccess checkSlotAccess(int slotId, long srcSlotEpoch, long srcLeaderEpoch); - boolean isLeader(int slotId); + List getSlotStatuses(); - boolean isFollower(int slotId); + boolean isLeader(int slotId); - boolean updateSlotTable(SlotTable slotTable); + boolean isFollower(int slotId); - long getSlotTableEpoch(); + boolean updateSlotTable(SlotTable slotTable); - void triggerUpdateSlotTable(long epoch); + long getSlotTableEpoch(); + void triggerUpdateSlotTable(long epoch); } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotManagerImpl.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotManagerImpl.java index 355082027..accc24743 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotManagerImpl.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotManagerImpl.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.data.slot; +import static com.alipay.sofa.registry.server.data.slot.SlotMetrics.Manager.*; + import com.alipay.sofa.registry.common.model.Tuple; import com.alipay.sofa.registry.common.model.slot.*; import com.alipay.sofa.registry.common.model.slot.func.SlotFunction; @@ -42,702 +44,749 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.util.*; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; - -import static com.alipay.sofa.registry.server.data.slot.SlotMetrics.Manager.*; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; /** * @author yuzhi.lyz * @version v 0.1 2020-12-02 09:44 yuzhi.lyz Exp $ */ public final class SlotManagerImpl implements SlotManager { - private static final Logger LOGGER = LoggerFactory - .getLogger(SlotManagerImpl.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SlotManagerImpl.class); - private static final Logger MIGRATING_LOGGER = LoggerFactory - .getLogger("MIGRATING"); + private static final Logger MIGRATING_LOGGER = LoggerFactory.getLogger("MIGRATING"); - private static final Logger ERROR_LOGGER = LoggerFactory - .getLogger("MIGRATING-ERROR"); + private static final Logger ERROR_LOGGER = LoggerFactory.getLogger("MIGRATING-ERROR"); - private final SlotFunction slotFunction = SlotFunctionRegistry.getFunc(); + private final SlotFunction slotFunction = SlotFunctionRegistry.getFunc(); - @Autowired - private DataNodeExchanger dataNodeExchanger; + @Autowired private DataNodeExchanger dataNodeExchanger; - @Autowired - private SessionNodeExchanger sessionNodeExchanger; + @Autowired private SessionNodeExchanger sessionNodeExchanger; - @Autowired - private MetaServerServiceImpl metaServerService; + @Autowired private MetaServerServiceImpl metaServerService; - @Autowired - private DataServerConfig dataServerConfig; + @Autowired private DataServerConfig dataServerConfig; - @Autowired - private DatumStorage localDatumStorage; + @Autowired private DatumStorage localDatumStorage; - @Autowired - private DataChangeEventCenter dataChangeEventCenter; + @Autowired private DataChangeEventCenter dataChangeEventCenter; - @Autowired - private SessionLeaseManager sessionLeaseManager; + @Autowired private SessionLeaseManager sessionLeaseManager; - @Autowired - private SlotGenericResource slotGenericResource; + @Autowired private SlotGenericResource slotGenericResource; - private List recorders = Collections.EMPTY_LIST; + private List recorders = Collections.EMPTY_LIST; - private final List slotChangeListeners = new ArrayList<>(); + private final List slotChangeListeners = new ArrayList<>(); - private KeyedThreadPoolExecutor migrateSessionExecutor; - private KeyedThreadPoolExecutor syncSessionExecutor; - private KeyedThreadPoolExecutor syncLeaderExecutor; + private KeyedThreadPoolExecutor migrateSessionExecutor; + private KeyedThreadPoolExecutor syncSessionExecutor; + private KeyedThreadPoolExecutor syncLeaderExecutor; - /** - * the sync and migrating may happen parallelly when slot role has modified. - * make sure the datum merging is idempotent - */ - private final SyncingWatchDog watchDog = new SyncingWatchDog(); - private final AtomicReference updatingSlotTable = new AtomicReference(); - private final ReadWriteLock updateLock = new ReentrantReadWriteLock(); - private final SlotTableStates slotTableStates = new SlotTableStates(); + /** + * the sync and migrating may happen parallelly when slot role has modified. make sure the datum + * merging is idempotent + */ + private final SyncingWatchDog watchDog = new SyncingWatchDog(); - @PostConstruct - public void init() { - recorders = Lists.newArrayList(slotGenericResource, new DiskSlotTableRecorder()); - initSlotChangeListener(); - initExecutors(); - ConcurrentUtils.createDaemonThread("SyncingWatchDog", watchDog).start(); - } + private final AtomicReference updatingSlotTable = new AtomicReference(); + private final ReadWriteLock updateLock = new ReentrantReadWriteLock(); + private final SlotTableStates slotTableStates = new SlotTableStates(); - void initSlotChangeListener() { - SlotChangeListener l = localDatumStorage.getSlotChangeListener(); - if (l != null) { - this.slotChangeListeners.add(l); - } + @PostConstruct + public void init() { + recorders = Lists.newArrayList(slotGenericResource, new DiskSlotTableRecorder()); + initSlotChangeListener(); + initExecutors(); + ConcurrentUtils.createDaemonThread("SyncingWatchDog", watchDog).start(); + } + + void initSlotChangeListener() { + SlotChangeListener l = localDatumStorage.getSlotChangeListener(); + if (l != null) { + this.slotChangeListeners.add(l); } + } - void initExecutors() { - this.migrateSessionExecutor = new KeyedThreadPoolExecutor("migrate-session", + void initExecutors() { + this.migrateSessionExecutor = + new KeyedThreadPoolExecutor( + "migrate-session", dataServerConfig.getSlotLeaderSyncSessionExecutorThreadSize(), dataServerConfig.getSlotLeaderSyncSessionExecutorQueueSize()); - this.syncSessionExecutor = new KeyedThreadPoolExecutor("sync-session", + this.syncSessionExecutor = + new KeyedThreadPoolExecutor( + "sync-session", dataServerConfig.getSlotLeaderSyncSessionExecutorThreadSize(), dataServerConfig.getSlotLeaderSyncSessionExecutorQueueSize()); - this.syncLeaderExecutor = new KeyedThreadPoolExecutor("sync-leader", + this.syncLeaderExecutor = + new KeyedThreadPoolExecutor( + "sync-leader", dataServerConfig.getSlotFollowerSyncLeaderExecutorThreadSize(), dataServerConfig.getSlotFollowerSyncLeaderExecutorQueueSize()); - } - - @Override - public int slotOf(String dataInfoId) { - return slotFunction.slotOf(dataInfoId); - } - - @Override - public Slot getSlot(int slotId) { - final SlotState state = slotTableStates.slotStates.get(slotId); - return state == null ? null : state.slot; - } - - @Override - public SlotAccess checkSlotAccess(int slotId, long srcSlotEpoch, long srcLeaderEpoch) { - SlotTable currentSlotTable; - SlotState state; - updateLock.readLock().lock(); - try { - currentSlotTable = slotTableStates.table; - state = slotTableStates.slotStates.get(slotId); - } finally { - updateLock.readLock().unlock(); - } - - final long currentEpoch = currentSlotTable.getEpoch(); - if (currentEpoch < srcSlotEpoch) { - triggerUpdateSlotTable(srcSlotEpoch); - } - return checkSlotAccess(slotId, currentEpoch, state, srcLeaderEpoch); - } - - static SlotAccess checkSlotAccess(int slotId, long currentSlotTableEpoch, SlotState state, - long srcLeaderEpoch) { - if (state == null) { - return new SlotAccess(slotId, currentSlotTableEpoch, SlotAccess.Status.Moved, -1); - } - final Slot slot = state.slot; - if (!localIsLeader(slot)) { - return new SlotAccess(slotId, currentSlotTableEpoch, SlotAccess.Status.Moved, - slot.getLeaderEpoch()); - } - if (!state.migrated) { - return new SlotAccess(slotId, currentSlotTableEpoch, SlotAccess.Status.Migrating, - slot.getLeaderEpoch()); - } - if (slot.getLeaderEpoch() != srcLeaderEpoch) { - return new SlotAccess(slotId, currentSlotTableEpoch, SlotAccess.Status.MisMatch, - slot.getLeaderEpoch()); - } - return new SlotAccess(slotId, currentSlotTableEpoch, SlotAccess.Status.Accept, - slot.getLeaderEpoch()); - } - - @Override - public List getSlotStatuses() { - List slotStatuses = Lists - .newArrayListWithCapacity(slotTableStates.slotStates.size()); - updateLock.readLock().lock(); + } + + @Override + public int slotOf(String dataInfoId) { + return slotFunction.slotOf(dataInfoId); + } + + @Override + public Slot getSlot(int slotId) { + final SlotState state = slotTableStates.slotStates.get(slotId); + return state == null ? null : state.slot; + } + + @Override + public SlotAccess checkSlotAccess(int slotId, long srcSlotEpoch, long srcLeaderEpoch) { + SlotTable currentSlotTable; + SlotState state; + updateLock.readLock().lock(); + try { + currentSlotTable = slotTableStates.table; + state = slotTableStates.slotStates.get(slotId); + } finally { + updateLock.readLock().unlock(); + } + + final long currentEpoch = currentSlotTable.getEpoch(); + if (currentEpoch < srcSlotEpoch) { + triggerUpdateSlotTable(srcSlotEpoch); + } + return checkSlotAccess(slotId, currentEpoch, state, srcLeaderEpoch); + } + + static SlotAccess checkSlotAccess( + int slotId, long currentSlotTableEpoch, SlotState state, long srcLeaderEpoch) { + if (state == null) { + return new SlotAccess(slotId, currentSlotTableEpoch, SlotAccess.Status.Moved, -1); + } + final Slot slot = state.slot; + if (!localIsLeader(slot)) { + return new SlotAccess( + slotId, currentSlotTableEpoch, SlotAccess.Status.Moved, slot.getLeaderEpoch()); + } + if (!state.migrated) { + return new SlotAccess( + slotId, currentSlotTableEpoch, SlotAccess.Status.Migrating, slot.getLeaderEpoch()); + } + if (slot.getLeaderEpoch() != srcLeaderEpoch) { + return new SlotAccess( + slotId, currentSlotTableEpoch, SlotAccess.Status.MisMatch, slot.getLeaderEpoch()); + } + return new SlotAccess( + slotId, currentSlotTableEpoch, SlotAccess.Status.Accept, slot.getLeaderEpoch()); + } + + @Override + public List getSlotStatuses() { + List slotStatuses = + Lists.newArrayListWithCapacity(slotTableStates.slotStates.size()); + updateLock.readLock().lock(); + try { + for (Map.Entry entry : slotTableStates.slotStates.entrySet()) { + int slotId = entry.getKey(); + SlotState slotState = entry.getValue(); + if (localIsLeader(slotState.slot)) { + LeaderSlotStatus status = + new LeaderSlotStatus( + slotId, + slotState.slot.getLeaderEpoch(), + ServerEnv.IP, + slotState.migrated + ? BaseSlotStatus.LeaderStatus.HEALTHY + : BaseSlotStatus.LeaderStatus.UNHEALTHY); + slotStatuses.add(status); + } else { + final KeyedTask syncLeaderTask = slotState.syncLeaderTask; + FollowerSlotStatus status = + new FollowerSlotStatus( + slotId, + slotState.slot.getLeaderEpoch(), + ServerEnv.IP, + syncLeaderTask != null ? syncLeaderTask.getStartTime() : 0, + slotState.lastSuccessLeaderSyncTime); + slotStatuses.add(status); + } + } + return slotStatuses; + } finally { + updateLock.readLock().unlock(); + } + } + + @Override + public boolean isLeader(int slotId) { + final SlotState state = slotTableStates.slotStates.get(slotId); + return state != null && localIsLeader(state.slot); + } + + @Override + public boolean isFollower(int slotId) { + final SlotState state = slotTableStates.slotStates.get(slotId); + return state != null && state.slot.getFollowers().contains(ServerEnv.IP); + } + + @Override + public boolean updateSlotTable(SlotTable update) { + final SlotTable curSlotTable = this.slotTableStates.table; + if (curSlotTable.getEpoch() >= update.getEpoch()) { + return false; + } + final SlotTable updating = this.updatingSlotTable.get(); + if (updating != null && updating.getEpoch() >= update.getEpoch()) { + return false; + } + recordSlotTable(update); + // confirmed that slotTable is related to us + update = update.filter(ServerEnv.IP); + + curSlotTable.assertSlotLessThan(update); + if (updating != null) { + updating.assertSlotLessThan(update); + } + + // do that async, not block the heartbeat + updatingSlotTable.set(update); + watchDog.wakeup(); + LOGGER.info( + "updating slot table, new={}, current={}", update.getEpoch(), curSlotTable.getEpoch()); + return true; + } + + private void recordSlotTable(SlotTable slotTable) { + recorders.forEach( + recorder -> { + if (recorder != null) { + recorder.record(slotTable); + } + }); + } + + private void updateSlotState(SlotTable updating) { + for (Slot s : updating.getSlots()) { + SlotState state = slotTableStates.slotStates.get(s.getId()); + listenAdd(s); + if (state != null) { + state.update(s); + } else { + slotTableStates.slotStates.put(s.getId(), new SlotState(s)); + LOGGER.info("add slot, slot={}", s); + } + } + + final Iterator> it = + slotTableStates.slotStates.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry e = it.next(); + if (updating.getSlot(e.getKey()) == null) { + final Slot slot = e.getValue().slot; + it.remove(); + // import + // first remove the slot for GetData Access check, then clean the data + listenRemove(slot); + observeLeaderMigratingFinish(slot.getId()); + LOGGER.info("remove slot, slot={}", slot); + } + } + slotTableStates.table = updating; + observeLeaderAssignGauge(slotTableStates.table.getLeaderNum(ServerEnv.IP)); + observeFollowerAssignGauge(slotTableStates.table.getFollowerNum(ServerEnv.IP)); + } + + @Override + public Lock readLock() { + return updateLock.readLock(); + } + + @Override + public Lock writeLock() { + return updateLock.writeLock(); + } + + private static final class SlotTableStates { + volatile SlotTable table = SlotTable.INIT; + final Map slotStates = Maps.newConcurrentMap(); + } + + boolean processUpdating() { + final SlotTable updating = updatingSlotTable.getAndSet(null); + if (updating != null) { + if (updating.getEpoch() > slotTableStates.table.getEpoch()) { + // lock for update, avoid the checkAccess get the wrong epoch + updateLock.writeLock().lock(); try { - for (Map.Entry entry : slotTableStates.slotStates.entrySet()) { - int slotId = entry.getKey(); - SlotState slotState = entry.getValue(); - if (localIsLeader(slotState.slot)) { - LeaderSlotStatus status = new LeaderSlotStatus(slotId, - slotState.slot.getLeaderEpoch(), ServerEnv.IP, - slotState.migrated ? BaseSlotStatus.LeaderStatus.HEALTHY - : BaseSlotStatus.LeaderStatus.UNHEALTHY); - slotStatuses.add(status); - } else { - final KeyedTask syncLeaderTask = slotState.syncLeaderTask; - FollowerSlotStatus status = new FollowerSlotStatus(slotId, - slotState.slot.getLeaderEpoch(), ServerEnv.IP, - syncLeaderTask != null ? syncLeaderTask.getStartTime() : 0, - slotState.lastSuccessLeaderSyncTime); - slotStatuses.add(status); - } - } - return slotStatuses; + updateSlotState(updating); } finally { - updateLock.readLock().unlock(); + updateLock.writeLock().unlock(); } - } - - @Override - public boolean isLeader(int slotId) { - final SlotState state = slotTableStates.slotStates.get(slotId); - return state != null && localIsLeader(state.slot); - } - - @Override - public boolean isFollower(int slotId) { - final SlotState state = slotTableStates.slotStates.get(slotId); - return state != null && state.slot.getFollowers().contains(ServerEnv.IP); - } - - @Override - public boolean updateSlotTable(SlotTable update) { - final SlotTable curSlotTable = this.slotTableStates.table; - if (curSlotTable.getEpoch() >= update.getEpoch()) { - return false; - } - final SlotTable updating = this.updatingSlotTable.get(); - if (updating != null && updating.getEpoch() >= update.getEpoch()) { - return false; - } - recordSlotTable(update); - //confirmed that slotTable is related to us - update = update.filter(ServerEnv.IP); - - curSlotTable.assertSlotLessThan(update); - if (updating != null) { - updating.assertSlotLessThan(update); - } - - // do that async, not block the heartbeat - updatingSlotTable.set(update); - watchDog.wakeup(); - LOGGER.info("updating slot table, new={}, current={}", update.getEpoch(), - curSlotTable.getEpoch()); + List leaders = updating.transfer(ServerEnv.IP, true); + LOGGER.info("updating slot table, leaders={}, {}, ", leaders, updating); return true; + } else { + LOGGER.warn( + "skip updating={}, current={}", updating.getEpoch(), slotTableStates.table.getEpoch()); + } } + return false; + } - private void recordSlotTable(SlotTable slotTable) { - recorders.forEach(recorder -> { - if (recorder != null) { - recorder.record(slotTable); - } - }); - } - - private void updateSlotState(SlotTable updating) { - for (Slot s : updating.getSlots()) { - SlotState state = slotTableStates.slotStates.get(s.getId()); - listenAdd(s); - if (state != null) { - state.update(s); - } else { - slotTableStates.slotStates.put(s.getId(), new SlotState(s)); - LOGGER.info("add slot, slot={}", s); - } - } - - final Iterator> it = slotTableStates.slotStates.entrySet() - .iterator(); - while (it.hasNext()) { - Map.Entry e = it.next(); - if (updating.getSlot(e.getKey()) == null) { - final Slot slot = e.getValue().slot; - it.remove(); - // import - // first remove the slot for GetData Access check, then clean the data - listenRemove(slot); - observeLeaderMigratingFinish(slot.getId()); - LOGGER.info("remove slot, slot={}", slot); - } - } - slotTableStates.table = updating; - observeLeaderAssignGauge(slotTableStates.table.getLeaderNum(ServerEnv.IP)); - observeFollowerAssignGauge(slotTableStates.table.getFollowerNum(ServerEnv.IP)); - } + private final class SyncingWatchDog extends WakeUpLoopRunnable { @Override - public Lock readLock() { - return updateLock.readLock(); + public void runUnthrowable() { + try { + processUpdating(); + syncWatch(); + } catch (Throwable e) { + ERROR_LOGGER.error("[syncWatch]failed to do sync watching", e); + } } @Override - public Lock writeLock() { - return updateLock.writeLock(); - } - - private static final class SlotTableStates { - volatile SlotTable table = SlotTable.INIT; - final Map slotStates = Maps.newConcurrentMap(); - } - - boolean processUpdating() { - final SlotTable updating = updatingSlotTable.getAndSet(null); - if (updating != null) { - if (updating.getEpoch() > slotTableStates.table.getEpoch()) { - // lock for update, avoid the checkAccess get the wrong epoch - updateLock.writeLock().lock(); - try { - updateSlotState(updating); - } finally { - updateLock.writeLock().unlock(); - } - List leaders = updating.transfer(ServerEnv.IP, true); - LOGGER.info("updating slot table, leaders={}, {}, ", leaders, updating); - return true; - } else { - LOGGER.warn("skip updating={}, current={}", updating.getEpoch(), - slotTableStates.table.getEpoch()); - } - } + public int getWaitingMillis() { + return 200; + } + } + + void syncWatch() { + final int syncSessionIntervalMs = + dataServerConfig.getSlotLeaderSyncSessionIntervalSecs() * 1000; + final int syncLeaderIntervalMs = + dataServerConfig.getSlotFollowerSyncLeaderIntervalSecs() * 1000; + final long slotTableEpoch = slotTableStates.table.getEpoch(); + for (SlotState slotState : slotTableStates.slotStates.values()) { + try { + sync(slotState, syncSessionIntervalMs, syncLeaderIntervalMs, slotTableEpoch); + } catch (Throwable e) { + ERROR_LOGGER.error( + "[syncCommit]failed to do sync slot {}, migrated={}", + slotState.slot, + slotState.migrated, + e); + } + } + } + + boolean sync( + SlotState slotState, + int syncSessionIntervalMs, + int syncLeaderIntervalMs, + long slotTableEpoch) { + final Slot slot = slotState.slot; + if (localIsLeader(slot)) { + final KeyedTask syncLeaderTask = slotState.syncLeaderTask; + if (syncLeaderTask != null && !syncLeaderTask.isFinished()) { + // must wait the sync leader finish, avoid the sync-leader conflict with sync-session + LOGGER.warn("wait for sync-leader to finish, {}", slot, syncLeaderTask); return false; - } - - private final class SyncingWatchDog extends WakeUpLoopRunnable { - - @Override - public void runUnthrowable() { - try { - processUpdating(); - syncWatch(); - } catch (Throwable e) { - ERROR_LOGGER.error("[syncWatch]failed to do sync watching", e); - } - } - - @Override - public int getWaitingMillis() { - return 200; - } - } - - void syncWatch() { - final int syncSessionIntervalMs = dataServerConfig.getSlotLeaderSyncSessionIntervalSecs() * 1000; - final int syncLeaderIntervalMs = dataServerConfig.getSlotFollowerSyncLeaderIntervalSecs() * 1000; - final long slotTableEpoch = slotTableStates.table.getEpoch(); - for (SlotState slotState : slotTableStates.slotStates.values()) { - try { - sync(slotState, syncSessionIntervalMs, syncLeaderIntervalMs, slotTableEpoch); - } catch (Throwable e) { - ERROR_LOGGER.error("[syncCommit]failed to do sync slot {}, migrated={}", - slotState.slot, slotState.migrated, e); - } - } - } - - boolean sync(SlotState slotState, int syncSessionIntervalMs, int syncLeaderIntervalMs, - long slotTableEpoch) { - final Slot slot = slotState.slot; - if (localIsLeader(slot)) { - final KeyedTask syncLeaderTask = slotState.syncLeaderTask; - if (syncLeaderTask != null && !syncLeaderTask.isFinished()) { - // must wait the sync leader finish, avoid the sync-leader conflict with sync-session - LOGGER.warn("wait for sync-leader to finish, {}", slot, syncLeaderTask); - return false; - } - slotState.syncLeaderTask = null; - final Set sessions = metaServerService.getSessionServerList(); - if (slotState.migrated) { - syncSessions(slotState, sessions, syncSessionIntervalMs, slotTableEpoch); - } else { - syncMigrating(slotState, sessions, syncSessionIntervalMs, slotTableEpoch); - // check all migrating task - checkMigratingTask(slotState, sessions); - } - } else { - // sync leader - syncLeader(slotState, syncLeaderIntervalMs, slotTableEpoch); - } - return true; - } - - private boolean checkMigratingTask(SlotState slotState, Collection sessions) { - final Slot slot = slotState.slot; - - MIGRATING_LOGGER.info("[migrating]{},span={},tasks={}/{},sessions={}/{},remains={}", - slot.getId(), System.currentTimeMillis() - slotState.migratingStartTime, - slotState.migratingTasks.size(), slotState.migratingTasks.keySet(), sessions.size(), - sessions, getMigratingSpans(slotState)); - + } + slotState.syncLeaderTask = null; + final Set sessions = metaServerService.getSessionServerList(); + if (slotState.migrated) { + syncSessions(slotState, sessions, syncSessionIntervalMs, slotTableEpoch); + } else { + syncMigrating(slotState, sessions, syncSessionIntervalMs, slotTableEpoch); // check all migrating task - if (slotState.migratingTasks.isEmpty() || sessions.isEmpty()) { - LOGGER.warn("sessionNodes or migratingTask is empty when migrating, {}", slot); - return false; - } - // TODO the session down and up in a short time. session.processId is important - if (slotState.isFinish(sessions)) { - // after migrated, force to update the version - // make sure the version is newly than old leader's - localDatumStorage.updateVersion(slot.getId()); - slotState.migrated = true; - final long span = System.currentTimeMillis() - slotState.migratingStartTime; - LOGGER.info("slotId={}, migrating finish, span={}, slot={}, sessions={}", slot.getId(), - span, slot, sessions); - slotState.migratingTasks.clear(); - observeLeaderMigratingFinish(slot.getId()); - observeLeaderMigratingHistogram(slot.getId(), span); - return true; - } - return false; - } - - private Map getMigratingSpans(SlotState slotState) { - final long now = System.currentTimeMillis(); - Map spans = Maps.newTreeMap(); - for (Map.Entry e : slotState.migratingTasks.entrySet()) { - MigratingTask m = e.getValue(); - if (!m.task.isFinished() || m.task.isFailed()) { - spans.put(e.getKey(), now - m.createTimestamp); - } - } - return spans; - } - - private void syncMigrating(SlotState slotState, Collection sessions, - int syncSessionIntervalMs, long slotTableEpoch) { - final Slot slot = slotState.slot; - if (slotState.migratingStartTime == 0) { - slotState.migratingStartTime = System.currentTimeMillis(); - slotState.migratingTasks.clear(); - observeLeaderMigratingStart(slot.getId()); - LOGGER.info("start migrating, slotId={}, sessionSize={}, sessions={}", slot.getId(), - sessions.size(), sessions); - } - for (String sessionIp : sessions) { - MigratingTask mtask = slotState.migratingTasks.get(sessionIp); - if (mtask == null || mtask.task.isFailed()) { - KeyedTask ktask = commitSyncSessionTask(slot, slotTableEpoch, - sessionIp, true); - if (mtask == null) { - mtask = new MigratingTask(ktask); - slotState.migratingTasks.put(sessionIp, mtask); - } else { - // fail - observeLeaderMigratingFail(slot.getId(), sessionIp); - mtask.task = ktask; - } - // TODO add max trycount, avoid the unhealth session block the migrating - mtask.tryCount++; - continue; - } - // migrating finish. try to sync session - // avoid the time of migrating is too long and block the syncing of session - if (mtask.task.isOverAfter(syncSessionIntervalMs)) { - if (syncSession(slotState, sessionIp, syncSessionIntervalMs, slotTableEpoch)) { - LOGGER.info("slotId={}, sync session in migrating, session={}", slot.getId(), - sessionIp); - } - } - } - - } - - private void syncSessions(SlotState slotState, Collection sessions, - int syncSessionIntervalMs, long slotTableEpoch) { - for (String sessionIp : sessions) { - syncSession(slotState, sessionIp, syncSessionIntervalMs, slotTableEpoch); - } - } - - private boolean syncSession(SlotState slotState, String sessionIp, int syncSessionIntervalMs, - long slotTableEpoch) { - final Slot slot = slotState.slot; - KeyedTask task = slotState.syncSessionTasks.get(sessionIp); - if (task == null || task.isOverAfter(syncSessionIntervalMs)) { - task = commitSyncSessionTask(slot, slotTableEpoch, sessionIp, false); - slotState.syncSessionTasks.put(sessionIp, task); - return true; - } - return false; - } - - private void syncLeader(SlotState slotState, int syncLeaderIntervalMs, long slotTableEpoch) { - final Slot slot = slotState.slot; - final KeyedTask syncLeaderTask = slotState.syncLeaderTask; - if (syncLeaderTask != null && syncLeaderTask.isFinished()) { - slotState.completeSyncLeaderTask(); - } - if (syncLeaderTask == null || syncLeaderTask.isOverAfter(syncLeaderIntervalMs)) { - //sync leader no need to notify event - SlotDiffSyncer syncer = new SlotDiffSyncer(dataServerConfig, localDatumStorage, null, - sessionLeaseManager); - SyncContinues continues = new SyncContinues() { - @Override - public boolean continues() { - return isFollower(slot.getId()); - } - }; - SyncLeaderTask task = new SyncLeaderTask(slotTableEpoch, slot, syncer, - dataNodeExchanger, continues); - slotState.syncLeaderTask = syncLeaderExecutor.execute(slot.getId(), task); - } else if (!syncLeaderTask.isFinished()) { - if (System.currentTimeMillis() - syncLeaderTask.getCreateTime() > 5000) { - // the sync leader is running more than 5secs, print - LOGGER.info("sync-leader running, {}", syncLeaderTask); - } - } - } - - private KeyedTask commitSyncSessionTask(Slot slot, long slotTableEpoch, - String sessionIp, boolean migrate) { - SlotDiffSyncer syncer = new SlotDiffSyncer(dataServerConfig, localDatumStorage, - dataChangeEventCenter, sessionLeaseManager); - SyncContinues continues = new SyncContinues() { + checkMigratingTask(slotState, sessions); + } + } else { + // sync leader + syncLeader(slotState, syncLeaderIntervalMs, slotTableEpoch); + } + return true; + } + + private boolean checkMigratingTask(SlotState slotState, Collection sessions) { + final Slot slot = slotState.slot; + + MIGRATING_LOGGER.info( + "[migrating]{},span={},tasks={}/{},sessions={}/{},remains={}", + slot.getId(), + System.currentTimeMillis() - slotState.migratingStartTime, + slotState.migratingTasks.size(), + slotState.migratingTasks.keySet(), + sessions.size(), + sessions, + getMigratingSpans(slotState)); + + // check all migrating task + if (slotState.migratingTasks.isEmpty() || sessions.isEmpty()) { + LOGGER.warn("sessionNodes or migratingTask is empty when migrating, {}", slot); + return false; + } + // TODO the session down and up in a short time. session.processId is important + if (slotState.isFinish(sessions)) { + // after migrated, force to update the version + // make sure the version is newly than old leader's + localDatumStorage.updateVersion(slot.getId()); + slotState.migrated = true; + final long span = System.currentTimeMillis() - slotState.migratingStartTime; + LOGGER.info( + "slotId={}, migrating finish, span={}, slot={}, sessions={}", + slot.getId(), + span, + slot, + sessions); + slotState.migratingTasks.clear(); + observeLeaderMigratingFinish(slot.getId()); + observeLeaderMigratingHistogram(slot.getId(), span); + return true; + } + return false; + } + + private Map getMigratingSpans(SlotState slotState) { + final long now = System.currentTimeMillis(); + Map spans = Maps.newTreeMap(); + for (Map.Entry e : slotState.migratingTasks.entrySet()) { + MigratingTask m = e.getValue(); + if (!m.task.isFinished() || m.task.isFailed()) { + spans.put(e.getKey(), now - m.createTimestamp); + } + } + return spans; + } + + private void syncMigrating( + SlotState slotState, + Collection sessions, + int syncSessionIntervalMs, + long slotTableEpoch) { + final Slot slot = slotState.slot; + if (slotState.migratingStartTime == 0) { + slotState.migratingStartTime = System.currentTimeMillis(); + slotState.migratingTasks.clear(); + observeLeaderMigratingStart(slot.getId()); + LOGGER.info( + "start migrating, slotId={}, sessionSize={}, sessions={}", + slot.getId(), + sessions.size(), + sessions); + } + for (String sessionIp : sessions) { + MigratingTask mtask = slotState.migratingTasks.get(sessionIp); + if (mtask == null || mtask.task.isFailed()) { + KeyedTask ktask = + commitSyncSessionTask(slot, slotTableEpoch, sessionIp, true); + if (mtask == null) { + mtask = new MigratingTask(ktask); + slotState.migratingTasks.put(sessionIp, mtask); + } else { + // fail + observeLeaderMigratingFail(slot.getId(), sessionIp); + mtask.task = ktask; + } + // TODO add max trycount, avoid the unhealth session block the migrating + mtask.tryCount++; + continue; + } + // migrating finish. try to sync session + // avoid the time of migrating is too long and block the syncing of session + if (mtask.task.isOverAfter(syncSessionIntervalMs)) { + if (syncSession(slotState, sessionIp, syncSessionIntervalMs, slotTableEpoch)) { + LOGGER.info("slotId={}, sync session in migrating, session={}", slot.getId(), sessionIp); + } + } + } + } + + private void syncSessions( + SlotState slotState, + Collection sessions, + int syncSessionIntervalMs, + long slotTableEpoch) { + for (String sessionIp : sessions) { + syncSession(slotState, sessionIp, syncSessionIntervalMs, slotTableEpoch); + } + } + + private boolean syncSession( + SlotState slotState, String sessionIp, int syncSessionIntervalMs, long slotTableEpoch) { + final Slot slot = slotState.slot; + KeyedTask task = slotState.syncSessionTasks.get(sessionIp); + if (task == null || task.isOverAfter(syncSessionIntervalMs)) { + task = commitSyncSessionTask(slot, slotTableEpoch, sessionIp, false); + slotState.syncSessionTasks.put(sessionIp, task); + return true; + } + return false; + } + + private void syncLeader(SlotState slotState, int syncLeaderIntervalMs, long slotTableEpoch) { + final Slot slot = slotState.slot; + final KeyedTask syncLeaderTask = slotState.syncLeaderTask; + if (syncLeaderTask != null && syncLeaderTask.isFinished()) { + slotState.completeSyncLeaderTask(); + } + if (syncLeaderTask == null || syncLeaderTask.isOverAfter(syncLeaderIntervalMs)) { + // sync leader no need to notify event + SlotDiffSyncer syncer = + new SlotDiffSyncer(dataServerConfig, localDatumStorage, null, sessionLeaseManager); + SyncContinues continues = + new SyncContinues() { @Override public boolean continues() { - // if not leader, the syncing need to break - return isLeader(slot.getId()); + return isFollower(slot.getId()); } + }; + SyncLeaderTask task = + new SyncLeaderTask(slotTableEpoch, slot, syncer, dataNodeExchanger, continues); + slotState.syncLeaderTask = syncLeaderExecutor.execute(slot.getId(), task); + } else if (!syncLeaderTask.isFinished()) { + if (System.currentTimeMillis() - syncLeaderTask.getCreateTime() > 5000) { + // the sync leader is running more than 5secs, print + LOGGER.info("sync-leader running, {}", syncLeaderTask); + } + } + } + + private KeyedTask commitSyncSessionTask( + Slot slot, long slotTableEpoch, String sessionIp, boolean migrate) { + SlotDiffSyncer syncer = + new SlotDiffSyncer( + dataServerConfig, localDatumStorage, dataChangeEventCenter, sessionLeaseManager); + SyncContinues continues = + new SyncContinues() { + @Override + public boolean continues() { + // if not leader, the syncing need to break + return isLeader(slot.getId()); + } }; - SyncSessionTask task = new SyncSessionTask(slotTableEpoch, slot, sessionIp, syncer, - sessionNodeExchanger, continues); - if (migrate) { - // group by slotId and session - return migrateSessionExecutor.execute(new Tuple(slot.getId(), sessionIp), task); - } else { - // to a session node, at most there is 8 tasks running, avoid too many task hit the same session - return syncSessionExecutor.execute(new Tuple((slot.getId() % 8), sessionIp), task); - } - } - - static final class SlotState { - final int slotId; - volatile Slot slot; - volatile boolean migrated; - volatile long migratingStartTime; - volatile long lastSuccessLeaderSyncTime = -1L; - final Map migratingTasks = Maps.newTreeMap(); - final Map> syncSessionTasks = Maps.newTreeMap(); - volatile KeyedTask syncLeaderTask; - - SlotState(Slot slot) { - this.slotId = slot.getId(); - this.slot = slot; - } - - void update(Slot s) { - ParaCheckUtil.checkEquals(slotId, s.getId(), "slot.id"); - if (slot.getLeaderEpoch() != s.getLeaderEpoch()) { - this.migrated = false; - this.syncSessionTasks.clear(); - this.migratingTasks.clear(); - this.migratingStartTime = 0; - if (localIsLeader(s)) { - // leader change - observeLeaderUpdateCounter(); - } - observeLeaderMigratingFinish(slot.getId()); - LOGGER.info("update slot with leaderEpoch, exist={}, now={}", slot, s); - } - this.slot = s; - LOGGER.info("update slot, slot={}", slot); - } - - void completeSyncLeaderTask() { - if (syncLeaderTask != null && syncLeaderTask.isSuccess()) { - this.lastSuccessLeaderSyncTime = syncLeaderTask.getEndTime(); - } - } - - boolean isFinish(Collection sessions) { - if (sessions.isEmpty()) { - return false; - } - boolean finished = true; - for (String session : sessions) { - MigratingTask t = migratingTasks.get(session); - if (t == null || !t.task.isSuccess()) { - finished = false; - break; - } - } - return finished; - } - } - - static class MigratingTask { - final long createTimestamp = System.currentTimeMillis(); - KeyedTask task; - int tryCount; - - MigratingTask(KeyedTask task) { - this.task = task; - } - } - - private static final class SyncSessionTask implements Runnable { - final long slotTableEpoch; - final Slot slot; - final String sessionIp; - final SlotDiffSyncer syncer; - final SessionNodeExchanger sessionNodeExchanger; - final SyncContinues continues; - - SyncSessionTask(long slotTableEpoch, Slot slot, String sessionIp, SlotDiffSyncer syncer, - SessionNodeExchanger sessionNodeExchanger, SyncContinues continues) { - this.slotTableEpoch = slotTableEpoch; - this.slot = slot; - this.sessionIp = sessionIp; - this.syncer = syncer; - this.sessionNodeExchanger = sessionNodeExchanger; - this.continues = continues; - } - - public void run() { - try { - if (!syncer.syncSession(slot.getId(), sessionIp, sessionNodeExchanger, - slotTableEpoch, continues)) { - // sync failed - throw new RuntimeException("sync session failed"); - } - } catch (Throwable e) { - ERROR_LOGGER.error("[syncSession]sync failed: {}, slot={}", sessionIp, - slot.getId(), e); - throw new RuntimeException(StringFormatter.format( - "sync session failed: {}, slot={}", sessionIp, slot.getId()), e); - } - } - - @Override - public String toString() { - return "SyncSessionTask{" + "slotTableEpoch=" + slotTableEpoch + ", sessionIp='" - + sessionIp + '\'' + ", slot=" + slot + '}'; - } - } - - private static final class SyncLeaderTask implements Runnable { - final long slotTableEpoch; - final Slot slot; - final SlotDiffSyncer syncer; - final DataNodeExchanger dataNodeExchanger; - final SyncContinues continues; - - SyncLeaderTask(long slotTableEpoch, Slot slot, SlotDiffSyncer syncer, - DataNodeExchanger dataNodeExchanger, SyncContinues continues) { - this.slotTableEpoch = slotTableEpoch; - this.slot = slot; - this.syncer = syncer; - this.dataNodeExchanger = dataNodeExchanger; - this.continues = continues; - } - - @Override - public void run() { - try { - if (!syncer.syncSlotLeader(slot.getId(), slot.getLeader(), dataNodeExchanger, - slotTableEpoch, continues)) { - throw new RuntimeException("sync leader failed"); - } - } catch (Throwable e) { - ERROR_LOGGER.error("[syncLeader]sync failed: {}, slot={}", slot.getLeader(), - slot.getId(), e); - throw new RuntimeException(StringFormatter.format( - "sync leader failed: {}, slot={}", slot.getLeader(), slot.getId()), e); - } - } - - @Override - public String toString() { - return "SyncLeaderTask{" + "slotTableEpoch=" + slotTableEpoch + ", slot=" + slot + '}'; - } + SyncSessionTask task = + new SyncSessionTask( + slotTableEpoch, slot, sessionIp, syncer, sessionNodeExchanger, continues); + if (migrate) { + // group by slotId and session + return migrateSessionExecutor.execute(new Tuple(slot.getId(), sessionIp), task); + } else { + // to a session node, at most there is 8 tasks running, avoid too many task hit the same + // session + return syncSessionExecutor.execute(new Tuple((slot.getId() % 8), sessionIp), task); + } + } + + static final class SlotState { + final int slotId; + volatile Slot slot; + volatile boolean migrated; + volatile long migratingStartTime; + volatile long lastSuccessLeaderSyncTime = -1L; + final Map migratingTasks = Maps.newTreeMap(); + final Map> syncSessionTasks = Maps.newTreeMap(); + volatile KeyedTask syncLeaderTask; + + SlotState(Slot slot) { + this.slotId = slot.getId(); + this.slot = slot; + } + + void update(Slot s) { + ParaCheckUtil.checkEquals(slotId, s.getId(), "slot.id"); + if (slot.getLeaderEpoch() != s.getLeaderEpoch()) { + this.migrated = false; + this.syncSessionTasks.clear(); + this.migratingTasks.clear(); + this.migratingStartTime = 0; + if (localIsLeader(s)) { + // leader change + observeLeaderUpdateCounter(); + } + observeLeaderMigratingFinish(slot.getId()); + LOGGER.info("update slot with leaderEpoch, exist={}, now={}", slot, s); + } + this.slot = s; + LOGGER.info("update slot, slot={}", slot); + } + + void completeSyncLeaderTask() { + if (syncLeaderTask != null && syncLeaderTask.isSuccess()) { + this.lastSuccessLeaderSyncTime = syncLeaderTask.getEndTime(); + } + } + + boolean isFinish(Collection sessions) { + if (sessions.isEmpty()) { + return false; + } + boolean finished = true; + for (String session : sessions) { + MigratingTask t = migratingTasks.get(session); + if (t == null || !t.task.isSuccess()) { + finished = false; + break; + } + } + return finished; + } + } + + static class MigratingTask { + final long createTimestamp = System.currentTimeMillis(); + KeyedTask task; + int tryCount; + + MigratingTask(KeyedTask task) { + this.task = task; + } + } + + private static final class SyncSessionTask implements Runnable { + final long slotTableEpoch; + final Slot slot; + final String sessionIp; + final SlotDiffSyncer syncer; + final SessionNodeExchanger sessionNodeExchanger; + final SyncContinues continues; + + SyncSessionTask( + long slotTableEpoch, + Slot slot, + String sessionIp, + SlotDiffSyncer syncer, + SessionNodeExchanger sessionNodeExchanger, + SyncContinues continues) { + this.slotTableEpoch = slotTableEpoch; + this.slot = slot; + this.sessionIp = sessionIp; + this.syncer = syncer; + this.sessionNodeExchanger = sessionNodeExchanger; + this.continues = continues; + } + + public void run() { + try { + if (!syncer.syncSession( + slot.getId(), sessionIp, sessionNodeExchanger, slotTableEpoch, continues)) { + // sync failed + throw new RuntimeException("sync session failed"); + } + } catch (Throwable e) { + ERROR_LOGGER.error("[syncSession]sync failed: {}, slot={}", sessionIp, slot.getId(), e); + throw new RuntimeException( + StringFormatter.format("sync session failed: {}, slot={}", sessionIp, slot.getId()), e); + } } @Override - public void triggerUpdateSlotTable(long expectEpoch) { - // TODO + public String toString() { + return "SyncSessionTask{" + + "slotTableEpoch=" + + slotTableEpoch + + ", sessionIp='" + + sessionIp + + '\'' + + ", slot=" + + slot + + '}'; + } + } + + private static final class SyncLeaderTask implements Runnable { + final long slotTableEpoch; + final Slot slot; + final SlotDiffSyncer syncer; + final DataNodeExchanger dataNodeExchanger; + final SyncContinues continues; + + SyncLeaderTask( + long slotTableEpoch, + Slot slot, + SlotDiffSyncer syncer, + DataNodeExchanger dataNodeExchanger, + SyncContinues continues) { + this.slotTableEpoch = slotTableEpoch; + this.slot = slot; + this.syncer = syncer; + this.dataNodeExchanger = dataNodeExchanger; + this.continues = continues; } @Override - public long getSlotTableEpoch() { - return slotTableStates.table.getEpoch(); - } - - private static Slot.Role getRole(Slot s) { - return localIsLeader(s) ? Slot.Role.Leader : Slot.Role.Follower; - } - - private void listenAdd(Slot s) { - slotChangeListeners.forEach(listener -> listener.onSlotAdd(s.getId(), getRole(s))); - } - - private void listenRemove(Slot s) { - slotChangeListeners.forEach(listener -> listener.onSlotRemove(s.getId(), getRole(s))); - } - - private static boolean localIsLeader(Slot slot) { - return ServerEnv.isLocalServer(slot.getLeader()); - } - - @VisibleForTesting - void setMetaServerService(MetaServerServiceImpl metaServerService) { - this.metaServerService = metaServerService; + public void run() { + try { + if (!syncer.syncSlotLeader( + slot.getId(), slot.getLeader(), dataNodeExchanger, slotTableEpoch, continues)) { + throw new RuntimeException("sync leader failed"); + } + } catch (Throwable e) { + ERROR_LOGGER.error( + "[syncLeader]sync failed: {}, slot={}", slot.getLeader(), slot.getId(), e); + throw new RuntimeException( + StringFormatter.format( + "sync leader failed: {}, slot={}", slot.getLeader(), slot.getId()), + e); + } } - @VisibleForTesting - void setDataServerConfig(DataServerConfig dataServerConfig) { - this.dataServerConfig = dataServerConfig; - } - - @VisibleForTesting - void setLocalDatumStorage(DatumStorage localDatumStorage) { - this.localDatumStorage = localDatumStorage; - } - - @VisibleForTesting - void setDataChangeEventCenter(DataChangeEventCenter dataChangeEventCenter) { - this.dataChangeEventCenter = dataChangeEventCenter; - } - - @VisibleForTesting - void setSessionLeaseManager(SessionLeaseManager sessionLeaseManager) { - this.sessionLeaseManager = sessionLeaseManager; - } - - @VisibleForTesting - void setSlotGenericResource(SlotGenericResource slotGenericResource) { - this.slotGenericResource = slotGenericResource; - } + @Override + public String toString() { + return "SyncLeaderTask{" + "slotTableEpoch=" + slotTableEpoch + ", slot=" + slot + '}'; + } + } + + @Override + public void triggerUpdateSlotTable(long expectEpoch) { + // TODO + } + + @Override + public long getSlotTableEpoch() { + return slotTableStates.table.getEpoch(); + } + + private static Slot.Role getRole(Slot s) { + return localIsLeader(s) ? Slot.Role.Leader : Slot.Role.Follower; + } + + private void listenAdd(Slot s) { + slotChangeListeners.forEach(listener -> listener.onSlotAdd(s.getId(), getRole(s))); + } + + private void listenRemove(Slot s) { + slotChangeListeners.forEach(listener -> listener.onSlotRemove(s.getId(), getRole(s))); + } + + private static boolean localIsLeader(Slot slot) { + return ServerEnv.isLocalServer(slot.getLeader()); + } + + @VisibleForTesting + void setMetaServerService(MetaServerServiceImpl metaServerService) { + this.metaServerService = metaServerService; + } + + @VisibleForTesting + void setDataServerConfig(DataServerConfig dataServerConfig) { + this.dataServerConfig = dataServerConfig; + } + + @VisibleForTesting + void setLocalDatumStorage(DatumStorage localDatumStorage) { + this.localDatumStorage = localDatumStorage; + } + + @VisibleForTesting + void setDataChangeEventCenter(DataChangeEventCenter dataChangeEventCenter) { + this.dataChangeEventCenter = dataChangeEventCenter; + } + + @VisibleForTesting + void setSessionLeaseManager(SessionLeaseManager sessionLeaseManager) { + this.sessionLeaseManager = sessionLeaseManager; + } + + @VisibleForTesting + void setSlotGenericResource(SlotGenericResource slotGenericResource) { + this.slotGenericResource = slotGenericResource; + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotMetrics.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotMetrics.java index 5c9d3d082..5f41531d3 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotMetrics.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SlotMetrics.java @@ -21,143 +21,188 @@ import io.prometheus.client.Histogram; public final class SlotMetrics { - private SlotMetrics() { - } - - static final class Manager { - private static final Counter LEADER_UPDATE_COUNTER = Counter.build() - .namespace("data").subsystem("slot") - .name("leader_update_total").help("count leader update") - .register(); - - private static final Gauge LEADER_ASSIGN_GAUGE = Gauge.build() - .namespace("data").subsystem("slot") - .name("leader_assign_total").help("leader assign").register(); - - private static final Gauge FOLLOWER_ASSIGN_GAUGE = Gauge.build() - .namespace("data").subsystem("slot") - .name("follower_assign_total").help("follower assign") - .register(); - - private static final Gauge LEADER_MIGRATING_GAUGE = Gauge.build() - .namespace("data").subsystem("slot") - .name("leader_migrating_total") - .help("count leader is migrating").labelNames("slot") - .register(); - - private static final Counter LEADER_MIGRATING_FAIL_COUNTER = Counter - .build().namespace("data").subsystem("slot") - .name("leader_migrating_fail_total") - .help("count leader migrating fail") - .labelNames("slot", "session").register(); - - private static final Histogram LEADER_MIGRATING_HISTOGRAM = Histogram - .build().namespace("data").subsystem("slot") - .name("leader_migrating_secs").help("migrating in seconds.") - .labelNames("slot") - .buckets(3, 5, 10, 20, 30, 60, 120, 180, 240).register(); - - static void observeLeaderUpdateCounter() { - LEADER_UPDATE_COUNTER.inc(); - } - - static void observeLeaderAssignGauge(int num) { - LEADER_ASSIGN_GAUGE.set(num); - } - - static void observeFollowerAssignGauge(int num) { - FOLLOWER_ASSIGN_GAUGE.set(num); - } - - static void observeLeaderMigratingStart(int slotId) { - LEADER_MIGRATING_GAUGE.labels(String.valueOf(slotId)).set(1); - } - - static void observeLeaderMigratingFinish(int slotId) { - LEADER_MIGRATING_GAUGE.labels(String.valueOf(slotId)).set(0); - } - - static void observeLeaderMigratingFail(int slotId, String sessionIp) { - LEADER_MIGRATING_FAIL_COUNTER.labels(String.valueOf(slotId), - sessionIp).inc(); - } - - static void observeLeaderMigratingHistogram(int slotId, long millis) { - // seconds - LEADER_MIGRATING_HISTOGRAM.labels(String.valueOf(slotId)).observe( - millis / 1000d); - } - } - - static final class SyncSession { - private static final Counter SYNC_SESSION_ID_COUNTER = Counter.build() - .namespace("data").subsystem("sync").name("session_id_total") - .help("count sync session dataInfoIds").labelNames("slot") - .register(); - - private static final Counter SYNC_SESSION_ID_NUM_COUNTER = Counter - .build().namespace("data").subsystem("sync") - .name("session_id_num_total") - .help("count sync session dataInfoId's num").labelNames("slot") - .register(); - - private static final Counter SYNC_SESSION_PUB_COUNTER = Counter.build() - .namespace("data").subsystem("sync").name("session_pub_total") - .help("count sync session pubs").labelNames("slot").register(); - - private static final Counter SYNC_SESSION_PUB_NUM_COUNTER = Counter - .build().namespace("data").subsystem("sync") - .name("session_pub_num_total") - .help("count sync session pub's num").labelNames("slot") - .register(); - - static void observeSyncSessionId(int slotId, int idNum) { - final String str = String.valueOf(slotId); - SYNC_SESSION_ID_COUNTER.labels(str).inc(); - SYNC_SESSION_ID_NUM_COUNTER.labels(str).inc(idNum); - } - - static void observeSyncSessionPub(int slotId, int pubNum) { - final String str = String.valueOf(slotId); - SYNC_SESSION_PUB_COUNTER.labels(str).inc(); - SYNC_SESSION_PUB_NUM_COUNTER.labels(str).inc(pubNum); - } - - } - - static final class SyncLeader { - private static final Counter SYNC_LEADER_ID_COUNTER = Counter.build() - .namespace("data").subsystem("sync").name("leader_id_total") - .help("count sync leader dataInfoIds").labelNames("slot") - .register(); - - private static final Counter SYNC_LEADER_ID_NUM_COUNTER = Counter - .build().namespace("data").subsystem("sync") - .name("leader_id_num_total") - .help("count sync leader dataInfoId's num").labelNames("slot") - .register(); - - private static final Counter SYNC_LEADER_PUB_COUNTER = Counter.build() - .namespace("data").subsystem("sync").name("leader_pub_total") - .help("count sync leader pubs").labelNames("slot").register(); - - private static final Counter SYNC_LEADER_PUB_NUM_COUNTER = Counter - .build().namespace("data").subsystem("sync") - .name("leader_pub_num_total") - .help("count sync leader pub's num").labelNames("slot") - .register(); - - static void observeSyncLeaderId(int slotId, int idNum) { - final String str = String.valueOf(slotId); - SYNC_LEADER_ID_COUNTER.labels(str).inc(); - SYNC_LEADER_ID_NUM_COUNTER.labels(str).inc(idNum); - } - - static void observeSyncLeaderPub(int slotId, int pubNum) { - final String str = String.valueOf(slotId); - SYNC_LEADER_PUB_COUNTER.labels(str).inc(); - SYNC_LEADER_PUB_NUM_COUNTER.labels(str).inc(pubNum); - } - - } + private SlotMetrics() {} + + static final class Manager { + private static final Counter LEADER_UPDATE_COUNTER = + Counter.build() + .namespace("data") + .subsystem("slot") + .name("leader_update_total") + .help("count leader update") + .register(); + + private static final Gauge LEADER_ASSIGN_GAUGE = + Gauge.build() + .namespace("data") + .subsystem("slot") + .name("leader_assign_total") + .help("leader assign") + .register(); + + private static final Gauge FOLLOWER_ASSIGN_GAUGE = + Gauge.build() + .namespace("data") + .subsystem("slot") + .name("follower_assign_total") + .help("follower assign") + .register(); + + private static final Gauge LEADER_MIGRATING_GAUGE = + Gauge.build() + .namespace("data") + .subsystem("slot") + .name("leader_migrating_total") + .help("count leader is migrating") + .labelNames("slot") + .register(); + + private static final Counter LEADER_MIGRATING_FAIL_COUNTER = + Counter.build() + .namespace("data") + .subsystem("slot") + .name("leader_migrating_fail_total") + .help("count leader migrating fail") + .labelNames("slot", "session") + .register(); + + private static final Histogram LEADER_MIGRATING_HISTOGRAM = + Histogram.build() + .namespace("data") + .subsystem("slot") + .name("leader_migrating_secs") + .help("migrating in seconds.") + .labelNames("slot") + .buckets(3, 5, 10, 20, 30, 60, 120, 180, 240) + .register(); + + static void observeLeaderUpdateCounter() { + LEADER_UPDATE_COUNTER.inc(); + } + + static void observeLeaderAssignGauge(int num) { + LEADER_ASSIGN_GAUGE.set(num); + } + + static void observeFollowerAssignGauge(int num) { + FOLLOWER_ASSIGN_GAUGE.set(num); + } + + static void observeLeaderMigratingStart(int slotId) { + LEADER_MIGRATING_GAUGE.labels(String.valueOf(slotId)).set(1); + } + + static void observeLeaderMigratingFinish(int slotId) { + LEADER_MIGRATING_GAUGE.labels(String.valueOf(slotId)).set(0); + } + + static void observeLeaderMigratingFail(int slotId, String sessionIp) { + LEADER_MIGRATING_FAIL_COUNTER.labels(String.valueOf(slotId), sessionIp).inc(); + } + + static void observeLeaderMigratingHistogram(int slotId, long millis) { + // seconds + LEADER_MIGRATING_HISTOGRAM.labels(String.valueOf(slotId)).observe(millis / 1000d); + } + } + + static final class SyncSession { + private static final Counter SYNC_SESSION_ID_COUNTER = + Counter.build() + .namespace("data") + .subsystem("sync") + .name("session_id_total") + .help("count sync session dataInfoIds") + .labelNames("slot") + .register(); + + private static final Counter SYNC_SESSION_ID_NUM_COUNTER = + Counter.build() + .namespace("data") + .subsystem("sync") + .name("session_id_num_total") + .help("count sync session dataInfoId's num") + .labelNames("slot") + .register(); + + private static final Counter SYNC_SESSION_PUB_COUNTER = + Counter.build() + .namespace("data") + .subsystem("sync") + .name("session_pub_total") + .help("count sync session pubs") + .labelNames("slot") + .register(); + + private static final Counter SYNC_SESSION_PUB_NUM_COUNTER = + Counter.build() + .namespace("data") + .subsystem("sync") + .name("session_pub_num_total") + .help("count sync session pub's num") + .labelNames("slot") + .register(); + + static void observeSyncSessionId(int slotId, int idNum) { + final String str = String.valueOf(slotId); + SYNC_SESSION_ID_COUNTER.labels(str).inc(); + SYNC_SESSION_ID_NUM_COUNTER.labels(str).inc(idNum); + } + + static void observeSyncSessionPub(int slotId, int pubNum) { + final String str = String.valueOf(slotId); + SYNC_SESSION_PUB_COUNTER.labels(str).inc(); + SYNC_SESSION_PUB_NUM_COUNTER.labels(str).inc(pubNum); + } + } + + static final class SyncLeader { + private static final Counter SYNC_LEADER_ID_COUNTER = + Counter.build() + .namespace("data") + .subsystem("sync") + .name("leader_id_total") + .help("count sync leader dataInfoIds") + .labelNames("slot") + .register(); + + private static final Counter SYNC_LEADER_ID_NUM_COUNTER = + Counter.build() + .namespace("data") + .subsystem("sync") + .name("leader_id_num_total") + .help("count sync leader dataInfoId's num") + .labelNames("slot") + .register(); + + private static final Counter SYNC_LEADER_PUB_COUNTER = + Counter.build() + .namespace("data") + .subsystem("sync") + .name("leader_pub_total") + .help("count sync leader pubs") + .labelNames("slot") + .register(); + + private static final Counter SYNC_LEADER_PUB_NUM_COUNTER = + Counter.build() + .namespace("data") + .subsystem("sync") + .name("leader_pub_num_total") + .help("count sync leader pub's num") + .labelNames("slot") + .register(); + + static void observeSyncLeaderId(int slotId, int idNum) { + final String str = String.valueOf(slotId); + SYNC_LEADER_ID_COUNTER.labels(str).inc(); + SYNC_LEADER_ID_NUM_COUNTER.labels(str).inc(idNum); + } + + static void observeSyncLeaderPub(int slotId, int pubNum) { + final String str = String.valueOf(slotId); + SYNC_LEADER_PUB_COUNTER.labels(str).inc(); + SYNC_LEADER_PUB_NUM_COUNTER.labels(str).inc(pubNum); + } + } } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SyncContinues.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SyncContinues.java index d41e49ad6..e4db7a3ce 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SyncContinues.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/slot/SyncContinues.java @@ -17,5 +17,5 @@ package com.alipay.sofa.registry.server.data.slot; public interface SyncContinues { - boolean continues(); + boolean continues(); } diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/timer/CacheCountTask.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/timer/CacheCountTask.java index 29046ed4b..e4cee8b5e 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/timer/CacheCountTask.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/timer/CacheCountTask.java @@ -24,9 +24,6 @@ import com.alipay.sofa.registry.server.data.cache.DatumCache; import com.alipay.sofa.registry.util.ConcurrentUtils; import com.alipay.sofa.registry.util.NamedThreadFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -34,82 +31,89 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; /** * @author qian.lqlq * @version $Id: CacheDigestTask.java, v 0.1 2018-04-27 17:40 qian.lqlq Exp $ */ public class CacheCountTask { - private static final Logger LOGGER = LoggerFactory.getLogger(CacheCountTask.class, - "[CacheCountTask]"); - private static final Logger COUNT_LOGGER = LoggerFactory.getLogger("CACHE-COUNT"); - - @Autowired - private DatumCache datumCache; + private static final Logger LOGGER = + LoggerFactory.getLogger(CacheCountTask.class, "[CacheCountTask]"); + private static final Logger COUNT_LOGGER = LoggerFactory.getLogger("CACHE-COUNT"); - @Autowired - private DataServerConfig dataServerConfig; + @Autowired private DatumCache datumCache; - @PostConstruct - public void init() { - final int intervalSec = dataServerConfig.getCacheCountIntervalSecs(); - if (intervalSec <= 0) { - LOGGER.info("cache count off with intervalSecs={}", intervalSec); - return; - } - ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1, - new NamedThreadFactory("CacheCountTask")); - executor.scheduleWithFixedDelay(() -> { - try { - Map>> allMap = datumCache.getAllPublisher(); - if (!allMap.isEmpty()) { - for (Entry>> dataCenterEntry : allMap.entrySet()) { - final String dataCenter = dataCenterEntry.getKey(); - List all = new ArrayList<>(512); - for (List publishers : dataCenterEntry.getValue().values()) { - all.addAll(publishers); - } - Map> groupCounts = DataUtils.countGroupByInstanceIdGroup(all); - printGroupCount(dataCenter, groupCounts); + @Autowired private DataServerConfig dataServerConfig; - Map>> counts = DataUtils.countGroupByInstanceIdGroupApp(all); - printCount(dataCenter, counts); - } - } else { - LOGGER.info("datum cache is empty"); + @PostConstruct + public void init() { + final int intervalSec = dataServerConfig.getCacheCountIntervalSecs(); + if (intervalSec <= 0) { + LOGGER.info("cache count off with intervalSecs={}", intervalSec); + return; + } + ScheduledExecutorService executor = + new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("CacheCountTask")); + executor.scheduleWithFixedDelay( + () -> { + try { + Map>> allMap = datumCache.getAllPublisher(); + if (!allMap.isEmpty()) { + for (Entry>> dataCenterEntry : + allMap.entrySet()) { + final String dataCenter = dataCenterEntry.getKey(); + List all = new ArrayList<>(512); + for (List publishers : dataCenterEntry.getValue().values()) { + all.addAll(publishers); } + Map> groupCounts = + DataUtils.countGroupByInstanceIdGroup(all); + printGroupCount(dataCenter, groupCounts); - } catch (Throwable t) { - LOGGER.error("cache count error", t); + Map>> counts = + DataUtils.countGroupByInstanceIdGroupApp(all); + printCount(dataCenter, counts); + } + } else { + LOGGER.info("datum cache is empty"); } - }, intervalSec, intervalSec, TimeUnit.SECONDS); - } - private static void printCount(String dataCenter, - Map>> counts) { - for (Entry>> count : counts.entrySet()) { - final String instanceId = count.getKey(); - for (Entry> groupCounts : count.getValue().entrySet()) { - final String group = groupCounts.getKey(); - for (Entry apps : groupCounts.getValue().entrySet()) { - final String app = apps.getKey(); - COUNT_LOGGER.info("[Pub]{},{},{},{},{}", dataCenter, instanceId, group, app, - apps.getValue()); - } - ConcurrentUtils.sleepUninterruptibly(100, TimeUnit.MILLISECONDS); - } + } catch (Throwable t) { + LOGGER.error("cache count error", t); + } + }, + intervalSec, + intervalSec, + TimeUnit.SECONDS); + } + + private static void printCount( + String dataCenter, Map>> counts) { + for (Entry>> count : counts.entrySet()) { + final String instanceId = count.getKey(); + for (Entry> groupCounts : count.getValue().entrySet()) { + final String group = groupCounts.getKey(); + for (Entry apps : groupCounts.getValue().entrySet()) { + final String app = apps.getKey(); + COUNT_LOGGER.info( + "[Pub]{},{},{},{},{}", dataCenter, instanceId, group, app, apps.getValue()); } + ConcurrentUtils.sleepUninterruptibly(100, TimeUnit.MILLISECONDS); + } } + } - private static void printGroupCount(String dataCenter, Map> counts) { - for (Map.Entry> count : counts.entrySet()) { - final String instanceId = count.getKey(); - Map groupCounts = count.getValue(); - for (Entry groupCount : groupCounts.entrySet()) { - final String group = groupCount.getKey(); - COUNT_LOGGER.info("[PubGroup]{},{},{},{}", dataCenter, instanceId, group, - groupCount.getValue()); - } - } + private static void printGroupCount(String dataCenter, Map> counts) { + for (Map.Entry> count : counts.entrySet()) { + final String instanceId = count.getKey(); + Map groupCounts = count.getValue(); + for (Entry groupCount : groupCounts.entrySet()) { + final String group = groupCount.getKey(); + COUNT_LOGGER.info( + "[PubGroup]{},{},{},{}", dataCenter, instanceId, group, groupCount.getValue()); + } } -} \ No newline at end of file + } +} diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/timer/CacheDigestTask.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/timer/CacheDigestTask.java index d3775b76e..246df7f3a 100644 --- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/timer/CacheDigestTask.java +++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/timer/CacheDigestTask.java @@ -25,91 +25,97 @@ import com.alipay.sofa.registry.server.data.cache.DatumCache; import com.alipay.sofa.registry.util.ConcurrentUtils; import com.alipay.sofa.registry.util.StringFormatter; -import org.apache.commons.lang.time.DateUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.CollectionUtils; - -import javax.annotation.PostConstruct; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import javax.annotation.PostConstruct; +import org.apache.commons.lang.time.DateUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; /** * @author qian.lqlq * @version $Id: CacheDigestTask.java, v 0.1 2018-04-27 17:40 qian.lqlq Exp $ */ public class CacheDigestTask { - private static final Logger LOGGER = LoggerFactory.getLogger("CACHE-DIGEST"); + private static final Logger LOGGER = LoggerFactory.getLogger("CACHE-DIGEST"); - @Autowired - private DatumCache datumCache; + @Autowired private DatumCache datumCache; - @Autowired - private DataServerConfig dataServerConfig; + @Autowired private DataServerConfig dataServerConfig; - @PostConstruct - public void init() { - final int intervalMinutes = dataServerConfig.getCacheDigestIntervalMinutes(); - if (intervalMinutes <= 0) { - LOGGER.info("cache digest off with intervalMinutes={}", intervalMinutes); - return; - } - Date firstDate = new Date(); - firstDate = DateUtils.round(firstDate, Calendar.MINUTE); - firstDate.setMinutes(firstDate.getMinutes() / intervalMinutes * intervalMinutes - + intervalMinutes); - Timer timer = new Timer("CacheDigestTask", true); - TimerTask task = new TimerTask() { - @Override - public void run() { - dump(); - } - }; - timer.scheduleAtFixedRate(task, firstDate, intervalMinutes * 60 * 1000); + @PostConstruct + public void init() { + final int intervalMinutes = dataServerConfig.getCacheDigestIntervalMinutes(); + if (intervalMinutes <= 0) { + LOGGER.info("cache digest off with intervalMinutes={}", intervalMinutes); + return; } + Date firstDate = new Date(); + firstDate = DateUtils.round(firstDate, Calendar.MINUTE); + firstDate.setMinutes( + firstDate.getMinutes() / intervalMinutes * intervalMinutes + intervalMinutes); + Timer timer = new Timer("CacheDigestTask", true); + TimerTask task = + new TimerTask() { + @Override + public void run() { + dump(); + } + }; + timer.scheduleAtFixedRate(task, firstDate, intervalMinutes * 60 * 1000); + } - private void dump() { - try { - Map> allMap = datumCache.getAll(); - if (!allMap.isEmpty()) { - for (Entry> dataCenterEntry : allMap.entrySet()) { - String dataCenter = dataCenterEntry.getKey(); - Map datumMap = dataCenterEntry.getValue(); - LOGGER.info("size of datum in {} is {}", dataCenter, datumMap.size()); - for (Entry dataInfoEntry : datumMap.entrySet()) { - String dataInfoId = dataInfoEntry.getKey(); - Datum data = dataInfoEntry.getValue(); - Map pubMap = data.getPubMap(); - StringBuilder pubStr = new StringBuilder(4096); - if (!CollectionUtils.isEmpty(pubMap)) { - for (Publisher publisher : pubMap.values()) { - pubStr.append(logPublisher(publisher)).append(";"); - } - } - LOGGER.info("[Datum]{},{},{},[{}]", dataInfoId, - data.getVersion(), dataCenter, pubStr.toString()); - // avoid io is busy - ConcurrentUtils.sleepUninterruptibly(2, TimeUnit.MILLISECONDS); - } - int pubCount = datumMap.values().stream().mapToInt(Datum::publisherSize).sum(); - LOGGER.info("size of publisher in {} is {}", dataCenter, pubCount); - } - } else { - LOGGER.info("datum cache is empty"); + private void dump() { + try { + Map> allMap = datumCache.getAll(); + if (!allMap.isEmpty()) { + for (Entry> dataCenterEntry : allMap.entrySet()) { + String dataCenter = dataCenterEntry.getKey(); + Map datumMap = dataCenterEntry.getValue(); + LOGGER.info("size of datum in {} is {}", dataCenter, datumMap.size()); + for (Entry dataInfoEntry : datumMap.entrySet()) { + String dataInfoId = dataInfoEntry.getKey(); + Datum data = dataInfoEntry.getValue(); + Map pubMap = data.getPubMap(); + StringBuilder pubStr = new StringBuilder(4096); + if (!CollectionUtils.isEmpty(pubMap)) { + for (Publisher publisher : pubMap.values()) { + pubStr.append(logPublisher(publisher)).append(";"); + } } - - } catch (Throwable t) { - LOGGER.error("cache digest error", t); + LOGGER.info( + "[Datum]{},{},{},[{}]", + dataInfoId, + data.getVersion(), + dataCenter, + pubStr.toString()); + // avoid io is busy + ConcurrentUtils.sleepUninterruptibly(2, TimeUnit.MILLISECONDS); + } + int pubCount = datumMap.values().stream().mapToInt(Datum::publisherSize).sum(); + LOGGER.info("size of publisher in {} is {}", dataCenter, pubCount); } + } else { + LOGGER.info("datum cache is empty"); + } + + } catch (Throwable t) { + LOGGER.error("cache digest error", t); } + } - private String logPublisher(Publisher publisher) { - if (publisher != null) { - URL url = publisher.getSourceAddress(); - String urlStr = url != null ? url.getAddressString() : "null"; - return StringFormatter.format("{},{},{},{}", publisher.getRegisterId(), - publisher.getRegisterTimestamp(), urlStr, publisher.getVersion()); - } - return ""; + private String logPublisher(Publisher publisher) { + if (publisher != null) { + URL url = publisher.getSourceAddress(); + String urlStr = url != null ? url.getAddressString() : "null"; + return StringFormatter.format( + "{},{},{},{}", + publisher.getRegisterId(), + publisher.getRegisterTimestamp(), + urlStr, + publisher.getVersion()); } -} \ No newline at end of file + return ""; + } +} diff --git a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/MigrateTest.java b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/MigrateTest.java index 8f223b2ce..569a39202 100644 --- a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/MigrateTest.java +++ b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/MigrateTest.java @@ -20,47 +20,43 @@ import com.alipay.sofa.registry.common.model.RegisterVersion; import com.alipay.sofa.registry.common.model.dataserver.DatumSummary; import com.alipay.sofa.registry.common.model.slot.DataSlotDiffPublisherRequest; -import com.alipay.sofa.registry.common.model.store.Publisher; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Test; - import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.util.*; import java.util.zip.GZIPOutputStream; +import org.junit.Test; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-18 14:09 yuzhi.lyz Exp $ */ public class MigrateTest { - @Test - public void testBody() throws Exception { - HessianSerializer s = new HessianSerializer(); - List list = Lists.newArrayList(); - for (int i = 0; i < 10; i++) { - Map publisherMap = Maps.newHashMap(); - for (int j = 0; j < 1000; j++) { - publisherMap.put(UUID.randomUUID().toString(), - RegisterVersion.of(0, System.currentTimeMillis())); - } - DatumSummary summary = new DatumSummary("app" + System.currentTimeMillis(), - publisherMap); - list.add(summary); - } - DataSlotDiffPublisherRequest request = new DataSlotDiffPublisherRequest(100, 200, list); - byte[] bs = s.serialize(request); - ByteArrayOutputStream b = new ByteArrayOutputStream(); - GZIPOutputStream zip = new GZIPOutputStream(b); - OutputStream out = new BufferedOutputStream(zip); - - out.write(bs); - out.flush(); - out.close(); - System.out.println(bs.length); - System.out.println(b.toByteArray().length); + @Test + public void testBody() throws Exception { + HessianSerializer s = new HessianSerializer(); + List list = Lists.newArrayList(); + for (int i = 0; i < 10; i++) { + Map publisherMap = Maps.newHashMap(); + for (int j = 0; j < 1000; j++) { + publisherMap.put( + UUID.randomUUID().toString(), RegisterVersion.of(0, System.currentTimeMillis())); + } + DatumSummary summary = new DatumSummary("app" + System.currentTimeMillis(), publisherMap); + list.add(summary); } + DataSlotDiffPublisherRequest request = new DataSlotDiffPublisherRequest(100, 200, list); + byte[] bs = s.serialize(request); + ByteArrayOutputStream b = new ByteArrayOutputStream(); + GZIPOutputStream zip = new GZIPOutputStream(b); + OutputStream out = new BufferedOutputStream(zip); + + out.write(bs); + out.flush(); + out.close(); + System.out.println(bs.length); + System.out.println(b.toByteArray().length); + } } diff --git a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/TestBaseUtils.java b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/TestBaseUtils.java index 9bc51f2f7..258ae76e6 100644 --- a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/TestBaseUtils.java +++ b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/TestBaseUtils.java @@ -16,9 +16,11 @@ */ package com.alipay.sofa.registry.server.data; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.common.model.ConnectId; import com.alipay.sofa.registry.common.model.RegisterVersion; -import com.alipay.sofa.registry.common.model.Tuple; import com.alipay.sofa.registry.common.model.dataserver.Datum; import com.alipay.sofa.registry.common.model.dataserver.DatumSummary; import com.alipay.sofa.registry.common.model.slot.Slot; @@ -34,125 +36,123 @@ import com.alipay.sofa.registry.server.shared.env.ServerEnv; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; - import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.junit.Assert; public final class TestBaseUtils { - private static final AtomicLong REGISTER_ID_SEQ = new AtomicLong(); - private static final AtomicLong CLIENT_VERSION = new AtomicLong(); - - public final static String TEST_DATA_ID = "testDataId"; - public final static String TEST_DATA_INFO_ID; - - private final static String TEST_REGISTER_ID = "testRegisterId"; - - private static final AtomicLong DATA_ID_SEQ = new AtomicLong(); - - static { - Publisher p = TestBaseUtils.createTestPublisher(TEST_DATA_ID); - TEST_DATA_INFO_ID = p.getDataInfoId(); - } - - private TestBaseUtils() { - } - - public static Publisher createTestPublisher(String dataId) { - Publisher publisher = new Publisher(); - DataInfo dataInfo = DataInfo.valueOf(DataInfo.toDataInfoId(dataId, "I", "G")); - publisher.setDataInfoId(dataInfo.getDataInfoId()); - publisher.setDataId(dataInfo.getDataId()); - publisher.setInstanceId(dataInfo.getInstanceId()); - publisher.setGroup(dataInfo.getGroup()); - publisher.setRegisterId(TEST_REGISTER_ID + REGISTER_ID_SEQ.incrementAndGet()); - publisher.setSessionProcessId(ServerEnv.PROCESS_ID); - publisher.setRegisterTimestamp(System.currentTimeMillis()); - publisher.setVersion(100 + CLIENT_VERSION.incrementAndGet()); - ConnectId connectId = ConnectId.of(ServerEnv.PROCESS_ID.getHostAddress() + ":9999", + private static final AtomicLong REGISTER_ID_SEQ = new AtomicLong(); + private static final AtomicLong CLIENT_VERSION = new AtomicLong(); + + public static final String TEST_DATA_ID = "testDataId"; + public static final String TEST_DATA_INFO_ID; + + private static final String TEST_REGISTER_ID = "testRegisterId"; + + private static final AtomicLong DATA_ID_SEQ = new AtomicLong(); + + static { + Publisher p = TestBaseUtils.createTestPublisher(TEST_DATA_ID); + TEST_DATA_INFO_ID = p.getDataInfoId(); + } + + private TestBaseUtils() {} + + public static Publisher createTestPublisher(String dataId) { + Publisher publisher = new Publisher(); + DataInfo dataInfo = DataInfo.valueOf(DataInfo.toDataInfoId(dataId, "I", "G")); + publisher.setDataInfoId(dataInfo.getDataInfoId()); + publisher.setDataId(dataInfo.getDataId()); + publisher.setInstanceId(dataInfo.getInstanceId()); + publisher.setGroup(dataInfo.getGroup()); + publisher.setRegisterId(TEST_REGISTER_ID + REGISTER_ID_SEQ.incrementAndGet()); + publisher.setSessionProcessId(ServerEnv.PROCESS_ID); + publisher.setRegisterTimestamp(System.currentTimeMillis()); + publisher.setVersion(100 + CLIENT_VERSION.incrementAndGet()); + ConnectId connectId = + ConnectId.of( + ServerEnv.PROCESS_ID.getHostAddress() + ":9999", ServerEnv.PROCESS_ID.getHostAddress() + ":9998"); - publisher.setSourceAddress(URL.valueOf(connectId.clientAddress())); - publisher.setTargetAddress(URL.valueOf(connectId.sessionAddress())); - return publisher; + publisher.setSourceAddress(URL.valueOf(connectId.clientAddress())); + publisher.setTargetAddress(URL.valueOf(connectId.sessionAddress())); + return publisher; + } + + public static Publisher cloneBase(Publisher publisher) { + Publisher clone = TestBaseUtils.createTestPublisher(publisher.getDataId()); + clone.setRegisterId(publisher.getRegisterId()); + clone.setVersion(publisher.getVersion()); + clone.setRegisterTimestamp(publisher.getRegisterTimestamp()); + clone.setSessionProcessId(publisher.getSessionProcessId()); + return clone; + } + + public static void assertEquals(Datum datum, Publisher publisher) { + Assert.assertEquals(publisher.getDataInfoId(), datum.getDataInfoId()); + Assert.assertEquals(publisher.getDataId(), datum.getDataId()); + Assert.assertEquals(publisher.getInstanceId(), datum.getInstanceId()); + Assert.assertEquals(publisher.getGroup(), datum.getGroup()); + Assert.assertTrue(datum.getPubMap().containsKey(publisher.getRegisterId())); + } + + public static ConnectId notExistConnectId() { + return ConnectId.of("notExist:9999", "notExist:9998"); + } + + public static LocalDatumStorage newLocalStorage(String dataCenter, boolean init) { + CommonConfig commonConfig = mock(CommonConfig.class); + when(commonConfig.getLocalDataCenter()).thenReturn(dataCenter); + DataServerConfig dataServerConfig = new DataServerConfig(commonConfig); + LocalDatumStorage storage = new LocalDatumStorage(); + storage.setDataServerConfig(dataServerConfig); + if (init) { + for (int i = 0; i < SlotConfig.SLOT_NUM; i++) { + storage.getSlotChangeListener().onSlotAdd(i, Slot.Role.Leader); + } } - - public static Publisher cloneBase(Publisher publisher) { - Publisher clone = TestBaseUtils.createTestPublisher(publisher.getDataId()); - clone.setRegisterId(publisher.getRegisterId()); - clone.setVersion(publisher.getVersion()); - clone.setRegisterTimestamp(publisher.getRegisterTimestamp()); - clone.setSessionProcessId(publisher.getSessionProcessId()); - return clone; - } - - public static void assertEquals(Datum datum, Publisher publisher) { - Assert.assertEquals(publisher.getDataInfoId(), datum.getDataInfoId()); - Assert.assertEquals(publisher.getDataId(), datum.getDataId()); - Assert.assertEquals(publisher.getInstanceId(), datum.getInstanceId()); - Assert.assertEquals(publisher.getGroup(), datum.getGroup()); - Assert.assertTrue(datum.getPubMap().containsKey(publisher.getRegisterId())); - } - - public static ConnectId notExistConnectId() { - return ConnectId.of("notExist:9999", "notExist:9998"); - } - - public static LocalDatumStorage newLocalStorage(String dataCenter, boolean init) { - CommonConfig commonConfig = mock(CommonConfig.class); - when(commonConfig.getLocalDataCenter()).thenReturn(dataCenter); - DataServerConfig dataServerConfig = new DataServerConfig(commonConfig); - LocalDatumStorage storage = new LocalDatumStorage(); - storage.setDataServerConfig(dataServerConfig); - if (init) { - for (int i = 0; i < SlotConfig.SLOT_NUM; i++) { - storage.getSlotChangeListener().onSlotAdd(i, Slot.Role.Leader); - } - } - return storage; + return storage; + } + + public static DatumCache newLocalDatumCache(String localDataCenter, boolean init) { + DatumCache cache = new DatumCache(); + LocalDatumStorage storage = TestBaseUtils.newLocalStorage(localDataCenter, init); + cache.setLocalDatumStorage(storage); + cache.setDataServerConfig(storage.getDataServerConfig()); + return cache; + } + + public static DatumSummary newDatumSummary(int pubCount) { + final String dataId = TEST_DATA_ID + "-" + DATA_ID_SEQ.incrementAndGet(); + return newDatumSummary(pubCount, dataId); + } + + public static DatumSummary newDatumSummary(int pubCount, String dataInfoId) { + Map versions = Maps.newHashMap(); + for (int i = 0; i < pubCount; i++) { + final String registerId = TEST_REGISTER_ID + "-" + REGISTER_ID_SEQ.incrementAndGet(); + versions.put( + registerId, + RegisterVersion.of(CLIENT_VERSION.incrementAndGet(), System.currentTimeMillis())); } - - public static DatumCache newLocalDatumCache(String localDataCenter, boolean init) { - DatumCache cache = new DatumCache(); - LocalDatumStorage storage = TestBaseUtils.newLocalStorage(localDataCenter, init); - cache.setLocalDatumStorage(storage); - cache.setDataServerConfig(storage.getDataServerConfig()); - return cache; - } - - public static DatumSummary newDatumSummary(int pubCount) { - final String dataId = TEST_DATA_ID + "-" + DATA_ID_SEQ.incrementAndGet(); - return newDatumSummary(pubCount, dataId); - } - - public static DatumSummary newDatumSummary(int pubCount, String dataInfoId) { - Map versions = Maps.newHashMap(); - for (int i = 0; i < pubCount; i++) { - final String registerId = TEST_REGISTER_ID + "-" + REGISTER_ID_SEQ.incrementAndGet(); - versions.put(registerId, - RegisterVersion.of(CLIENT_VERSION.incrementAndGet(), System.currentTimeMillis())); - } - return new DatumSummary(dataInfoId, versions); - } - - public static List createTestPublishers(int slotId, int count) { - List list = Lists.newArrayListWithCapacity(count); - for (int i = 0; i < Integer.MAX_VALUE; i++) { - Publisher p = createTestPublisher(TEST_DATA_ID + "-" + DATA_ID_SEQ.incrementAndGet() - + "-" + i); - int id = SlotFunctionRegistry.getFunc().slotOf(p.getDataInfoId()); - if (id == slotId) { - // find the slotId - list.add(p); - for (int j = 1; j < count; j++) { - list.add(createTestPublisher(p.getDataId())); - } - break; - } + return new DatumSummary(dataInfoId, versions); + } + + public static List createTestPublishers(int slotId, int count) { + List list = Lists.newArrayListWithCapacity(count); + for (int i = 0; i < Integer.MAX_VALUE; i++) { + Publisher p = + createTestPublisher(TEST_DATA_ID + "-" + DATA_ID_SEQ.incrementAndGet() + "-" + i); + int id = SlotFunctionRegistry.getFunc().slotOf(p.getDataInfoId()); + if (id == slotId) { + // find the slotId + list.add(p); + for (int j = 1; j < count; j++) { + list.add(createTestPublisher(p.getDataId())); } - return list; + break; + } } + return list; + } } diff --git a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/DatumCacheTest.java b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/DatumCacheTest.java index 8b32d85e0..227124c96 100644 --- a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/DatumCacheTest.java +++ b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/DatumCacheTest.java @@ -21,51 +21,48 @@ import com.alipay.sofa.registry.common.model.slot.func.SlotFunctionRegistry; import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.server.data.TestBaseUtils; -import org.junit.Assert; -import org.junit.Test; - import java.util.List; import java.util.Map; +import org.junit.Assert; +import org.junit.Test; public class DatumCacheTest { - private static final String testDataId = TestBaseUtils.TEST_DATA_ID; - private static final String testDataInfoId = TestBaseUtils.TEST_DATA_INFO_ID; - private static final String testDc = "localDc"; + private static final String testDataId = TestBaseUtils.TEST_DATA_ID; + private static final String testDataInfoId = TestBaseUtils.TEST_DATA_INFO_ID; + private static final String testDc = "localDc"; - @Test - public void test() { - DatumCache cache = TestBaseUtils.newLocalDatumCache(testDc, true); - LocalDatumStorage storage = (LocalDatumStorage) cache.getLocalDatumStorage(); + @Test + public void test() { + DatumCache cache = TestBaseUtils.newLocalDatumCache(testDc, true); + LocalDatumStorage storage = (LocalDatumStorage) cache.getLocalDatumStorage(); - Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); - storage.put(publisher); + Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); + storage.put(publisher); - Datum datum = cache.get("xx", publisher.getDataInfoId()); - TestBaseUtils.assertEquals(datum, publisher); - Map> datumMap = cache.getAll(); - TestBaseUtils.assertEquals(datumMap.get(testDc).get(publisher.getDataInfoId()), publisher); + Datum datum = cache.get("xx", publisher.getDataInfoId()); + TestBaseUtils.assertEquals(datum, publisher); + Map> datumMap = cache.getAll(); + TestBaseUtils.assertEquals(datumMap.get(testDc).get(publisher.getDataInfoId()), publisher); - Map>> publisherMaps = cache.getAllPublisher(); - Assert.assertTrue(publisherMaps.get(testDc).get(publisher.getDataInfoId()) - .contains(publisher)); + Map>> publisherMaps = cache.getAllPublisher(); + Assert.assertTrue(publisherMaps.get(testDc).get(publisher.getDataInfoId()).contains(publisher)); - Map publisherMap = cache.getByConnectId(publisher.connectId()); - Assert.assertTrue(publisherMap.get(publisher.getRegisterId()) == publisher); + Map publisherMap = cache.getByConnectId(publisher.connectId()); + Assert.assertTrue(publisherMap.get(publisher.getRegisterId()) == publisher); - DatumVersion v = cache.getVersion("xx", publisher.getDataInfoId()); - Assert.assertEquals(v.getValue(), datum.getVersion()); + DatumVersion v = cache.getVersion("xx", publisher.getDataInfoId()); + Assert.assertEquals(v.getValue(), datum.getVersion()); - final int slotId = SlotFunctionRegistry.getFunc().slotOf(publisher.getDataInfoId()); - Map versionMap = cache.getVersions("xx", slotId, null); - Assert.assertEquals(versionMap.get(publisher.getDataInfoId()).getValue(), - datum.getVersion()); - v = cache.updateVersion("xx", publisher.getDataInfoId()); - Assert.assertTrue(v.getValue() > datum.getVersion()); + final int slotId = SlotFunctionRegistry.getFunc().slotOf(publisher.getDataInfoId()); + Map versionMap = cache.getVersions("xx", slotId, null); + Assert.assertEquals(versionMap.get(publisher.getDataInfoId()).getValue(), datum.getVersion()); + v = cache.updateVersion("xx", publisher.getDataInfoId()); + Assert.assertTrue(v.getValue() > datum.getVersion()); - cache.clean("xx", publisher.getDataInfoId()); + cache.clean("xx", publisher.getDataInfoId()); - datum = cache.get("xx", publisher.getDataInfoId()); - Assert.assertTrue(datum.getPubMap().isEmpty()); - Assert.assertTrue(v.getValue() < datum.getVersion()); - } + datum = cache.get("xx", publisher.getDataInfoId()); + Assert.assertTrue(datum.getPubMap().isEmpty()); + Assert.assertTrue(v.getValue() < datum.getVersion()); + } } diff --git a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/LocalDatumStorageTest.java b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/LocalDatumStorageTest.java index 28832b79f..c18acabfb 100644 --- a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/LocalDatumStorageTest.java +++ b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/LocalDatumStorageTest.java @@ -26,200 +26,201 @@ import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.server.data.TestBaseUtils; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; - import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; +import org.junit.Assert; +import org.junit.Test; public class LocalDatumStorageTest { - private static final String testDataId = TestBaseUtils.TEST_DATA_ID; - private static final String testDataInfoId = TestBaseUtils.TEST_DATA_INFO_ID; - private static final String testDc = "localDc"; - - @Test - public void testNew() { - LocalDatumStorage storage = TestBaseUtils.newLocalStorage(testDc, false); - assertEmpty(storage); - } - - private void assertEmpty(LocalDatumStorage storage) { - Datum datum = storage.get(testDataInfoId); - Assert.assertNull(datum); - - DatumVersion v = storage.getVersion(testDataInfoId); - Assert.assertNull(v); - - Map datumMap = storage.getAll(); - Assert.assertTrue(datumMap.isEmpty()); - - Map> publisherMap = storage.getAllPublisher(); - Assert.assertTrue(publisherMap.isEmpty()); - - Map versionMap = storage.getVersions(0, null); - Assert.assertTrue(versionMap.isEmpty()); - - Map> publisherMaps = storage.getPublishers(0); - Assert.assertTrue(publisherMaps.isEmpty()); - - Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); - v = storage.put(publisher); - Assert.assertNull(v); - v = storage.createEmptyDatumIfAbsent(testDataInfoId, testDc); - Assert.assertNull(v); - v = storage.put(publisher.getDataInfoId(), Lists.newArrayList(publisher)); - Assert.assertNull(v); - } - - @Test - public void testPut() { - LocalDatumStorage storage = TestBaseUtils.newLocalStorage(testDc, true); - Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); - DatumVersion v = storage.put(publisher); - Assert.assertNotNull(v); - Datum datum = storage.get(publisher.getDataInfoId()); - TestBaseUtils.assertEquals(datum, publisher); - v = storage.getVersion(publisher.getDataInfoId()); - Assert.assertEquals(v.getValue(), datum.getVersion()); - - Map publisherMap = storage.getByConnectId(publisher.connectId()); - Assert.assertEquals(publisherMap.size(), 1); - Assert.assertEquals(publisherMap.get(publisher.getRegisterId()), publisher); - - Map> publisherMaps = storage.getAllPublisher(); - Assert.assertEquals(publisherMaps.size(), 1); - Assert.assertEquals(publisherMaps.get(publisher.getDataInfoId()).size(), 1); - Assert.assertTrue(publisherMaps.get(publisher.getDataInfoId()).contains(publisher)); - - Map datumMap = storage.getAll(); - Assert.assertEquals(datumMap.size(), 1); - TestBaseUtils.assertEquals(datumMap.get(publisher.getDataInfoId()), publisher); - - final int slotId = SlotFunctionRegistry.getFunc().slotOf(publisher.getDataInfoId()); - Map> slotMaps = storage.getPublishers(slotId); - Assert.assertEquals(slotMaps.size(), 1); - Assert.assertEquals(slotMaps.get(publisher.getDataInfoId()).size(), 1); - Assert.assertEquals(slotMaps.get(publisher.getDataInfoId()).get(publisher.getRegisterId()), - publisher); - - Map versionMap = storage.getVersions(slotId, null); - Assert.assertEquals(versionMap.size(), 1); - Assert.assertEquals(versionMap.get(publisher.getDataInfoId()).getValue(), - datum.getVersion()); - - versionMap = storage.getVersions(slotId + 1, null); - Assert.assertEquals(versionMap.size(), 0); - - versionMap = storage.getVersions(slotId - 1, null); - Assert.assertEquals(versionMap.size(), 0); - - Set processIds = storage.getSessionProcessIds(); - Assert.assertEquals(processIds.size(), 1); - Assert.assertTrue(processIds.contains(publisher.getSessionProcessId())); - - Map summaryMap = storage.getDatumSummary(slotId, "xxx"); - Assert.assertEquals(summaryMap.size(), 0); - - summaryMap = storage.getDatumSummary(slotId, publisher.getTargetAddress().getIpAddress()); - Assert.assertEquals(summaryMap.size(), 1); - Assert.assertEquals(summaryMap.get(publisher.getDataInfoId()).getDataInfoId(), - publisher.getDataInfoId()); - Assert.assertEquals( - summaryMap.get(publisher.getDataInfoId()).getPublisherVersions().size(), 1); - Assert.assertEquals( - summaryMap.get(publisher.getDataInfoId()).getPublisherVersions() - .get(publisher.getRegisterId()), publisher.registerVersion()); - - summaryMap = storage.getDatumSummary(slotId, null); - Assert.assertEquals(summaryMap.size(), 1); - Assert.assertEquals(summaryMap.get(publisher.getDataInfoId()).getDataInfoId(), - publisher.getDataInfoId()); - Assert.assertEquals( - summaryMap.get(publisher.getDataInfoId()).getPublisherVersions().size(), 1); - Assert.assertEquals( - summaryMap.get(publisher.getDataInfoId()).getPublisherVersions() - .get(publisher.getRegisterId()), publisher.registerVersion()); - - for (int i = 0; i < SlotConfig.SLOT_NUM; i++) { - storage.getSlotChangeListener().onSlotRemove(i, Slot.Role.Leader); - } - assertEmpty(storage); + private static final String testDataId = TestBaseUtils.TEST_DATA_ID; + private static final String testDataInfoId = TestBaseUtils.TEST_DATA_INFO_ID; + private static final String testDc = "localDc"; + + @Test + public void testNew() { + LocalDatumStorage storage = TestBaseUtils.newLocalStorage(testDc, false); + assertEmpty(storage); + } + + private void assertEmpty(LocalDatumStorage storage) { + Datum datum = storage.get(testDataInfoId); + Assert.assertNull(datum); + + DatumVersion v = storage.getVersion(testDataInfoId); + Assert.assertNull(v); + + Map datumMap = storage.getAll(); + Assert.assertTrue(datumMap.isEmpty()); + + Map> publisherMap = storage.getAllPublisher(); + Assert.assertTrue(publisherMap.isEmpty()); + + Map versionMap = storage.getVersions(0, null); + Assert.assertTrue(versionMap.isEmpty()); + + Map> publisherMaps = storage.getPublishers(0); + Assert.assertTrue(publisherMaps.isEmpty()); + + Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); + v = storage.put(publisher); + Assert.assertNull(v); + v = storage.createEmptyDatumIfAbsent(testDataInfoId, testDc); + Assert.assertNull(v); + v = storage.put(publisher.getDataInfoId(), Lists.newArrayList(publisher)); + Assert.assertNull(v); + } + + @Test + public void testPut() { + LocalDatumStorage storage = TestBaseUtils.newLocalStorage(testDc, true); + Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); + DatumVersion v = storage.put(publisher); + Assert.assertNotNull(v); + Datum datum = storage.get(publisher.getDataInfoId()); + TestBaseUtils.assertEquals(datum, publisher); + v = storage.getVersion(publisher.getDataInfoId()); + Assert.assertEquals(v.getValue(), datum.getVersion()); + + Map publisherMap = storage.getByConnectId(publisher.connectId()); + Assert.assertEquals(publisherMap.size(), 1); + Assert.assertEquals(publisherMap.get(publisher.getRegisterId()), publisher); + + Map> publisherMaps = storage.getAllPublisher(); + Assert.assertEquals(publisherMaps.size(), 1); + Assert.assertEquals(publisherMaps.get(publisher.getDataInfoId()).size(), 1); + Assert.assertTrue(publisherMaps.get(publisher.getDataInfoId()).contains(publisher)); + + Map datumMap = storage.getAll(); + Assert.assertEquals(datumMap.size(), 1); + TestBaseUtils.assertEquals(datumMap.get(publisher.getDataInfoId()), publisher); + + final int slotId = SlotFunctionRegistry.getFunc().slotOf(publisher.getDataInfoId()); + Map> slotMaps = storage.getPublishers(slotId); + Assert.assertEquals(slotMaps.size(), 1); + Assert.assertEquals(slotMaps.get(publisher.getDataInfoId()).size(), 1); + Assert.assertEquals( + slotMaps.get(publisher.getDataInfoId()).get(publisher.getRegisterId()), publisher); + + Map versionMap = storage.getVersions(slotId, null); + Assert.assertEquals(versionMap.size(), 1); + Assert.assertEquals(versionMap.get(publisher.getDataInfoId()).getValue(), datum.getVersion()); + + versionMap = storage.getVersions(slotId + 1, null); + Assert.assertEquals(versionMap.size(), 0); + + versionMap = storage.getVersions(slotId - 1, null); + Assert.assertEquals(versionMap.size(), 0); + + Set processIds = storage.getSessionProcessIds(); + Assert.assertEquals(processIds.size(), 1); + Assert.assertTrue(processIds.contains(publisher.getSessionProcessId())); + + Map summaryMap = storage.getDatumSummary(slotId, "xxx"); + Assert.assertEquals(summaryMap.size(), 0); + + summaryMap = storage.getDatumSummary(slotId, publisher.getTargetAddress().getIpAddress()); + Assert.assertEquals(summaryMap.size(), 1); + Assert.assertEquals( + summaryMap.get(publisher.getDataInfoId()).getDataInfoId(), publisher.getDataInfoId()); + Assert.assertEquals(summaryMap.get(publisher.getDataInfoId()).getPublisherVersions().size(), 1); + Assert.assertEquals( + summaryMap + .get(publisher.getDataInfoId()) + .getPublisherVersions() + .get(publisher.getRegisterId()), + publisher.registerVersion()); + + summaryMap = storage.getDatumSummary(slotId, null); + Assert.assertEquals(summaryMap.size(), 1); + Assert.assertEquals( + summaryMap.get(publisher.getDataInfoId()).getDataInfoId(), publisher.getDataInfoId()); + Assert.assertEquals(summaryMap.get(publisher.getDataInfoId()).getPublisherVersions().size(), 1); + Assert.assertEquals( + summaryMap + .get(publisher.getDataInfoId()) + .getPublisherVersions() + .get(publisher.getRegisterId()), + publisher.registerVersion()); + + for (int i = 0; i < SlotConfig.SLOT_NUM; i++) { + storage.getSlotChangeListener().onSlotRemove(i, Slot.Role.Leader); } - - @Test - public void testRemove() { - LocalDatumStorage storage = TestBaseUtils.newLocalStorage(testDc, true); - Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); - Publisher publisher2 = TestBaseUtils.createTestPublisher(testDataId); - - Publisher publisher3 = TestBaseUtils.createTestPublisher(testDataId + "-3"); - - storage.put(publisher); - storage.put(publisher2); - storage.put(publisher3); - DatumVersion v = storage - .remove(publisher.getDataInfoId(), publisher2.getSessionProcessId()); - Assert.assertNotNull(v); - Map> map = storage.getAllPublisher(); - Assert.assertEquals(map.size(), 2); - Assert.assertEquals(map.get(publisher.getDataInfoId()).size(), 0); - Assert.assertEquals(map.get(publisher3.getDataInfoId()).size(), 1); - - v = storage.remove(publisher3.getDataInfoId(), publisher3.getSessionProcessId(), + assertEmpty(storage); + } + + @Test + public void testRemove() { + LocalDatumStorage storage = TestBaseUtils.newLocalStorage(testDc, true); + Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); + Publisher publisher2 = TestBaseUtils.createTestPublisher(testDataId); + + Publisher publisher3 = TestBaseUtils.createTestPublisher(testDataId + "-3"); + + storage.put(publisher); + storage.put(publisher2); + storage.put(publisher3); + DatumVersion v = storage.remove(publisher.getDataInfoId(), publisher2.getSessionProcessId()); + Assert.assertNotNull(v); + Map> map = storage.getAllPublisher(); + Assert.assertEquals(map.size(), 2); + Assert.assertEquals(map.get(publisher.getDataInfoId()).size(), 0); + Assert.assertEquals(map.get(publisher3.getDataInfoId()).size(), 1); + + v = + storage.remove( + publisher3.getDataInfoId(), + publisher3.getSessionProcessId(), Collections.singletonMap(publisher3.getRegisterId(), publisher3.registerVersion())); - Assert.assertNotNull(v); - - map = storage.getAllPublisher(); - Assert.assertEquals(map.size(), 2); - Assert.assertEquals(map.get(publisher.getDataInfoId()).size(), 0); - Assert.assertEquals(map.get(publisher3.getDataInfoId()).size(), 0); - - v = storage.put(publisher3); - Assert.assertNull(v); - - Map compacts = storage.compact(Long.MIN_VALUE); - Assert.assertEquals(compacts.size(), 0); - - compacts = storage.compact(System.currentTimeMillis()); - Assert.assertEquals(compacts.size(), 1); - Assert.assertTrue(compacts.containsKey(publisher3.getDataInfoId())); - - v = storage.put(publisher3); - Assert.assertNotNull(v); - } - - @Test - public void testUpdateVersion() { - LocalDatumStorage storage = TestBaseUtils.newLocalStorage(testDc, true); - Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); - storage.put(publisher); - DatumVersion v1 = storage.getVersion(publisher.getDataInfoId()); - DatumVersion v2 = storage.updateVersion(publisher.getDataInfoId()); - Assert.assertTrue(v2.getValue() > v1.getValue()); - final int slotId = SlotFunctionRegistry.getFunc().slotOf(publisher.getDataInfoId()); - storage.updateVersion(slotId); - DatumVersion v3 = storage.getVersion(publisher.getDataInfoId()); - Assert.assertTrue(v3.getValue() > v2.getValue()); - - } - - @Test - public void testClean() { - LocalDatumStorage storage = TestBaseUtils.newLocalStorage(testDc, true); - Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); - Publisher publisher2 = TestBaseUtils.createTestPublisher(testDataId); - storage.put(publisher); - storage.put(publisher2); - - Map versionMap = storage.clean(publisher.getSessionProcessId()); - Assert.assertEquals(versionMap.size(), 1); - Assert.assertTrue(versionMap.containsKey(publisher.getDataInfoId())); - Map> map = storage.getAllPublisher(); - Assert.assertEquals(map.size(), 1); - Assert.assertEquals(map.get(publisher.getDataInfoId()).size(), 0); - - } - + Assert.assertNotNull(v); + + map = storage.getAllPublisher(); + Assert.assertEquals(map.size(), 2); + Assert.assertEquals(map.get(publisher.getDataInfoId()).size(), 0); + Assert.assertEquals(map.get(publisher3.getDataInfoId()).size(), 0); + + v = storage.put(publisher3); + Assert.assertNull(v); + + Map compacts = storage.compact(Long.MIN_VALUE); + Assert.assertEquals(compacts.size(), 0); + + compacts = storage.compact(System.currentTimeMillis()); + Assert.assertEquals(compacts.size(), 1); + Assert.assertTrue(compacts.containsKey(publisher3.getDataInfoId())); + + v = storage.put(publisher3); + Assert.assertNotNull(v); + } + + @Test + public void testUpdateVersion() { + LocalDatumStorage storage = TestBaseUtils.newLocalStorage(testDc, true); + Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); + storage.put(publisher); + DatumVersion v1 = storage.getVersion(publisher.getDataInfoId()); + DatumVersion v2 = storage.updateVersion(publisher.getDataInfoId()); + Assert.assertTrue(v2.getValue() > v1.getValue()); + final int slotId = SlotFunctionRegistry.getFunc().slotOf(publisher.getDataInfoId()); + storage.updateVersion(slotId); + DatumVersion v3 = storage.getVersion(publisher.getDataInfoId()); + Assert.assertTrue(v3.getValue() > v2.getValue()); + } + + @Test + public void testClean() { + LocalDatumStorage storage = TestBaseUtils.newLocalStorage(testDc, true); + Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); + Publisher publisher2 = TestBaseUtils.createTestPublisher(testDataId); + storage.put(publisher); + storage.put(publisher2); + + Map versionMap = storage.clean(publisher.getSessionProcessId()); + Assert.assertEquals(versionMap.size(), 1); + Assert.assertTrue(versionMap.containsKey(publisher.getDataInfoId())); + Map> map = storage.getAllPublisher(); + Assert.assertEquals(map.size(), 1); + Assert.assertEquals(map.get(publisher.getDataInfoId()).size(), 0); + } } diff --git a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherEnvelopeTest.java b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherEnvelopeTest.java index 94f00fee7..ab3e645c3 100644 --- a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherEnvelopeTest.java +++ b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherEnvelopeTest.java @@ -28,44 +28,45 @@ public class PublisherEnvelopeTest { - @Test(expected = IllegalArgumentException.class) - public void testErrorType() { - Publisher p = new Publisher() { - public DataType getDataType() { - return DataType.SUBSCRIBER; - } + @Test(expected = IllegalArgumentException.class) + public void testErrorType() { + Publisher p = + new Publisher() { + public DataType getDataType() { + return DataType.SUBSCRIBER; + } - public ProcessId getSessionProcessId() { - return ServerEnv.PROCESS_ID; - } + public ProcessId getSessionProcessId() { + return ServerEnv.PROCESS_ID; + } }; - PublisherEnvelope.of(p); - } + PublisherEnvelope.of(p); + } - @Test - public void test() { - Publisher publisher = TestBaseUtils.createTestPublisher("testDataInfoId"); - PublisherEnvelope envelope = PublisherEnvelope.of(publisher); - ParaCheckUtil.checkNotBlank(envelope.toString(), "tostring"); - Assert.assertTrue(publisher == envelope.publisher); - Assert.assertEquals(publisher.registerVersion(), envelope.registerVersion); - Assert.assertEquals(publisher.registerVersion(), envelope.getVersionIfPub()); - Assert.assertEquals(publisher.getSessionProcessId(), ServerEnv.PROCESS_ID); - Assert.assertEquals(Long.MAX_VALUE, envelope.tombstoneTimestamp); - Assert.assertTrue(envelope.isPub()); - Assert.assertTrue(envelope.isConnectId(publisher.connectId())); - Assert.assertFalse(envelope.isConnectId(ConnectId.of("127.0.0.1:9999", "xxx:9997"))); + @Test + public void test() { + Publisher publisher = TestBaseUtils.createTestPublisher("testDataInfoId"); + PublisherEnvelope envelope = PublisherEnvelope.of(publisher); + ParaCheckUtil.checkNotBlank(envelope.toString(), "tostring"); + Assert.assertTrue(publisher == envelope.publisher); + Assert.assertEquals(publisher.registerVersion(), envelope.registerVersion); + Assert.assertEquals(publisher.registerVersion(), envelope.getVersionIfPub()); + Assert.assertEquals(publisher.getSessionProcessId(), ServerEnv.PROCESS_ID); + Assert.assertEquals(Long.MAX_VALUE, envelope.tombstoneTimestamp); + Assert.assertTrue(envelope.isPub()); + Assert.assertTrue(envelope.isConnectId(publisher.connectId())); + Assert.assertFalse(envelope.isConnectId(ConnectId.of("127.0.0.1:9999", "xxx:9997"))); - UnPublisher unPublisher = UnPublisher.of(publisher); - envelope = PublisherEnvelope.of(unPublisher); + UnPublisher unPublisher = UnPublisher.of(publisher); + envelope = PublisherEnvelope.of(unPublisher); - Assert.assertNull(envelope.publisher); - Assert.assertEquals(unPublisher.registerVersion(), envelope.registerVersion); - Assert.assertNull(envelope.getVersionIfPub()); - Assert.assertEquals(unPublisher.getSessionProcessId(), ServerEnv.PROCESS_ID); - Assert.assertTrue(envelope.tombstoneTimestamp <= System.currentTimeMillis()); - Assert.assertFalse(envelope.isPub()); - Assert.assertFalse(envelope.isConnectId(publisher.connectId())); - Assert.assertFalse(envelope.isConnectId(ConnectId.of("127.0.0.1:9999", "xxx:9997"))); - } + Assert.assertNull(envelope.publisher); + Assert.assertEquals(unPublisher.registerVersion(), envelope.registerVersion); + Assert.assertNull(envelope.getVersionIfPub()); + Assert.assertEquals(unPublisher.getSessionProcessId(), ServerEnv.PROCESS_ID); + Assert.assertTrue(envelope.tombstoneTimestamp <= System.currentTimeMillis()); + Assert.assertFalse(envelope.isPub()); + Assert.assertFalse(envelope.isConnectId(publisher.connectId())); + Assert.assertFalse(envelope.isConnectId(ConnectId.of("127.0.0.1:9999", "xxx:9997"))); + } } diff --git a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherGroupTest.java b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherGroupTest.java index fbc11da7f..8f39dc273 100644 --- a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherGroupTest.java +++ b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherGroupTest.java @@ -28,289 +28,303 @@ import com.alipay.sofa.registry.server.shared.env.ServerEnv; import com.alipay.sofa.registry.util.DatumVersionUtil; import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; - import java.util.Collections; -import java.util.HashSet; import java.util.Map; -import java.util.Set; +import org.junit.Assert; +import org.junit.Test; public class PublisherGroupTest { - @Test - public void testBaseOp() { - final String dataId = "testDataInfoId"; - long start = DatumVersionUtil.nextId(); - Publisher publisher = TestBaseUtils.createTestPublisher(dataId); - PublisherGroup group = new PublisherGroup(publisher.getDataInfoId(), "dc"); - - Assert.assertEquals(group.dataInfoId, publisher.getDataInfoId()); - Assert.assertEquals(group.dataId, publisher.getDataId()); - Assert.assertEquals(group.instanceId, publisher.getInstanceId()); - Assert.assertEquals(group.group, publisher.getGroup()); - Assert.assertEquals(group.dataCenter, "dc"); - Assert.assertTrue(group.getVersion().getValue() > start); - - Datum datum = group.toDatum(); - - Assert.assertEquals(group.dataInfoId, datum.getDataInfoId()); - Assert.assertEquals(group.dataId, datum.getDataId()); - Assert.assertEquals(group.instanceId, datum.getInstanceId()); - Assert.assertEquals(group.group, datum.getGroup()); - Assert.assertEquals(group.dataCenter, datum.getDataCenter()); - Assert.assertEquals(group.getPublishers().size(), datum.getPubMap().size()); - Assert.assertEquals(group.getVersion().getValue(), datum.getVersion()); - - DatumVersion version = group.getVersion(); - DatumVersion v = group.addPublisher(publisher); - Assert.assertTrue(v.getValue() > version.getValue()); - Assert.assertEquals(group.getPublishers().size(), 1); - datum = group.toDatum(); - Assert.assertEquals(group.getPublishers().size(), datum.getPubMap().size()); - Assert.assertTrue(group.getPublishers().get(0) == datum.getPubMap().values().iterator() - .next()); - - // add same pub, not change - v = group.addPublisher(publisher); - Assert.assertNull(v); - Assert.assertEquals(group.getPublishers().size(), 1); - - // add version older pub - Publisher older = TestBaseUtils.cloneBase(publisher); - older.setVersion(publisher.getVersion() - 1); - v = group.addPublisher(older); - Assert.assertNull(v); - Assert.assertEquals(group.getPublishers().size(), 1); - - // add registerTimestamp older pub - older = TestBaseUtils.cloneBase(publisher); - older.setRegisterTimestamp(publisher.getRegisterTimestamp() - 1); - v = group.addPublisher(older); - Assert.assertNull(v); - Assert.assertEquals(group.getPublishers().size(), 1); - - // add newer version - Publisher newer = TestBaseUtils.createTestPublisher(dataId); - newer.setRegisterId(publisher.getRegisterId()); - v = group.addPublisher(newer); - Assert.assertNotNull(v); - Assert.assertEquals(group.getPublishers().size(), 1); - Assert.assertTrue(group.getPublishers().get(0) == newer); - - final ProcessId mockProcessId = new ProcessId("xxx", System.currentTimeMillis(), 1, 1); - v = group.clean(mockProcessId); - Assert.assertNull(v); - - v = group.clean(null); - Assert.assertNotNull(v); - Assert.assertTrue(group.getPublishers().isEmpty()); - - group.addPublisher(newer); - v = group.clean(ServerEnv.PROCESS_ID); - Assert.assertNotNull(v); - Assert.assertTrue(group.getPublishers().isEmpty()); - - group.addPublisher(newer); - v = group.remove(ServerEnv.PROCESS_ID, Collections.EMPTY_MAP); - Assert.assertNull(v); - - v = group.remove(mockProcessId, Collections.EMPTY_MAP); - Assert.assertNull(v); - - v = group.remove(ServerEnv.PROCESS_ID, Collections.singletonMap(newer.getRegisterId(), - new RegisterVersion(newer.getVersion() + 1, newer.getRegisterTimestamp()))); - Assert.assertNull(v); - Assert.assertFalse(group.getPublishers().isEmpty()); - - v = group.remove(ServerEnv.PROCESS_ID, Collections.singletonMap(newer.getRegisterId(), - new RegisterVersion(newer.getVersion(), newer.getRegisterTimestamp() + 1))); - Assert.assertNull(v); - Assert.assertFalse(group.getPublishers().isEmpty()); - - v = group.remove( + @Test + public void testBaseOp() { + final String dataId = "testDataInfoId"; + long start = DatumVersionUtil.nextId(); + Publisher publisher = TestBaseUtils.createTestPublisher(dataId); + PublisherGroup group = new PublisherGroup(publisher.getDataInfoId(), "dc"); + + Assert.assertEquals(group.dataInfoId, publisher.getDataInfoId()); + Assert.assertEquals(group.dataId, publisher.getDataId()); + Assert.assertEquals(group.instanceId, publisher.getInstanceId()); + Assert.assertEquals(group.group, publisher.getGroup()); + Assert.assertEquals(group.dataCenter, "dc"); + Assert.assertTrue(group.getVersion().getValue() > start); + + Datum datum = group.toDatum(); + + Assert.assertEquals(group.dataInfoId, datum.getDataInfoId()); + Assert.assertEquals(group.dataId, datum.getDataId()); + Assert.assertEquals(group.instanceId, datum.getInstanceId()); + Assert.assertEquals(group.group, datum.getGroup()); + Assert.assertEquals(group.dataCenter, datum.getDataCenter()); + Assert.assertEquals(group.getPublishers().size(), datum.getPubMap().size()); + Assert.assertEquals(group.getVersion().getValue(), datum.getVersion()); + + DatumVersion version = group.getVersion(); + DatumVersion v = group.addPublisher(publisher); + Assert.assertTrue(v.getValue() > version.getValue()); + Assert.assertEquals(group.getPublishers().size(), 1); + datum = group.toDatum(); + Assert.assertEquals(group.getPublishers().size(), datum.getPubMap().size()); + Assert.assertTrue(group.getPublishers().get(0) == datum.getPubMap().values().iterator().next()); + + // add same pub, not change + v = group.addPublisher(publisher); + Assert.assertNull(v); + Assert.assertEquals(group.getPublishers().size(), 1); + + // add version older pub + Publisher older = TestBaseUtils.cloneBase(publisher); + older.setVersion(publisher.getVersion() - 1); + v = group.addPublisher(older); + Assert.assertNull(v); + Assert.assertEquals(group.getPublishers().size(), 1); + + // add registerTimestamp older pub + older = TestBaseUtils.cloneBase(publisher); + older.setRegisterTimestamp(publisher.getRegisterTimestamp() - 1); + v = group.addPublisher(older); + Assert.assertNull(v); + Assert.assertEquals(group.getPublishers().size(), 1); + + // add newer version + Publisher newer = TestBaseUtils.createTestPublisher(dataId); + newer.setRegisterId(publisher.getRegisterId()); + v = group.addPublisher(newer); + Assert.assertNotNull(v); + Assert.assertEquals(group.getPublishers().size(), 1); + Assert.assertTrue(group.getPublishers().get(0) == newer); + + final ProcessId mockProcessId = new ProcessId("xxx", System.currentTimeMillis(), 1, 1); + v = group.clean(mockProcessId); + Assert.assertNull(v); + + v = group.clean(null); + Assert.assertNotNull(v); + Assert.assertTrue(group.getPublishers().isEmpty()); + + group.addPublisher(newer); + v = group.clean(ServerEnv.PROCESS_ID); + Assert.assertNotNull(v); + Assert.assertTrue(group.getPublishers().isEmpty()); + + group.addPublisher(newer); + v = group.remove(ServerEnv.PROCESS_ID, Collections.EMPTY_MAP); + Assert.assertNull(v); + + v = group.remove(mockProcessId, Collections.EMPTY_MAP); + Assert.assertNull(v); + + v = + group.remove( + ServerEnv.PROCESS_ID, + Collections.singletonMap( + newer.getRegisterId(), + new RegisterVersion(newer.getVersion() + 1, newer.getRegisterTimestamp()))); + Assert.assertNull(v); + Assert.assertFalse(group.getPublishers().isEmpty()); + + v = + group.remove( ServerEnv.PROCESS_ID, - Collections.singletonMap(newer.getRegisterId() + "aa", + Collections.singletonMap( + newer.getRegisterId(), + new RegisterVersion(newer.getVersion(), newer.getRegisterTimestamp() + 1))); + Assert.assertNull(v); + Assert.assertFalse(group.getPublishers().isEmpty()); + + v = + group.remove( + ServerEnv.PROCESS_ID, + Collections.singletonMap( + newer.getRegisterId() + "aa", + new RegisterVersion(newer.getVersion(), newer.getRegisterTimestamp()))); + Assert.assertNull(v); + Assert.assertFalse(group.getPublishers().isEmpty()); + + v = + group.remove( + ServerEnv.PROCESS_ID, + Collections.singletonMap( + newer.getRegisterId(), + new RegisterVersion(newer.getVersion(), newer.getRegisterTimestamp()))); + Assert.assertNotNull(v); + Assert.assertTrue(group.getPublishers().isEmpty()); + + // has tombstone + v = group.addPublisher(newer); + Assert.assertNull(v); + Assert.assertTrue(group.getPublishers().isEmpty()); + + int compactCount = group.compact(Long.MIN_VALUE); + Assert.assertEquals(0, compactCount); + compactCount = group.compact(Long.MAX_VALUE); + Assert.assertEquals(1, compactCount); + // add again + + v = group.addPublisher(newer); + Assert.assertNotNull(v); + Assert.assertEquals(group.getPublishers().size(), 1); + + // remove processId=null, no tombstone + v = + group.remove( + null, + Collections.singletonMap( + newer.getRegisterId(), new RegisterVersion(newer.getVersion(), newer.getRegisterTimestamp()))); - Assert.assertNull(v); - Assert.assertFalse(group.getPublishers().isEmpty()); - - v = group.remove(ServerEnv.PROCESS_ID, Collections.singletonMap(newer.getRegisterId(), - new RegisterVersion(newer.getVersion(), newer.getRegisterTimestamp()))); - Assert.assertNotNull(v); - Assert.assertTrue(group.getPublishers().isEmpty()); - - // has tombstone - v = group.addPublisher(newer); - Assert.assertNull(v); - Assert.assertTrue(group.getPublishers().isEmpty()); - - int compactCount = group.compact(Long.MIN_VALUE); - Assert.assertEquals(0, compactCount); - compactCount = group.compact(Long.MAX_VALUE); - Assert.assertEquals(1, compactCount); - // add again - - v = group.addPublisher(newer); - Assert.assertNotNull(v); - Assert.assertEquals(group.getPublishers().size(), 1); - - // remove processId=null, no tombstone - v = group.remove(null, Collections.singletonMap(newer.getRegisterId(), new RegisterVersion( - newer.getVersion(), newer.getRegisterTimestamp()))); - Assert.assertNotNull(v); - Assert.assertTrue(group.getPublishers().isEmpty()); - - v = group.addPublisher(newer); - Assert.assertNotNull(v); - Assert.assertEquals(group.getPublishers().size(), 1); - - Assert.assertTrue(group.toString().length() != 0); - } - - @Test - public void testUpdate() { - final String dataId = "testDataInfoId"; - Publisher publisher = TestBaseUtils.createTestPublisher(dataId); - PublisherGroup group = new PublisherGroup(publisher.getDataInfoId(), "dc"); - DatumVersion startV = group.getVersion(); - DatumVersion v = group.put(Lists.newArrayList(publisher, publisher)); - Assert.assertNotNull(v); - Assert.assertTrue(v.getValue() > startV.getValue()); - Assert.assertEquals(group.getPublishers().size(), 1); - Assert.assertEquals(group.getPublishers().get(0), publisher); - - Publisher older = TestBaseUtils.cloneBase(publisher); - older.setVersion(older.getVersion() - 1); - v = group.put(Lists.newArrayList(older)); - Assert.assertNull(v); - Assert.assertEquals(group.getPublishers().size(), 1); - Assert.assertEquals(group.getPublishers().get(0), publisher); - - Publisher newer = TestBaseUtils.cloneBase(publisher); - newer.setVersion(publisher.getVersion() + 1); - v = group.put(Lists.newArrayList(older, newer)); - - Assert.assertNotNull(v); - Assert.assertEquals(group.getPublishers().size(), 1); - Assert.assertEquals(group.getPublishers().get(0), newer); - - Assert.assertEquals(group.getSessionProcessIds().size(), 1); - Assert.assertTrue(group.getSessionProcessIds().contains(ServerEnv.PROCESS_ID)); - - DatumSummary summary = group.getSummary("xxx"); - Assert.assertEquals(summary.getDataInfoId(), group.dataInfoId); - Assert.assertEquals(summary.getPublisherVersions().size(), 0); - - summary = group.getSummary(publisher.getTargetAddress().getIpAddress()); - Assert.assertEquals(summary.getPublisherVersions().size(), 1); - - final ProcessId mockProcessId = new ProcessId(ServerEnv.PROCESS_ID.getHostAddress(), - System.currentTimeMillis(), 1, 1); - - Publisher add = TestBaseUtils.createTestPublisher(dataId); - add.setTargetAddress(URL.valueOf("xxx:1000")); - add.setSessionProcessId(mockProcessId); - v = group.put(Lists.newArrayList(add)); - Assert.assertNotNull(v); - Assert.assertEquals(group.getPublishers().size(), 2); - Assert.assertTrue(group.getPublishers().contains(newer)); - Assert.assertTrue(group.getPublishers().contains(add)); - - summary = group.getSummary(publisher.getTargetAddress().getIpAddress()); - Assert.assertEquals(summary.getPublisherVersions().size(), 2); - - summary = group.getSummary(null); - Assert.assertEquals(summary.getPublisherVersions().size(), 2); - - Assert.assertEquals(group.getSessionProcessIds().size(), 2); - Assert.assertTrue(group.getSessionProcessIds().contains(ServerEnv.PROCESS_ID)); - Assert.assertTrue(group.getSessionProcessIds().contains(mockProcessId)); - - Map conns = group.getByConnectId(ConnectId.of("unknown:999", - "unknown:999")); - Assert.assertTrue(conns.isEmpty()); - - conns = group.getByConnectId(add.connectId()); - Assert.assertEquals(conns.size(), 1); - Assert.assertEquals(conns.get(add.getRegisterId()), add); - - conns = group.getByConnectId(newer.connectId()); - Assert.assertEquals(conns.size(), 1); - Assert.assertEquals(conns.get(newer.getRegisterId()), newer); - - v = group.remove(mockProcessId, - Collections.singletonMap(add.getRegisterId(), add.registerVersion())); - Assert.assertNotNull(v); - Assert.assertEquals(group.getPublishers().size(), 1); - - Assert.assertEquals(group.getSessionProcessIds().size(), 1); - Assert.assertTrue(group.getSessionProcessIds().contains(ServerEnv.PROCESS_ID)); - - summary = group.getSummary(null); - Assert.assertEquals(summary.getPublisherVersions().size(), 1); - - conns = group.getByConnectId(add.connectId()); - Assert.assertEquals(conns.size(), 0); - - conns = group.getByConnectId(newer.connectId()); - Assert.assertEquals(conns.size(), 1); - Assert.assertEquals(conns.get(newer.getRegisterId()), newer); - } - - // public static void main(String[] args) { - // Map m = Maps.newConcurrentMap(); - // Set set = new HashSet<>(); - // int C = 2000; - // int T = 100; - // for (int i = 0; i < C; i++) { - // String k = System.currentTimeMillis() + "_dasddsadasdadadasdasagagsdafagasfasfadsdsdsadadasdasf" + i; - // m.put(k, new DatumVersion(System.currentTimeMillis())); - // if (i < T) { - // set.add(k); - // } - // } - // - // System.out.println("" + m.size() + "@" + set.size()); - // for (int i = 0; i < 1000000; i++) { - // scan(m, set); - // } - // - // for (int i = 0; i < 1000000; i++) { - // get(m, set); - // } - // - // long start = System.currentTimeMillis(); - // for (int i = 0; i < 1000000; i++) { - // scan(m, set); - // } - // - // System.out.println("" + (System.currentTimeMillis() - start)); - // start = System.currentTimeMillis(); - // for (int i = 0; i < 1000000; i++) { - // get(m, set); - // } - // System.out.println("" + (System.currentTimeMillis() - start)); - // } - // - // static Map scan(Map m, Set targets) { - // Map ret = Maps.newHashMapWithExpectedSize(targets.size()); - // for (Map.Entry e : m.entrySet()) { - // if (targets.contains(e.getKey())) { - // ret.put(e.getKey(), e.getValue()); - // } - // } - // return ret; - // } - // - // static Map get(Map m, Set targets) { - // Map ret = Maps.newHashMapWithExpectedSize(targets.size()); - // for (String k : targets) { - // DatumVersion v = m.get(k); - // if (v != null) { - // ret.put(k, v); - // } - // } - // return ret; - // } + Assert.assertNotNull(v); + Assert.assertTrue(group.getPublishers().isEmpty()); + + v = group.addPublisher(newer); + Assert.assertNotNull(v); + Assert.assertEquals(group.getPublishers().size(), 1); + + Assert.assertTrue(group.toString().length() != 0); + } + + @Test + public void testUpdate() { + final String dataId = "testDataInfoId"; + Publisher publisher = TestBaseUtils.createTestPublisher(dataId); + PublisherGroup group = new PublisherGroup(publisher.getDataInfoId(), "dc"); + DatumVersion startV = group.getVersion(); + DatumVersion v = group.put(Lists.newArrayList(publisher, publisher)); + Assert.assertNotNull(v); + Assert.assertTrue(v.getValue() > startV.getValue()); + Assert.assertEquals(group.getPublishers().size(), 1); + Assert.assertEquals(group.getPublishers().get(0), publisher); + + Publisher older = TestBaseUtils.cloneBase(publisher); + older.setVersion(older.getVersion() - 1); + v = group.put(Lists.newArrayList(older)); + Assert.assertNull(v); + Assert.assertEquals(group.getPublishers().size(), 1); + Assert.assertEquals(group.getPublishers().get(0), publisher); + + Publisher newer = TestBaseUtils.cloneBase(publisher); + newer.setVersion(publisher.getVersion() + 1); + v = group.put(Lists.newArrayList(older, newer)); + + Assert.assertNotNull(v); + Assert.assertEquals(group.getPublishers().size(), 1); + Assert.assertEquals(group.getPublishers().get(0), newer); + + Assert.assertEquals(group.getSessionProcessIds().size(), 1); + Assert.assertTrue(group.getSessionProcessIds().contains(ServerEnv.PROCESS_ID)); + + DatumSummary summary = group.getSummary("xxx"); + Assert.assertEquals(summary.getDataInfoId(), group.dataInfoId); + Assert.assertEquals(summary.getPublisherVersions().size(), 0); + + summary = group.getSummary(publisher.getTargetAddress().getIpAddress()); + Assert.assertEquals(summary.getPublisherVersions().size(), 1); + + final ProcessId mockProcessId = + new ProcessId(ServerEnv.PROCESS_ID.getHostAddress(), System.currentTimeMillis(), 1, 1); + + Publisher add = TestBaseUtils.createTestPublisher(dataId); + add.setTargetAddress(URL.valueOf("xxx:1000")); + add.setSessionProcessId(mockProcessId); + v = group.put(Lists.newArrayList(add)); + Assert.assertNotNull(v); + Assert.assertEquals(group.getPublishers().size(), 2); + Assert.assertTrue(group.getPublishers().contains(newer)); + Assert.assertTrue(group.getPublishers().contains(add)); + + summary = group.getSummary(publisher.getTargetAddress().getIpAddress()); + Assert.assertEquals(summary.getPublisherVersions().size(), 2); + + summary = group.getSummary(null); + Assert.assertEquals(summary.getPublisherVersions().size(), 2); + + Assert.assertEquals(group.getSessionProcessIds().size(), 2); + Assert.assertTrue(group.getSessionProcessIds().contains(ServerEnv.PROCESS_ID)); + Assert.assertTrue(group.getSessionProcessIds().contains(mockProcessId)); + + Map conns = group.getByConnectId(ConnectId.of("unknown:999", "unknown:999")); + Assert.assertTrue(conns.isEmpty()); + + conns = group.getByConnectId(add.connectId()); + Assert.assertEquals(conns.size(), 1); + Assert.assertEquals(conns.get(add.getRegisterId()), add); + + conns = group.getByConnectId(newer.connectId()); + Assert.assertEquals(conns.size(), 1); + Assert.assertEquals(conns.get(newer.getRegisterId()), newer); + + v = + group.remove( + mockProcessId, Collections.singletonMap(add.getRegisterId(), add.registerVersion())); + Assert.assertNotNull(v); + Assert.assertEquals(group.getPublishers().size(), 1); + + Assert.assertEquals(group.getSessionProcessIds().size(), 1); + Assert.assertTrue(group.getSessionProcessIds().contains(ServerEnv.PROCESS_ID)); + + summary = group.getSummary(null); + Assert.assertEquals(summary.getPublisherVersions().size(), 1); + + conns = group.getByConnectId(add.connectId()); + Assert.assertEquals(conns.size(), 0); + + conns = group.getByConnectId(newer.connectId()); + Assert.assertEquals(conns.size(), 1); + Assert.assertEquals(conns.get(newer.getRegisterId()), newer); + } + + // public static void main(String[] args) { + // Map m = Maps.newConcurrentMap(); + // Set set = new HashSet<>(); + // int C = 2000; + // int T = 100; + // for (int i = 0; i < C; i++) { + // String k = System.currentTimeMillis() + + // "_dasddsadasdadadasdasagagsdafagasfasfadsdsdsadadasdasf" + i; + // m.put(k, new DatumVersion(System.currentTimeMillis())); + // if (i < T) { + // set.add(k); + // } + // } + // + // System.out.println("" + m.size() + "@" + set.size()); + // for (int i = 0; i < 1000000; i++) { + // scan(m, set); + // } + // + // for (int i = 0; i < 1000000; i++) { + // get(m, set); + // } + // + // long start = System.currentTimeMillis(); + // for (int i = 0; i < 1000000; i++) { + // scan(m, set); + // } + // + // System.out.println("" + (System.currentTimeMillis() - start)); + // start = System.currentTimeMillis(); + // for (int i = 0; i < 1000000; i++) { + // get(m, set); + // } + // System.out.println("" + (System.currentTimeMillis() - start)); + // } + // + // static Map scan(Map m, Set targets) { + // Map ret = Maps.newHashMapWithExpectedSize(targets.size()); + // for (Map.Entry e : m.entrySet()) { + // if (targets.contains(e.getKey())) { + // ret.put(e.getKey(), e.getValue()); + // } + // } + // return ret; + // } + // + // static Map get(Map m, Set targets) { + // Map ret = Maps.newHashMapWithExpectedSize(targets.size()); + // for (String k : targets) { + // DatumVersion v = m.get(k); + // if (v != null) { + // ret.put(k, v); + // } + // } + // return ret; + // } } diff --git a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherGroupsTest.java b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherGroupsTest.java index a15e4fa7b..cf26238ad 100644 --- a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherGroupsTest.java +++ b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/cache/PublisherGroupsTest.java @@ -24,363 +24,391 @@ import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.server.data.TestBaseUtils; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; - import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; +import org.junit.Assert; +import org.junit.Test; public class PublisherGroupsTest { - private final String testDataId = TestBaseUtils.TEST_DATA_ID; - private final String testDataInfoId = TestBaseUtils.TEST_DATA_INFO_ID; - private final String testDc = "testDc"; - - @Test - public void testEmpty() { - PublisherGroups groups = new PublisherGroups(testDc); - assertEmpty(groups, testDataInfoId); - Assert.assertTrue(groups.toString().length() != 0); - } - - @Test - public void testCreate() { - PublisherGroups groups = new PublisherGroups(testDc); - PublisherGroup group = groups.createGroupIfAbsent(testDataInfoId); - Assert.assertNotNull(group); - PublisherGroup group1 = groups.createGroupIfAbsent(testDataInfoId); - Assert.assertTrue(group == group1); - group1 = groups.createGroupIfAbsent(testDataInfoId + "tt"); - Assert.assertTrue(group != group1); - } - - @Test - public void testPut() { - PublisherGroups groups = new PublisherGroups(testDc); - PublisherGroup group = groups.createGroupIfAbsent(testDataInfoId); - Assert.assertNotNull(group); - Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); - DatumVersion v = groups - .put(publisher.getDataInfoId(), Collections.singletonList(publisher)); - Assert.assertNotNull(v); - // add again - v = groups.put(publisher.getDataInfoId(), Collections.singletonList(publisher)); - Assert.assertNull(v); - - Datum datum = groups.getDatum(publisher.getDataInfoId()); - Assert.assertNotNull(datum); - TestBaseUtils.assertEquals(datum, publisher); - v = groups.getVersion(publisher.getDataInfoId()); - Assert.assertEquals(datum.getVersion(), v.getValue()); - Map vers = groups.getVersions(null); - Assert.assertEquals(vers.size(), 1); - Assert.assertEquals(vers.get(publisher.getDataInfoId()), v); - Map publisherMap = groups.getByConnectId(publisher.connectId()); - Assert.assertEquals(publisherMap.size(), 1); - Assert.assertEquals(publisherMap.get(publisher.getRegisterId()), publisher); - Map datumMap = groups.getAllDatum(); - Assert.assertEquals(datumMap.size(), 1); - Assert.assertTrue(datumMap.containsKey(publisher.getDataInfoId())); - Map> publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 1); - Assert.assertEquals(publishers.get(publisher.getDataInfoId()).get(0), publisher); - - Map summaryMap = groups.getSummary("noFound"); - Assert.assertEquals(summaryMap.size(), 0); - - summaryMap = groups.getSummary(null); - Assert.assertEquals(summaryMap.size(), 1); - Assert.assertEquals( - summaryMap.get(publisher.getDataInfoId()).getPublisherVersions() - .get(publisher.getRegisterId()), publisher.registerVersion()); - - summaryMap = groups.getSummary(publisher.getTargetAddress().getIpAddress()); - Assert.assertEquals(summaryMap.size(), 1); - Assert.assertEquals( - summaryMap.get(publisher.getDataInfoId()).getPublisherVersions() - .get(publisher.getRegisterId()), publisher.registerVersion()); - - Set processIds = groups.getSessionProcessIds(); - Assert.assertEquals(processIds.size(), 1); - Assert.assertTrue(processIds.contains(publisher.getSessionProcessId())); - - Publisher publisher2 = TestBaseUtils.createTestPublisher(testDataId + "aa"); - v = groups.put(publisher2.getDataInfoId(), Collections.singletonList(publisher2)); - Assert.assertNotNull(v); - - datum = groups.getDatum(publisher2.getDataInfoId()); - Assert.assertNotNull(datum); - TestBaseUtils.assertEquals(datum, publisher2); - v = groups.getVersion(publisher2.getDataInfoId()); - Assert.assertEquals(datum.getVersion(), v.getValue()); - vers = groups.getVersions(null); - Assert.assertEquals(vers.size(), 2); - Assert.assertEquals(vers.get(publisher2.getDataInfoId()), v); - publisherMap = groups.getByConnectId(publisher.connectId()); - Assert.assertEquals(publisherMap.size(), 2); - Assert.assertEquals(publisherMap.get(publisher.getRegisterId()), publisher); - Assert.assertEquals(publisherMap.get(publisher2.getRegisterId()), publisher2); - publisherMap = groups.getByConnectId(TestBaseUtils.notExistConnectId()); - Assert.assertEquals(publisherMap.size(), 0); - datumMap = groups.getAllDatum(); - Assert.assertEquals(datumMap.size(), 2); - Assert.assertTrue(datumMap.containsKey(publisher.getDataInfoId())); - Assert.assertTrue(datumMap.containsKey(publisher2.getDataInfoId())); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher.getDataInfoId()).get(0), publisher); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).get(0), publisher2); - - summaryMap = groups.getSummary("noFound"); - Assert.assertEquals(summaryMap.size(), 0); - - summaryMap = groups.getSummary(null); - Assert.assertEquals(summaryMap.size(), 2); - Assert.assertEquals( - summaryMap.get(publisher.getDataInfoId()).getPublisherVersions() - .get(publisher.getRegisterId()), publisher.registerVersion()); - Assert.assertEquals( - summaryMap.get(publisher2.getDataInfoId()).getPublisherVersions() - .get(publisher2.getRegisterId()), publisher2.registerVersion()); - - summaryMap = groups.getSummary(publisher.getTargetAddress().getIpAddress()); - Assert.assertEquals(summaryMap.size(), 2); - Assert.assertEquals( - summaryMap.get(publisher.getDataInfoId()).getPublisherVersions() - .get(publisher.getRegisterId()), publisher.registerVersion()); - Assert.assertEquals( - summaryMap.get(publisher2.getDataInfoId()).getPublisherVersions() - .get(publisher2.getRegisterId()), publisher2.registerVersion()); - - processIds = groups.getSessionProcessIds(); - Assert.assertEquals(processIds.size(), 1); - Assert.assertTrue(processIds.contains(publisher.getSessionProcessId())); - Assert.assertTrue(processIds.contains(publisher2.getSessionProcessId())); - - } - - @Test - public void testUpdateRemove() { - PublisherGroups groups = new PublisherGroups(testDc); - Publisher publisher1 = TestBaseUtils.createTestPublisher(testDataId); - Publisher publisher2 = TestBaseUtils.createTestPublisher(testDataId); - ProcessId processId2 = new ProcessId("ip2", System.currentTimeMillis(), 100, 200); - publisher2.setSessionProcessId(processId2); - - DatumVersion v = groups.put(publisher2.getDataInfoId(), Collections.EMPTY_LIST); - Assert.assertNull(v); - v = groups.put(publisher2.getDataInfoId(), Lists.newArrayList(publisher1, publisher2)); - Assert.assertNotNull(v); - Set processIds = groups.getSessionProcessIds(); - Assert.assertEquals(processIds.size(), 2); - Assert.assertTrue(processIds.contains(publisher1.getSessionProcessId())); - Assert.assertTrue(processIds.contains(publisher2.getSessionProcessId())); - - Publisher publisher3 = TestBaseUtils.createTestPublisher(testDataId + "-3"); - publisher3.setTargetAddress(URL.valueOf("ip3:1000")); - v = groups.put(publisher3.getDataInfoId(), Lists.newArrayList(publisher3)); - Assert.assertNotNull(v); - processIds = groups.getSessionProcessIds(); - Assert.assertEquals(processIds.size(), 2); - Assert.assertTrue(processIds.contains(publisher1.getSessionProcessId())); - Assert.assertTrue(processIds.contains(publisher2.getSessionProcessId())); - - Map publisherMap = groups.getByConnectId(publisher3.connectId()); - Assert.assertEquals(publisherMap.size(), 1); - Assert.assertEquals(publisherMap.get(publisher3.getRegisterId()), publisher3); - - publisher2 = TestBaseUtils.cloneBase(publisher2); - publisher2.setVersion(publisher2.getVersion() + 1); - - publisher3 = TestBaseUtils.cloneBase(publisher3); - publisher3.setRegisterTimestamp(publisher3.getRegisterTimestamp() + 1); - - Publisher publisher4 = TestBaseUtils.cloneBase(publisher1); - publisher4.setVersion(publisher4.getVersion() - 1); - - v = groups.put(publisher3.getDataInfoId(), Lists.newArrayList(publisher3)); - Assert.assertNotNull(v); - v = groups.put(publisher1.getDataInfoId(), - Lists.newArrayList(publisher1, publisher2, publisher4)); - Assert.assertNotNull(v); - - Map> publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 1); - - Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher1)); - Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); - Assert.assertTrue(publishers.get(publisher3.getDataInfoId()).contains(publisher3)); - - // not remove - v = groups.remove(publisher3.getDataInfoId(), processId2); - Assert.assertNull(v); - - v = groups.remove(publisher3.getDataInfoId(), publisher3.getSessionProcessId()); - Assert.assertNotNull(v); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - // update again - v = groups.put(publisher3.getDataInfoId(), Lists.newArrayList(publisher3)); - Assert.assertNotNull(v); - v = groups.remove(publisher3.getDataInfoId(), null); - Assert.assertNotNull(v); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - // now contains publisher1 and publisher2 - v = groups.remove(publisher2.getDataInfoId(), + private final String testDataId = TestBaseUtils.TEST_DATA_ID; + private final String testDataInfoId = TestBaseUtils.TEST_DATA_INFO_ID; + private final String testDc = "testDc"; + + @Test + public void testEmpty() { + PublisherGroups groups = new PublisherGroups(testDc); + assertEmpty(groups, testDataInfoId); + Assert.assertTrue(groups.toString().length() != 0); + } + + @Test + public void testCreate() { + PublisherGroups groups = new PublisherGroups(testDc); + PublisherGroup group = groups.createGroupIfAbsent(testDataInfoId); + Assert.assertNotNull(group); + PublisherGroup group1 = groups.createGroupIfAbsent(testDataInfoId); + Assert.assertTrue(group == group1); + group1 = groups.createGroupIfAbsent(testDataInfoId + "tt"); + Assert.assertTrue(group != group1); + } + + @Test + public void testPut() { + PublisherGroups groups = new PublisherGroups(testDc); + PublisherGroup group = groups.createGroupIfAbsent(testDataInfoId); + Assert.assertNotNull(group); + Publisher publisher = TestBaseUtils.createTestPublisher(testDataId); + DatumVersion v = groups.put(publisher.getDataInfoId(), Collections.singletonList(publisher)); + Assert.assertNotNull(v); + // add again + v = groups.put(publisher.getDataInfoId(), Collections.singletonList(publisher)); + Assert.assertNull(v); + + Datum datum = groups.getDatum(publisher.getDataInfoId()); + Assert.assertNotNull(datum); + TestBaseUtils.assertEquals(datum, publisher); + v = groups.getVersion(publisher.getDataInfoId()); + Assert.assertEquals(datum.getVersion(), v.getValue()); + Map vers = groups.getVersions(null); + Assert.assertEquals(vers.size(), 1); + Assert.assertEquals(vers.get(publisher.getDataInfoId()), v); + Map publisherMap = groups.getByConnectId(publisher.connectId()); + Assert.assertEquals(publisherMap.size(), 1); + Assert.assertEquals(publisherMap.get(publisher.getRegisterId()), publisher); + Map datumMap = groups.getAllDatum(); + Assert.assertEquals(datumMap.size(), 1); + Assert.assertTrue(datumMap.containsKey(publisher.getDataInfoId())); + Map> publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 1); + Assert.assertEquals(publishers.get(publisher.getDataInfoId()).get(0), publisher); + + Map summaryMap = groups.getSummary("noFound"); + Assert.assertEquals(summaryMap.size(), 0); + + summaryMap = groups.getSummary(null); + Assert.assertEquals(summaryMap.size(), 1); + Assert.assertEquals( + summaryMap + .get(publisher.getDataInfoId()) + .getPublisherVersions() + .get(publisher.getRegisterId()), + publisher.registerVersion()); + + summaryMap = groups.getSummary(publisher.getTargetAddress().getIpAddress()); + Assert.assertEquals(summaryMap.size(), 1); + Assert.assertEquals( + summaryMap + .get(publisher.getDataInfoId()) + .getPublisherVersions() + .get(publisher.getRegisterId()), + publisher.registerVersion()); + + Set processIds = groups.getSessionProcessIds(); + Assert.assertEquals(processIds.size(), 1); + Assert.assertTrue(processIds.contains(publisher.getSessionProcessId())); + + Publisher publisher2 = TestBaseUtils.createTestPublisher(testDataId + "aa"); + v = groups.put(publisher2.getDataInfoId(), Collections.singletonList(publisher2)); + Assert.assertNotNull(v); + + datum = groups.getDatum(publisher2.getDataInfoId()); + Assert.assertNotNull(datum); + TestBaseUtils.assertEquals(datum, publisher2); + v = groups.getVersion(publisher2.getDataInfoId()); + Assert.assertEquals(datum.getVersion(), v.getValue()); + vers = groups.getVersions(null); + Assert.assertEquals(vers.size(), 2); + Assert.assertEquals(vers.get(publisher2.getDataInfoId()), v); + publisherMap = groups.getByConnectId(publisher.connectId()); + Assert.assertEquals(publisherMap.size(), 2); + Assert.assertEquals(publisherMap.get(publisher.getRegisterId()), publisher); + Assert.assertEquals(publisherMap.get(publisher2.getRegisterId()), publisher2); + publisherMap = groups.getByConnectId(TestBaseUtils.notExistConnectId()); + Assert.assertEquals(publisherMap.size(), 0); + datumMap = groups.getAllDatum(); + Assert.assertEquals(datumMap.size(), 2); + Assert.assertTrue(datumMap.containsKey(publisher.getDataInfoId())); + Assert.assertTrue(datumMap.containsKey(publisher2.getDataInfoId())); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher.getDataInfoId()).get(0), publisher); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).get(0), publisher2); + + summaryMap = groups.getSummary("noFound"); + Assert.assertEquals(summaryMap.size(), 0); + + summaryMap = groups.getSummary(null); + Assert.assertEquals(summaryMap.size(), 2); + Assert.assertEquals( + summaryMap + .get(publisher.getDataInfoId()) + .getPublisherVersions() + .get(publisher.getRegisterId()), + publisher.registerVersion()); + Assert.assertEquals( + summaryMap + .get(publisher2.getDataInfoId()) + .getPublisherVersions() + .get(publisher2.getRegisterId()), + publisher2.registerVersion()); + + summaryMap = groups.getSummary(publisher.getTargetAddress().getIpAddress()); + Assert.assertEquals(summaryMap.size(), 2); + Assert.assertEquals( + summaryMap + .get(publisher.getDataInfoId()) + .getPublisherVersions() + .get(publisher.getRegisterId()), + publisher.registerVersion()); + Assert.assertEquals( + summaryMap + .get(publisher2.getDataInfoId()) + .getPublisherVersions() + .get(publisher2.getRegisterId()), + publisher2.registerVersion()); + + processIds = groups.getSessionProcessIds(); + Assert.assertEquals(processIds.size(), 1); + Assert.assertTrue(processIds.contains(publisher.getSessionProcessId())); + Assert.assertTrue(processIds.contains(publisher2.getSessionProcessId())); + } + + @Test + public void testUpdateRemove() { + PublisherGroups groups = new PublisherGroups(testDc); + Publisher publisher1 = TestBaseUtils.createTestPublisher(testDataId); + Publisher publisher2 = TestBaseUtils.createTestPublisher(testDataId); + ProcessId processId2 = new ProcessId("ip2", System.currentTimeMillis(), 100, 200); + publisher2.setSessionProcessId(processId2); + + DatumVersion v = groups.put(publisher2.getDataInfoId(), Collections.EMPTY_LIST); + Assert.assertNull(v); + v = groups.put(publisher2.getDataInfoId(), Lists.newArrayList(publisher1, publisher2)); + Assert.assertNotNull(v); + Set processIds = groups.getSessionProcessIds(); + Assert.assertEquals(processIds.size(), 2); + Assert.assertTrue(processIds.contains(publisher1.getSessionProcessId())); + Assert.assertTrue(processIds.contains(publisher2.getSessionProcessId())); + + Publisher publisher3 = TestBaseUtils.createTestPublisher(testDataId + "-3"); + publisher3.setTargetAddress(URL.valueOf("ip3:1000")); + v = groups.put(publisher3.getDataInfoId(), Lists.newArrayList(publisher3)); + Assert.assertNotNull(v); + processIds = groups.getSessionProcessIds(); + Assert.assertEquals(processIds.size(), 2); + Assert.assertTrue(processIds.contains(publisher1.getSessionProcessId())); + Assert.assertTrue(processIds.contains(publisher2.getSessionProcessId())); + + Map publisherMap = groups.getByConnectId(publisher3.connectId()); + Assert.assertEquals(publisherMap.size(), 1); + Assert.assertEquals(publisherMap.get(publisher3.getRegisterId()), publisher3); + + publisher2 = TestBaseUtils.cloneBase(publisher2); + publisher2.setVersion(publisher2.getVersion() + 1); + + publisher3 = TestBaseUtils.cloneBase(publisher3); + publisher3.setRegisterTimestamp(publisher3.getRegisterTimestamp() + 1); + + Publisher publisher4 = TestBaseUtils.cloneBase(publisher1); + publisher4.setVersion(publisher4.getVersion() - 1); + + v = groups.put(publisher3.getDataInfoId(), Lists.newArrayList(publisher3)); + Assert.assertNotNull(v); + v = + groups.put( + publisher1.getDataInfoId(), Lists.newArrayList(publisher1, publisher2, publisher4)); + Assert.assertNotNull(v); + + Map> publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 1); + + Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher1)); + Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); + Assert.assertTrue(publishers.get(publisher3.getDataInfoId()).contains(publisher3)); + + // not remove + v = groups.remove(publisher3.getDataInfoId(), processId2); + Assert.assertNull(v); + + v = groups.remove(publisher3.getDataInfoId(), publisher3.getSessionProcessId()); + Assert.assertNotNull(v); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + // update again + v = groups.put(publisher3.getDataInfoId(), Lists.newArrayList(publisher3)); + Assert.assertNotNull(v); + v = groups.remove(publisher3.getDataInfoId(), null); + Assert.assertNotNull(v); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + // now contains publisher1 and publisher2 + v = + groups.remove( + publisher2.getDataInfoId(), new ProcessId("ip3", System.currentTimeMillis(), 100, 200), Collections.singletonMap(publisher1.getRegisterId(), publisher1.registerVersion())); - Assert.assertNull(v); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - v = groups.remove( + Assert.assertNull(v); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + v = + groups.remove( publisher2.getDataInfoId(), publisher1.getSessionProcessId(), - Collections.singletonMap(publisher1.getRegisterId() + "aa", - publisher1.registerVersion())); - Assert.assertNull(v); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - v = groups.remove( + Collections.singletonMap( + publisher1.getRegisterId() + "aa", publisher1.registerVersion())); + Assert.assertNull(v); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + v = + groups.remove( + publisher2.getDataInfoId(), + publisher1.getSessionProcessId(), + Collections.singletonMap( + publisher1.getRegisterId() + "aa", publisher1.registerVersion())); + Assert.assertNull(v); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + v = + groups.remove( publisher2.getDataInfoId(), publisher1.getSessionProcessId(), - Collections.singletonMap(publisher1.getRegisterId() + "aa", - publisher1.registerVersion())); - Assert.assertNull(v); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - v = groups.remove(publisher2.getDataInfoId(), publisher1.getSessionProcessId(), Collections.singletonMap(publisher1.getRegisterId(), publisher2.registerVersion())); - Assert.assertNull(v); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - v = groups.remove(publisher2.getDataInfoId(), publisher1.getSessionProcessId(), + Assert.assertNull(v); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + v = + groups.remove( + publisher2.getDataInfoId(), + publisher1.getSessionProcessId(), Collections.singletonMap(publisher1.getRegisterId(), publisher1.registerVersion())); - Assert.assertNotNull(v); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); - Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - // update the same publisher1 again failed without compact - v = groups.put(publisher1.getDataInfoId(), Lists.newArrayList(publisher1)); - Assert.assertNull(v); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); - Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - Assert.assertEquals(groups.tombstoneNum(), 1); - Map compacts = groups.compact(Long.MAX_VALUE); - Assert.assertEquals(groups.tombstoneNum(), 0); - Assert.assertEquals(compacts.size(), 1); - Assert.assertEquals(compacts.get(publisher1.getDataInfoId()).intValue(), 1); - - v = groups.put(publisher1.getDataInfoId(), Lists.newArrayList(publisher1)); - Assert.assertNotNull(v); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); - Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); - Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher1)); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - compacts = groups.compact(Long.MAX_VALUE); - Assert.assertEquals(compacts.size(), 0); - - v = groups.remove(publisher2.getDataInfoId(), null, + Assert.assertNotNull(v); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); + Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + // update the same publisher1 again failed without compact + v = groups.put(publisher1.getDataInfoId(), Lists.newArrayList(publisher1)); + Assert.assertNull(v); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); + Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + Assert.assertEquals(groups.tombstoneNum(), 1); + Map compacts = groups.compact(Long.MAX_VALUE); + Assert.assertEquals(groups.tombstoneNum(), 0); + Assert.assertEquals(compacts.size(), 1); + Assert.assertEquals(compacts.get(publisher1.getDataInfoId()).intValue(), 1); + + v = groups.put(publisher1.getDataInfoId(), Lists.newArrayList(publisher1)); + Assert.assertNotNull(v); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 2); + Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); + Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher1)); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + compacts = groups.compact(Long.MAX_VALUE); + Assert.assertEquals(compacts.size(), 0); + + v = + groups.remove( + publisher2.getDataInfoId(), + null, Collections.singletonMap(publisher1.getRegisterId(), publisher1.registerVersion())); - Assert.assertNotNull(v); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); - // remove with null sessionProcessId, no compact - compacts = groups.compact(Long.MAX_VALUE); - Assert.assertEquals(compacts.size(), 0); - - DatumVersion v1 = groups.updateVersion(publisher2.getDataInfoId()); - Assert.assertTrue(v1.getValue() > v.getValue()); - groups.updateVersion(); - Assert.assertTrue(groups.getVersion(publisher2.getDataInfoId()).getValue() > v.getValue()); - - Map map = groups.clean(new ProcessId("xxx", 100, 100, 100)); - Assert.assertTrue(map.isEmpty()); - - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); - Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - //remain publisher2 - map = groups.clean(publisher1.getSessionProcessId()); - Assert.assertTrue(map.isEmpty()); - - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); - Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - map = groups.clean(publisher2.getSessionProcessId()); - Assert.assertTrue(map.get(publisher2.getDataInfoId()).getValue() > v.getValue()); - - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 0); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - v = groups.put(publisher1.getDataInfoId(), Lists.newArrayList(publisher1)); - Assert.assertNotNull(v); - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); - Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher1)); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - compacts = groups.compact(Long.MAX_VALUE); - Assert.assertEquals(compacts.size(), 0); - - map = groups.clean(null); - Assert.assertTrue(map.get(publisher2.getDataInfoId()).getValue() > v.getValue()); - - publishers = groups.getAllPublisher(); - Assert.assertEquals(publishers.size(), 2); - Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 0); - Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); - - } - - private void assertEmpty(PublisherGroups groups, String dataInfoId) { - Assert.assertNull(groups.getDatum(dataInfoId)); - Assert.assertNull(groups.getVersion(dataInfoId)); - Assert.assertTrue(groups.getVersions(null).isEmpty()); - Assert.assertTrue(groups.getAllDatum().isEmpty()); - Assert.assertTrue(groups.getAllPublisher().isEmpty()); - } + Assert.assertNotNull(v); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); + // remove with null sessionProcessId, no compact + compacts = groups.compact(Long.MAX_VALUE); + Assert.assertEquals(compacts.size(), 0); + + DatumVersion v1 = groups.updateVersion(publisher2.getDataInfoId()); + Assert.assertTrue(v1.getValue() > v.getValue()); + groups.updateVersion(); + Assert.assertTrue(groups.getVersion(publisher2.getDataInfoId()).getValue() > v.getValue()); + + Map map = groups.clean(new ProcessId("xxx", 100, 100, 100)); + Assert.assertTrue(map.isEmpty()); + + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); + Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + // remain publisher2 + map = groups.clean(publisher1.getSessionProcessId()); + Assert.assertTrue(map.isEmpty()); + + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); + Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher2)); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + map = groups.clean(publisher2.getSessionProcessId()); + Assert.assertTrue(map.get(publisher2.getDataInfoId()).getValue() > v.getValue()); + + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 0); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + v = groups.put(publisher1.getDataInfoId(), Lists.newArrayList(publisher1)); + Assert.assertNotNull(v); + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 1); + Assert.assertTrue(publishers.get(publisher2.getDataInfoId()).contains(publisher1)); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + + compacts = groups.compact(Long.MAX_VALUE); + Assert.assertEquals(compacts.size(), 0); + + map = groups.clean(null); + Assert.assertTrue(map.get(publisher2.getDataInfoId()).getValue() > v.getValue()); + + publishers = groups.getAllPublisher(); + Assert.assertEquals(publishers.size(), 2); + Assert.assertEquals(publishers.get(publisher2.getDataInfoId()).size(), 0); + Assert.assertEquals(publishers.get(publisher3.getDataInfoId()).size(), 0); + } + + private void assertEmpty(PublisherGroups groups, String dataInfoId) { + Assert.assertNull(groups.getDatum(dataInfoId)); + Assert.assertNull(groups.getVersion(dataInfoId)); + Assert.assertTrue(groups.getVersions(null).isEmpty()); + Assert.assertTrue(groups.getAllDatum().isEmpty()); + Assert.assertTrue(groups.getAllPublisher().isEmpty()); + } } diff --git a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/lease/SessionLeaseManagerTest.java b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/lease/SessionLeaseManagerTest.java index 13670ab09..0081ea193 100644 --- a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/lease/SessionLeaseManagerTest.java +++ b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/lease/SessionLeaseManagerTest.java @@ -27,75 +27,76 @@ import org.junit.Test; public class SessionLeaseManagerTest { - @Test(expected = IllegalArgumentException.class) - public void testValidate() { - SessionLeaseManager slm = new SessionLeaseManager(); - slm.validateSessionLeaseSec(1); - } + @Test(expected = IllegalArgumentException.class) + public void testValidate() { + SessionLeaseManager slm = new SessionLeaseManager(); + slm.validateSessionLeaseSec(1); + } - @Test - public void test() throws Exception { - SessionLeaseManager slm = new SessionLeaseManager(); - SessionServerConnectionFactory ssc = new SessionServerConnectionFactory(); - slm.setSessionServerConnectionFactory(ssc); - LocalDatumStorage storage = TestBaseUtils.newLocalStorage("testDc", true); - slm.setLocalDatumStorage(storage); - DataServerConfig config = storage.getDataServerConfig(); - config.setDatumCompactDelaySecs(1); - config.setSessionLeaseSecs(1); - slm.setDataServerConfig(config); - ssc.registerSession(ServerEnv.PROCESS_ID, - new SessionServerConnectionFactoryTest.MockBlotChannel(ServerEnv.IP, 1000)); - slm.renewSession(ServerEnv.PROCESS_ID); - Assert.assertTrue(slm.contains(ServerEnv.PROCESS_ID)); - Publisher p = TestBaseUtils.createTestPublisher("dataId"); - storage.put(p); - Assert.assertEquals(storage.get(p.getDataInfoId()).getPubMap().get(p.getRegisterId()), p); - //wait to clean, but connection remains - Thread.sleep(1500); - slm.clean(); - Assert.assertTrue(slm.contains(ServerEnv.PROCESS_ID)); - Assert.assertEquals(storage.tombstoneNum(), 0); - Assert.assertEquals(storage.get(p.getDataInfoId()).getPubMap().get(p.getRegisterId()), p); + @Test + public void test() throws Exception { + SessionLeaseManager slm = new SessionLeaseManager(); + SessionServerConnectionFactory ssc = new SessionServerConnectionFactory(); + slm.setSessionServerConnectionFactory(ssc); + LocalDatumStorage storage = TestBaseUtils.newLocalStorage("testDc", true); + slm.setLocalDatumStorage(storage); + DataServerConfig config = storage.getDataServerConfig(); + config.setDatumCompactDelaySecs(1); + config.setSessionLeaseSecs(1); + slm.setDataServerConfig(config); + ssc.registerSession( + ServerEnv.PROCESS_ID, + new SessionServerConnectionFactoryTest.MockBlotChannel(ServerEnv.IP, 1000)); + slm.renewSession(ServerEnv.PROCESS_ID); + Assert.assertTrue(slm.contains(ServerEnv.PROCESS_ID)); + Publisher p = TestBaseUtils.createTestPublisher("dataId"); + storage.put(p); + Assert.assertEquals(storage.get(p.getDataInfoId()).getPubMap().get(p.getRegisterId()), p); + // wait to clean, but connection remains + Thread.sleep(1500); + slm.clean(); + Assert.assertTrue(slm.contains(ServerEnv.PROCESS_ID)); + Assert.assertEquals(storage.tombstoneNum(), 0); + Assert.assertEquals(storage.get(p.getDataInfoId()).getPubMap().get(p.getRegisterId()), p); - // reset the connections - slm.setSessionServerConnectionFactory(new SessionServerConnectionFactory()); - Thread.sleep(1500); - // wait to clean - slm.clean(); - Assert.assertFalse(slm.contains(ServerEnv.PROCESS_ID)); - Assert.assertEquals(storage.tombstoneNum(), 0); - Assert.assertEquals(storage.get(p.getDataInfoId()).publisherSize(), 0); + // reset the connections + slm.setSessionServerConnectionFactory(new SessionServerConnectionFactory()); + Thread.sleep(1500); + // wait to clean + slm.clean(); + Assert.assertFalse(slm.contains(ServerEnv.PROCESS_ID)); + Assert.assertEquals(storage.tombstoneNum(), 0); + Assert.assertEquals(storage.get(p.getDataInfoId()).publisherSize(), 0); - // wait to compact - Thread.sleep(1500); - slm.clean(); - Assert.assertEquals(storage.tombstoneNum(), 0); - Assert.assertEquals(storage.get(p.getDataInfoId()).publisherSize(), 0); - } + // wait to compact + Thread.sleep(1500); + slm.clean(); + Assert.assertEquals(storage.tombstoneNum(), 0); + Assert.assertEquals(storage.get(p.getDataInfoId()).publisherSize(), 0); + } - @Test - public void testLoop() throws Exception { - SessionLeaseManager slm = new SessionLeaseManager(); - SessionServerConnectionFactory ssc = new SessionServerConnectionFactory(); - slm.setSessionServerConnectionFactory(ssc); - LocalDatumStorage storage = TestBaseUtils.newLocalStorage("testDc", true); - slm.setLocalDatumStorage(storage); - DataServerConfig config = storage.getDataServerConfig(); - config.setDatumCompactDelaySecs(1); - config.setSessionLeaseSecs(5); - slm.setDataServerConfig(config); - slm.init(); - slm.renewSession(ServerEnv.PROCESS_ID); - Assert.assertTrue(slm.contains(ServerEnv.PROCESS_ID)); - Publisher p = TestBaseUtils.createTestPublisher("dataId"); - storage.put(p); - Assert.assertEquals(storage.get(p.getDataInfoId()).getPubMap().get(p.getRegisterId()), p); - //wait to clean - config.setSessionLeaseSecs(1); - slm.setSessionServerConnectionFactory(new SessionServerConnectionFactory()); - Thread.sleep(2000); - Assert.assertEquals(storage.tombstoneNum(), 0); - Assert.assertEquals(storage.get(p.getDataInfoId()).publisherSize(), 0); - } + @Test + public void testLoop() throws Exception { + SessionLeaseManager slm = new SessionLeaseManager(); + SessionServerConnectionFactory ssc = new SessionServerConnectionFactory(); + slm.setSessionServerConnectionFactory(ssc); + LocalDatumStorage storage = TestBaseUtils.newLocalStorage("testDc", true); + slm.setLocalDatumStorage(storage); + DataServerConfig config = storage.getDataServerConfig(); + config.setDatumCompactDelaySecs(1); + config.setSessionLeaseSecs(5); + slm.setDataServerConfig(config); + slm.init(); + slm.renewSession(ServerEnv.PROCESS_ID); + Assert.assertTrue(slm.contains(ServerEnv.PROCESS_ID)); + Publisher p = TestBaseUtils.createTestPublisher("dataId"); + storage.put(p); + Assert.assertEquals(storage.get(p.getDataInfoId()).getPubMap().get(p.getRegisterId()), p); + // wait to clean + config.setSessionLeaseSecs(1); + slm.setSessionServerConnectionFactory(new SessionServerConnectionFactory()); + Thread.sleep(2000); + Assert.assertEquals(storage.tombstoneNum(), 0); + Assert.assertEquals(storage.get(p.getDataInfoId()).publisherSize(), 0); + } } diff --git a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/SessionServerConnectionFactoryTest.java b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/SessionServerConnectionFactoryTest.java index 500629f35..32ec04e4b 100644 --- a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/SessionServerConnectionFactoryTest.java +++ b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/remoting/sessionserver/SessionServerConnectionFactoryTest.java @@ -24,367 +24,361 @@ import io.netty.channel.*; import io.netty.util.Attribute; import io.netty.util.AttributeKey; -import org.junit.Assert; -import org.junit.Test; - import java.net.InetSocketAddress; import java.net.SocketAddress; +import org.junit.Assert; +import org.junit.Test; public class SessionServerConnectionFactoryTest { - @Test - public void testIllegal() { - SessionServerConnectionFactory factory = new SessionServerConnectionFactory(); - Assert.assertFalse(factory.registerSession(ServerEnv.PROCESS_ID, null)); - Assert.assertFalse(factory.registerSession(ServerEnv.PROCESS_ID, new BoltChannel())); - MockBlotChannel channel1 = new MockBlotChannel("66.66.66.66", 5550); - channel1.connected = false; - Assert.assertFalse(factory.registerSession(ServerEnv.PROCESS_ID, channel1)); - } - - @Test - public void testConnection() throws Exception { - SessionServerConnectionFactory factory = new SessionServerConnectionFactory(); - final String IP1 = "66.66.66.66"; - final String IP2 = "66.66.66.65"; - - MockBlotChannel channel1 = new MockBlotChannel(IP1, 5550); - Assert.assertTrue(factory.registerSession(ServerEnv.PROCESS_ID, channel1)); - Assert.assertFalse(factory.registerSession(ServerEnv.PROCESS_ID, channel1)); - - Assert.assertTrue(factory.containsConnection(ServerEnv.PROCESS_ID)); - Assert.assertEquals(1, factory.getSessionConnections().size()); - Assert.assertEquals(1, factory.getProcessIds().size()); - Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP1)); - - MockBlotChannel channel2 = new MockBlotChannel(IP1, 5551); - factory.registerSession(ServerEnv.PROCESS_ID, channel2); - - Assert.assertTrue(factory.containsConnection(ServerEnv.PROCESS_ID)); - Assert.assertEquals(1, factory.getSessionConnections().size()); - Assert.assertEquals(1, factory.getProcessIds().size()); - Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP1)); - - ProcessId processId2 = new ProcessId("unknown", System.currentTimeMillis(), 100, 100); - MockBlotChannel channel3 = new MockBlotChannel(IP2, 5551); - factory.registerSession(processId2, channel3); - - Assert.assertTrue(factory.containsConnection(ServerEnv.PROCESS_ID)); - Assert.assertTrue(factory.containsConnection(processId2)); - Assert.assertEquals(2, factory.getProcessIds().size()); - Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP1)); - Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP2)); - - channel1.connected = false; - factory.sessionDisconnected(channel1); - - Assert.assertTrue(factory.containsConnection(ServerEnv.PROCESS_ID)); - Assert.assertTrue(factory.containsConnection(processId2)); - Assert.assertEquals(2, factory.getProcessIds().size()); - Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP1)); - Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP2)); - Assert.assertEquals(1, factory.getAllSessionConnections().get(IP1).size()); - Assert.assertEquals(1, factory.getAllSessionConnections().get(IP2).size()); - - factory.sessionDisconnected(channel3); - - Assert.assertTrue(factory.containsConnection(ServerEnv.PROCESS_ID)); - Assert.assertTrue(!factory.containsConnection(processId2)); - Assert.assertEquals(1, factory.getProcessIds().size()); - Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP1)); - Assert.assertTrue(!factory.getSessionConnectionMap().containsKey(IP2)); - Assert.assertEquals(1, factory.getAllSessionConnections().get(IP1).size()); - Assert.assertEquals(0, factory.getAllSessionConnections().get(IP2).size()); - } - - public static final class MockBlotChannel extends BoltChannel { - final InetSocketAddress remote; - final InetSocketAddress local = new InetSocketAddress(ServerEnv.IP, 9602); - boolean connected = true; - final Connection conn = new Connection(new MockNettyChannel()); - - public MockBlotChannel(String remoteAddress, int remotePort) { - this.remote = new InetSocketAddress(remoteAddress, remotePort); - } + @Test + public void testIllegal() { + SessionServerConnectionFactory factory = new SessionServerConnectionFactory(); + Assert.assertFalse(factory.registerSession(ServerEnv.PROCESS_ID, null)); + Assert.assertFalse(factory.registerSession(ServerEnv.PROCESS_ID, new BoltChannel())); + MockBlotChannel channel1 = new MockBlotChannel("66.66.66.66", 5550); + channel1.connected = false; + Assert.assertFalse(factory.registerSession(ServerEnv.PROCESS_ID, channel1)); + } + + @Test + public void testConnection() throws Exception { + SessionServerConnectionFactory factory = new SessionServerConnectionFactory(); + final String IP1 = "66.66.66.66"; + final String IP2 = "66.66.66.65"; + + MockBlotChannel channel1 = new MockBlotChannel(IP1, 5550); + Assert.assertTrue(factory.registerSession(ServerEnv.PROCESS_ID, channel1)); + Assert.assertFalse(factory.registerSession(ServerEnv.PROCESS_ID, channel1)); + + Assert.assertTrue(factory.containsConnection(ServerEnv.PROCESS_ID)); + Assert.assertEquals(1, factory.getSessionConnections().size()); + Assert.assertEquals(1, factory.getProcessIds().size()); + Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP1)); + + MockBlotChannel channel2 = new MockBlotChannel(IP1, 5551); + factory.registerSession(ServerEnv.PROCESS_ID, channel2); + + Assert.assertTrue(factory.containsConnection(ServerEnv.PROCESS_ID)); + Assert.assertEquals(1, factory.getSessionConnections().size()); + Assert.assertEquals(1, factory.getProcessIds().size()); + Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP1)); + + ProcessId processId2 = new ProcessId("unknown", System.currentTimeMillis(), 100, 100); + MockBlotChannel channel3 = new MockBlotChannel(IP2, 5551); + factory.registerSession(processId2, channel3); + + Assert.assertTrue(factory.containsConnection(ServerEnv.PROCESS_ID)); + Assert.assertTrue(factory.containsConnection(processId2)); + Assert.assertEquals(2, factory.getProcessIds().size()); + Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP1)); + Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP2)); + + channel1.connected = false; + factory.sessionDisconnected(channel1); + + Assert.assertTrue(factory.containsConnection(ServerEnv.PROCESS_ID)); + Assert.assertTrue(factory.containsConnection(processId2)); + Assert.assertEquals(2, factory.getProcessIds().size()); + Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP1)); + Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP2)); + Assert.assertEquals(1, factory.getAllSessionConnections().get(IP1).size()); + Assert.assertEquals(1, factory.getAllSessionConnections().get(IP2).size()); + + factory.sessionDisconnected(channel3); + + Assert.assertTrue(factory.containsConnection(ServerEnv.PROCESS_ID)); + Assert.assertTrue(!factory.containsConnection(processId2)); + Assert.assertEquals(1, factory.getProcessIds().size()); + Assert.assertTrue(factory.getSessionConnectionMap().containsKey(IP1)); + Assert.assertTrue(!factory.getSessionConnectionMap().containsKey(IP2)); + Assert.assertEquals(1, factory.getAllSessionConnections().get(IP1).size()); + Assert.assertEquals(0, factory.getAllSessionConnections().get(IP2).size()); + } + + public static final class MockBlotChannel extends BoltChannel { + final InetSocketAddress remote; + final InetSocketAddress local = new InetSocketAddress(ServerEnv.IP, 9602); + boolean connected = true; + final Connection conn = new Connection(new MockNettyChannel()); + + public MockBlotChannel(String remoteAddress, int remotePort) { + this.remote = new InetSocketAddress(remoteAddress, remotePort); + } - @Override - public InetSocketAddress getRemoteAddress() { - return remote; - } + @Override + public InetSocketAddress getRemoteAddress() { + return remote; + } - @Override - public InetSocketAddress getLocalAddress() { - return local; - } + @Override + public InetSocketAddress getLocalAddress() { + return local; + } - @Override - public boolean isConnected() { - return connected; - } + @Override + public boolean isConnected() { + return connected; + } - public Connection getConnection() { - return conn; - } + public Connection getConnection() { + return conn; } + } - private static final class MockNettyChannel implements io.netty.channel.Channel { + private static final class MockNettyChannel implements io.netty.channel.Channel { - @Override - public ChannelId id() { - return null; - } + @Override + public ChannelId id() { + return null; + } - @Override - public EventLoop eventLoop() { - return null; - } + @Override + public EventLoop eventLoop() { + return null; + } - @Override - public Channel parent() { - return null; - } + @Override + public Channel parent() { + return null; + } - @Override - public ChannelConfig config() { - return null; - } + @Override + public ChannelConfig config() { + return null; + } - @Override - public boolean isOpen() { - return false; - } + @Override + public boolean isOpen() { + return false; + } - @Override - public boolean isRegistered() { - return false; - } + @Override + public boolean isRegistered() { + return false; + } - @Override - public boolean isActive() { - return false; - } + @Override + public boolean isActive() { + return false; + } - @Override - public ChannelMetadata metadata() { - return null; - } + @Override + public ChannelMetadata metadata() { + return null; + } - @Override - public SocketAddress localAddress() { - return null; - } + @Override + public SocketAddress localAddress() { + return null; + } - @Override - public SocketAddress remoteAddress() { - return null; - } + @Override + public SocketAddress remoteAddress() { + return null; + } - @Override - public ChannelFuture closeFuture() { - return null; - } + @Override + public ChannelFuture closeFuture() { + return null; + } - @Override - public boolean isWritable() { - return false; - } + @Override + public boolean isWritable() { + return false; + } - @Override - public long bytesBeforeUnwritable() { - return 0; - } + @Override + public long bytesBeforeUnwritable() { + return 0; + } - @Override - public long bytesBeforeWritable() { - return 0; - } + @Override + public long bytesBeforeWritable() { + return 0; + } - @Override - public Unsafe unsafe() { - return null; - } + @Override + public Unsafe unsafe() { + return null; + } - @Override - public ChannelPipeline pipeline() { - return null; - } + @Override + public ChannelPipeline pipeline() { + return null; + } - @Override - public ByteBufAllocator alloc() { - return null; - } + @Override + public ByteBufAllocator alloc() { + return null; + } - @Override - public ChannelFuture bind(SocketAddress localAddress) { - return null; - } + @Override + public ChannelFuture bind(SocketAddress localAddress) { + return null; + } - @Override - public ChannelFuture connect(SocketAddress remoteAddress) { - return null; - } + @Override + public ChannelFuture connect(SocketAddress remoteAddress) { + return null; + } - @Override - public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { - return null; - } + @Override + public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { + return null; + } - @Override - public ChannelFuture disconnect() { - return null; - } + @Override + public ChannelFuture disconnect() { + return null; + } - @Override - public ChannelFuture close() { - return null; - } + @Override + public ChannelFuture close() { + return null; + } - @Override - public ChannelFuture deregister() { - return null; - } + @Override + public ChannelFuture deregister() { + return null; + } - @Override - public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { - return null; - } + @Override + public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { + return null; + } - @Override - public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { - return null; - } + @Override + public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { + return null; + } - @Override - public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, - ChannelPromise promise) { - return null; - } + @Override + public ChannelFuture connect( + SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { + return null; + } - @Override - public ChannelFuture disconnect(ChannelPromise promise) { - return null; - } + @Override + public ChannelFuture disconnect(ChannelPromise promise) { + return null; + } - @Override - public ChannelFuture close(ChannelPromise promise) { - return null; - } + @Override + public ChannelFuture close(ChannelPromise promise) { + return null; + } - @Override - public ChannelFuture deregister(ChannelPromise promise) { - return null; - } + @Override + public ChannelFuture deregister(ChannelPromise promise) { + return null; + } - @Override - public Channel read() { - return null; - } + @Override + public Channel read() { + return null; + } - @Override - public ChannelFuture write(Object msg) { - return null; - } + @Override + public ChannelFuture write(Object msg) { + return null; + } - @Override - public ChannelFuture write(Object msg, ChannelPromise promise) { - return null; - } + @Override + public ChannelFuture write(Object msg, ChannelPromise promise) { + return null; + } - @Override - public Channel flush() { - return null; - } + @Override + public Channel flush() { + return null; + } - @Override - public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { - return null; - } + @Override + public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { + return null; + } - @Override - public ChannelFuture writeAndFlush(Object msg) { - return null; - } + @Override + public ChannelFuture writeAndFlush(Object msg) { + return null; + } + + @Override + public ChannelPromise newPromise() { + return null; + } + + @Override + public ChannelProgressivePromise newProgressivePromise() { + return null; + } + + @Override + public ChannelFuture newSucceededFuture() { + return null; + } + + @Override + public ChannelFuture newFailedFuture(Throwable cause) { + return null; + } + + @Override + public ChannelPromise voidPromise() { + return null; + } + + @Override + public Attribute attr(AttributeKey key) { + return new Attribute() { @Override - public ChannelPromise newPromise() { - return null; + public AttributeKey key() { + return null; } @Override - public ChannelProgressivePromise newProgressivePromise() { - return null; + public Object get() { + return null; } @Override - public ChannelFuture newSucceededFuture() { - return null; - } + public void set(Object value) {} @Override - public ChannelFuture newFailedFuture(Throwable cause) { - return null; + public Object getAndSet(Object value) { + return null; } @Override - public ChannelPromise voidPromise() { - return null; + public Object setIfAbsent(Object value) { + return null; } @Override - public Attribute attr(AttributeKey key) { - return new Attribute() { - - @Override - public AttributeKey key() { - return null; - } - - @Override - public Object get() { - return null; - } - - @Override - public void set(Object value) { - - } - - @Override - public Object getAndSet(Object value) { - return null; - } - - @Override - public Object setIfAbsent(Object value) { - return null; - } - - @Override - public Object getAndRemove() { - return null; - } - - @Override - public boolean compareAndSet(Object oldValue, Object newValue) { - return false; - } - - @Override - public void remove() { - - } - }; + public Object getAndRemove() { + return null; } @Override - public boolean hasAttr(AttributeKey key) { - return false; + public boolean compareAndSet(Object oldValue, Object newValue) { + return false; } @Override - public int compareTo(Channel o) { - return 0; - } + public void remove() {} + }; + } + + @Override + public boolean hasAttr(AttributeKey key) { + return false; } + @Override + public int compareTo(Channel o) { + return 0; + } + } } diff --git a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/slot/SlotDiffSyncerTest.java b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/slot/SlotDiffSyncerTest.java index 1bb2de148..2650e4f7a 100644 --- a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/slot/SlotDiffSyncerTest.java +++ b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/slot/SlotDiffSyncerTest.java @@ -16,6 +16,10 @@ */ package com.alipay.sofa.registry.server.data.slot; +import static org.mockito.Matchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.common.model.GenericResponse; import com.alipay.sofa.registry.common.model.dataserver.Datum; import com.alipay.sofa.registry.common.model.dataserver.DatumSummary; @@ -36,455 +40,508 @@ import com.alipay.sofa.registry.server.shared.remoting.ClientSideExchanger; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; -import org.mockito.Matchers; - import java.util.Collections; import java.util.List; import java.util.Map; - -import static org.mockito.Matchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.junit.Assert; +import org.junit.Test; +import org.mockito.Matchers; public class SlotDiffSyncerTest { - private static final SyncContinues TRUE = new SyncContinues() { - @Override - public boolean continues() { - return true; - } - }; - - private static final SyncContinues FALSE = new SyncContinues() { - @Override - public boolean continues() { - return false; - } - }; - - @Test - public void testPick() { - Map summaryMap = Maps.newLinkedHashMap(); - for (int i = 0; i < 10; i++) { - DatumSummary summary0 = TestBaseUtils.newDatumSummary(0); - summaryMap.put(summary0.getDataInfoId(), summary0); - } - DatumSummary summary1 = TestBaseUtils.newDatumSummary(2); - summaryMap.put(summary1.getDataInfoId(), summary1); - Map picks = SlotDiffSyncer.pickSummaries(summaryMap, 5); - // empty consume 1 publisher budget - Assert.assertEquals(picks.size(), 5); - for (DatumSummary summary : picks.values()) { - Assert.assertEquals(summary.size(), 0); + private static final SyncContinues TRUE = + new SyncContinues() { + @Override + public boolean continues() { + return true; } + }; - picks = SlotDiffSyncer.pickSummaries(summaryMap, 11); - Assert.assertEquals(picks.size(), 11); - // get all publishers in datum - Assert.assertEquals(picks.get(summary1.getDataInfoId()).size(), 2); + private static final SyncContinues FALSE = + new SyncContinues() { + @Override + public boolean continues() { + return false; + } + }; + + @Test + public void testPick() { + Map summaryMap = Maps.newLinkedHashMap(); + for (int i = 0; i < 10; i++) { + DatumSummary summary0 = TestBaseUtils.newDatumSummary(0); + summaryMap.put(summary0.getDataInfoId(), summary0); + } + DatumSummary summary1 = TestBaseUtils.newDatumSummary(2); + summaryMap.put(summary1.getDataInfoId(), summary1); + Map picks = SlotDiffSyncer.pickSummaries(summaryMap, 5); + // empty consume 1 publisher budget + Assert.assertEquals(picks.size(), 5); + for (DatumSummary summary : picks.values()) { + Assert.assertEquals(summary.size(), 0); } - @Test - public void testSyncDigestResp() { - SlotDiffSyncer syncer = newSyncer(); - Assert.assertNull(syncer.processSyncDigestResp(10, failDigestResp(), null, - Collections.emptyMap())); - Assert.assertNull(syncer.processSyncDigestResp(10, null, null, Collections.emptyMap())); - Assert.assertTrue(syncer.processSyncDigestResp(10, emptyDigestResp(), null, - Collections.emptyMap()).isEmpty()); - - DatumStorage storage = syncer.getDatumStorage(); - Publisher publisher1 = TestBaseUtils.createTestPublisher("dataId1"); - storage.put(publisher1); - Publisher publisher2 = TestBaseUtils.createTestPublisher("dataId2"); - storage.put(publisher2); - Publisher publisher3 = TestBaseUtils.createTestPublisher("dataId3"); - storage.put(publisher3); - - GenericResponse resp = newDigestResp(Lists.newArrayList(publisher1.getDataInfoId()), + picks = SlotDiffSyncer.pickSummaries(summaryMap, 11); + Assert.assertEquals(picks.size(), 11); + // get all publishers in datum + Assert.assertEquals(picks.get(summary1.getDataInfoId()).size(), 2); + } + + @Test + public void testSyncDigestResp() { + SlotDiffSyncer syncer = newSyncer(); + Assert.assertNull( + syncer.processSyncDigestResp(10, failDigestResp(), null, Collections.emptyMap())); + Assert.assertNull(syncer.processSyncDigestResp(10, null, null, Collections.emptyMap())); + Assert.assertTrue( + syncer + .processSyncDigestResp(10, emptyDigestResp(), null, Collections.emptyMap()) + .isEmpty()); + + DatumStorage storage = syncer.getDatumStorage(); + Publisher publisher1 = TestBaseUtils.createTestPublisher("dataId1"); + storage.put(publisher1); + Publisher publisher2 = TestBaseUtils.createTestPublisher("dataId2"); + storage.put(publisher2); + Publisher publisher3 = TestBaseUtils.createTestPublisher("dataId3"); + storage.put(publisher3); + + GenericResponse resp = + newDigestResp( + Lists.newArrayList(publisher1.getDataInfoId()), Lists.newArrayList(publisher2.getDataInfoId()), Lists.newArrayList(publisher3.getDataInfoId())); - Map summaryMap = Maps.newHashMap(); - summaryMap.put(publisher1.getDataInfoId(), - TestBaseUtils.newDatumSummary(3, publisher1.getDataInfoId())); - summaryMap.put(publisher3.getDataInfoId(), - TestBaseUtils.newDatumSummary(2, publisher3.getDataInfoId())); - // try remove publisher3, but not match register.version - Assert.assertFalse(syncer.processSyncDigestResp(10, resp, null, summaryMap).isEmpty()); - Datum datum1 = storage.get(publisher3.getDataInfoId()); - Assert.assertTrue(datum1.publisherSize() != 0); - - // remove publisher3 - summaryMap.put(publisher3.getDataInfoId(), new DatumSummary(publisher3.getDataInfoId(), + Map summaryMap = Maps.newHashMap(); + summaryMap.put( + publisher1.getDataInfoId(), TestBaseUtils.newDatumSummary(3, publisher1.getDataInfoId())); + summaryMap.put( + publisher3.getDataInfoId(), TestBaseUtils.newDatumSummary(2, publisher3.getDataInfoId())); + // try remove publisher3, but not match register.version + Assert.assertFalse(syncer.processSyncDigestResp(10, resp, null, summaryMap).isEmpty()); + Datum datum1 = storage.get(publisher3.getDataInfoId()); + Assert.assertTrue(datum1.publisherSize() != 0); + + // remove publisher3 + summaryMap.put( + publisher3.getDataInfoId(), + new DatumSummary( + publisher3.getDataInfoId(), Collections.singletonMap(publisher3.getRegisterId(), publisher3.registerVersion()))); - DataSlotDiffDigestResult result = syncer.processSyncDigestResp(10, resp, null, summaryMap); - Assert.assertFalse(result.isEmpty()); - Datum datum2 = storage.get(publisher3.getDataInfoId()); - Assert.assertTrue(datum2.publisherSize() == 0); - Assert.assertTrue(datum2.getVersion() > datum1.getVersion()); - } - - @Test - public void testSyncPublisherResp() { - SlotDiffSyncer syncer = newSyncer(); - Assert.assertNull(syncer.processSyncPublisherResp(10, failPublisherResp(), null, - Collections.emptyMap())); - Assert.assertNull(syncer.processSyncPublisherResp(10, null, null, Collections.emptyMap())); - Assert.assertTrue(syncer.processSyncPublisherResp(10, emptyPublisherResp(), null, - Collections.emptyMap()).isEmpty()); - - DatumStorage storage = syncer.getDatumStorage(); - Publisher publisher1 = TestBaseUtils.createTestPublisher("dataId1"); - storage.put(publisher1); - Publisher publisher2 = TestBaseUtils.createTestPublisher("dataId2"); - storage.put(publisher2); - Publisher publisher3 = TestBaseUtils.createTestPublisher("dataId3"); - storage.put(publisher3); - - Map summaryMap = Maps.newHashMap(); - summaryMap.put(publisher1.getDataInfoId(), new DatumSummary(publisher1.getDataInfoId(), + DataSlotDiffDigestResult result = syncer.processSyncDigestResp(10, resp, null, summaryMap); + Assert.assertFalse(result.isEmpty()); + Datum datum2 = storage.get(publisher3.getDataInfoId()); + Assert.assertTrue(datum2.publisherSize() == 0); + Assert.assertTrue(datum2.getVersion() > datum1.getVersion()); + } + + @Test + public void testSyncPublisherResp() { + SlotDiffSyncer syncer = newSyncer(); + Assert.assertNull( + syncer.processSyncPublisherResp(10, failPublisherResp(), null, Collections.emptyMap())); + Assert.assertNull(syncer.processSyncPublisherResp(10, null, null, Collections.emptyMap())); + Assert.assertTrue( + syncer + .processSyncPublisherResp(10, emptyPublisherResp(), null, Collections.emptyMap()) + .isEmpty()); + + DatumStorage storage = syncer.getDatumStorage(); + Publisher publisher1 = TestBaseUtils.createTestPublisher("dataId1"); + storage.put(publisher1); + Publisher publisher2 = TestBaseUtils.createTestPublisher("dataId2"); + storage.put(publisher2); + Publisher publisher3 = TestBaseUtils.createTestPublisher("dataId3"); + storage.put(publisher3); + + Map summaryMap = Maps.newHashMap(); + summaryMap.put( + publisher1.getDataInfoId(), + new DatumSummary( + publisher1.getDataInfoId(), Collections.singletonMap(publisher1.getRegisterId(), publisher1.registerVersion()))); - summaryMap.put(publisher2.getDataInfoId(), - TestBaseUtils.newDatumSummary(3, publisher2.getDataInfoId())); - summaryMap.put(publisher3.getDataInfoId(), new DatumSummary(publisher3.getDataInfoId(), + summaryMap.put( + publisher2.getDataInfoId(), TestBaseUtils.newDatumSummary(3, publisher2.getDataInfoId())); + summaryMap.put( + publisher3.getDataInfoId(), + new DatumSummary( + publisher3.getDataInfoId(), Collections.singletonMap(publisher3.getRegisterId(), publisher3.registerVersion()))); - publisher1 = TestBaseUtils.cloneBase(publisher1); - publisher1.setVersion(publisher1.getVersion() + 1); - GenericResponse resp = newPublishResp( + publisher1 = TestBaseUtils.cloneBase(publisher1); + publisher1.setVersion(publisher1.getVersion() + 1); + GenericResponse resp = + newPublishResp( false, - Collections.singletonMap(publisher1.getDataInfoId(), - Collections.singletonList(publisher1)), - Collections.singletonMap(publisher3.getDataInfoId(), - Collections.singletonList(publisher3.getRegisterId()))); - - Datum datum1 = storage.get(publisher1.getDataInfoId()); - Datum datum3 = storage.get(publisher3.getDataInfoId()); - Assert.assertTrue(datum1.publisherSize() == 1); - Assert.assertTrue(datum3.publisherSize() == 1); - - DataSlotDiffPublisherResult result = syncer.processSyncPublisherResp(10, resp, null, - summaryMap); - Assert.assertFalse(result.isEmpty()); - - Datum datum1_1 = storage.get(publisher1.getDataInfoId()); - Assert.assertTrue(datum1_1.publisherSize() == 1); - Assert.assertEquals(datum1_1.getPubMap().get(publisher1.getRegisterId()), publisher1); - Assert.assertTrue(datum1_1.getVersion() > datum1.getVersion()); - - Datum datum3_3 = storage.get(publisher3.getDataInfoId()); - Assert.assertTrue(datum3_3.publisherSize() == 0); - Assert.assertTrue(datum3_3.getVersion() > datum3.getVersion()); - } - - @Test - public void testSyncSession() { - MockSync mockSync = mockSync(10, "testDc"); - SlotDiffSyncer syncer = mockSync.syncer; - LocalDatumStorage storage = (LocalDatumStorage) syncer.getDatumStorage(); - List p1 = mockSync.p1; - List p2 = mockSync.p2; - List p3 = mockSync.p3; - List p4 = mockSync.p4; - - // sync failed or empty - SessionNodeExchanger exchanger = mockExchange(SessionNodeExchanger.class, null, - DataSlotDiffDigestRequest.class, null, null); - Assert.assertFalse(syncer.syncSession(10, ServerEnv.IP, exchanger, 10, TRUE)); - - exchanger = mockExchange(SessionNodeExchanger.class, failDigestResp(), - DataSlotDiffDigestRequest.class, null, null); - Assert.assertFalse(syncer.syncSession(10, ServerEnv.IP, exchanger, 10, TRUE)); - - exchanger = mockExchange(SessionNodeExchanger.class, emptyDigestResp(), - DataSlotDiffDigestRequest.class, null, null); - Assert.assertTrue(syncer.syncSession(10, ServerEnv.IP, exchanger, 10, TRUE)); - - // update p1.0, remove p2.0, remove p3.all, add p4 - GenericResponse digestResp = newDigestResp( + Collections.singletonMap( + publisher1.getDataInfoId(), Collections.singletonList(publisher1)), + Collections.singletonMap( + publisher3.getDataInfoId(), Collections.singletonList(publisher3.getRegisterId()))); + + Datum datum1 = storage.get(publisher1.getDataInfoId()); + Datum datum3 = storage.get(publisher3.getDataInfoId()); + Assert.assertTrue(datum1.publisherSize() == 1); + Assert.assertTrue(datum3.publisherSize() == 1); + + DataSlotDiffPublisherResult result = + syncer.processSyncPublisherResp(10, resp, null, summaryMap); + Assert.assertFalse(result.isEmpty()); + + Datum datum1_1 = storage.get(publisher1.getDataInfoId()); + Assert.assertTrue(datum1_1.publisherSize() == 1); + Assert.assertEquals(datum1_1.getPubMap().get(publisher1.getRegisterId()), publisher1); + Assert.assertTrue(datum1_1.getVersion() > datum1.getVersion()); + + Datum datum3_3 = storage.get(publisher3.getDataInfoId()); + Assert.assertTrue(datum3_3.publisherSize() == 0); + Assert.assertTrue(datum3_3.getVersion() > datum3.getVersion()); + } + + @Test + public void testSyncSession() { + MockSync mockSync = mockSync(10, "testDc"); + SlotDiffSyncer syncer = mockSync.syncer; + LocalDatumStorage storage = (LocalDatumStorage) syncer.getDatumStorage(); + List p1 = mockSync.p1; + List p2 = mockSync.p2; + List p3 = mockSync.p3; + List p4 = mockSync.p4; + + // sync failed or empty + SessionNodeExchanger exchanger = + mockExchange(SessionNodeExchanger.class, null, DataSlotDiffDigestRequest.class, null, null); + Assert.assertFalse(syncer.syncSession(10, ServerEnv.IP, exchanger, 10, TRUE)); + + exchanger = + mockExchange( + SessionNodeExchanger.class, + failDigestResp(), + DataSlotDiffDigestRequest.class, + null, + null); + Assert.assertFalse(syncer.syncSession(10, ServerEnv.IP, exchanger, 10, TRUE)); + + exchanger = + mockExchange( + SessionNodeExchanger.class, + emptyDigestResp(), + DataSlotDiffDigestRequest.class, + null, + null); + Assert.assertTrue(syncer.syncSession(10, ServerEnv.IP, exchanger, 10, TRUE)); + + // update p1.0, remove p2.0, remove p3.all, add p4 + GenericResponse digestResp = + newDigestResp( Lists.newArrayList(p1.get(0).getDataInfoId(), p2.get(0).getDataInfoId()), Collections.singletonList(p4.get(0).getDataInfoId()), Collections.singletonList(p3.get(0).getDataInfoId())); - Publisher p1Update = TestBaseUtils.cloneBase(p1.get(0)); - p1Update.setVersion(p1Update.getVersion() + 1); - Map> update = Maps.newHashMap(); - update.put(p1Update.getDataInfoId(), Collections.singletonList(p1Update)); - update.put(p4.get(0).getDataInfoId(), p4); - Map> remove = Maps.newHashMap(); - remove.put(p2.get(0).getDataInfoId(), Collections.singletonList(p2.get(0).getRegisterId())); - - // sync publisher, - GenericResponse publisherResp = newPublishResp(false, update, remove); - exchanger = mockExchange(SessionNodeExchanger.class, digestResp, - DataSlotDiffDigestRequest.class, publisherResp, DataSlotDiffPublisherRequest.class); - boolean v = syncer.syncSession(10, ServerEnv.IP, exchanger, 10, TRUE); - Assert.assertTrue(v); - - // p1 update - Datum datum1 = storage.get(p1Update.getDataInfoId()); - Assert.assertEquals(datum1.publisherSize(), 3); - Assert.assertEquals(datum1.getPubMap().get(p1Update.getRegisterId()), p1Update); - Assert.assertEquals(datum1.getPubMap().get(p1.get(1).getRegisterId()), p1.get(1)); - Assert.assertEquals(datum1.getPubMap().get(p1.get(2).getRegisterId()), p1.get(2)); - - // p2 remains 1 - Datum datum2 = storage.get(p2.get(0).getDataInfoId()); - Assert.assertEquals(datum2.publisherSize(), 1); - Assert.assertEquals(datum2.getPubMap().get(p2.get(1).getRegisterId()), p2.get(1)); - - // p3 remove all - Datum datum3 = storage.get(p3.get(0).getDataInfoId()); - Assert.assertEquals(datum3.publisherSize(), 0); - - // p4 add all - Datum datum4 = storage.get(p4.get(0).getDataInfoId()); - Assert.assertEquals(datum4.publisherSize(), 2); - Assert.assertEquals(datum4.getPubMap().get(p4.get(0).getRegisterId()), p4.get(0)); - Assert.assertEquals(datum4.getPubMap().get(p4.get(1).getRegisterId()), p4.get(1)); - } - - @Test - public void testSyncBreak() { - MockSync mockSync = mockSync(10, "testDc"); - SlotDiffSyncer syncer = mockSync.syncer; - LocalDatumStorage storage = (LocalDatumStorage) syncer.getDatumStorage(); - List p1 = mockSync.p1; - List p2 = mockSync.p2; - List p3 = mockSync.p3; - List p4 = mockSync.p4; - - // update p1.0, remove p2.0, remove p3.all, add p4 - GenericResponse digestResp = newDigestResp( + Publisher p1Update = TestBaseUtils.cloneBase(p1.get(0)); + p1Update.setVersion(p1Update.getVersion() + 1); + Map> update = Maps.newHashMap(); + update.put(p1Update.getDataInfoId(), Collections.singletonList(p1Update)); + update.put(p4.get(0).getDataInfoId(), p4); + Map> remove = Maps.newHashMap(); + remove.put(p2.get(0).getDataInfoId(), Collections.singletonList(p2.get(0).getRegisterId())); + + // sync publisher, + GenericResponse publisherResp = newPublishResp(false, update, remove); + exchanger = + mockExchange( + SessionNodeExchanger.class, + digestResp, + DataSlotDiffDigestRequest.class, + publisherResp, + DataSlotDiffPublisherRequest.class); + boolean v = syncer.syncSession(10, ServerEnv.IP, exchanger, 10, TRUE); + Assert.assertTrue(v); + + // p1 update + Datum datum1 = storage.get(p1Update.getDataInfoId()); + Assert.assertEquals(datum1.publisherSize(), 3); + Assert.assertEquals(datum1.getPubMap().get(p1Update.getRegisterId()), p1Update); + Assert.assertEquals(datum1.getPubMap().get(p1.get(1).getRegisterId()), p1.get(1)); + Assert.assertEquals(datum1.getPubMap().get(p1.get(2).getRegisterId()), p1.get(2)); + + // p2 remains 1 + Datum datum2 = storage.get(p2.get(0).getDataInfoId()); + Assert.assertEquals(datum2.publisherSize(), 1); + Assert.assertEquals(datum2.getPubMap().get(p2.get(1).getRegisterId()), p2.get(1)); + + // p3 remove all + Datum datum3 = storage.get(p3.get(0).getDataInfoId()); + Assert.assertEquals(datum3.publisherSize(), 0); + + // p4 add all + Datum datum4 = storage.get(p4.get(0).getDataInfoId()); + Assert.assertEquals(datum4.publisherSize(), 2); + Assert.assertEquals(datum4.getPubMap().get(p4.get(0).getRegisterId()), p4.get(0)); + Assert.assertEquals(datum4.getPubMap().get(p4.get(1).getRegisterId()), p4.get(1)); + } + + @Test + public void testSyncBreak() { + MockSync mockSync = mockSync(10, "testDc"); + SlotDiffSyncer syncer = mockSync.syncer; + LocalDatumStorage storage = (LocalDatumStorage) syncer.getDatumStorage(); + List p1 = mockSync.p1; + List p2 = mockSync.p2; + List p3 = mockSync.p3; + List p4 = mockSync.p4; + + // update p1.0, remove p2.0, remove p3.all, add p4 + GenericResponse digestResp = + newDigestResp( Lists.newArrayList(p1.get(0).getDataInfoId(), p2.get(0).getDataInfoId()), Collections.singletonList(p4.get(0).getDataInfoId()), Collections.singletonList(p3.get(0).getDataInfoId())); - Publisher p1Update = TestBaseUtils.cloneBase(p1.get(0)); - p1Update.setVersion(p1Update.getVersion() + 1); - Map> update = Maps.newHashMap(); - update.put(p1Update.getDataInfoId(), Collections.singletonList(p1Update)); - update.put(p4.get(0).getDataInfoId(), p4); - Map> remove = Maps.newHashMap(); - remove.put(p2.get(0).getDataInfoId(), Collections.singletonList(p2.get(0).getRegisterId())); - - // sync publisher, - GenericResponse publisherResp = newPublishResp(false, update, remove); - SessionNodeExchanger exchanger = mockExchange(SessionNodeExchanger.class, digestResp, - DataSlotDiffDigestRequest.class, publisherResp, DataSlotDiffPublisherRequest.class); - boolean v = syncer.syncSession(10, ServerEnv.IP, exchanger, 10, FALSE); - Assert.assertTrue(v); - - // sync break, only remove dataInfoIds - Datum datum1 = storage.get(p1Update.getDataInfoId()); - Assert.assertEquals(datum1.publisherSize(), 3); - Assert.assertEquals(datum1.getPubMap().get(p1.get(0).getRegisterId()), p1.get(0)); - Assert.assertEquals(datum1.getPubMap().get(p1.get(1).getRegisterId()), p1.get(1)); - Assert.assertEquals(datum1.getPubMap().get(p1.get(2).getRegisterId()), p1.get(2)); - - // p2 remains 2 - Datum datum2 = storage.get(p2.get(0).getDataInfoId()); - Assert.assertEquals(datum2.publisherSize(), 2); - Assert.assertEquals(datum2.getPubMap().get(p2.get(0).getRegisterId()), p2.get(0)); - Assert.assertEquals(datum2.getPubMap().get(p2.get(1).getRegisterId()), p2.get(1)); - - // p3 remove all - Datum datum3 = storage.get(p3.get(0).getDataInfoId()); - Assert.assertEquals(datum3.publisherSize(), 0); - - // p4 is empty - Datum datum4 = storage.get(p4.get(0).getDataInfoId()); - Assert.assertEquals(datum4.publisherSize(), 0); - } - - @Test - public void testSyncLeader() { - MockSync mockSync = mockSync(10, "testDc"); - SlotDiffSyncer syncer = mockSync.syncer; - LocalDatumStorage storage = (LocalDatumStorage) syncer.getDatumStorage(); - List p1 = mockSync.p1; - List p2 = mockSync.p2; - List p3 = mockSync.p3; - List p4 = mockSync.p4; - - // sync failed or empty - DataNodeExchanger exchanger = mockExchange(DataNodeExchanger.class, null, - DataSlotDiffDigestRequest.class, null, null); - Assert.assertFalse(syncer.syncSlotLeader(10, ServerEnv.IP, exchanger, 10, TRUE)); - - exchanger = mockExchange(DataNodeExchanger.class, failDigestResp(), - DataSlotDiffDigestRequest.class, null, null); - Assert.assertFalse(syncer.syncSlotLeader(10, ServerEnv.IP, exchanger, 10, TRUE)); - - exchanger = mockExchange(DataNodeExchanger.class, emptyDigestResp(), - DataSlotDiffDigestRequest.class, null, null); - Assert.assertTrue(syncer.syncSlotLeader(10, ServerEnv.IP, exchanger, 10, TRUE)); - - // sync success - // update p1.0, remove p2.0, remove p3.all, add p4 - GenericResponse digestResp = newDigestResp( + Publisher p1Update = TestBaseUtils.cloneBase(p1.get(0)); + p1Update.setVersion(p1Update.getVersion() + 1); + Map> update = Maps.newHashMap(); + update.put(p1Update.getDataInfoId(), Collections.singletonList(p1Update)); + update.put(p4.get(0).getDataInfoId(), p4); + Map> remove = Maps.newHashMap(); + remove.put(p2.get(0).getDataInfoId(), Collections.singletonList(p2.get(0).getRegisterId())); + + // sync publisher, + GenericResponse publisherResp = newPublishResp(false, update, remove); + SessionNodeExchanger exchanger = + mockExchange( + SessionNodeExchanger.class, + digestResp, + DataSlotDiffDigestRequest.class, + publisherResp, + DataSlotDiffPublisherRequest.class); + boolean v = syncer.syncSession(10, ServerEnv.IP, exchanger, 10, FALSE); + Assert.assertTrue(v); + + // sync break, only remove dataInfoIds + Datum datum1 = storage.get(p1Update.getDataInfoId()); + Assert.assertEquals(datum1.publisherSize(), 3); + Assert.assertEquals(datum1.getPubMap().get(p1.get(0).getRegisterId()), p1.get(0)); + Assert.assertEquals(datum1.getPubMap().get(p1.get(1).getRegisterId()), p1.get(1)); + Assert.assertEquals(datum1.getPubMap().get(p1.get(2).getRegisterId()), p1.get(2)); + + // p2 remains 2 + Datum datum2 = storage.get(p2.get(0).getDataInfoId()); + Assert.assertEquals(datum2.publisherSize(), 2); + Assert.assertEquals(datum2.getPubMap().get(p2.get(0).getRegisterId()), p2.get(0)); + Assert.assertEquals(datum2.getPubMap().get(p2.get(1).getRegisterId()), p2.get(1)); + + // p3 remove all + Datum datum3 = storage.get(p3.get(0).getDataInfoId()); + Assert.assertEquals(datum3.publisherSize(), 0); + + // p4 is empty + Datum datum4 = storage.get(p4.get(0).getDataInfoId()); + Assert.assertEquals(datum4.publisherSize(), 0); + } + + @Test + public void testSyncLeader() { + MockSync mockSync = mockSync(10, "testDc"); + SlotDiffSyncer syncer = mockSync.syncer; + LocalDatumStorage storage = (LocalDatumStorage) syncer.getDatumStorage(); + List p1 = mockSync.p1; + List p2 = mockSync.p2; + List p3 = mockSync.p3; + List p4 = mockSync.p4; + + // sync failed or empty + DataNodeExchanger exchanger = + mockExchange(DataNodeExchanger.class, null, DataSlotDiffDigestRequest.class, null, null); + Assert.assertFalse(syncer.syncSlotLeader(10, ServerEnv.IP, exchanger, 10, TRUE)); + + exchanger = + mockExchange( + DataNodeExchanger.class, failDigestResp(), DataSlotDiffDigestRequest.class, null, null); + Assert.assertFalse(syncer.syncSlotLeader(10, ServerEnv.IP, exchanger, 10, TRUE)); + + exchanger = + mockExchange( + DataNodeExchanger.class, + emptyDigestResp(), + DataSlotDiffDigestRequest.class, + null, + null); + Assert.assertTrue(syncer.syncSlotLeader(10, ServerEnv.IP, exchanger, 10, TRUE)); + + // sync success + // update p1.0, remove p2.0, remove p3.all, add p4 + GenericResponse digestResp = + newDigestResp( Lists.newArrayList(p1.get(0).getDataInfoId(), p2.get(0).getDataInfoId()), Collections.singletonList(p4.get(0).getDataInfoId()), Collections.singletonList(p3.get(0).getDataInfoId())); - Publisher p1Update = TestBaseUtils.cloneBase(p1.get(0)); - p1Update.setVersion(p1Update.getVersion() + 1); - Map> update = Maps.newHashMap(); - update.put(p1Update.getDataInfoId(), Collections.singletonList(p1Update)); - update.put(p4.get(0).getDataInfoId(), p4); - Map> remove = Maps.newHashMap(); - remove.put(p2.get(0).getDataInfoId(), Collections.singletonList(p2.get(0).getRegisterId())); - - // sync publisher, - GenericResponse publisherResp = newPublishResp(false, update, remove); - exchanger = mockExchange(DataNodeExchanger.class, digestResp, - DataSlotDiffDigestRequest.class, publisherResp, DataSlotDiffPublisherRequest.class); - boolean v = syncer.syncSlotLeader(10, ServerEnv.IP, exchanger, 10, TRUE); - Assert.assertTrue(v); - - // p1 update - Datum datum1 = storage.get(p1Update.getDataInfoId()); - Assert.assertEquals(datum1.publisherSize(), 3); - Assert.assertEquals(datum1.getPubMap().get(p1Update.getRegisterId()), p1Update); - Assert.assertEquals(datum1.getPubMap().get(p1.get(1).getRegisterId()), p1.get(1)); - Assert.assertEquals(datum1.getPubMap().get(p1.get(2).getRegisterId()), p1.get(2)); - - // p2 remains 1 - Datum datum2 = storage.get(p2.get(0).getDataInfoId()); - Assert.assertEquals(datum2.publisherSize(), 1); - Assert.assertEquals(datum2.getPubMap().get(p2.get(1).getRegisterId()), p2.get(1)); - - // p3 remove all - Datum datum3 = storage.get(p3.get(0).getDataInfoId()); - Assert.assertEquals(datum3.publisherSize(), 0); - - // p4 add all - Datum datum4 = storage.get(p4.get(0).getDataInfoId()); - Assert.assertEquals(datum4.publisherSize(), 2); - Assert.assertEquals(datum4.getPubMap().get(p4.get(0).getRegisterId()), p4.get(0)); - Assert.assertEquals(datum4.getPubMap().get(p4.get(1).getRegisterId()), p4.get(1)); - } - - private static T mockExchange(Class c, Object result1, - Class reqClazz1, Object result2, - Class reqClazz2) { - T exchanger = mock(c); - when(exchanger.requestRaw(anyString(), Matchers.isA(reqClazz1))).thenReturn(new Response() { - @Override - public Object getResult() { + Publisher p1Update = TestBaseUtils.cloneBase(p1.get(0)); + p1Update.setVersion(p1Update.getVersion() + 1); + Map> update = Maps.newHashMap(); + update.put(p1Update.getDataInfoId(), Collections.singletonList(p1Update)); + update.put(p4.get(0).getDataInfoId(), p4); + Map> remove = Maps.newHashMap(); + remove.put(p2.get(0).getDataInfoId(), Collections.singletonList(p2.get(0).getRegisterId())); + + // sync publisher, + GenericResponse publisherResp = newPublishResp(false, update, remove); + exchanger = + mockExchange( + DataNodeExchanger.class, + digestResp, + DataSlotDiffDigestRequest.class, + publisherResp, + DataSlotDiffPublisherRequest.class); + boolean v = syncer.syncSlotLeader(10, ServerEnv.IP, exchanger, 10, TRUE); + Assert.assertTrue(v); + + // p1 update + Datum datum1 = storage.get(p1Update.getDataInfoId()); + Assert.assertEquals(datum1.publisherSize(), 3); + Assert.assertEquals(datum1.getPubMap().get(p1Update.getRegisterId()), p1Update); + Assert.assertEquals(datum1.getPubMap().get(p1.get(1).getRegisterId()), p1.get(1)); + Assert.assertEquals(datum1.getPubMap().get(p1.get(2).getRegisterId()), p1.get(2)); + + // p2 remains 1 + Datum datum2 = storage.get(p2.get(0).getDataInfoId()); + Assert.assertEquals(datum2.publisherSize(), 1); + Assert.assertEquals(datum2.getPubMap().get(p2.get(1).getRegisterId()), p2.get(1)); + + // p3 remove all + Datum datum3 = storage.get(p3.get(0).getDataInfoId()); + Assert.assertEquals(datum3.publisherSize(), 0); + + // p4 add all + Datum datum4 = storage.get(p4.get(0).getDataInfoId()); + Assert.assertEquals(datum4.publisherSize(), 2); + Assert.assertEquals(datum4.getPubMap().get(p4.get(0).getRegisterId()), p4.get(0)); + Assert.assertEquals(datum4.getPubMap().get(p4.get(1).getRegisterId()), p4.get(1)); + } + + private static T mockExchange( + Class c, Object result1, Class reqClazz1, Object result2, Class reqClazz2) { + T exchanger = mock(c); + when(exchanger.requestRaw(anyString(), Matchers.isA(reqClazz1))) + .thenReturn( + new Response() { + @Override + public Object getResult() { return result1; - } - }); - if (reqClazz2 != null) { - when(exchanger.requestRaw(anyString(), Matchers.isA(reqClazz2))).thenReturn( - new Response() { - @Override - public Object getResult() { - return result2; - } - }); - } - return exchanger; + } + }); + if (reqClazz2 != null) { + when(exchanger.requestRaw(anyString(), Matchers.isA(reqClazz2))) + .thenReturn( + new Response() { + @Override + public Object getResult() { + return result2; + } + }); } - - static SlotDiffSyncer newSyncer() { - return newSyncer(true); - } - - static SlotDiffSyncer newSyncer(boolean init) { - LocalDatumStorage storage = TestBaseUtils.newLocalStorage("testDc", init); - DataChangeEventCenter eventCenter = new DataChangeEventCenter(); - SessionLeaseManager sessionLeaseManager = new SessionLeaseManager(); - SlotDiffSyncer syncer = new SlotDiffSyncer(storage.getDataServerConfig(), storage, - eventCenter, sessionLeaseManager); - return syncer; - } - - private static GenericResponse failPublisherResp() { - GenericResponse resp = new GenericResponse<>(); - resp.fillFailed("fail"); - return resp; - } - - private static GenericResponse emptyPublisherResp() { - GenericResponse resp = new GenericResponse<>(); - DataSlotDiffPublisherResult empty = new DataSlotDiffPublisherResult(false, - Collections.emptyMap(), Collections.emptyMap()); - empty.setSessionProcessId(ServerEnv.PROCESS_ID); - resp.fillSucceed(empty); - return resp; - } - - private static GenericResponse newPublishResp(boolean hasRemain, - Map> updatedPublishers, - Map> removedPublishers) { - GenericResponse resp = new GenericResponse<>(); - DataSlotDiffPublisherResult result = new DataSlotDiffPublisherResult(hasRemain, - updatedPublishers, removedPublishers); - result.setSessionProcessId(ServerEnv.PROCESS_ID); - resp.fillSucceed(result); - return resp; + return exchanger; + } + + static SlotDiffSyncer newSyncer() { + return newSyncer(true); + } + + static SlotDiffSyncer newSyncer(boolean init) { + LocalDatumStorage storage = TestBaseUtils.newLocalStorage("testDc", init); + DataChangeEventCenter eventCenter = new DataChangeEventCenter(); + SessionLeaseManager sessionLeaseManager = new SessionLeaseManager(); + SlotDiffSyncer syncer = + new SlotDiffSyncer( + storage.getDataServerConfig(), storage, eventCenter, sessionLeaseManager); + return syncer; + } + + private static GenericResponse failPublisherResp() { + GenericResponse resp = new GenericResponse<>(); + resp.fillFailed("fail"); + return resp; + } + + private static GenericResponse emptyPublisherResp() { + GenericResponse resp = new GenericResponse<>(); + DataSlotDiffPublisherResult empty = + new DataSlotDiffPublisherResult(false, Collections.emptyMap(), Collections.emptyMap()); + empty.setSessionProcessId(ServerEnv.PROCESS_ID); + resp.fillSucceed(empty); + return resp; + } + + private static GenericResponse newPublishResp( + boolean hasRemain, + Map> updatedPublishers, + Map> removedPublishers) { + GenericResponse resp = new GenericResponse<>(); + DataSlotDiffPublisherResult result = + new DataSlotDiffPublisherResult(hasRemain, updatedPublishers, removedPublishers); + result.setSessionProcessId(ServerEnv.PROCESS_ID); + resp.fillSucceed(result); + return resp; + } + + private static GenericResponse failDigestResp() { + GenericResponse resp = new GenericResponse<>(); + resp.fillFailed("fail"); + return resp; + } + + private static GenericResponse emptyDigestResp() { + GenericResponse resp = new GenericResponse<>(); + DataSlotDiffDigestResult empty = + new DataSlotDiffDigestResult( + Collections.EMPTY_LIST, Collections.EMPTY_LIST, Collections.EMPTY_LIST); + empty.setSessionProcessId(ServerEnv.PROCESS_ID); + resp.fillSucceed(empty); + return resp; + } + + private static GenericResponse newDigestResp( + List updatedDataInfoIds, + List addedDataInfoIds, + List removedDataInfoIds) { + GenericResponse resp = new GenericResponse<>(); + DataSlotDiffDigestResult result = + new DataSlotDiffDigestResult(updatedDataInfoIds, addedDataInfoIds, removedDataInfoIds); + result.setSessionProcessId(ServerEnv.PROCESS_ID); + resp.fillSucceed(result); + return resp; + } + + static final class MockSync { + SlotDiffSyncer syncer; + List p1; + List p2; + List p3; + List p4; + } + + static MockSync mockSync(int slotId, String dc, boolean init) { + SlotDiffSyncer syncer = newSyncer(init); + MockSync ms = new MockSync(); + if (init) { + LocalDatumStorage storage = (LocalDatumStorage) syncer.getDatumStorage(); + List p1 = TestBaseUtils.createTestPublishers(slotId, 3); + List p2 = TestBaseUtils.createTestPublishers(slotId, 2); + List p3 = TestBaseUtils.createTestPublishers(slotId, 2); + List p4 = TestBaseUtils.createTestPublishers(slotId, 2); + storage.put(p1.get(0).getDataInfoId(), p1); + storage.put(p2.get(0).getDataInfoId(), p2); + storage.put(p3.get(0).getDataInfoId(), p3); + // empty d4 + storage.createEmptyDatumIfAbsent(p4.get(0).getDataInfoId(), dc); + ms.p1 = p1; + ms.p2 = p2; + ms.p3 = p3; + ms.p4 = p4; } + ms.syncer = syncer; + return ms; + } - private static GenericResponse failDigestResp() { - GenericResponse resp = new GenericResponse<>(); - resp.fillFailed("fail"); - return resp; - } - - private static GenericResponse emptyDigestResp() { - GenericResponse resp = new GenericResponse<>(); - DataSlotDiffDigestResult empty = new DataSlotDiffDigestResult(Collections.EMPTY_LIST, - Collections.EMPTY_LIST, Collections.EMPTY_LIST); - empty.setSessionProcessId(ServerEnv.PROCESS_ID); - resp.fillSucceed(empty); - return resp; - } - - private static GenericResponse newDigestResp(List updatedDataInfoIds, - List addedDataInfoIds, - List removedDataInfoIds) { - GenericResponse resp = new GenericResponse<>(); - DataSlotDiffDigestResult result = new DataSlotDiffDigestResult(updatedDataInfoIds, - addedDataInfoIds, removedDataInfoIds); - result.setSessionProcessId(ServerEnv.PROCESS_ID); - resp.fillSucceed(result); - return resp; - } - - static final class MockSync { - SlotDiffSyncer syncer; - List p1; - List p2; - List p3; - List p4; - } - - static MockSync mockSync(int slotId, String dc, boolean init) { - SlotDiffSyncer syncer = newSyncer(init); - MockSync ms = new MockSync(); - if (init) { - LocalDatumStorage storage = (LocalDatumStorage) syncer.getDatumStorage(); - List p1 = TestBaseUtils.createTestPublishers(slotId, 3); - List p2 = TestBaseUtils.createTestPublishers(slotId, 2); - List p3 = TestBaseUtils.createTestPublishers(slotId, 2); - List p4 = TestBaseUtils.createTestPublishers(slotId, 2); - storage.put(p1.get(0).getDataInfoId(), p1); - storage.put(p2.get(0).getDataInfoId(), p2); - storage.put(p3.get(0).getDataInfoId(), p3); - // empty d4 - storage.createEmptyDatumIfAbsent(p4.get(0).getDataInfoId(), dc); - ms.p1 = p1; - ms.p2 = p2; - ms.p3 = p3; - ms.p4 = p4; - } - ms.syncer = syncer; - return ms; - } - - static MockSync mockSync(int slotId, String dc) { - return mockSync(slotId, dc, true); - } + static MockSync mockSync(int slotId, String dc) { + return mockSync(slotId, dc, true); + } } diff --git a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/slot/SlotManagerImplTest.java b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/slot/SlotManagerImplTest.java index e618bc7a7..cb944d7cc 100644 --- a/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/slot/SlotManagerImplTest.java +++ b/server/server/data/src/test/java/com/alipay/sofa/registry/server/data/slot/SlotManagerImplTest.java @@ -26,241 +26,235 @@ import com.alipay.sofa.registry.task.KeyedTask; import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import java.util.*; import org.junit.Assert; import org.junit.Test; import org.mockito.Mockito; -import java.util.*; - public class SlotManagerImplTest { - @Test - public void testUpdate() { - SlotManagerImpl sm = mockSM(10, false, false, Collections.EMPTY_SET).slotManager; - SlotTable slotTable = new SlotTable(1, Collections.emptyList()); - Assert.assertTrue(sm.updateSlotTable(slotTable)); - Assert.assertFalse(sm.updateSlotTable(slotTable)); - - slotTable = newTable_0_1(2, 2); - Assert.assertTrue(sm.updateSlotTable(slotTable)); - - try { - sm.updateSlotTable(newTable_0_1(3, 1)); - Assert.assertTrue(false); - } catch (RuntimeException e) { - Assert.assertTrue(e.getMessage().contains("not expect Slot.LeaderEpoch")); - } - slotTable = newTable_0_1(3, 3); - Assert.assertTrue(sm.updateSlotTable(slotTable)); - - sm.processUpdating(); - Assert.assertEquals(sm.getSlotTableEpoch(), slotTable.getEpoch()); - slotEquals(slotTable, sm); - } - - @Test - public void testSlots() { - Mock mock = mockSM(10, false, false, Collections.EMPTY_SET); - SlotManagerImpl sm = mock.slotManager; - SlotTable slotTable = newTable_0_1(3, 3); - Assert.assertTrue(sm.updateSlotTable(slotTable)); - sm.processUpdating(); - LocalDatumStorage storage = (LocalDatumStorage) mock.mockSync.syncer.getDatumStorage(); - // check slots, 2 slots [0,1] - Assert.assertTrue(storage.updateVersion(0)); - Assert.assertTrue(storage.updateVersion(1)); - Assert.assertFalse(storage.updateVersion(2)); - - Assert.assertTrue(sm.isLeader(0)); - Assert.assertTrue(sm.isFollower(1)); - - Assert.assertFalse(sm.isFollower(0)); - Assert.assertFalse(sm.isLeader(1)); - - slotTable = newTable_1_2(4, 4); - Assert.assertTrue(sm.updateSlotTable(slotTable)); - sm.processUpdating(); - // check slots, 2 slots [1,2] - Assert.assertFalse(storage.updateVersion(0)); - Assert.assertTrue(storage.updateVersion(1)); - Assert.assertTrue(storage.updateVersion(2)); - Assert.assertFalse(storage.updateVersion(3)); - - Assert.assertTrue(sm.isLeader(1)); - Assert.assertTrue(sm.isFollower(2)); - - Assert.assertFalse(sm.isFollower(1)); - Assert.assertFalse(sm.isLeader(2)); - - } - - @Test - public void testCheckAccess() { - Mock mock = mockSM(10, false, false, Collections.EMPTY_SET); - SlotManagerImpl sm = mock.slotManager; - SlotTable slotTable = newTable_0_1(3, 3); - sm.updateSlotTable(slotTable); - sm.processUpdating(); - - SlotAccess access0 = sm.checkSlotAccess(0, 100, slotTable.getSlot(0).getLeaderEpoch()); - Assert.assertTrue(access0.isMigrating()); - SlotAccess access1 = sm.checkSlotAccess(1, 100, slotTable.getSlot(1).getLeaderEpoch()); - Assert.assertTrue(access1.isMoved()); - } - - @Test - public void testCheckAccessFull() { - Mock mock = mockSM(10, false, false, Collections.EMPTY_SET); - SlotManagerImpl sm = mock.slotManager; - SlotAccess access = sm.checkSlotAccess(0, 100, null, 100); - Assert.assertTrue(access.isMoved()); - SlotManagerImpl.SlotState slotState = new SlotManagerImpl.SlotState(createFollower(0, 100)); - access = sm.checkSlotAccess(0, 100, slotState, 100); - Assert.assertTrue(access.isMoved()); - - slotState = new SlotManagerImpl.SlotState(createLeader(0, 100)); - access = sm.checkSlotAccess(0, 100, slotState, 100); - Assert.assertTrue(access.isMigrating()); - - slotState = new SlotManagerImpl.SlotState(createLeader(0, 100)); - slotState.migrated = true; - access = sm.checkSlotAccess(0, 100, slotState, 101); - Assert.assertTrue(access.isMisMatch()); - - slotState = new SlotManagerImpl.SlotState(createLeader(0, 100)); - slotState.migrated = true; - access = sm.checkSlotAccess(0, 100, slotState, 100); - Assert.assertTrue(access.isAccept()); - } - - @Test - public void testSync() throws Exception { - Mock mock = mockSM(10, true, true, Sets.newHashSet("xx1", "xx2")); - SlotManagerImpl sm = mock.slotManager; - Assert.assertEquals(sm.slotOf(mock.mockSync.p1.get(0).getDataInfoId()), 10); - SlotTable slotTable = newTable_0_1(3, 3); - sm.updateSlotTable(slotTable); - sm.processUpdating(); - SlotManagerImpl.SlotState slotState = new SlotManagerImpl.SlotState(createLeader(0, 3)); - slotState.migrated = false; - // migrating - KeyedTask kt = Mockito.mock(KeyedTask.class); - slotState.syncLeaderTask = kt; - - Mockito.when(kt.isFinished()).thenReturn(false); - boolean sync = sm.sync(slotState, 1000, 1000, 100); - Assert.assertFalse(sync); - - Mockito.when(kt.isFinished()).thenReturn(true); - sync = sm.sync(slotState, 1000, 1000, 100); - Assert.assertTrue(sync); - Assert.assertFalse(slotState.migrated); - Assert.assertEquals(slotState.migratingTasks.size(), 2); - Mockito.when(kt.isSuccess()).thenReturn(true); - Thread.sleep(3000); - for (SlotManagerImpl.MigratingTask mt : slotState.migratingTasks.values()) { - Assert.assertTrue(mt.task.isFailed()); - // mock the migrate task success - mt.task = kt; - } - Assert.assertEquals(slotState.syncSessionTasks.size(), 0); - - sync = sm.sync(slotState, 1000, 1000, 100); - Assert.assertTrue(sync); - Assert.assertTrue(slotState.migrated); - - sync = sm.sync(slotState, 1000, 1000, 100); - Assert.assertTrue(sync); - Thread.sleep(2000); - - sync = sm.sync(slotState, 1000, 1000, 100); - Assert.assertTrue(sync); - - // test sync leader - slotState = new SlotManagerImpl.SlotState(createFollower(1, 3)); - slotState.syncLeaderTask = kt; - sync = sm.sync(slotState, 1000, 1000, 100); - Assert.assertTrue(sync); - Mockito.when(kt.isOverAfter(Mockito.anyInt())).thenReturn(true); - sync = sm.sync(slotState, 1000, 1000, 100); - Assert.assertTrue(sync); - Assert.assertTrue(slotState.syncLeaderTask != kt); - Thread.sleep(2000); - Assert.assertTrue(slotState.syncLeaderTask.isFailed()); - - sm.syncWatch(); - Thread.sleep(1000); - List list = sm.getSlotStatuses(); - Assert.assertTrue(list.size() == 2); - - LeaderSlotStatus leaderStatus = (LeaderSlotStatus) list.get(0); - Assert.assertEquals(leaderStatus.getLeaderStatus(), BaseSlotStatus.LeaderStatus.UNHEALTHY); - - FollowerSlotStatus followerstatus = (FollowerSlotStatus) list.get(1); - Assert.assertTrue(followerstatus.getLastSyncTaskStartTime() > 0); - Assert.assertTrue(followerstatus.getLastLeaderSyncTime() <= 0); - - } - - static void slotEquals(SlotTable table, SlotManagerImpl sm) { - Map slotMap = table.getSlotMap(); - for (Slot slot : slotMap.values()) { - Slot s = sm.getSlot(slot.getId()); - Assert.assertEquals(s, slot); - } - Assert.assertEquals(sm.getSlotStatuses().size(), slotMap.size()); - } - - static Slot createLeader(int slotId, long leaderEpoch) { - return new Slot(slotId, ServerEnv.IP, leaderEpoch, Lists.newArrayList("xxx")); - } - - static Slot createFollower(int slotId, long leaderEpoch) { - return new Slot(slotId, "xxx", leaderEpoch, Lists.newArrayList(ServerEnv.IP, "yyy")); + @Test + public void testUpdate() { + SlotManagerImpl sm = mockSM(10, false, false, Collections.EMPTY_SET).slotManager; + SlotTable slotTable = new SlotTable(1, Collections.emptyList()); + Assert.assertTrue(sm.updateSlotTable(slotTable)); + Assert.assertFalse(sm.updateSlotTable(slotTable)); + + slotTable = newTable_0_1(2, 2); + Assert.assertTrue(sm.updateSlotTable(slotTable)); + + try { + sm.updateSlotTable(newTable_0_1(3, 1)); + Assert.assertTrue(false); + } catch (RuntimeException e) { + Assert.assertTrue(e.getMessage().contains("not expect Slot.LeaderEpoch")); } - - static SlotTable newTable_0_1(int tableEpoch, int leaderEpoch) { - Slot slot0 = createLeader(0, leaderEpoch); - Slot slot1 = createFollower(1, leaderEpoch); - SlotTable slotTable = new SlotTable(tableEpoch, Lists.newArrayList(slot0, slot1)); - return slotTable; + slotTable = newTable_0_1(3, 3); + Assert.assertTrue(sm.updateSlotTable(slotTable)); + + sm.processUpdating(); + Assert.assertEquals(sm.getSlotTableEpoch(), slotTable.getEpoch()); + slotEquals(slotTable, sm); + } + + @Test + public void testSlots() { + Mock mock = mockSM(10, false, false, Collections.EMPTY_SET); + SlotManagerImpl sm = mock.slotManager; + SlotTable slotTable = newTable_0_1(3, 3); + Assert.assertTrue(sm.updateSlotTable(slotTable)); + sm.processUpdating(); + LocalDatumStorage storage = (LocalDatumStorage) mock.mockSync.syncer.getDatumStorage(); + // check slots, 2 slots [0,1] + Assert.assertTrue(storage.updateVersion(0)); + Assert.assertTrue(storage.updateVersion(1)); + Assert.assertFalse(storage.updateVersion(2)); + + Assert.assertTrue(sm.isLeader(0)); + Assert.assertTrue(sm.isFollower(1)); + + Assert.assertFalse(sm.isFollower(0)); + Assert.assertFalse(sm.isLeader(1)); + + slotTable = newTable_1_2(4, 4); + Assert.assertTrue(sm.updateSlotTable(slotTable)); + sm.processUpdating(); + // check slots, 2 slots [1,2] + Assert.assertFalse(storage.updateVersion(0)); + Assert.assertTrue(storage.updateVersion(1)); + Assert.assertTrue(storage.updateVersion(2)); + Assert.assertFalse(storage.updateVersion(3)); + + Assert.assertTrue(sm.isLeader(1)); + Assert.assertTrue(sm.isFollower(2)); + + Assert.assertFalse(sm.isFollower(1)); + Assert.assertFalse(sm.isLeader(2)); + } + + @Test + public void testCheckAccess() { + Mock mock = mockSM(10, false, false, Collections.EMPTY_SET); + SlotManagerImpl sm = mock.slotManager; + SlotTable slotTable = newTable_0_1(3, 3); + sm.updateSlotTable(slotTable); + sm.processUpdating(); + + SlotAccess access0 = sm.checkSlotAccess(0, 100, slotTable.getSlot(0).getLeaderEpoch()); + Assert.assertTrue(access0.isMigrating()); + SlotAccess access1 = sm.checkSlotAccess(1, 100, slotTable.getSlot(1).getLeaderEpoch()); + Assert.assertTrue(access1.isMoved()); + } + + @Test + public void testCheckAccessFull() { + Mock mock = mockSM(10, false, false, Collections.EMPTY_SET); + SlotManagerImpl sm = mock.slotManager; + SlotAccess access = sm.checkSlotAccess(0, 100, null, 100); + Assert.assertTrue(access.isMoved()); + SlotManagerImpl.SlotState slotState = new SlotManagerImpl.SlotState(createFollower(0, 100)); + access = sm.checkSlotAccess(0, 100, slotState, 100); + Assert.assertTrue(access.isMoved()); + + slotState = new SlotManagerImpl.SlotState(createLeader(0, 100)); + access = sm.checkSlotAccess(0, 100, slotState, 100); + Assert.assertTrue(access.isMigrating()); + + slotState = new SlotManagerImpl.SlotState(createLeader(0, 100)); + slotState.migrated = true; + access = sm.checkSlotAccess(0, 100, slotState, 101); + Assert.assertTrue(access.isMisMatch()); + + slotState = new SlotManagerImpl.SlotState(createLeader(0, 100)); + slotState.migrated = true; + access = sm.checkSlotAccess(0, 100, slotState, 100); + Assert.assertTrue(access.isAccept()); + } + + @Test + public void testSync() throws Exception { + Mock mock = mockSM(10, true, true, Sets.newHashSet("xx1", "xx2")); + SlotManagerImpl sm = mock.slotManager; + Assert.assertEquals(sm.slotOf(mock.mockSync.p1.get(0).getDataInfoId()), 10); + SlotTable slotTable = newTable_0_1(3, 3); + sm.updateSlotTable(slotTable); + sm.processUpdating(); + SlotManagerImpl.SlotState slotState = new SlotManagerImpl.SlotState(createLeader(0, 3)); + slotState.migrated = false; + // migrating + KeyedTask kt = Mockito.mock(KeyedTask.class); + slotState.syncLeaderTask = kt; + + Mockito.when(kt.isFinished()).thenReturn(false); + boolean sync = sm.sync(slotState, 1000, 1000, 100); + Assert.assertFalse(sync); + + Mockito.when(kt.isFinished()).thenReturn(true); + sync = sm.sync(slotState, 1000, 1000, 100); + Assert.assertTrue(sync); + Assert.assertFalse(slotState.migrated); + Assert.assertEquals(slotState.migratingTasks.size(), 2); + Mockito.when(kt.isSuccess()).thenReturn(true); + Thread.sleep(3000); + for (SlotManagerImpl.MigratingTask mt : slotState.migratingTasks.values()) { + Assert.assertTrue(mt.task.isFailed()); + // mock the migrate task success + mt.task = kt; } - - static SlotTable newTable_1_2(int tableEpoch, int leaderEpoch) { - Slot slot1 = createLeader(1, leaderEpoch); - Slot slot2 = createFollower(2, leaderEpoch); - SlotTable slotTable = new SlotTable(tableEpoch, Lists.newArrayList(slot1, slot2)); - return slotTable; + Assert.assertEquals(slotState.syncSessionTasks.size(), 0); + + sync = sm.sync(slotState, 1000, 1000, 100); + Assert.assertTrue(sync); + Assert.assertTrue(slotState.migrated); + + sync = sm.sync(slotState, 1000, 1000, 100); + Assert.assertTrue(sync); + Thread.sleep(2000); + + sync = sm.sync(slotState, 1000, 1000, 100); + Assert.assertTrue(sync); + + // test sync leader + slotState = new SlotManagerImpl.SlotState(createFollower(1, 3)); + slotState.syncLeaderTask = kt; + sync = sm.sync(slotState, 1000, 1000, 100); + Assert.assertTrue(sync); + Mockito.when(kt.isOverAfter(Mockito.anyInt())).thenReturn(true); + sync = sm.sync(slotState, 1000, 1000, 100); + Assert.assertTrue(sync); + Assert.assertTrue(slotState.syncLeaderTask != kt); + Thread.sleep(2000); + Assert.assertTrue(slotState.syncLeaderTask.isFailed()); + + sm.syncWatch(); + Thread.sleep(1000); + List list = sm.getSlotStatuses(); + Assert.assertTrue(list.size() == 2); + + LeaderSlotStatus leaderStatus = (LeaderSlotStatus) list.get(0); + Assert.assertEquals(leaderStatus.getLeaderStatus(), BaseSlotStatus.LeaderStatus.UNHEALTHY); + + FollowerSlotStatus followerstatus = (FollowerSlotStatus) list.get(1); + Assert.assertTrue(followerstatus.getLastSyncTaskStartTime() > 0); + Assert.assertTrue(followerstatus.getLastLeaderSyncTime() <= 0); + } + + static void slotEquals(SlotTable table, SlotManagerImpl sm) { + Map slotMap = table.getSlotMap(); + for (Slot slot : slotMap.values()) { + Slot s = sm.getSlot(slot.getId()); + Assert.assertEquals(s, slot); } - - static Mock mockSM(int slotId, boolean initSync, boolean initExecutor, Set sessions) { - SlotDiffSyncerTest.MockSync mockSync = SlotDiffSyncerTest.mockSync(slotId, "testDc", - initSync); - SlotDiffSyncer syncer = mockSync.syncer; - SlotManagerImpl slotManager = new SlotManagerImpl(); - slotManager.setDataChangeEventCenter(new DataChangeEventCenter()); - slotManager.setSessionLeaseManager(new SessionLeaseManager()); - slotManager.setSlotGenericResource(new SlotGenericResource()); - slotManager.setLocalDatumStorage(syncer.getDatumStorage()); - slotManager.setDataServerConfig(syncer.getDataServerConfig()); - MetaServerServiceImpl mss = Mockito.mock(MetaServerServiceImpl.class); - Mockito.when(mss.getSessionServerList()).thenReturn(sessions); - slotManager.setMetaServerService(mss); - slotManager.initSlotChangeListener(); - if (initExecutor) { - slotManager.initExecutors(); - } - - Mock mock = new Mock(); - mock.mockSync = mockSync; - mock.slotManager = slotManager; - return mock; + Assert.assertEquals(sm.getSlotStatuses().size(), slotMap.size()); + } + + static Slot createLeader(int slotId, long leaderEpoch) { + return new Slot(slotId, ServerEnv.IP, leaderEpoch, Lists.newArrayList("xxx")); + } + + static Slot createFollower(int slotId, long leaderEpoch) { + return new Slot(slotId, "xxx", leaderEpoch, Lists.newArrayList(ServerEnv.IP, "yyy")); + } + + static SlotTable newTable_0_1(int tableEpoch, int leaderEpoch) { + Slot slot0 = createLeader(0, leaderEpoch); + Slot slot1 = createFollower(1, leaderEpoch); + SlotTable slotTable = new SlotTable(tableEpoch, Lists.newArrayList(slot0, slot1)); + return slotTable; + } + + static SlotTable newTable_1_2(int tableEpoch, int leaderEpoch) { + Slot slot1 = createLeader(1, leaderEpoch); + Slot slot2 = createFollower(2, leaderEpoch); + SlotTable slotTable = new SlotTable(tableEpoch, Lists.newArrayList(slot1, slot2)); + return slotTable; + } + + static Mock mockSM(int slotId, boolean initSync, boolean initExecutor, Set sessions) { + SlotDiffSyncerTest.MockSync mockSync = SlotDiffSyncerTest.mockSync(slotId, "testDc", initSync); + SlotDiffSyncer syncer = mockSync.syncer; + SlotManagerImpl slotManager = new SlotManagerImpl(); + slotManager.setDataChangeEventCenter(new DataChangeEventCenter()); + slotManager.setSessionLeaseManager(new SessionLeaseManager()); + slotManager.setSlotGenericResource(new SlotGenericResource()); + slotManager.setLocalDatumStorage(syncer.getDatumStorage()); + slotManager.setDataServerConfig(syncer.getDataServerConfig()); + MetaServerServiceImpl mss = Mockito.mock(MetaServerServiceImpl.class); + Mockito.when(mss.getSessionServerList()).thenReturn(sessions); + slotManager.setMetaServerService(mss); + slotManager.initSlotChangeListener(); + if (initExecutor) { + slotManager.initExecutors(); } - static final class Mock { - SlotDiffSyncerTest.MockSync mockSync; - SlotManagerImpl slotManager; - - } + Mock mock = new Mock(); + mock.mockSync = mockSync; + mock.slotManager = slotManager; + return mock; + } + static final class Mock { + SlotDiffSyncerTest.MockSync mockSync; + SlotManagerImpl slotManager; + } } diff --git a/server/server/integration/src/main/java/com/alipay/sofa/registry/server/integration/RegistryApplication.java b/server/server/integration/src/main/java/com/alipay/sofa/registry/server/integration/RegistryApplication.java index ca4b6d001..606c247e6 100644 --- a/server/server/integration/src/main/java/com/alipay/sofa/registry/server/integration/RegistryApplication.java +++ b/server/server/integration/src/main/java/com/alipay/sofa/registry/server/integration/RegistryApplication.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.integration; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; + import com.alipay.sofa.registry.common.model.CommonResponse; import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.log.Logger; @@ -30,266 +32,273 @@ import com.alipay.sofa.registry.server.session.bootstrap.SessionServerBootstrap; import com.alipay.sofa.registry.util.FileUtils; import com.alipay.sofa.registry.util.PropertySplitter; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.logging.log4j.util.Strings; -import org.springframework.boot.builder.SpringApplicationBuilder; -import org.springframework.context.ConfigurableApplicationContext; - import java.io.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Collection; - -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.logging.log4j.util.Strings; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.context.ConfigurableApplicationContext; /** * @author xuanbei * @since 2019/2/15 */ public class RegistryApplication { - private static final Logger LOGGER = LoggerFactory - .getLogger(RegistryApplication.class); - private static final String META_HTTP_SERVER_PORT = "meta.server.httpServerPort"; - private static final String DATA_HTTP_SERVER_PORT = "data.server.httpServerPort"; - private static final String SESSION_HTTP_SERVER_PORT = "session.server.httpServerPort"; - private static final String META_NODES = "nodes.metaNode"; - private static final String NODES_LOCAL_DATA_CENTER = "nodes.localDataCenter"; - - private static ConfigurableApplicationContext metaApplicationContext; - private static ConfigurableApplicationContext sessionApplicationContext; - private static ConfigurableApplicationContext dataApplicationContext; - - public static void main(String[] args) throws Exception { - System.setProperty("spring.profiles.active", "integrate"); - System.setProperty("lease.duration", "2"); - // setup DefaultUncaughtExceptionHandler - Thread.setDefaultUncaughtExceptionHandler((t, e) -> { - LOGGER.error(String.format("UncaughtException in Thread(%s): %s", t.getName(), e.getMessage()), e); + private static final Logger LOGGER = LoggerFactory.getLogger(RegistryApplication.class); + private static final String META_HTTP_SERVER_PORT = "meta.server.httpServerPort"; + private static final String DATA_HTTP_SERVER_PORT = "data.server.httpServerPort"; + private static final String SESSION_HTTP_SERVER_PORT = "session.server.httpServerPort"; + private static final String META_NODES = "nodes.metaNode"; + private static final String NODES_LOCAL_DATA_CENTER = "nodes.localDataCenter"; + + private static ConfigurableApplicationContext metaApplicationContext; + private static ConfigurableApplicationContext sessionApplicationContext; + private static ConfigurableApplicationContext dataApplicationContext; + + public static void main(String[] args) throws Exception { + System.setProperty("spring.profiles.active", "integrate"); + System.setProperty("lease.duration", "2"); + // setup DefaultUncaughtExceptionHandler + Thread.setDefaultUncaughtExceptionHandler( + (t, e) -> { + LOGGER.error( + String.format("UncaughtException in Thread(%s): %s", t.getName(), e.getMessage()), e); }); - // start registry application - ConfigurableApplicationContext commonContext = - new SpringApplicationBuilder(RegistryApplication.class).run(args); - - // get all server address list - Collection serverList = getServerList(commonContext); - - String driver = commonContext.getEnvironment().getProperty("jdbc.driverClassName"); - if ("org.h2.Driver".equals(driver)) { - createTables(commonContext); - } - - // start meta - SpringApplicationBuilder springApplicationBuilder = new SpringApplicationBuilder(MetaApplication.class); - springApplicationBuilder.parent(commonContext); - metaApplicationContext = springApplicationBuilder.run(); - - // wait meta cluster start - waitClusterStart(serverList, - Integer.parseInt(commonContext.getEnvironment().getProperty(META_HTTP_SERVER_PORT))); + // start registry application + ConfigurableApplicationContext commonContext = + new SpringApplicationBuilder(RegistryApplication.class).run(args); - // start data - dataApplicationContext = new SpringApplicationBuilder(DataApplication.class).parent(commonContext).run(); + // get all server address list + Collection serverList = getServerList(commonContext); - // wait data cluster start - waitClusterStart(serverList, - Integer.parseInt(commonContext.getEnvironment().getProperty(DATA_HTTP_SERVER_PORT))); - - // start session - sessionApplicationContext = new SpringApplicationBuilder(SessionApplication.class).parent(commonContext).run(); - - // wait session cluster start - waitClusterStart(serverList, - Integer.parseInt(commonContext.getEnvironment().getProperty(SESSION_HTTP_SERVER_PORT))); + String driver = commonContext.getEnvironment().getProperty("jdbc.driverClassName"); + if ("org.h2.Driver".equals(driver)) { + createTables(commonContext); } - public static void stop() { - if (sessionApplicationContext != null) { - sessionApplicationContext.getBean("sessionServerBootstrap", - SessionServerBootstrap.class).destroy(); - } - - if (dataApplicationContext != null) { - dataApplicationContext.getBean("dataServerBootstrap", DataServerBootstrap.class) - .destroy(); - } - - if (metaApplicationContext != null) { - metaApplicationContext.getBean("metaServerBootstrap", MetaServerBootstrap.class) - .destroy(); - } + // start meta + SpringApplicationBuilder springApplicationBuilder = + new SpringApplicationBuilder(MetaApplication.class); + springApplicationBuilder.parent(commonContext); + metaApplicationContext = springApplicationBuilder.run(); + + // wait meta cluster start + waitClusterStart( + serverList, + Integer.parseInt(commonContext.getEnvironment().getProperty(META_HTTP_SERVER_PORT))); + + // start data + dataApplicationContext = + new SpringApplicationBuilder(DataApplication.class).parent(commonContext).run(); + + // wait data cluster start + waitClusterStart( + serverList, + Integer.parseInt(commonContext.getEnvironment().getProperty(DATA_HTTP_SERVER_PORT))); + + // start session + sessionApplicationContext = + new SpringApplicationBuilder(SessionApplication.class).parent(commonContext).run(); + + // wait session cluster start + waitClusterStart( + serverList, + Integer.parseInt(commonContext.getEnvironment().getProperty(SESSION_HTTP_SERVER_PORT))); + } + + public static void stop() { + if (sessionApplicationContext != null) { + sessionApplicationContext + .getBean("sessionServerBootstrap", SessionServerBootstrap.class) + .destroy(); } - private static Collection getServerList(ConfigurableApplicationContext commonContext) { - String metaNodes = commonContext.getEnvironment().getProperty(META_NODES); - String localDataCenter = commonContext.getEnvironment() - .getProperty(NODES_LOCAL_DATA_CENTER); - return new PropertySplitter().mapOfList(metaNodes).get(localDataCenter); + if (dataApplicationContext != null) { + dataApplicationContext.getBean("dataServerBootstrap", DataServerBootstrap.class).destroy(); } - private static void waitClusterStart(Collection serverList, int httpPort) - throws Exception { - for (String serverAddress : serverList) { - while (true) { - if (nodeHealthCheck(serverAddress, httpPort)) { - LOGGER.info("{}:{} health check success.", serverAddress, httpPort); - break; - } - LOGGER.error("{}:{} health check failed.", serverAddress, httpPort); - Thread.sleep(1000); - } - } + if (metaApplicationContext != null) { + metaApplicationContext.getBean("metaServerBootstrap", MetaServerBootstrap.class).destroy(); } - - private static boolean nodeHealthCheck(String serverAddress, int httpPort) { - CommonResponse resp = null; - try { - JerseyClient jerseyClient = JerseyClient.getInstance(); - Channel channel = jerseyClient.connect(new URL(serverAddress, httpPort)); - LOGGER.info("{}:{} health check", serverAddress, httpPort); - resp = channel.getWebTarget().path("health/check").request(APPLICATION_JSON) - .get(CommonResponse.class); - return resp.isSuccess(); - } catch (Throwable t) { - LOGGER.error("{}:{} health check failed. {}", serverAddress, httpPort, resp, t); - return false; + } + + private static Collection getServerList(ConfigurableApplicationContext commonContext) { + String metaNodes = commonContext.getEnvironment().getProperty(META_NODES); + String localDataCenter = commonContext.getEnvironment().getProperty(NODES_LOCAL_DATA_CENTER); + return new PropertySplitter().mapOfList(metaNodes).get(localDataCenter); + } + + private static void waitClusterStart(Collection serverList, int httpPort) + throws Exception { + for (String serverAddress : serverList) { + while (true) { + if (nodeHealthCheck(serverAddress, httpPort)) { + LOGGER.info("{}:{} health check success.", serverAddress, httpPort); + break; } + LOGGER.error("{}:{} health check failed.", serverAddress, httpPort); + Thread.sleep(1000); + } } - - public static ConfigurableApplicationContext getMetaApplicationContext() { - return metaApplicationContext; + } + + private static boolean nodeHealthCheck(String serverAddress, int httpPort) { + CommonResponse resp = null; + try { + JerseyClient jerseyClient = JerseyClient.getInstance(); + Channel channel = jerseyClient.connect(new URL(serverAddress, httpPort)); + LOGGER.info("{}:{} health check", serverAddress, httpPort); + resp = + channel + .getWebTarget() + .path("health/check") + .request(APPLICATION_JSON) + .get(CommonResponse.class); + return resp.isSuccess(); + } catch (Throwable t) { + LOGGER.error("{}:{} health check failed. {}", serverAddress, httpPort, resp, t); + return false; } - - public static ConfigurableApplicationContext getSessionApplicationContext() { - return sessionApplicationContext; + } + + public static ConfigurableApplicationContext getMetaApplicationContext() { + return metaApplicationContext; + } + + public static ConfigurableApplicationContext getSessionApplicationContext() { + return sessionApplicationContext; + } + + public static ConfigurableApplicationContext getDataApplicationContext() { + return dataApplicationContext; + } + + public static FileInputStream openInputStream(File file) throws IOException { + if (file.exists()) { + if (file.isDirectory()) { + throw new IOException("File '" + file + "' exists but is a directory"); + } + if (!file.canRead()) { + throw new IOException("File '" + file + "' cannot be read"); + } + } else { + throw new FileNotFoundException("File '" + file + "' does not exist"); } - - public static ConfigurableApplicationContext getDataApplicationContext() { - return dataApplicationContext; + return new FileInputStream(file); + } + + private static void createTables(ConfigurableApplicationContext commonContext) + throws ClassNotFoundException, SQLException, IOException { + String driver = commonContext.getEnvironment().getProperty("jdbc.driverClassName"); + Class.forName(driver); + String url = commonContext.getEnvironment().getProperty("jdbc.url"); + String username = commonContext.getEnvironment().getProperty("jdbc.username"); + String password = commonContext.getEnvironment().getProperty("jdbc.password"); + Connection connection = null; + try { + connection = DriverManager.getConnection(url, username, password); + executeSqlScript(connection, readFileAsString("sql/h2/create_table.sql")); + } finally { + if (connection != null) { + connection.close(); + } } + } - public static FileInputStream openInputStream(File file) throws IOException { - if (file.exists()) { - if (file.isDirectory()) { - throw new IOException("File '" + file - + "' exists but is a directory"); - } - if (!file.canRead()) { - throw new IOException("File '" + file + "' cannot be read"); - } - } else { - throw new FileNotFoundException("File '" + file - + "' does not exist"); - } - return new FileInputStream(file); - } + public static String readFileAsString(String fileName) throws IOException { - private static void createTables(ConfigurableApplicationContext commonContext) throws ClassNotFoundException, SQLException, IOException { - String driver = commonContext.getEnvironment().getProperty("jdbc.driverClassName"); - Class.forName(driver); - String url = commonContext.getEnvironment().getProperty("jdbc.url"); - String username = commonContext.getEnvironment().getProperty("jdbc.username"); - String password = commonContext.getEnvironment().getProperty("jdbc.password"); - Connection connection = null; - try { - connection = DriverManager.getConnection(url, username, password); - executeSqlScript(connection, readFileAsString("sql/h2/create_table.sql")); - } finally { - if (connection != null) { - connection.close(); - } - } + try (InputStream ins = getFileInputStream(fileName)) { + String fileContent = IOUtils.toString(ins); + return fileContent; } + } - public static String readFileAsString(String fileName) throws IOException{ + public static InputStream getFileInputStream(String fileName) throws FileNotFoundException { - try(InputStream ins = getFileInputStream(fileName)){ - String fileContent = IOUtils.toString(ins); - return fileContent; - } - } + return getFileInputStream("./", fileName, FileUtils.class); + } - public static InputStream getFileInputStream(String fileName) throws FileNotFoundException{ + public static InputStream getFileInputStream(String path, String fileName, Class clazz) + throws FileNotFoundException { - return getFileInputStream("./", fileName, FileUtils.class); + File f = null; + if (path != null) { + f = new File(path + "/" + fileName); + if (f.exists()) { + try { + LOGGER.info("[getFileInputStream]{}", f.getAbsolutePath()); + return new FileInputStream(f); + } catch (IOException e) { + throw new IllegalArgumentException("file load fail:" + f, e); + } + } } - public static InputStream getFileInputStream(String path, String fileName, Class clazz) throws FileNotFoundException{ - - File f = null; - if(path != null){ - f = new File(path+ "/" + fileName); - if(f.exists()){ - try { - LOGGER.info("[getFileInputStream]{}", f.getAbsolutePath()); - return new FileInputStream(f); - } catch (IOException e) { - throw new IllegalArgumentException("file load fail:" + f, e); - } - } - } + // try file + f = new File(fileName); + if (f.exists()) { + try { + LOGGER.info("[getFileInputStream]{}", f.getAbsolutePath()); + return new FileInputStream(f); + } catch (IOException e) { + throw new IllegalArgumentException("file load fail:" + f, e); + } + } - //try file - f = new File(fileName); - if(f.exists()){ - try { - LOGGER.info("[getFileInputStream]{}", f.getAbsolutePath()); - return new FileInputStream(f); - } catch (IOException e) { - throw new IllegalArgumentException("file load fail:" + f, e); - } - } + // try classpath + java.net.URL url = clazz.getResource(fileName); + if (url == null) { + url = clazz.getClassLoader().getResource(fileName); + } + if (url != null) { + try { + LOGGER.info("[load]{}", url); + return url.openStream(); + } catch (IOException e) { + throw new IllegalArgumentException("classpath load fail:" + url, e); + } + } - //try classpath - java.net.URL url = clazz.getResource(fileName); - if(url == null){ - url = clazz.getClassLoader().getResource(fileName); - } - if(url != null){ - try { - LOGGER.info("[load]{}", url); - return url.openStream(); - } catch (IOException e) { - throw new IllegalArgumentException("classpath load fail:" + url, e); - } - } + throw new FileNotFoundException(path + "," + fileName); + } - throw new FileNotFoundException(path + "," + fileName); + protected static void executeSqlScript(Connection connection, String prepareSql) + throws SQLException { + if (StringUtils.isEmpty(prepareSql)) { + return; } - - protected static void executeSqlScript(Connection connection, String prepareSql) throws SQLException { - if (StringUtils.isEmpty(prepareSql)) { - return; - } - java.sql.Connection conn = connection; - PreparedStatement stmt = null; - try { - conn.setAutoCommit(false); - if (!Strings.isEmpty(prepareSql)) { - for (String sql : prepareSql.split(";")) { - LOGGER.debug("[setup][data]{}", sql.trim()); - stmt = conn.prepareStatement(sql); - stmt.executeUpdate(); - } - } - conn.commit(); - - } catch (Exception ex) { - LOGGER.error("[SetUpTestDataSource][fail]:", ex); - if (null != conn) { - conn.rollback(); - } - } finally { - if (null != stmt) { - stmt.close(); - } - if (null != conn) { - conn.setAutoCommit(true); - conn.close(); - } + java.sql.Connection conn = connection; + PreparedStatement stmt = null; + try { + conn.setAutoCommit(false); + if (!Strings.isEmpty(prepareSql)) { + for (String sql : prepareSql.split(";")) { + LOGGER.debug("[setup][data]{}", sql.trim()); + stmt = conn.prepareStatement(sql); + stmt.executeUpdate(); } + } + conn.commit(); + + } catch (Exception ex) { + LOGGER.error("[SetUpTestDataSource][fail]:", ex); + if (null != conn) { + conn.rollback(); + } + } finally { + if (null != stmt) { + stmt.close(); + } + if (null != conn) { + conn.setAutoCommit(true); + conn.close(); + } } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaApplication.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaApplication.java index 92f570cae..c3cf804bf 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaApplication.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaApplication.java @@ -24,22 +24,23 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; /** - * * @author zhuoyu.sjw * @version $Id: MetaApplication.java, v 0.1 2017-11-13 19:03 zhuoyu.sjw Exp $$ */ @EnableMetaServer -@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class MetaApplication { - private static final Logger LOGGER = LoggerFactory.getLogger(MetaApplication.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MetaApplication.class); - public static void main(String[] args) { - // setup DefaultUncaughtExceptionHandler - Thread.setDefaultUncaughtExceptionHandler((t, e) -> { - LOGGER.error(String.format("UncaughtException in Thread(%s): %s", t.getName(), e.getMessage()), e); + public static void main(String[] args) { + // setup DefaultUncaughtExceptionHandler + Thread.setDefaultUncaughtExceptionHandler( + (t, e) -> { + LOGGER.error( + String.format("UncaughtException in Thread(%s): %s", t.getName(), e.getMessage()), e); }); - SpringApplication.run(MetaApplication.class, args); - } + SpringApplication.run(MetaApplication.class, args); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaLeaderService.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaLeaderService.java index 3cf3e877e..98407b3b8 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaLeaderService.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaLeaderService.java @@ -18,53 +18,51 @@ /** * @author chen.zhu - *

- * Mar 10, 2021 + *

Mar 10, 2021 */ public interface MetaLeaderService { - /** - * Am i elector boolean. - * - * @return the boolean - */ - boolean amILeader(); + /** + * Am i elector boolean. + * + * @return the boolean + */ + boolean amILeader(); - /** - * Gets get elector. - * - * @return the get elector - */ - String getLeader(); + /** + * Gets get elector. + * + * @return the get elector + */ + String getLeader(); + /** + * Gets get elector epoch. + * + * @return the get elector epoch + */ + long getLeaderEpoch(); - /** - * Gets get elector epoch. - * - * @return the get elector epoch - */ - long getLeaderEpoch(); + /** + * Gets get meta server elector state. + * + * @return the get meta server elector state + */ + boolean isWarmup(); - /** - * Gets get meta server elector state. - * - * @return the get meta server elector state - */ - boolean isWarmup(); + /** + * Am i stable as elector boolean. + * + * @return the boolean + */ + default boolean amIStableAsLeader() { + return amILeader() && !isWarmup(); + } - /** - * Am i stable as elector boolean. - * - * @return the boolean - */ - default boolean amIStableAsLeader() { - return amILeader() && !isWarmup(); - } + public interface MetaLeaderElectorListener { - public interface MetaLeaderElectorListener { + void becomeLeader(); - void becomeLeader(); - - void loseLeader(); - } + void loseLeader(); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaServer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaServer.java index 2b72627e3..7fe92ff0c 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaServer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/MetaServer.java @@ -21,9 +21,6 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ -public interface MetaServer extends SlotTableAware, Lifecycle { - -} +public interface MetaServer extends SlotTableAware, Lifecycle {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/EnableMetaServer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/EnableMetaServer.java index 95c144b6f..5f6feee3f 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/EnableMetaServer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/EnableMetaServer.java @@ -16,12 +16,10 @@ */ package com.alipay.sofa.registry.server.meta.bootstrap; -import org.springframework.context.annotation.Import; - import java.lang.annotation.*; +import org.springframework.context.annotation.Import; /** - * * @author shangyu.wh * @version $Id: EnableMetaServer.java, v 0.1 2018-01-16 11:26 shangyu.wh Exp $ */ @@ -29,5 +27,4 @@ @Retention(RetentionPolicy.RUNTIME) @Documented @Import(MetaServerConfiguration.class) -public @interface EnableMetaServer { -} \ No newline at end of file +public @interface EnableMetaServer {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerBootstrap.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerBootstrap.java index bb4444a0d..692ffab87 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerBootstrap.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerBootstrap.java @@ -36,271 +36,264 @@ import com.github.rholder.retry.StopStrategies; import com.github.rholder.retry.WaitStrategies; import com.google.common.base.Predicate; -import org.apache.commons.lang.StringUtils; -import org.glassfish.jersey.server.ResourceConfig; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; - -import javax.ws.rs.Path; -import javax.ws.rs.ext.Provider; import java.lang.annotation.Annotation; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import javax.ws.rs.Path; +import javax.ws.rs.ext.Provider; +import org.apache.commons.lang.StringUtils; +import org.glassfish.jersey.server.ResourceConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; /** - * * @author shangyu.wh * @version $Id: MetaServerBootstrap.java, v 0.1 2018-01-16 11:28 shangyu.wh Exp $ */ public class MetaServerBootstrap { - private static final Logger LOGGER = LoggerFactory - .getLogger(MetaServerBootstrap.class); - - @Autowired - private MetaServerConfig metaServerConfig; + private static final Logger LOGGER = LoggerFactory.getLogger(MetaServerBootstrap.class); - @Autowired - private BoltExchange boltExchange; + @Autowired private MetaServerConfig metaServerConfig; - @Autowired - private JerseyExchange jerseyExchange; + @Autowired private BoltExchange boltExchange; - @Autowired - private List sessionServerHandlers; + @Autowired private JerseyExchange jerseyExchange; - @Autowired - private List dataServerHandlers; + @Autowired private List sessionServerHandlers; - @Autowired - private List metaServerHandlers; + @Autowired private List dataServerHandlers; - @Autowired - private ResourceConfig jerseyResourceConfig; + @Autowired private List metaServerHandlers; - @Autowired - private ApplicationContext applicationContext; + @Autowired private ResourceConfig jerseyResourceConfig; - @Autowired - private LeaderElector leaderElector; + @Autowired private ApplicationContext applicationContext; + @Autowired private LeaderElector leaderElector; - private Server sessionServer; + private Server sessionServer; - private Server dataServer; + private Server dataServer; - private Server metaServer; + private Server metaServer; - private Server httpServer; + private Server httpServer; - private final AtomicBoolean sessionStart = new AtomicBoolean(false); + private final AtomicBoolean sessionStart = new AtomicBoolean(false); - private final AtomicBoolean dataStart = new AtomicBoolean(false); + private final AtomicBoolean dataStart = new AtomicBoolean(false); - private final AtomicBoolean metaStart = new AtomicBoolean(false); + private final AtomicBoolean metaStart = new AtomicBoolean(false); - private final AtomicBoolean httpStart = new AtomicBoolean(false); + private final AtomicBoolean httpStart = new AtomicBoolean(false); - private final Retryer retryer = RetryerBuilder - . newBuilder() - .retryIfException() - .retryIfResult(new Predicate() { + private final Retryer retryer = + RetryerBuilder.newBuilder() + .retryIfException() + .retryIfResult( + new Predicate() { @Override public boolean apply(Boolean input) { - return !input; + return !input; } - }) - .withWaitStrategy( - WaitStrategies - .exponentialWait( - 1000, - 10000, - TimeUnit.MILLISECONDS)) - .withStopStrategy( - StopStrategies - .stopAfterAttempt(10)) - .build(); - /** - * Do initialized. - */ - public void start() { - try { - LOGGER.info("the configuration items are as follows: " + metaServerConfig.toString()); - ReporterUtils.enablePrometheusDefaultExports(); - - openSessionRegisterServer(); - - openDataRegisterServer(); - - openMetaRegisterServer(); - - openHttpServer(); - - retryer.call(()->{ - return !StringUtils.isEmpty(leaderElector.getLeader()) - && leaderElector.getLeaderEpoch() != AbstractLeaderElector.LeaderInfo.initEpoch; - }); - LOGGER.warn("[MetaBootstrap] leader info: {}, [{}]", leaderElector.getLeader(), leaderElector.getLeaderEpoch()); - Runtime.getRuntime().addShutdownHook(new Thread(this::doStop)); - } catch (Throwable e) { - LOGGER.error("Bootstrap Meta Server got error!", e); - throw new RuntimeException("Bootstrap Meta Server got error!", e); - } + }) + .withWaitStrategy(WaitStrategies.exponentialWait(1000, 10000, TimeUnit.MILLISECONDS)) + .withStopStrategy(StopStrategies.stopAfterAttempt(10)) + .build(); + /** Do initialized. */ + public void start() { + try { + LOGGER.info("the configuration items are as follows: " + metaServerConfig.toString()); + ReporterUtils.enablePrometheusDefaultExports(); + + openSessionRegisterServer(); + + openDataRegisterServer(); + + openMetaRegisterServer(); + + openHttpServer(); + + retryer.call( + () -> { + return !StringUtils.isEmpty(leaderElector.getLeader()) + && leaderElector.getLeaderEpoch() != AbstractLeaderElector.LeaderInfo.initEpoch; + }); + LOGGER.warn( + "[MetaBootstrap] leader info: {}, [{}]", + leaderElector.getLeader(), + leaderElector.getLeaderEpoch()); + Runtime.getRuntime().addShutdownHook(new Thread(this::doStop)); + } catch (Throwable e) { + LOGGER.error("Bootstrap Meta Server got error!", e); + throw new RuntimeException("Bootstrap Meta Server got error!", e); } + } - public void destroy() { - doStop(); - } + public void destroy() { + doStop(); + } - private void doStop() { - try { - LOGGER.info("{} Shutting down Meta Server..", new Date().toString()); + private void doStop() { + try { + LOGGER.info("{} Shutting down Meta Server..", new Date().toString()); - stopServer(); + stopServer(); - } catch (Throwable e) { - LOGGER.error("Shutting down Meta Server error!", e); - } - LOGGER.info("{} Meta server is now shutdown...", new Date().toString()); + } catch (Throwable e) { + LOGGER.error("Shutting down Meta Server error!", e); } - - private void openSessionRegisterServer() { - try { - if (sessionStart.compareAndSet(false, true)) { - sessionServer = boltExchange - .open( - new URL(NetUtil.getLocalAddress().getHostAddress(), metaServerConfig - .getSessionServerPort()), sessionServerHandlers - .toArray(new ChannelHandler[sessionServerHandlers.size()])); - - LOGGER.info("Open session node register server port {} success!", - metaServerConfig.getSessionServerPort()); - } - } catch (Exception e) { - sessionStart.set(false); - LOGGER.error("Open session node register server port {} error!", - metaServerConfig.getSessionServerPort(), e); - throw new RuntimeException("Open session node register server error!", e); - } + LOGGER.info("{} Meta server is now shutdown...", new Date().toString()); + } + + private void openSessionRegisterServer() { + try { + if (sessionStart.compareAndSet(false, true)) { + sessionServer = + boltExchange.open( + new URL( + NetUtil.getLocalAddress().getHostAddress(), + metaServerConfig.getSessionServerPort()), + sessionServerHandlers.toArray(new ChannelHandler[sessionServerHandlers.size()])); + + LOGGER.info( + "Open session node register server port {} success!", + metaServerConfig.getSessionServerPort()); + } + } catch (Exception e) { + sessionStart.set(false); + LOGGER.error( + "Open session node register server port {} error!", + metaServerConfig.getSessionServerPort(), + e); + throw new RuntimeException("Open session node register server error!", e); } - - private void openDataRegisterServer() { - try { - if (dataStart.compareAndSet(false, true)) { - dataServer = boltExchange.open(new URL(NetUtil.getLocalAddress().getHostAddress(), - metaServerConfig.getDataServerPort()), dataServerHandlers - .toArray(new ChannelHandler[dataServerHandlers.size()])); - - LOGGER.info("Open data node register server port {} success!", - metaServerConfig.getDataServerPort()); - } - } catch (Exception e) { - dataStart.set(false); - LOGGER.error("Open data node register server port {} error!", - metaServerConfig.getDataServerPort(), e); - throw new RuntimeException("Open data node register server error!", e); - } + } + + private void openDataRegisterServer() { + try { + if (dataStart.compareAndSet(false, true)) { + dataServer = + boltExchange.open( + new URL( + NetUtil.getLocalAddress().getHostAddress(), + metaServerConfig.getDataServerPort()), + dataServerHandlers.toArray(new ChannelHandler[dataServerHandlers.size()])); + + LOGGER.info( + "Open data node register server port {} success!", + metaServerConfig.getDataServerPort()); + } + } catch (Exception e) { + dataStart.set(false); + LOGGER.error( + "Open data node register server port {} error!", metaServerConfig.getDataServerPort(), e); + throw new RuntimeException("Open data node register server error!", e); } - - private void openMetaRegisterServer() { - try { - if (metaStart.compareAndSet(false, true)) { - metaServer = boltExchange.open(new URL(NetUtil.getLocalAddress().getHostAddress(), - metaServerConfig.getMetaServerPort()), metaServerHandlers - .toArray(new ChannelHandler[metaServerHandlers.size()])); - - LOGGER.info("Open meta server port {} success!", - metaServerConfig.getMetaServerPort()); - } - } catch (Exception e) { - metaStart.set(false); - LOGGER - .error("Open meta server port {} error!", metaServerConfig.getMetaServerPort(), e); - throw new RuntimeException("Open meta server error!", e); - } + } + + private void openMetaRegisterServer() { + try { + if (metaStart.compareAndSet(false, true)) { + metaServer = + boltExchange.open( + new URL( + NetUtil.getLocalAddress().getHostAddress(), + metaServerConfig.getMetaServerPort()), + metaServerHandlers.toArray(new ChannelHandler[metaServerHandlers.size()])); + + LOGGER.info("Open meta server port {} success!", metaServerConfig.getMetaServerPort()); + } + } catch (Exception e) { + metaStart.set(false); + LOGGER.error("Open meta server port {} error!", metaServerConfig.getMetaServerPort(), e); + throw new RuntimeException("Open meta server error!", e); } - - private void openHttpServer() { - try { - if (httpStart.compareAndSet(false, true)) { - bindResourceConfig(); - httpServer = jerseyExchange.open( - new URL(NetUtil.getLocalAddress().getHostAddress(), metaServerConfig - .getHttpServerPort()), new ResourceConfig[] { jerseyResourceConfig }); - LOGGER.info("Open http server port {} success!", - metaServerConfig.getHttpServerPort()); - } - } catch (Exception e) { - httpStart.set(false); - LOGGER - .error("Open http server port {} error!", metaServerConfig.getHttpServerPort(), e); - throw new RuntimeException("Open http server error!", e); - } + } + + private void openHttpServer() { + try { + if (httpStart.compareAndSet(false, true)) { + bindResourceConfig(); + httpServer = + jerseyExchange.open( + new URL( + NetUtil.getLocalAddress().getHostAddress(), + metaServerConfig.getHttpServerPort()), + new ResourceConfig[] {jerseyResourceConfig}); + LOGGER.info("Open http server port {} success!", metaServerConfig.getHttpServerPort()); + } + } catch (Exception e) { + httpStart.set(false); + LOGGER.error("Open http server port {} error!", metaServerConfig.getHttpServerPort(), e); + throw new RuntimeException("Open http server error!", e); } + } - private void bindResourceConfig() { - registerInstances(Path.class); - registerInstances(Provider.class); - } - - private void registerInstances(Class annotationType) { - Map beans = applicationContext.getBeansWithAnnotation(annotationType); - if (beans != null && beans.size() > 0) { - beans.forEach((beanName, bean) -> jerseyResourceConfig.registerInstances(bean)); - } - } + private void bindResourceConfig() { + registerInstances(Path.class); + registerInstances(Provider.class); + } - private void stopServer() { - if (sessionServer != null && sessionServer.isOpen()) { - sessionServer.close(); - } - if (dataServer != null && dataServer.isOpen()) { - dataServer.close(); - } - if (metaServer != null && metaServer.isOpen()) { - metaServer.close(); - } - if (httpServer != null && httpServer.isOpen()) { - httpServer.close(); - } + private void registerInstances(Class annotationType) { + Map beans = applicationContext.getBeansWithAnnotation(annotationType); + if (beans != null && beans.size() > 0) { + beans.forEach((beanName, bean) -> jerseyResourceConfig.registerInstances(bean)); } + } - /** - * Getter method for property sessionStart. - * - * @return property value of sessionStart - */ - public boolean getSessionStart() { - return sessionStart.get(); + private void stopServer() { + if (sessionServer != null && sessionServer.isOpen()) { + sessionServer.close(); } - - /** - * Getter method for property dataStart. - * - * @return property value of dataStart - */ - public boolean getDataStart() { - return dataStart.get(); + if (dataServer != null && dataServer.isOpen()) { + dataServer.close(); } - - /** - * Getter method for property metaStart. - * - * @return property value of metaStart - */ - public boolean getMetaStart() { - return metaStart.get(); + if (metaServer != null && metaServer.isOpen()) { + metaServer.close(); } - - /** - * Getter method for property httpStart. - * - * @return property value of httpStart - */ - public boolean getHttpStart() { - return httpStart.get(); + if (httpServer != null && httpServer.isOpen()) { + httpServer.close(); } -} \ No newline at end of file + } + + /** + * Getter method for property sessionStart. + * + * @return property value of sessionStart + */ + public boolean getSessionStart() { + return sessionStart.get(); + } + + /** + * Getter method for property dataStart. + * + * @return property value of dataStart + */ + public boolean getDataStart() { + return dataStart.get(); + } + + /** + * Getter method for property metaStart. + * + * @return property value of metaStart + */ + public boolean getMetaStart() { + return metaStart.get(); + } + + /** + * Getter method for property httpStart. + * + * @return property value of httpStart + */ + public boolean getHttpStart() { + return httpStart.get(); + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerConfiguration.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerConfiguration.java index b0756e2e0..1529ea418 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerConfiguration.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerConfiguration.java @@ -35,6 +35,7 @@ import com.alipay.sofa.registry.util.NamedThreadFactory; import com.alipay.sofa.registry.util.OsUtils; import com.alipay.sofa.registry.util.PropertySplitter; +import java.util.concurrent.*; import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.server.ResourceConfig; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -44,174 +45,180 @@ import org.springframework.context.annotation.Import; import org.springframework.context.annotation.Profile; -import java.util.concurrent.*; - /** * @author shangyu.wh * @version $Id: MetaServerConfiguration.java, v 0.1 2018-01-12 14:53 shangyu.wh Exp $ */ @Configuration -@Import({ MetaServerInitializerConfiguration.class, JdbcConfiguration.class, - RaftConfiguration.class }) +@Import({ + MetaServerInitializerConfiguration.class, + JdbcConfiguration.class, + RaftConfiguration.class +}) @EnableConfigurationProperties public class MetaServerConfiguration { - public static final String SHARED_SCHEDULE_EXECUTOR = "sharedScheduleExecutor"; - public static final String GLOBAL_EXECUTOR = "globalExecutor"; + public static final String SHARED_SCHEDULE_EXECUTOR = "sharedScheduleExecutor"; + public static final String GLOBAL_EXECUTOR = "globalExecutor"; + @Bean + @ConditionalOnMissingBean + public MetaServerBootstrap metaServerBootstrap() { + return new MetaServerBootstrap(); + } + + @Configuration + protected static class MetaServerConfigBeanConfiguration { @Bean @ConditionalOnMissingBean - public MetaServerBootstrap metaServerBootstrap() { - return new MetaServerBootstrap(); - } - - @Configuration - protected static class MetaServerConfigBeanConfiguration { - @Bean - @ConditionalOnMissingBean - public MetaServerConfig metaServerConfig() { - return new MetaServerConfigBean(); - } - - @Bean - public NodeConfig nodeConfig() { - return new NodeConfigBeanProperty(); - } - - @Bean(name = "PropertySplitter") - public PropertySplitter propertySplitter() { - return new PropertySplitter(); - } - } - - @Configuration - public static class ThreadPoolResourceConfiguration { - @Bean(name = GLOBAL_EXECUTOR) - public ExecutorService getGlobalExecutorService() { - int corePoolSize = Math.min(OsUtils.getCpuCount() * 2, 8); - int maxPoolSize = 50 * OsUtils.getCpuCount(); - DefaultExecutorFactory executorFactory = new DefaultExecutorFactory(GLOBAL_EXECUTOR, - corePoolSize, maxPoolSize, new ThreadPoolExecutor.AbortPolicy()); - return executorFactory.create(); - } - - @Bean(name = SHARED_SCHEDULE_EXECUTOR) - public ScheduledExecutorService getScheduledService() { - return new ScheduledThreadPoolExecutor(Math.min(OsUtils.getCpuCount() * 2, 12), - new NamedThreadFactory("MetaServerGlobalScheduler")); - } - } - - @Configuration - public static class MetaServerRemotingConfiguration { - - @Bean - public BoltExchange boltExchange() { - return new BoltExchange(); - } - - @Bean - public JerseyExchange jerseyExchange() { - return new JerseyExchange(); - } - - } - - @Configuration - public static class ResourceConfiguration { - - @Bean - public ResourceConfig jerseyResourceConfig() { - ResourceConfig resourceConfig = new ResourceConfig(); - resourceConfig.register(JacksonFeature.class); - return resourceConfig; - } - - @Bean - public LeaderAwareFilter leaderAwareFilter() { - return new LeaderAwareFilter(); - } - - @Bean - public ProvideDataResource provideDataResource() { - return new ProvideDataResource(); - } - - @Bean - public MetaDigestResource metaDigestResource() { - return new MetaDigestResource(); - } - - @Bean - public HealthResource healthResource() { - return new HealthResource(); - } - - @Bean - @ConditionalOnMissingBean - public StopPushDataResource stopPushDataResource() { - return new StopPushDataResource(); - } - - @Bean - public BlacklistDataResource blacklistDataResource() { - return new BlacklistDataResource(); - } - - @Bean - public SlotSyncResource renewSwitchResource() { - return new SlotSyncResource(); - } - - @Bean - public SlotTableResource slotTableResource() { - return new SlotTableResource(); - } - - @Bean - public SlotGenericResource slotResource() { - return new SlotGenericResource(); - } - - @Bean - public MetricsResource metricsResource() { - return new MetricsResource(); - } - } - - @Configuration - public static class ExecutorConfiguation { - - @Bean - public ThreadPoolExecutor defaultRequestExecutor(MetaServerConfig metaServerConfig) { - ThreadPoolExecutor defaultRequestExecutor = new MetricsableThreadPoolExecutor( - "MetaHandlerDefaultExecutor", metaServerConfig.getDefaultRequestExecutorMinSize(), - metaServerConfig.getDefaultRequestExecutorMaxSize(), 300, TimeUnit.SECONDS, - new LinkedBlockingQueue<>(metaServerConfig.getDefaultRequestExecutorQueueSize()), - new NamedThreadFactory("MetaHandler-DefaultRequest")); - defaultRequestExecutor.allowCoreThreadTimeOut(true); - return defaultRequestExecutor; - } - } - - @Configuration - public static class MetaPersistenceConfiguration { - - @Bean - public RepositoryConfig repositoryConfig() { - return new RepositoryConfig(); - } - - @Bean - @Profile(SpringContext.META_STORE_API_JDBC) - public JdbcConfiguration jdbcConfiguration() { - return new JdbcConfiguration(); - } - - @Bean - @Profile(SpringContext.META_STORE_API_RAFT) - public RaftConfiguration raftConfiguration() { - return new RaftConfiguration(); - } - } -} \ No newline at end of file + public MetaServerConfig metaServerConfig() { + return new MetaServerConfigBean(); + } + + @Bean + public NodeConfig nodeConfig() { + return new NodeConfigBeanProperty(); + } + + @Bean(name = "PropertySplitter") + public PropertySplitter propertySplitter() { + return new PropertySplitter(); + } + } + + @Configuration + public static class ThreadPoolResourceConfiguration { + @Bean(name = GLOBAL_EXECUTOR) + public ExecutorService getGlobalExecutorService() { + int corePoolSize = Math.min(OsUtils.getCpuCount() * 2, 8); + int maxPoolSize = 50 * OsUtils.getCpuCount(); + DefaultExecutorFactory executorFactory = + new DefaultExecutorFactory( + GLOBAL_EXECUTOR, corePoolSize, maxPoolSize, new ThreadPoolExecutor.AbortPolicy()); + return executorFactory.create(); + } + + @Bean(name = SHARED_SCHEDULE_EXECUTOR) + public ScheduledExecutorService getScheduledService() { + return new ScheduledThreadPoolExecutor( + Math.min(OsUtils.getCpuCount() * 2, 12), + new NamedThreadFactory("MetaServerGlobalScheduler")); + } + } + + @Configuration + public static class MetaServerRemotingConfiguration { + + @Bean + public BoltExchange boltExchange() { + return new BoltExchange(); + } + + @Bean + public JerseyExchange jerseyExchange() { + return new JerseyExchange(); + } + } + + @Configuration + public static class ResourceConfiguration { + + @Bean + public ResourceConfig jerseyResourceConfig() { + ResourceConfig resourceConfig = new ResourceConfig(); + resourceConfig.register(JacksonFeature.class); + return resourceConfig; + } + + @Bean + public LeaderAwareFilter leaderAwareFilter() { + return new LeaderAwareFilter(); + } + + @Bean + public ProvideDataResource provideDataResource() { + return new ProvideDataResource(); + } + + @Bean + public MetaDigestResource metaDigestResource() { + return new MetaDigestResource(); + } + + @Bean + public HealthResource healthResource() { + return new HealthResource(); + } + + @Bean + @ConditionalOnMissingBean + public StopPushDataResource stopPushDataResource() { + return new StopPushDataResource(); + } + + @Bean + public BlacklistDataResource blacklistDataResource() { + return new BlacklistDataResource(); + } + + @Bean + public SlotSyncResource renewSwitchResource() { + return new SlotSyncResource(); + } + + @Bean + public SlotTableResource slotTableResource() { + return new SlotTableResource(); + } + + @Bean + public SlotGenericResource slotResource() { + return new SlotGenericResource(); + } + + @Bean + public MetricsResource metricsResource() { + return new MetricsResource(); + } + } + + @Configuration + public static class ExecutorConfiguation { + + @Bean + public ThreadPoolExecutor defaultRequestExecutor(MetaServerConfig metaServerConfig) { + ThreadPoolExecutor defaultRequestExecutor = + new MetricsableThreadPoolExecutor( + "MetaHandlerDefaultExecutor", + metaServerConfig.getDefaultRequestExecutorMinSize(), + metaServerConfig.getDefaultRequestExecutorMaxSize(), + 300, + TimeUnit.SECONDS, + new LinkedBlockingQueue<>(metaServerConfig.getDefaultRequestExecutorQueueSize()), + new NamedThreadFactory("MetaHandler-DefaultRequest")); + defaultRequestExecutor.allowCoreThreadTimeOut(true); + return defaultRequestExecutor; + } + } + + @Configuration + public static class MetaPersistenceConfiguration { + + @Bean + public RepositoryConfig repositoryConfig() { + return new RepositoryConfig(); + } + + @Bean + @Profile(SpringContext.META_STORE_API_JDBC) + public JdbcConfiguration jdbcConfiguration() { + return new JdbcConfiguration(); + } + + @Bean + @Profile(SpringContext.META_STORE_API_RAFT) + public RaftConfiguration raftConfiguration() { + return new RaftConfiguration(); + } + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerInitializerConfiguration.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerInitializerConfiguration.java index d635c77a4..95a7d04f1 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerInitializerConfiguration.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/MetaServerInitializerConfiguration.java @@ -18,65 +18,61 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; +import java.util.concurrent.atomic.AtomicBoolean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.SmartLifecycle; -import java.util.concurrent.atomic.AtomicBoolean; - /** - * * @author shangyu.wh * @version $Id: MetaServerInitializerConfiguration.java, v 0.1 2018-01-16 11:27 shangyu.wh Exp $ */ public class MetaServerInitializerConfiguration implements SmartLifecycle { - private static final Logger LOGGER = LoggerFactory - .getLogger(MetaServerInitializerConfiguration.class); - - private AtomicBoolean running = new AtomicBoolean(false); + private static final Logger LOGGER = + LoggerFactory.getLogger(MetaServerInitializerConfiguration.class); - @Autowired - private MetaServerBootstrap metaServerBootstrap; + private AtomicBoolean running = new AtomicBoolean(false); - @Override - public boolean isAutoStartup() { - return true; - } + @Autowired private MetaServerBootstrap metaServerBootstrap; - @Override - public void start() { + @Override + public boolean isAutoStartup() { + return true; + } - try { - metaServerBootstrap.start(); - LOGGER.info("Started MetaServer"); + @Override + public void start() { - MetaServerInitializerConfiguration.this.running.set(true); - } catch (Exception ex) { - MetaServerInitializerConfiguration.this.running.set(false); - LOGGER.error("Could not initialize Meta server!", ex); - } + try { + metaServerBootstrap.start(); + LOGGER.info("Started MetaServer"); + MetaServerInitializerConfiguration.this.running.set(true); + } catch (Exception ex) { + MetaServerInitializerConfiguration.this.running.set(false); + LOGGER.error("Could not initialize Meta server!", ex); } + } - @Override - public void stop() { - this.running.set(false); - metaServerBootstrap.destroy(); - } + @Override + public void stop() { + this.running.set(false); + metaServerBootstrap.destroy(); + } - @Override - public boolean isRunning() { - return this.running.get(); - } + @Override + public boolean isRunning() { + return this.running.get(); + } - @Override - public int getPhase() { - return 0; - } + @Override + public int getPhase() { + return 0; + } - @Override - public void stop(Runnable callback) { - callback.run(); - this.running.set(false); - } -} \ No newline at end of file + @Override + public void stop(Runnable callback) { + callback.run(); + this.running.set(false); + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/AbstractNodeConfigBean.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/AbstractNodeConfigBean.java index 70f406684..f9c2a6182 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/AbstractNodeConfigBean.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/AbstractNodeConfigBean.java @@ -19,103 +19,103 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.net.NetUtil; - import java.util.*; import java.util.concurrent.atomic.AtomicReference; /** - * * @author shangyu.wh * @version $Id: AbstractNodeConfigBean.java, v 0.1 2018-05-03 16:14 shangyu.wh Exp $ */ public abstract class AbstractNodeConfigBean implements NodeConfig { - private static final Logger LOGGER = LoggerFactory - .getLogger(AbstractNodeConfigBean.class); + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractNodeConfigBean.class); - protected Map> metaNodeIP; + protected Map> metaNodeIP; - private Map dataCenterMetaIPCache = new HashMap<>(); + private Map dataCenterMetaIPCache = new HashMap<>(); - /** - * Getter method for property metaNodeIP. - * - * @return property value of metaNodeIP - */ - @Override - public Map> getMetaNodeIP() { - if (metaNodeIP == null || metaNodeIP.isEmpty()) { - metaNodeIP = convertToIP(getMetaNode()); - } - return metaNodeIP; + /** + * Getter method for property metaNodeIP. + * + * @return property value of metaNodeIP + */ + @Override + public Map> getMetaNodeIP() { + if (metaNodeIP == null || metaNodeIP.isEmpty()) { + metaNodeIP = convertToIP(getMetaNode()); } - - private Map> convertToIP(Map> input) { - - Map> ret = new HashMap<>(); - try { - - if (input != null) { - input.forEach((dataCenter, domains) -> { - if (domains != null) { - List ipList = new ArrayList<>(); - domains.forEach((domain) -> { - if (domain != null) { - String ip = NetUtil.getIPAddressFromDomain(domain); - if (ip == null) { - LOGGER.error("Node config convert domain {} error!", domain); - throw new RuntimeException("Node config convert domain {" + domain + "} error!"); - } - ipList.add(ip); - } - }); - ret.put(dataCenter, ipList); - } - }); - } - } catch (Exception e) { - LOGGER.error("Node config convert domain error!", e); - throw new RuntimeException("Node config convert domain error!", e); - } - return ret; + return metaNodeIP; + } + + private Map> convertToIP( + Map> input) { + + Map> ret = new HashMap<>(); + try { + + if (input != null) { + input.forEach( + (dataCenter, domains) -> { + if (domains != null) { + List ipList = new ArrayList<>(); + domains.forEach( + (domain) -> { + if (domain != null) { + String ip = NetUtil.getIPAddressFromDomain(domain); + if (ip == null) { + LOGGER.error("Node config convert domain {} error!", domain); + throw new RuntimeException( + "Node config convert domain {" + domain + "} error!"); + } + ipList.add(ip); + } + }); + ret.put(dataCenter, ipList); + } + }); + } + } catch (Exception e) { + LOGGER.error("Node config convert domain error!", e); + throw new RuntimeException("Node config convert domain error!", e); + } + return ret; + } + + @Override + public String getMetaDataCenter(String metaIpAddress) { + if (metaIpAddress == null || metaIpAddress.isEmpty()) { + LOGGER.error("IpAddress:" + metaIpAddress + " cannot be null!"); + return null; } - @Override - public String getMetaDataCenter(String metaIpAddress) { - if (metaIpAddress == null || metaIpAddress.isEmpty()) { - LOGGER.error("IpAddress:" + metaIpAddress + " cannot be null!"); - return null; - } - - String dataCenterRet = dataCenterMetaIPCache.get(metaIpAddress); - - if (dataCenterRet == null || dataCenterRet.isEmpty()) { - Map> metaList = getMetaNodeIP(); + String dataCenterRet = dataCenterMetaIPCache.get(metaIpAddress); - AtomicReference ret = new AtomicReference<>(); - metaList.forEach((dataCenter, list) -> { - if (list.contains(metaIpAddress)) { - ret.set(dataCenter); - } - }); + if (dataCenterRet == null || dataCenterRet.isEmpty()) { + Map> metaList = getMetaNodeIP(); - dataCenterRet = ret.get(); - } - return dataCenterRet; - } - - @Override - public Set getDataCenterMetaServers(String dataCenterIn) { - Map> metaMap = getMetaNodeIP(); - Set metaServerIpSet = new HashSet<>(); - if (metaMap != null && metaMap.size() > 0) { - Collection list = metaMap.get(dataCenterIn); - if (list != null) { - metaServerIpSet.addAll(list); + AtomicReference ret = new AtomicReference<>(); + metaList.forEach( + (dataCenter, list) -> { + if (list.contains(metaIpAddress)) { + ret.set(dataCenter); } + }); - } - return metaServerIpSet; + dataCenterRet = ret.get(); } - -} \ No newline at end of file + return dataCenterRet; + } + + @Override + public Set getDataCenterMetaServers(String dataCenterIn) { + Map> metaMap = getMetaNodeIP(); + Set metaServerIpSet = new HashSet<>(); + if (metaMap != null && metaMap.size() > 0) { + Collection list = metaMap.get(dataCenterIn); + if (list != null) { + metaServerIpSet.addAll(list); + } + } + return metaServerIpSet; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/MetaServerConfig.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/MetaServerConfig.java index 54bc4ffb5..963b41622 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/MetaServerConfig.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/MetaServerConfig.java @@ -21,87 +21,87 @@ * @version $Id: MetaServerConfig.java, v 0.1 2018-01-16 10:58 shangyu.wh Exp $ */ public interface MetaServerConfig { - int getSessionServerPort(); + int getSessionServerPort(); - int getDataServerPort(); + int getDataServerPort(); - int getMetaServerPort(); + int getMetaServerPort(); - int getHttpServerPort(); + int getHttpServerPort(); - int getRaftServerPort(); + int getRaftServerPort(); - int getCrossDcMetaSyncIntervalMilli(); + int getCrossDcMetaSyncIntervalMilli(); - int getExpireCheckIntervalMilli(); + int getExpireCheckIntervalMilli(); - int getSchedulerCheckNodeListChangePushTimeout(); + int getSchedulerCheckNodeListChangePushTimeout(); - int getSchedulerCheckNodeListChangePushFirstDelay(); + int getSchedulerCheckNodeListChangePushFirstDelay(); - int getDataNodeExchangeTimeout(); + int getDataNodeExchangeTimeout(); - int getSessionNodeExchangeTimeout(); + int getSessionNodeExchangeTimeout(); - int getMetaNodeExchangeTimeout(); + int getMetaNodeExchangeTimeout(); - String getRaftGroup(); + String getRaftGroup(); - String getRaftDataPath(); + String getRaftDataPath(); - boolean isEnableMetrics(); + boolean isEnableMetrics(); - int getRockDBCacheSize(); + int getRockDBCacheSize(); - int getConnectMetaServerExecutorMinSize(); + int getConnectMetaServerExecutorMinSize(); - int getConnectMetaServerExecutorMaxSize(); + int getConnectMetaServerExecutorMaxSize(); - int getConnectMetaServerExecutorQueueSize(); + int getConnectMetaServerExecutorQueueSize(); - int getRaftClientRefreshExecutorMinSize(); + int getRaftClientRefreshExecutorMinSize(); - int getRaftClientRefreshExecutorMaxSize(); + int getRaftClientRefreshExecutorMaxSize(); - int getRaftClientRefreshExecutorQueueSize(); + int getRaftClientRefreshExecutorQueueSize(); - int getMetaSchedulerPoolSize(); + int getMetaSchedulerPoolSize(); - int getDefaultRequestExecutorMinSize(); + int getDefaultRequestExecutorMinSize(); - int getDefaultRequestExecutorMaxSize(); + int getDefaultRequestExecutorMaxSize(); - int getDefaultRequestExecutorQueueSize(); + int getDefaultRequestExecutorQueueSize(); - int getAppRevisionRegisterExecutorMinSize(); + int getAppRevisionRegisterExecutorMinSize(); - int getAppRevisionRegisterExecutorMaxSize(); + int getAppRevisionRegisterExecutorMaxSize(); - int getAppRevisionRegisterExecutorQueueSize(); + int getAppRevisionRegisterExecutorQueueSize(); - int getRaftExecutorMinSize(); + int getRaftExecutorMinSize(); - int getRaftExecutorQueueSize(); + int getRaftExecutorQueueSize(); - int getRaftExecutorMaxSize(); + int getRaftExecutorMaxSize(); - int getRaftServerExecutorMinSize(); + int getRaftServerExecutorMinSize(); - int getRaftServerExecutorMaxSize(); + int getRaftServerExecutorMaxSize(); - int getRaftServerExecutorQueueSize(); + int getRaftServerExecutorQueueSize(); - int getRaftFsmExecutorMinSize(); + int getRaftFsmExecutorMinSize(); - int getRaftFsmExecutorMaxSize(); + int getRaftFsmExecutorMaxSize(); - int getRaftFsmExecutorQueueSize(); + int getRaftFsmExecutorQueueSize(); - int getRaftElectionTimeout(); + int getRaftElectionTimeout(); - double getSessionLoadbalanceThresholdRatio(); + double getSessionLoadbalanceThresholdRatio(); - long getMetaLeaderWarmupMilli(); + long getMetaLeaderWarmupMilli(); - void setMetaLeaderWarmupMilli(long warmupMilli); -} \ No newline at end of file + void setMetaLeaderWarmupMilli(long warmupMilli); +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/MetaServerConfigBean.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/MetaServerConfigBean.java index 1c02b9ecb..cca185302 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/MetaServerConfigBean.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/MetaServerConfigBean.java @@ -19,13 +19,12 @@ import com.alipay.sofa.registry.common.model.constants.ValueConstants; import com.alipay.sofa.registry.common.model.metaserver.Lease; import com.alipay.sofa.registry.util.OsUtils; +import java.io.File; +import java.util.concurrent.TimeUnit; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.springframework.boot.context.properties.ConfigurationProperties; -import java.io.File; -import java.util.concurrent.TimeUnit; - /** * @author shangyu.wh * @version $Id: MetaServerConfigBean.java, v 0.1 2018-01-16 11:01 shangyu.wh Exp $ @@ -33,794 +32,800 @@ @ConfigurationProperties(prefix = MetaServerConfigBean.PREFIX) public class MetaServerConfigBean implements MetaServerConfig { - public static final String PREFIX = "meta.server"; + public static final String PREFIX = "meta.server"; + + private int sessionServerPort = 9610; - private int sessionServerPort = 9610; + private int dataServerPort = 9611; - private int dataServerPort = 9611; + private int metaServerPort = 9612; - private int metaServerPort = 9612; + private int httpServerPort = 9615; - private int httpServerPort = 9615; + private int schedulerCheckNodeListChangePushTimeout = 3; - private int schedulerCheckNodeListChangePushTimeout = 3; + private int schedulerCheckNodeListChangePushFirstDelay = 1; - private int schedulerCheckNodeListChangePushFirstDelay = 1; + private int dataNodeExchangeTimeout = 3000; - private int dataNodeExchangeTimeout = 3000; + private int sessionNodeExchangeTimeout = 3000; - private int sessionNodeExchangeTimeout = 3000; + private int metaNodeExchangeTimeout = 3000; - private int metaNodeExchangeTimeout = 3000; + private int raftElectionTimeout = 1000; - private int raftElectionTimeout = 1000; + /** Whether to enable metrics for node. */ + private boolean enableMetrics = true; - /** - * Whether to enable metrics for node. - */ - private boolean enableMetrics = true; - - private String raftDataPath = System - .getProperty("user.home") - + File.separator - + "raftData"; - - private int rockDBCacheSize = 64; //64M - - private int connectMetaServerExecutorMinSize = 3; - private int connectMetaServerExecutorMaxSize = 10; - private int connectMetaServerExecutorQueueSize = 1024; - - private int raftClientRefreshExecutorMinSize = 3; - private int raftClientRefreshExecutorMaxSize = 10; - private int raftClientRefreshExecutorQueueSize = 1024; - - private int defaultRequestExecutorMinSize = 20; - private int defaultRequestExecutorMaxSize = 600; - private int defaultRequestExecutorQueueSize = 500; - - private int appRevisionRegisterExecutorMinSize = OsUtils.getCpuCount() * 5; - private int appRevisionRegisterExecutorMaxSize = OsUtils.getCpuCount() * 20; - private int appRevisionRegisterExecutorQueueSize = 500; - - private int raftExecutorMinSize = 20; - private int raftExecutorMaxSize = 400; - private int raftExecutorQueueSize = 100; - - private int raftServerExecutorMinSize = 20; - private int raftServerExecutorMaxSize = 100; - private int raftServerExecutorQueueSize = 100; - - private int raftFsmExecutorMinSize = 3; - private int raftFsmExecutorMaxSize = 10; - private int raftFsmExecutorQueueSize = 100; - - private int metaSchedulerPoolSize = 6; - private double sessionLoadbalanceThresholdRatio = 1.1; - - private int expireCheckIntervalMilli = 1000; - - private long metaLeaderWarmupMilli = Long.getLong("elector.warm.up.milli", - TimeUnit.SECONDS.toMillis(Lease.DEFAULT_DURATION_SECS * 3 / 2)); - - /** - * Gets get session server port. - * - * @return the get session server port - */ - @Override - public int getSessionServerPort() { - return sessionServerPort; - } - - /** - * Setter method for property sessionServerPort. - * - * @param sessionServerPort value to be assigned to property sessionServerPort - */ - public void setSessionServerPort(int sessionServerPort) { - this.sessionServerPort = sessionServerPort; - } - - /** - * Gets get data server port. - * - * @return the get data server port - */ - @Override - public int getDataServerPort() { - return dataServerPort; - } - - /** - * Setter method for property dataServerPort. - * - * @param dataServerPort value to be assigned to property dataServerPort - */ - public void setDataServerPort(int dataServerPort) { - this.dataServerPort = dataServerPort; - } - - /** - * Gets get http server port. - * - * @return the get http server port - */ - @Override - public int getHttpServerPort() { - return httpServerPort; - } - - /** - * Setter method for property httpServerPort. - * - * @param httpServerPort value to be assigned to property httpServerPort - */ - public void setHttpServerPort(int httpServerPort) { - this.httpServerPort = httpServerPort; - } - - /** - * Getter method for property schedulerHeartbeatExpBackOffBound. - * - * @return property value of schedulerHeartbeatExpBackOffBound - */ - @Override - public int getExpireCheckIntervalMilli() { - return expireCheckIntervalMilli; - } - - /** - * Sets set expire check interval milli. - * - * @param expireCheckIntervalMilli the expire check interval milli - * @return the set expire check interval milli - */ - public MetaServerConfigBean setExpireCheckIntervalMilli(int expireCheckIntervalMilli) { - this.expireCheckIntervalMilli = expireCheckIntervalMilli; - return this; - } - - /** - * Getter method for property dataNodeExchangeTimeout. - * - * @return property value of dataNodeExchangeTimeout - */ - @Override - public int getDataNodeExchangeTimeout() { - return dataNodeExchangeTimeout; - } - - /** - * Setter method for property dataNodeExchangeTimeout. - * - * @param dataNodeExchangeTimeout value to be assigned to property dataNodeExchangeTimeout - */ - public void setDataNodeExchangeTimeout(int dataNodeExchangeTimeout) { - this.dataNodeExchangeTimeout = dataNodeExchangeTimeout; - } - - /** - * Getter method for property sessionNodeExchangeTimeout. - * - * @return property value of sessionNodeExchangeTimeout - */ - @Override - public int getSessionNodeExchangeTimeout() { - return sessionNodeExchangeTimeout; - } - - /** - * Setter method for property sessionNodeExchangeTimeout. - * - * @param sessionNodeExchangeTimeout value to be assigned to property sessionNodeExchangeTimeout - */ - public void setSessionNodeExchangeTimeout(int sessionNodeExchangeTimeout) { - this.sessionNodeExchangeTimeout = sessionNodeExchangeTimeout; - } - - /** - * Getter method for property metaServerPort. - * - * @return property value of metaServerPort - */ - @Override - public int getMetaServerPort() { - return metaServerPort; - } - - /** - * Setter method for property metaServerPort. - * - * @param metaServerPort value to be assigned to property metaServerPort - */ - public void setMetaServerPort(int metaServerPort) { - this.metaServerPort = metaServerPort; - } - - /** - * Getter method for property metaNodeExchangeTimeout. - * - * @return property value of metaNodeExchangeTimeout - */ - @Override - public int getMetaNodeExchangeTimeout() { - return metaNodeExchangeTimeout; - } - - /** - * Setter method for property metaNodeExchangeTimeout. - * - * @param metaNodeExchangeTimeout value to be assigned to property metaNodeExchangeTimeout - */ - public void setMetaNodeExchangeTimeout(int metaNodeExchangeTimeout) { - this.metaNodeExchangeTimeout = metaNodeExchangeTimeout; - } - - /** - * Getter method for property schedulerCheckNodeListChangePushTimeout. - * - * @return property value of schedulerCheckNodeListChangePushTimeout - */ - @Override - public int getSchedulerCheckNodeListChangePushTimeout() { - return schedulerCheckNodeListChangePushTimeout; - } - - /** - * Setter method for property schedulerCheckNodeListChangePushTimeout. - * - * @param schedulerCheckNodeListChangePushTimeout value to be assigned to property schedulerCheckNodeListChangePushTimeout - */ - public void setSchedulerCheckNodeListChangePushTimeout(int schedulerCheckNodeListChangePushTimeout) { - this.schedulerCheckNodeListChangePushTimeout = schedulerCheckNodeListChangePushTimeout; - } - - /** - * Getter method for property schedulerCheckNodeListChangePushFirstDelay. - * - * @return property value of schedulerCheckNodeListChangePushFirstDelay - */ - @Override - public int getSchedulerCheckNodeListChangePushFirstDelay() { - return schedulerCheckNodeListChangePushFirstDelay; - } - - /** - * Setter method for property schedulerCheckNodeListChangePushFirstDelay. - * - * @param schedulerCheckNodeListChangePushFirstDelay value to be assigned to property schedulerCheckNodeListChangePushFirstDelay - */ - public void setSchedulerCheckNodeListChangePushFirstDelay(int schedulerCheckNodeListChangePushFirstDelay) { - this.schedulerCheckNodeListChangePushFirstDelay = schedulerCheckNodeListChangePushFirstDelay; - } - - /** - * Getter method for property raftGroup. - * - * @return property value of raftGroup - */ - @Override - public String getRaftGroup() { - return ValueConstants.RAFT_SERVER_GROUP; - } - - /** - * Getter method for property raftServerPort. - * - * @return property value of raftServerPort - */ - @Override - public int getRaftServerPort() { - return ValueConstants.RAFT_SERVER_PORT; - } - - /** - * Gets get cross dc meta sync interval milli. - * - * @return the get cross dc meta sync interval milli - */ - @Override - public int getCrossDcMetaSyncIntervalMilli() { - return ValueConstants.CROSS_DC_META_SYNC_INTERVAL_MILLI; - } - - /** - * Getter method for property raftDataPath. - * - * @return property value of raftDataPath - */ - @Override - public String getRaftDataPath() { - return raftDataPath; - } - - /** - * Setter method for property raftDataPath. - * - * @param raftDataPath value to be assigned to property raftDataPath - */ - public void setRaftDataPath(String raftDataPath) { - this.raftDataPath = raftDataPath; - } - - /** - * Is enable metrics boolean. - * - * @return the boolean - */ - @Override - public boolean isEnableMetrics() { - return enableMetrics; - } - - /** - * Setter method for property enableMetrics. - * - * @param enableMetrics value to be assigned to property enableMetrics - */ - public void setEnableMetrics(boolean enableMetrics) { - this.enableMetrics = enableMetrics; - } - - /** - * Getter method for property RockDBCacheSize. - * - * @return property value of RockDBCacheSize - */ - public int getRockDBCacheSize() { - return rockDBCacheSize; - } - - /** - * Setter method for property RockDBCacheSize. - * - * @param rockDBCacheSize value to be assigned to property RockDBCacheSize - */ - public void setRockDBCacheSize(int rockDBCacheSize) { - this.rockDBCacheSize = rockDBCacheSize; - } - - /** - * Getter method for property connectMetaServerExecutorMinSize. - * - * @return property value of connectMetaServerExecutorMinSize - */ - @Override - public int getConnectMetaServerExecutorMinSize() { - return connectMetaServerExecutorMinSize; - } - - /** - * Getter method for property connectMetaServerExecutorMaxSize. - * - * @return property value of connectMetaServerExecutorMaxSize - */ - @Override - public int getConnectMetaServerExecutorMaxSize() { - return connectMetaServerExecutorMaxSize; - } - - /** - * Getter method for property connectMetaServerExecutorQueueSize. - * - * @return property value of connectMetaServerExecutorQueueSize - */ - @Override - public int getConnectMetaServerExecutorQueueSize() { - return connectMetaServerExecutorQueueSize; - } - - /** - * Getter method for property raftClientRefreshExecutorMinSize. - * - * @return property value of raftClientRefreshExecutorMinSize - */ - @Override - public int getRaftClientRefreshExecutorMinSize() { - return raftClientRefreshExecutorMinSize; - } - - /** - * Getter method for property raftClientRefreshExecutorMaxSize. - * - * @return property value of raftClientRefreshExecutorMaxSize - */ - @Override - public int getRaftClientRefreshExecutorMaxSize() { - return raftClientRefreshExecutorMaxSize; - } - - /** - * Getter method for property raftClientRefreshExecutorQueueSize. - * - * @return property value of raftClientRefreshExecutorQueueSize - */ - @Override - public int getRaftClientRefreshExecutorQueueSize() { - return raftClientRefreshExecutorQueueSize; - } - - /** - * Setter method for property metaSchedulerPoolSize . - * - * @param metaSchedulerPoolSize value to be assigned to property metaSchedulerPoolSize - */ - public void setMetaSchedulerPoolSize(int metaSchedulerPoolSize) { - this.metaSchedulerPoolSize = metaSchedulerPoolSize; - } - - /** - * Gets get meta scheduler pool size. - * - * @return the get meta scheduler pool size - */ - @Override - public int getMetaSchedulerPoolSize() { - return metaSchedulerPoolSize; - } - - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } - - /** - * Gets get default request executor min size. - * - * @return the get default request executor min size - */ - public int getDefaultRequestExecutorMinSize() { - return defaultRequestExecutorMinSize; - } - - /** - * Sets set default request executor min size. - * - * @param defaultRequestExecutorMinSize the default request executor min size - */ - public void setDefaultRequestExecutorMinSize(int defaultRequestExecutorMinSize) { - this.defaultRequestExecutorMinSize = defaultRequestExecutorMinSize; - } - - /** - * Gets get default request executor max size. - * - * @return the get default request executor max size - */ - public int getDefaultRequestExecutorMaxSize() { - return defaultRequestExecutorMaxSize; - } - - /** - * Sets set default request executor max size. - * - * @param defaultRequestExecutorMaxSize the default request executor max size - */ - public void setDefaultRequestExecutorMaxSize(int defaultRequestExecutorMaxSize) { - this.defaultRequestExecutorMaxSize = defaultRequestExecutorMaxSize; - } - - /** - * Gets get default request executor queue size. - * - * @return the get default request executor queue size - */ - public int getDefaultRequestExecutorQueueSize() { - return defaultRequestExecutorQueueSize; - } - - /** - * Sets set default request executor queue size. - * - * @param defaultRequestExecutorQueueSize the default request executor queue size - */ - public void setDefaultRequestExecutorQueueSize(int defaultRequestExecutorQueueSize) { - this.defaultRequestExecutorQueueSize = defaultRequestExecutorQueueSize; - } - - /** - * Gets get raft executor min size. - * - * @return the get raft executor min size - */ - public int getRaftExecutorMinSize() { - return raftExecutorMinSize; - } - - /** - * Sets set raft executor min size. - * - * @param raftExecutorMinSize the raft executor min size - */ - public void setRaftExecutorMinSize(int raftExecutorMinSize) { - this.raftExecutorMinSize = raftExecutorMinSize; - } - - /** - * Gets get raft executor max size. - * - * @return the get raft executor max size - */ - public int getRaftExecutorMaxSize() { - return raftExecutorMaxSize; - } - - /** - * Sets set raft executor max size. - * - * @param raftExecutorMaxSize the raft executor max size - */ - public void setRaftExecutorMaxSize(int raftExecutorMaxSize) { - this.raftExecutorMaxSize = raftExecutorMaxSize; - } - - /** - * Gets get raft executor queue size. - * - * @return the get raft executor queue size - */ - public int getRaftExecutorQueueSize() { - return raftExecutorQueueSize; - } - - /** - * Sets set raft executor queue size. - * - * @param raftExecutorQueueSize the raft executor queue size - */ - public void setRaftExecutorQueueSize(int raftExecutorQueueSize) { - this.raftExecutorQueueSize = raftExecutorQueueSize; - } - - /** - * Gets get raft server executor min size. - * - * @return the get raft server executor min size - */ - public int getRaftServerExecutorMinSize() { - return raftServerExecutorMinSize; - } - - /** - * Sets set raft server executor min size. - * - * @param raftServerExecutorMinSize the raft server executor min size - */ - public void setRaftServerExecutorMinSize(int raftServerExecutorMinSize) { - this.raftServerExecutorMinSize = raftServerExecutorMinSize; - } - - /** - * Gets get raft server executor max size. - * - * @return the get raft server executor max size - */ - public int getRaftServerExecutorMaxSize() { - return raftServerExecutorMaxSize; - } - - /** - * Sets set raft server executor max size. - * - * @param raftServerExecutorMaxSize the raft server executor max size - */ - public void setRaftServerExecutorMaxSize(int raftServerExecutorMaxSize) { - this.raftServerExecutorMaxSize = raftServerExecutorMaxSize; - } - - /** - * Gets get raft server executor queue size. - * - * @return the get raft server executor queue size - */ - public int getRaftServerExecutorQueueSize() { - return raftServerExecutorQueueSize; - } - - /** - * Sets set raft server executor queue size. - * - * @param raftServerExecutorQueueSize the raft server executor queue size - */ - public void setRaftServerExecutorQueueSize(int raftServerExecutorQueueSize) { - this.raftServerExecutorQueueSize = raftServerExecutorQueueSize; - } - - /** - * Gets get raft fsm executor min size. - * - * @return the get raft fsm executor min size - */ - @Override - public int getRaftFsmExecutorMinSize() { - return raftFsmExecutorMinSize; - } - - /** - * Sets set raft fsm executor min size. - * - * @param raftFsmExecutorMinSize the raft fsm executor min size - */ - public void setRaftFsmExecutorMinSize(int raftFsmExecutorMinSize) { - this.raftFsmExecutorMinSize = raftFsmExecutorMinSize; - } - - /** - * Gets get raft fsm executor max size. - * - * @return the get raft fsm executor max size - */ - @Override - public int getRaftFsmExecutorMaxSize() { - return raftFsmExecutorMaxSize; - } - - /** - * Sets set raft fsm executor max size. - * - * @param raftFsmExecutorMaxSize the raft fsm executor max size - */ - public void setRaftFsmExecutorMaxSize(int raftFsmExecutorMaxSize) { - this.raftFsmExecutorMaxSize = raftFsmExecutorMaxSize; - } - - /** - * Gets get raft fsm executor queue size. - * - * @return the get raft fsm executor queue size - */ - @Override - public int getRaftFsmExecutorQueueSize() { - return raftFsmExecutorQueueSize; - } - - /** - * Sets set raft fsm executor queue size. - * - * @param raftFsmExecutorQueueSize the raft fsm executor queue size - */ - public void setRaftFsmExecutorQueueSize(int raftFsmExecutorQueueSize) { - this.raftFsmExecutorQueueSize = raftFsmExecutorQueueSize; - } - - /** - * Gets get raft election timeout. - * - * @return the get raft election timeout - */ - public int getRaftElectionTimeout() { - return raftElectionTimeout; - } - - /** - * Sets set raft election timeout. - * - * @param raftElectionTimeout the raft election timeout - */ - public void setRaftElectionTimeout(int raftElectionTimeout) { - this.raftElectionTimeout = raftElectionTimeout; - } - - /** - * Gets get session loadbalance threshold ratio. - * - * @return the get session loadbalance threshold ratio - */ - @Override - public double getSessionLoadbalanceThresholdRatio() { - return sessionLoadbalanceThresholdRatio; - } - - /** - * Sets set session loadbalance threshold ratio. - * - * @param sessionLoadbalanceThresholdRatio the session loadbalance threshold ratio - */ - public void setSessionLoadbalanceThresholdRatio(double sessionLoadbalanceThresholdRatio) { - this.sessionLoadbalanceThresholdRatio = sessionLoadbalanceThresholdRatio; - } - - /** - * Sets set connect meta server executor min size. - * - * @param connectMetaServerExecutorMinSize the connect meta server executor min size - * @return the set connect meta server executor min size - */ - public MetaServerConfigBean setConnectMetaServerExecutorMinSize(int connectMetaServerExecutorMinSize) { - this.connectMetaServerExecutorMinSize = connectMetaServerExecutorMinSize; - return this; - } - - /** - * Sets set connect meta server executor max size. - * - * @param connectMetaServerExecutorMaxSize the connect meta server executor max size - * @return the set connect meta server executor max size - */ - public MetaServerConfigBean setConnectMetaServerExecutorMaxSize(int connectMetaServerExecutorMaxSize) { - this.connectMetaServerExecutorMaxSize = connectMetaServerExecutorMaxSize; - return this; - } - - /** - * Sets set connect meta server executor queue size. - * - * @param connectMetaServerExecutorQueueSize the connect meta server executor queue size - * @return the set connect meta server executor queue size - */ - public MetaServerConfigBean setConnectMetaServerExecutorQueueSize(int connectMetaServerExecutorQueueSize) { - this.connectMetaServerExecutorQueueSize = connectMetaServerExecutorQueueSize; - return this; - } - - /** - * Sets set raft client refresh executor min size. - * - * @param raftClientRefreshExecutorMinSize the raft client refresh executor min size - * @return the set raft client refresh executor min size - */ - public MetaServerConfigBean setRaftClientRefreshExecutorMinSize(int raftClientRefreshExecutorMinSize) { - this.raftClientRefreshExecutorMinSize = raftClientRefreshExecutorMinSize; - return this; - } - - /** - * Sets set raft client refresh executor max size. - * - * @param raftClientRefreshExecutorMaxSize the raft client refresh executor max size - * @return the set raft client refresh executor max size - */ - public MetaServerConfigBean setRaftClientRefreshExecutorMaxSize(int raftClientRefreshExecutorMaxSize) { - this.raftClientRefreshExecutorMaxSize = raftClientRefreshExecutorMaxSize; - return this; - } - - /** - * Sets set raft client refresh executor queue size. - * - * @param raftClientRefreshExecutorQueueSize the raft client refresh executor queue size - * @return the set raft client refresh executor queue size - */ - public MetaServerConfigBean setRaftClientRefreshExecutorQueueSize(int raftClientRefreshExecutorQueueSize) { - this.raftClientRefreshExecutorQueueSize = raftClientRefreshExecutorQueueSize; - return this; - } - - public int getAppRevisionRegisterExecutorMinSize() { - return appRevisionRegisterExecutorMinSize; - } - - public void setAppRevisionRegisterExecutorMinSize(int appRevisionRegisterExecutorMinSize) { - this.appRevisionRegisterExecutorMinSize = appRevisionRegisterExecutorMinSize; - } - - public int getAppRevisionRegisterExecutorMaxSize() { - return appRevisionRegisterExecutorMaxSize; - } - - public void setAppRevisionRegisterExecutorMaxSize(int appRevisionRegisterExecutorMaxSize) { - this.appRevisionRegisterExecutorMaxSize = appRevisionRegisterExecutorMaxSize; - } - - public int getAppRevisionRegisterExecutorQueueSize() { - return appRevisionRegisterExecutorQueueSize; - } - - public void setAppRevisionRegisterExecutorQueueSize(int appRevisionRegisterExecutorQueueSize) { - this.appRevisionRegisterExecutorQueueSize = appRevisionRegisterExecutorQueueSize; - } - - public long getMetaLeaderWarmupMilli() { - return metaLeaderWarmupMilli; - } - - public void setMetaLeaderWarmupMilli(long metaLeaderWarmupMilli) { - this.metaLeaderWarmupMilli = metaLeaderWarmupMilli; - } -} \ No newline at end of file + private String raftDataPath = System.getProperty("user.home") + File.separator + "raftData"; + + private int rockDBCacheSize = 64; // 64M + + private int connectMetaServerExecutorMinSize = 3; + private int connectMetaServerExecutorMaxSize = 10; + private int connectMetaServerExecutorQueueSize = 1024; + + private int raftClientRefreshExecutorMinSize = 3; + private int raftClientRefreshExecutorMaxSize = 10; + private int raftClientRefreshExecutorQueueSize = 1024; + + private int defaultRequestExecutorMinSize = 20; + private int defaultRequestExecutorMaxSize = 600; + private int defaultRequestExecutorQueueSize = 500; + + private int appRevisionRegisterExecutorMinSize = OsUtils.getCpuCount() * 5; + private int appRevisionRegisterExecutorMaxSize = OsUtils.getCpuCount() * 20; + private int appRevisionRegisterExecutorQueueSize = 500; + + private int raftExecutorMinSize = 20; + private int raftExecutorMaxSize = 400; + private int raftExecutorQueueSize = 100; + + private int raftServerExecutorMinSize = 20; + private int raftServerExecutorMaxSize = 100; + private int raftServerExecutorQueueSize = 100; + + private int raftFsmExecutorMinSize = 3; + private int raftFsmExecutorMaxSize = 10; + private int raftFsmExecutorQueueSize = 100; + + private int metaSchedulerPoolSize = 6; + private double sessionLoadbalanceThresholdRatio = 1.1; + + private int expireCheckIntervalMilli = 1000; + + private long metaLeaderWarmupMilli = + Long.getLong( + "elector.warm.up.milli", TimeUnit.SECONDS.toMillis(Lease.DEFAULT_DURATION_SECS * 3 / 2)); + + /** + * Gets get session server port. + * + * @return the get session server port + */ + @Override + public int getSessionServerPort() { + return sessionServerPort; + } + + /** + * Setter method for property sessionServerPort. + * + * @param sessionServerPort value to be assigned to property sessionServerPort + */ + public void setSessionServerPort(int sessionServerPort) { + this.sessionServerPort = sessionServerPort; + } + + /** + * Gets get data server port. + * + * @return the get data server port + */ + @Override + public int getDataServerPort() { + return dataServerPort; + } + + /** + * Setter method for property dataServerPort. + * + * @param dataServerPort value to be assigned to property dataServerPort + */ + public void setDataServerPort(int dataServerPort) { + this.dataServerPort = dataServerPort; + } + + /** + * Gets get http server port. + * + * @return the get http server port + */ + @Override + public int getHttpServerPort() { + return httpServerPort; + } + + /** + * Setter method for property httpServerPort. + * + * @param httpServerPort value to be assigned to property httpServerPort + */ + public void setHttpServerPort(int httpServerPort) { + this.httpServerPort = httpServerPort; + } + + /** + * Getter method for property schedulerHeartbeatExpBackOffBound. + * + * @return property value of schedulerHeartbeatExpBackOffBound + */ + @Override + public int getExpireCheckIntervalMilli() { + return expireCheckIntervalMilli; + } + + /** + * Sets set expire check interval milli. + * + * @param expireCheckIntervalMilli the expire check interval milli + * @return the set expire check interval milli + */ + public MetaServerConfigBean setExpireCheckIntervalMilli(int expireCheckIntervalMilli) { + this.expireCheckIntervalMilli = expireCheckIntervalMilli; + return this; + } + + /** + * Getter method for property dataNodeExchangeTimeout. + * + * @return property value of dataNodeExchangeTimeout + */ + @Override + public int getDataNodeExchangeTimeout() { + return dataNodeExchangeTimeout; + } + + /** + * Setter method for property dataNodeExchangeTimeout. + * + * @param dataNodeExchangeTimeout value to be assigned to property dataNodeExchangeTimeout + */ + public void setDataNodeExchangeTimeout(int dataNodeExchangeTimeout) { + this.dataNodeExchangeTimeout = dataNodeExchangeTimeout; + } + + /** + * Getter method for property sessionNodeExchangeTimeout. + * + * @return property value of sessionNodeExchangeTimeout + */ + @Override + public int getSessionNodeExchangeTimeout() { + return sessionNodeExchangeTimeout; + } + + /** + * Setter method for property sessionNodeExchangeTimeout. + * + * @param sessionNodeExchangeTimeout value to be assigned to property sessionNodeExchangeTimeout + */ + public void setSessionNodeExchangeTimeout(int sessionNodeExchangeTimeout) { + this.sessionNodeExchangeTimeout = sessionNodeExchangeTimeout; + } + + /** + * Getter method for property metaServerPort. + * + * @return property value of metaServerPort + */ + @Override + public int getMetaServerPort() { + return metaServerPort; + } + + /** + * Setter method for property metaServerPort. + * + * @param metaServerPort value to be assigned to property metaServerPort + */ + public void setMetaServerPort(int metaServerPort) { + this.metaServerPort = metaServerPort; + } + + /** + * Getter method for property metaNodeExchangeTimeout. + * + * @return property value of metaNodeExchangeTimeout + */ + @Override + public int getMetaNodeExchangeTimeout() { + return metaNodeExchangeTimeout; + } + + /** + * Setter method for property metaNodeExchangeTimeout. + * + * @param metaNodeExchangeTimeout value to be assigned to property metaNodeExchangeTimeout + */ + public void setMetaNodeExchangeTimeout(int metaNodeExchangeTimeout) { + this.metaNodeExchangeTimeout = metaNodeExchangeTimeout; + } + + /** + * Getter method for property schedulerCheckNodeListChangePushTimeout. + * + * @return property value of schedulerCheckNodeListChangePushTimeout + */ + @Override + public int getSchedulerCheckNodeListChangePushTimeout() { + return schedulerCheckNodeListChangePushTimeout; + } + + /** + * Setter method for property schedulerCheckNodeListChangePushTimeout. + * + * @param schedulerCheckNodeListChangePushTimeout value to be assigned to property + * schedulerCheckNodeListChangePushTimeout + */ + public void setSchedulerCheckNodeListChangePushTimeout( + int schedulerCheckNodeListChangePushTimeout) { + this.schedulerCheckNodeListChangePushTimeout = schedulerCheckNodeListChangePushTimeout; + } + + /** + * Getter method for property schedulerCheckNodeListChangePushFirstDelay. + * + * @return property value of schedulerCheckNodeListChangePushFirstDelay + */ + @Override + public int getSchedulerCheckNodeListChangePushFirstDelay() { + return schedulerCheckNodeListChangePushFirstDelay; + } + + /** + * Setter method for property schedulerCheckNodeListChangePushFirstDelay. + * + * @param schedulerCheckNodeListChangePushFirstDelay value to be assigned to property + * schedulerCheckNodeListChangePushFirstDelay + */ + public void setSchedulerCheckNodeListChangePushFirstDelay( + int schedulerCheckNodeListChangePushFirstDelay) { + this.schedulerCheckNodeListChangePushFirstDelay = schedulerCheckNodeListChangePushFirstDelay; + } + + /** + * Getter method for property raftGroup. + * + * @return property value of raftGroup + */ + @Override + public String getRaftGroup() { + return ValueConstants.RAFT_SERVER_GROUP; + } + + /** + * Getter method for property raftServerPort. + * + * @return property value of raftServerPort + */ + @Override + public int getRaftServerPort() { + return ValueConstants.RAFT_SERVER_PORT; + } + + /** + * Gets get cross dc meta sync interval milli. + * + * @return the get cross dc meta sync interval milli + */ + @Override + public int getCrossDcMetaSyncIntervalMilli() { + return ValueConstants.CROSS_DC_META_SYNC_INTERVAL_MILLI; + } + + /** + * Getter method for property raftDataPath. + * + * @return property value of raftDataPath + */ + @Override + public String getRaftDataPath() { + return raftDataPath; + } + + /** + * Setter method for property raftDataPath. + * + * @param raftDataPath value to be assigned to property raftDataPath + */ + public void setRaftDataPath(String raftDataPath) { + this.raftDataPath = raftDataPath; + } + + /** + * Is enable metrics boolean. + * + * @return the boolean + */ + @Override + public boolean isEnableMetrics() { + return enableMetrics; + } + + /** + * Setter method for property enableMetrics. + * + * @param enableMetrics value to be assigned to property enableMetrics + */ + public void setEnableMetrics(boolean enableMetrics) { + this.enableMetrics = enableMetrics; + } + + /** + * Getter method for property RockDBCacheSize. + * + * @return property value of RockDBCacheSize + */ + public int getRockDBCacheSize() { + return rockDBCacheSize; + } + + /** + * Setter method for property RockDBCacheSize. + * + * @param rockDBCacheSize value to be assigned to property RockDBCacheSize + */ + public void setRockDBCacheSize(int rockDBCacheSize) { + this.rockDBCacheSize = rockDBCacheSize; + } + + /** + * Getter method for property connectMetaServerExecutorMinSize. + * + * @return property value of connectMetaServerExecutorMinSize + */ + @Override + public int getConnectMetaServerExecutorMinSize() { + return connectMetaServerExecutorMinSize; + } + + /** + * Getter method for property connectMetaServerExecutorMaxSize. + * + * @return property value of connectMetaServerExecutorMaxSize + */ + @Override + public int getConnectMetaServerExecutorMaxSize() { + return connectMetaServerExecutorMaxSize; + } + + /** + * Getter method for property connectMetaServerExecutorQueueSize. + * + * @return property value of connectMetaServerExecutorQueueSize + */ + @Override + public int getConnectMetaServerExecutorQueueSize() { + return connectMetaServerExecutorQueueSize; + } + + /** + * Getter method for property raftClientRefreshExecutorMinSize. + * + * @return property value of raftClientRefreshExecutorMinSize + */ + @Override + public int getRaftClientRefreshExecutorMinSize() { + return raftClientRefreshExecutorMinSize; + } + + /** + * Getter method for property raftClientRefreshExecutorMaxSize. + * + * @return property value of raftClientRefreshExecutorMaxSize + */ + @Override + public int getRaftClientRefreshExecutorMaxSize() { + return raftClientRefreshExecutorMaxSize; + } + + /** + * Getter method for property raftClientRefreshExecutorQueueSize. + * + * @return property value of raftClientRefreshExecutorQueueSize + */ + @Override + public int getRaftClientRefreshExecutorQueueSize() { + return raftClientRefreshExecutorQueueSize; + } + + /** + * Setter method for property metaSchedulerPoolSize . + * + * @param metaSchedulerPoolSize value to be assigned to property metaSchedulerPoolSize + */ + public void setMetaSchedulerPoolSize(int metaSchedulerPoolSize) { + this.metaSchedulerPoolSize = metaSchedulerPoolSize; + } + + /** + * Gets get meta scheduler pool size. + * + * @return the get meta scheduler pool size + */ + @Override + public int getMetaSchedulerPoolSize() { + return metaSchedulerPoolSize; + } + + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } + + /** + * Gets get default request executor min size. + * + * @return the get default request executor min size + */ + public int getDefaultRequestExecutorMinSize() { + return defaultRequestExecutorMinSize; + } + + /** + * Sets set default request executor min size. + * + * @param defaultRequestExecutorMinSize the default request executor min size + */ + public void setDefaultRequestExecutorMinSize(int defaultRequestExecutorMinSize) { + this.defaultRequestExecutorMinSize = defaultRequestExecutorMinSize; + } + + /** + * Gets get default request executor max size. + * + * @return the get default request executor max size + */ + public int getDefaultRequestExecutorMaxSize() { + return defaultRequestExecutorMaxSize; + } + + /** + * Sets set default request executor max size. + * + * @param defaultRequestExecutorMaxSize the default request executor max size + */ + public void setDefaultRequestExecutorMaxSize(int defaultRequestExecutorMaxSize) { + this.defaultRequestExecutorMaxSize = defaultRequestExecutorMaxSize; + } + + /** + * Gets get default request executor queue size. + * + * @return the get default request executor queue size + */ + public int getDefaultRequestExecutorQueueSize() { + return defaultRequestExecutorQueueSize; + } + + /** + * Sets set default request executor queue size. + * + * @param defaultRequestExecutorQueueSize the default request executor queue size + */ + public void setDefaultRequestExecutorQueueSize(int defaultRequestExecutorQueueSize) { + this.defaultRequestExecutorQueueSize = defaultRequestExecutorQueueSize; + } + + /** + * Gets get raft executor min size. + * + * @return the get raft executor min size + */ + public int getRaftExecutorMinSize() { + return raftExecutorMinSize; + } + + /** + * Sets set raft executor min size. + * + * @param raftExecutorMinSize the raft executor min size + */ + public void setRaftExecutorMinSize(int raftExecutorMinSize) { + this.raftExecutorMinSize = raftExecutorMinSize; + } + + /** + * Gets get raft executor max size. + * + * @return the get raft executor max size + */ + public int getRaftExecutorMaxSize() { + return raftExecutorMaxSize; + } + + /** + * Sets set raft executor max size. + * + * @param raftExecutorMaxSize the raft executor max size + */ + public void setRaftExecutorMaxSize(int raftExecutorMaxSize) { + this.raftExecutorMaxSize = raftExecutorMaxSize; + } + + /** + * Gets get raft executor queue size. + * + * @return the get raft executor queue size + */ + public int getRaftExecutorQueueSize() { + return raftExecutorQueueSize; + } + + /** + * Sets set raft executor queue size. + * + * @param raftExecutorQueueSize the raft executor queue size + */ + public void setRaftExecutorQueueSize(int raftExecutorQueueSize) { + this.raftExecutorQueueSize = raftExecutorQueueSize; + } + + /** + * Gets get raft server executor min size. + * + * @return the get raft server executor min size + */ + public int getRaftServerExecutorMinSize() { + return raftServerExecutorMinSize; + } + + /** + * Sets set raft server executor min size. + * + * @param raftServerExecutorMinSize the raft server executor min size + */ + public void setRaftServerExecutorMinSize(int raftServerExecutorMinSize) { + this.raftServerExecutorMinSize = raftServerExecutorMinSize; + } + + /** + * Gets get raft server executor max size. + * + * @return the get raft server executor max size + */ + public int getRaftServerExecutorMaxSize() { + return raftServerExecutorMaxSize; + } + + /** + * Sets set raft server executor max size. + * + * @param raftServerExecutorMaxSize the raft server executor max size + */ + public void setRaftServerExecutorMaxSize(int raftServerExecutorMaxSize) { + this.raftServerExecutorMaxSize = raftServerExecutorMaxSize; + } + + /** + * Gets get raft server executor queue size. + * + * @return the get raft server executor queue size + */ + public int getRaftServerExecutorQueueSize() { + return raftServerExecutorQueueSize; + } + + /** + * Sets set raft server executor queue size. + * + * @param raftServerExecutorQueueSize the raft server executor queue size + */ + public void setRaftServerExecutorQueueSize(int raftServerExecutorQueueSize) { + this.raftServerExecutorQueueSize = raftServerExecutorQueueSize; + } + + /** + * Gets get raft fsm executor min size. + * + * @return the get raft fsm executor min size + */ + @Override + public int getRaftFsmExecutorMinSize() { + return raftFsmExecutorMinSize; + } + + /** + * Sets set raft fsm executor min size. + * + * @param raftFsmExecutorMinSize the raft fsm executor min size + */ + public void setRaftFsmExecutorMinSize(int raftFsmExecutorMinSize) { + this.raftFsmExecutorMinSize = raftFsmExecutorMinSize; + } + + /** + * Gets get raft fsm executor max size. + * + * @return the get raft fsm executor max size + */ + @Override + public int getRaftFsmExecutorMaxSize() { + return raftFsmExecutorMaxSize; + } + + /** + * Sets set raft fsm executor max size. + * + * @param raftFsmExecutorMaxSize the raft fsm executor max size + */ + public void setRaftFsmExecutorMaxSize(int raftFsmExecutorMaxSize) { + this.raftFsmExecutorMaxSize = raftFsmExecutorMaxSize; + } + + /** + * Gets get raft fsm executor queue size. + * + * @return the get raft fsm executor queue size + */ + @Override + public int getRaftFsmExecutorQueueSize() { + return raftFsmExecutorQueueSize; + } + + /** + * Sets set raft fsm executor queue size. + * + * @param raftFsmExecutorQueueSize the raft fsm executor queue size + */ + public void setRaftFsmExecutorQueueSize(int raftFsmExecutorQueueSize) { + this.raftFsmExecutorQueueSize = raftFsmExecutorQueueSize; + } + + /** + * Gets get raft election timeout. + * + * @return the get raft election timeout + */ + public int getRaftElectionTimeout() { + return raftElectionTimeout; + } + + /** + * Sets set raft election timeout. + * + * @param raftElectionTimeout the raft election timeout + */ + public void setRaftElectionTimeout(int raftElectionTimeout) { + this.raftElectionTimeout = raftElectionTimeout; + } + + /** + * Gets get session loadbalance threshold ratio. + * + * @return the get session loadbalance threshold ratio + */ + @Override + public double getSessionLoadbalanceThresholdRatio() { + return sessionLoadbalanceThresholdRatio; + } + + /** + * Sets set session loadbalance threshold ratio. + * + * @param sessionLoadbalanceThresholdRatio the session loadbalance threshold ratio + */ + public void setSessionLoadbalanceThresholdRatio(double sessionLoadbalanceThresholdRatio) { + this.sessionLoadbalanceThresholdRatio = sessionLoadbalanceThresholdRatio; + } + + /** + * Sets set connect meta server executor min size. + * + * @param connectMetaServerExecutorMinSize the connect meta server executor min size + * @return the set connect meta server executor min size + */ + public MetaServerConfigBean setConnectMetaServerExecutorMinSize( + int connectMetaServerExecutorMinSize) { + this.connectMetaServerExecutorMinSize = connectMetaServerExecutorMinSize; + return this; + } + + /** + * Sets set connect meta server executor max size. + * + * @param connectMetaServerExecutorMaxSize the connect meta server executor max size + * @return the set connect meta server executor max size + */ + public MetaServerConfigBean setConnectMetaServerExecutorMaxSize( + int connectMetaServerExecutorMaxSize) { + this.connectMetaServerExecutorMaxSize = connectMetaServerExecutorMaxSize; + return this; + } + + /** + * Sets set connect meta server executor queue size. + * + * @param connectMetaServerExecutorQueueSize the connect meta server executor queue size + * @return the set connect meta server executor queue size + */ + public MetaServerConfigBean setConnectMetaServerExecutorQueueSize( + int connectMetaServerExecutorQueueSize) { + this.connectMetaServerExecutorQueueSize = connectMetaServerExecutorQueueSize; + return this; + } + + /** + * Sets set raft client refresh executor min size. + * + * @param raftClientRefreshExecutorMinSize the raft client refresh executor min size + * @return the set raft client refresh executor min size + */ + public MetaServerConfigBean setRaftClientRefreshExecutorMinSize( + int raftClientRefreshExecutorMinSize) { + this.raftClientRefreshExecutorMinSize = raftClientRefreshExecutorMinSize; + return this; + } + + /** + * Sets set raft client refresh executor max size. + * + * @param raftClientRefreshExecutorMaxSize the raft client refresh executor max size + * @return the set raft client refresh executor max size + */ + public MetaServerConfigBean setRaftClientRefreshExecutorMaxSize( + int raftClientRefreshExecutorMaxSize) { + this.raftClientRefreshExecutorMaxSize = raftClientRefreshExecutorMaxSize; + return this; + } + + /** + * Sets set raft client refresh executor queue size. + * + * @param raftClientRefreshExecutorQueueSize the raft client refresh executor queue size + * @return the set raft client refresh executor queue size + */ + public MetaServerConfigBean setRaftClientRefreshExecutorQueueSize( + int raftClientRefreshExecutorQueueSize) { + this.raftClientRefreshExecutorQueueSize = raftClientRefreshExecutorQueueSize; + return this; + } + + public int getAppRevisionRegisterExecutorMinSize() { + return appRevisionRegisterExecutorMinSize; + } + + public void setAppRevisionRegisterExecutorMinSize(int appRevisionRegisterExecutorMinSize) { + this.appRevisionRegisterExecutorMinSize = appRevisionRegisterExecutorMinSize; + } + + public int getAppRevisionRegisterExecutorMaxSize() { + return appRevisionRegisterExecutorMaxSize; + } + + public void setAppRevisionRegisterExecutorMaxSize(int appRevisionRegisterExecutorMaxSize) { + this.appRevisionRegisterExecutorMaxSize = appRevisionRegisterExecutorMaxSize; + } + + public int getAppRevisionRegisterExecutorQueueSize() { + return appRevisionRegisterExecutorQueueSize; + } + + public void setAppRevisionRegisterExecutorQueueSize(int appRevisionRegisterExecutorQueueSize) { + this.appRevisionRegisterExecutorQueueSize = appRevisionRegisterExecutorQueueSize; + } + + public long getMetaLeaderWarmupMilli() { + return metaLeaderWarmupMilli; + } + + public void setMetaLeaderWarmupMilli(long metaLeaderWarmupMilli) { + this.metaLeaderWarmupMilli = metaLeaderWarmupMilli; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/NodeConfig.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/NodeConfig.java index d98392715..c6bc9ed38 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/NodeConfig.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/NodeConfig.java @@ -21,43 +21,45 @@ import java.util.Set; /** - * * @author shangyu.wh * @version $Id: NodeConfig.java, v 0.1 2018-01-23 15:00 shangyu.wh Exp $ */ public interface NodeConfig { - /** - * get other metaServer node - * - * @return - */ - Map> getMetaNode(); - - /** - * get other metaServer node ip - * @return - */ - Map> getMetaNodeIP(); + /** + * get other metaServer node + * + * @return + */ + Map> getMetaNode(); - /** - * local data Center id - * @return - */ - String getLocalDataCenter(); + /** + * get other metaServer node ip + * + * @return + */ + Map> getMetaNodeIP(); - /** - * get dataCenter by meta node ipAddress - * @param metaIpAddress - * @return - */ - String getMetaDataCenter(String metaIpAddress); + /** + * local data Center id + * + * @return + */ + String getLocalDataCenter(); - /** - * get datacenter meta servers - * @param dataCenter - * @return - */ - Set getDataCenterMetaServers(String dataCenter); + /** + * get dataCenter by meta node ipAddress + * + * @param metaIpAddress + * @return + */ + String getMetaDataCenter(String metaIpAddress); -} \ No newline at end of file + /** + * get datacenter meta servers + * + * @param dataCenter + * @return + */ + Set getDataCenterMetaServers(String dataCenter); +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/NodeConfigBeanProperty.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/NodeConfigBeanProperty.java index c44e073fe..72815389b 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/NodeConfigBeanProperty.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/config/NodeConfigBeanProperty.java @@ -16,37 +16,34 @@ */ package com.alipay.sofa.registry.server.meta.bootstrap.config; -import org.springframework.beans.factory.annotation.Value; - import java.util.Collection; import java.util.Map; +import org.springframework.beans.factory.annotation.Value; /** - * * @author shangyu.wh * @version $Id: NodeConfigBeanProperty.java, v 0.1 2018-05-03 16:21 shangyu.wh Exp $ */ public class NodeConfigBeanProperty extends AbstractNodeConfigBean { - @Value("#{PropertySplitter.mapOfList('${nodes.metaNode}')}") - private Map> metaNode; - - @Value("${nodes.localDataCenter}") - private String localDataCenter; - - @Override - public Map> getMetaNode() { - return metaNode; - } - - /** - * Getter method for property localDataCenter. - * - * @return property value of localDataCenter - */ - @Override - public String getLocalDataCenter() { - return localDataCenter; - } - -} \ No newline at end of file + @Value("#{PropertySplitter.mapOfList('${nodes.metaNode}')}") + private Map> metaNode; + + @Value("${nodes.localDataCenter}") + private String localDataCenter; + + @Override + public Map> getMetaNode() { + return metaNode; + } + + /** + * Getter method for property localDataCenter. + * + * @return property value of localDataCenter + */ + @Override + public String getLocalDataCenter() { + return localDataCenter; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/DataServerHandler.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/DataServerHandler.java index c3db17515..a115752b4 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/DataServerHandler.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/DataServerHandler.java @@ -18,8 +18,6 @@ /** * @author chen.zhu - *

- * Mar 11, 2021 + *

Mar 11, 2021 */ -public interface DataServerHandler { -} +public interface DataServerHandler {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/MetaServerHandler.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/MetaServerHandler.java index 63b8d5a8e..5494c6d9c 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/MetaServerHandler.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/MetaServerHandler.java @@ -18,8 +18,6 @@ /** * @author chen.zhu - *

- * Mar 11, 2021 + *

Mar 11, 2021 */ -public interface MetaServerHandler { -} +public interface MetaServerHandler {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/SessionServerHandler.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/SessionServerHandler.java index bab1ab5b9..04b6e2db2 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/SessionServerHandler.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/bootstrap/handler/SessionServerHandler.java @@ -18,8 +18,6 @@ /** * @author chen.zhu - *

- * Mar 11, 2021 + *

Mar 11, 2021 */ -public interface SessionServerHandler { -} +public interface SessionServerHandler {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/NodeCluster.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/NodeCluster.java index 54b627e6d..53b4593de 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/NodeCluster.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/NodeCluster.java @@ -22,11 +22,9 @@ /** * @author chen.zhu - *

- * Nov 20, 2020 + *

Nov 20, 2020 */ public interface NodeCluster extends Cluster { - VersionedList getClusterMeta(); - + VersionedList getClusterMeta(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/RemoteServer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/RemoteServer.java index 21046d7b2..608f3bf83 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/RemoteServer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/RemoteServer.java @@ -20,10 +20,9 @@ /** * @author chen.zhu - *

- * Nov 20, 2020 + *

Nov 20, 2020 */ public interface RemoteServer { - T getRemoteNode(); + T getRemoteNode(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/RemoteServers.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/RemoteServers.java index b6e827a07..8056574ba 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/RemoteServers.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/RemoteServers.java @@ -20,9 +20,6 @@ /** * @author chen.zhu - *

- * Nov 20, 2020 + *

Nov 20, 2020 */ -public interface RemoteServers { - -} +public interface RemoteServers {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/AbstractNodeEvent.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/AbstractNodeEvent.java index aa6490bc7..5ee8ada91 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/AbstractNodeEvent.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/AbstractNodeEvent.java @@ -20,23 +20,22 @@ /** * @author chen.zhu - *

- * Nov 25, 2020 + *

Nov 25, 2020 */ public abstract class AbstractNodeEvent implements NodeEvent { - private final T node; + private final T node; - public AbstractNodeEvent(T node) { - this.node = node; - } + public AbstractNodeEvent(T node) { + this.node = node; + } - public T getNode() { - return node; - } + public T getNode() { + return node; + } - @Override - public String toString() { - return getClass().getSimpleName() + "{" + "node=" + node + '}'; - } + @Override + public String toString() { + return getClass().getSimpleName() + "{" + "node=" + node + '}'; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeAdded.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeAdded.java index a6642a5c9..d727652a2 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeAdded.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeAdded.java @@ -20,12 +20,11 @@ /** * @author chen.zhu - *

- * Nov 25, 2020 + *

Nov 25, 2020 */ public class NodeAdded extends AbstractNodeEvent { - public NodeAdded(T node) { - super(node); - } + public NodeAdded(T node) { + super(node); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeEvent.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeEvent.java index c16fdd31b..20ac05979 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeEvent.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeEvent.java @@ -20,9 +20,6 @@ /** * @author chen.zhu - *

- * Nov 25, 2020 + *

Nov 25, 2020 */ -public interface NodeEvent { - -} +public interface NodeEvent {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeModified.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeModified.java index 970b89913..df4f17802 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeModified.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeModified.java @@ -20,24 +20,22 @@ /** * @author chen.zhu - *

- * Nov 25, 2020 + *

Nov 25, 2020 */ public class NodeModified implements NodeEvent { - private final T oldNode, newNode; + private final T oldNode, newNode; - public NodeModified(T oldNode, T newNode) { - this.oldNode = oldNode; - this.newNode = newNode; - } + public NodeModified(T oldNode, T newNode) { + this.oldNode = oldNode; + this.newNode = newNode; + } - public T getOldNode() { - return oldNode; - } - - public T getNewNode() { - return newNode; - } + public T getOldNode() { + return oldNode; + } + public T getNewNode() { + return newNode; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeRemoved.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeRemoved.java index e32302ff4..eeed2c676 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeRemoved.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeRemoved.java @@ -20,12 +20,11 @@ /** * @author chen.zhu - *

- * Nov 25, 2020 + *

Nov 25, 2020 */ public class NodeRemoved extends AbstractNodeEvent { - public NodeRemoved(T node) { - super(node); - } + public NodeRemoved(T node) { + super(node); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/Evictable.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/Evictable.java index 8c7db4ad3..3e3b744f4 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/Evictable.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/Evictable.java @@ -18,13 +18,10 @@ /** * @author chen.zhu - *

- * Mar 09, 2021 + *

Mar 09, 2021 */ public interface Evictable { - /** - * Evict. - */ - void evict(); + /** Evict. */ + void evict(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/LeaseManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/LeaseManager.java index 32a1ad1b7..283d445f8 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/LeaseManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/LeaseManager.java @@ -22,35 +22,32 @@ /** * @author chen.zhu - *

- * Nov 19, 2020 + *

Nov 19, 2020 */ public interface LeaseManager { - /** - * Renew Lease. - * Return true if the renewal has been existed and renew works - * Return false if the renewal is a new entry, we have to register it insteadof renew it - * - * @param renewal the renewal - * @param leaseDuration the lease duration - * @return the boolean - */ - boolean renew(T renewal, int leaseDuration); + /** + * Renew Lease. Return true if the renewal has been existed and renew works Return false if the + * renewal is a new entry, we have to register it insteadof renew it + * + * @param renewal the renewal + * @param leaseDuration the lease duration + * @return the boolean + */ + boolean renew(T renewal, int leaseDuration); - /** - * Gets get lease. - * - * @param renewal the renewal - * @return the get lease - */ - Lease getLease(T renewal); - - /** - * Gets get lease meta. - * - * @return the get lease meta - */ - VersionedList> getLeaseMeta(); + /** + * Gets get lease. + * + * @param renewal the renewal + * @return the get lease + */ + Lease getLease(T renewal); + /** + * Gets get lease meta. + * + * @return the get lease meta + */ + VersionedList> getLeaseMeta(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DataManagerObserver.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DataManagerObserver.java index 910d85d9f..308bfd2da 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DataManagerObserver.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DataManagerObserver.java @@ -20,8 +20,6 @@ /** * @author chen.zhu - *

- * Dec 15, 2020 + *

Dec 15, 2020 */ -public interface DataManagerObserver extends UnblockingObserver { -} +public interface DataManagerObserver extends UnblockingObserver {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DataServerManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DataServerManager.java index 5e4e68d3b..fc6a59479 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DataServerManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DataServerManager.java @@ -23,35 +23,33 @@ import com.alipay.sofa.registry.server.meta.lease.LeaseManager; import com.alipay.sofa.registry.server.meta.monitor.data.DataMessageListener; import com.alipay.sofa.registry.server.meta.monitor.data.DataServerStats; - import java.util.List; /** * @author chen.zhu - *

- * Nov 19, 2020 + *

Nov 19, 2020 */ -public interface DataServerManager extends Lifecycle, Observable, - LeaseManager, DataMessageListener { +public interface DataServerManager + extends Lifecycle, Observable, LeaseManager, DataMessageListener { - /** - * Gets get data servers stats. - * - * @return the get data servers stats - */ - List getDataServersStats(); + /** + * Gets get data servers stats. + * + * @return the get data servers stats + */ + List getDataServersStats(); - /** - * Gets get data server meta info. - * - * @return the get data server meta info - */ - VersionedList getDataServerMetaInfo(); + /** + * Gets get data server meta info. + * + * @return the get data server meta info + */ + VersionedList getDataServerMetaInfo(); - /** - * Gets get epoch. - * - * @return the get epoch - */ - long getEpoch(); + /** + * Gets get epoch. + * + * @return the get epoch + */ + long getEpoch(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DefaultDataServerManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DefaultDataServerManager.java index 429a5087b..fb83ec3f7 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DefaultDataServerManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/data/DefaultDataServerManager.java @@ -30,147 +30,141 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import java.util.Collections; import java.util.List; import java.util.Map; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * @author chen.zhu - *

- * Nov 24, 2020 + *

Nov 24, 2020 */ @Component -public class DefaultDataServerManager extends AbstractEvictableLeaseManager implements - DataServerManager { - - - @Autowired - private MetaServerConfig metaServerConfig; - - private final Map dataServerStatses = Maps.newConcurrentMap(); - - /** - * Constructor. - */ - public DefaultDataServerManager() { - } - - /** - * Constructor. - * - * @param metaServerConfig the meta server config - */ - public DefaultDataServerManager(MetaServerConfig metaServerConfig) { - this.metaServerConfig = metaServerConfig; - } - - /** - * Post construct. - * - * @throws Exception the exception - */ - @PostConstruct - public void postConstruct() throws Exception { - LifecycleHelper.initializeIfPossible(this); - LifecycleHelper.startIfPossible(this); - } - - /** - * Pre destory. - * - * @throws Exception the exception - */ - @PreDestroy - public void preDestory() throws Exception { - LifecycleHelper.stopIfPossible(this); - LifecycleHelper.disposeIfPossible(this); - } - - @Override - public void register(Lease lease) { - super.register(lease); - notifyObservers(new NodeAdded<>(lease.getRenewal())); +public class DefaultDataServerManager extends AbstractEvictableLeaseManager + implements DataServerManager { + + @Autowired private MetaServerConfig metaServerConfig; + + private final Map dataServerStatses = Maps.newConcurrentMap(); + + /** Constructor. */ + public DefaultDataServerManager() {} + + /** + * Constructor. + * + * @param metaServerConfig the meta server config + */ + public DefaultDataServerManager(MetaServerConfig metaServerConfig) { + this.metaServerConfig = metaServerConfig; + } + + /** + * Post construct. + * + * @throws Exception the exception + */ + @PostConstruct + public void postConstruct() throws Exception { + LifecycleHelper.initializeIfPossible(this); + LifecycleHelper.startIfPossible(this); + } + + /** + * Pre destory. + * + * @throws Exception the exception + */ + @PreDestroy + public void preDestory() throws Exception { + LifecycleHelper.stopIfPossible(this); + LifecycleHelper.disposeIfPossible(this); + } + + @Override + public void register(Lease lease) { + super.register(lease); + notifyObservers(new NodeAdded<>(lease.getRenewal())); + } + + @Override + public boolean cancel(Lease lease) { + boolean result = super.cancel(lease); + if (result) { + notifyObservers(new NodeRemoved<>(lease.getRenewal())); + Metrics.Heartbeat.onDataEvict(lease.getRenewal().getIp()); } - - @Override - public boolean cancel(Lease lease) { - boolean result = super.cancel(lease); - if (result) { - notifyObservers(new NodeRemoved<>(lease.getRenewal())); - Metrics.Heartbeat.onDataEvict(lease.getRenewal().getIp()); - } - return result; - } - - @Override - public boolean renew(DataNode renewal, int leaseDuration) { - Metrics.Heartbeat.onDataHeartbeat(renewal.getIp()); - return super.renew(renewal, leaseDuration); - } - - @Override - protected long getIntervalMilli() { - return metaServerConfig.getExpireCheckIntervalMilli(); - } - - @Override - protected long getEvictBetweenMilli() { - return metaServerConfig.getExpireCheckIntervalMilli(); - } - - @VisibleForTesting - DefaultDataServerManager setMetaServerConfig(MetaServerConfig metaServerConfig) { - this.metaServerConfig = metaServerConfig; - return this; - } - - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "DefaultDataServerManager"; - } - - /** - * On heartbeat. - * - * @param heartbeat the heartbeat - */ - @Override - public void onHeartbeat(HeartbeatRequest heartbeat) { - String dataServer = heartbeat.getNode().getIp(); - dataServerStatses.put( - dataServer, - new DataServerStats(dataServer, heartbeat.getSlotTableEpoch(), heartbeat - .getSlotStatus())); - } - - @Override - public List getDataServersStats() { - return Collections.unmodifiableList(Lists.newLinkedList(dataServerStatses.values())); - } - - @Override - public VersionedList getDataServerMetaInfo() { - VersionedList> leaseMetaInfo = getLeaseMeta(); - List dataNodes = Lists.newArrayList(); - leaseMetaInfo.getClusterMembers().forEach(lease -> { - dataNodes.add(lease.getRenewal()); - }); - return new VersionedList<>(leaseMetaInfo.getEpoch(), dataNodes); - } - - @Override - public long getEpoch() { - return currentEpoch.get(); - } - + return result; + } + + @Override + public boolean renew(DataNode renewal, int leaseDuration) { + Metrics.Heartbeat.onDataHeartbeat(renewal.getIp()); + return super.renew(renewal, leaseDuration); + } + + @Override + protected long getIntervalMilli() { + return metaServerConfig.getExpireCheckIntervalMilli(); + } + + @Override + protected long getEvictBetweenMilli() { + return metaServerConfig.getExpireCheckIntervalMilli(); + } + + @VisibleForTesting + DefaultDataServerManager setMetaServerConfig(MetaServerConfig metaServerConfig) { + this.metaServerConfig = metaServerConfig; + return this; + } + + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "DefaultDataServerManager"; + } + + /** + * On heartbeat. + * + * @param heartbeat the heartbeat + */ + @Override + public void onHeartbeat(HeartbeatRequest heartbeat) { + String dataServer = heartbeat.getNode().getIp(); + dataServerStatses.put( + dataServer, + new DataServerStats(dataServer, heartbeat.getSlotTableEpoch(), heartbeat.getSlotStatus())); + } + + @Override + public List getDataServersStats() { + return Collections.unmodifiableList(Lists.newLinkedList(dataServerStatses.values())); + } + + @Override + public VersionedList getDataServerMetaInfo() { + VersionedList> leaseMetaInfo = getLeaseMeta(); + List dataNodes = Lists.newArrayList(); + leaseMetaInfo + .getClusterMembers() + .forEach( + lease -> { + dataNodes.add(lease.getRenewal()); + }); + return new VersionedList<>(leaseMetaInfo.getEpoch(), dataNodes); + } + + @Override + public long getEpoch() { + return currentEpoch.get(); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/AbstractEvictableLeaseManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/AbstractEvictableLeaseManager.java index d227b4191..05b80d4ae 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/AbstractEvictableLeaseManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/AbstractEvictableLeaseManager.java @@ -24,92 +24,89 @@ import com.alipay.sofa.registry.util.ConcurrentUtils; import com.alipay.sofa.registry.util.WakeUpLoopRunnable; import com.google.common.collect.Lists; - import java.util.List; import java.util.concurrent.atomic.AtomicLong; /** * @author chen.zhu - *

- * Mar 09, 2021 + *

Mar 09, 2021 */ public abstract class AbstractEvictableLeaseManager - extends LeaderAwareLeaseManager implements Evictable { + extends LeaderAwareLeaseManager implements Evictable { - private final AtomicLong lastEvictTime = new AtomicLong(); + private final AtomicLong lastEvictTime = new AtomicLong(); - private final EvictTask evictTask = new EvictTask(); + private final EvictTask evictTask = new EvictTask(); - @Override - public void doInitialize() throws InitializeException { - super.doInitialize(); - ConcurrentUtils.createDaemonThread(getClass().getSimpleName(), evictTask).start(); - } + @Override + public void doInitialize() throws InitializeException { + super.doInitialize(); + ConcurrentUtils.createDaemonThread(getClass().getSimpleName(), evictTask).start(); + } - @Override - public void doDispose() throws DisposeException { - evictTask.close(); - super.doDispose(); - } + @Override + public void doDispose() throws DisposeException { + evictTask.close(); + super.doDispose(); + } - @Override - public void evict() { - if (lastEvictTime.get() + getEvictBetweenMilli() > System.currentTimeMillis()) { - logger.warn("[evict][too quick] last evict time: {}", lastEvictTime.get()); - return; - } - lastEvictTime.set(System.currentTimeMillis()); - List> expirations = getExpiredLeases(); - if (expirations.isEmpty()) { - return; - } + @Override + public void evict() { + if (lastEvictTime.get() + getEvictBetweenMilli() > System.currentTimeMillis()) { + logger.warn("[evict][too quick] last evict time: {}", lastEvictTime.get()); + return; + } + lastEvictTime.set(System.currentTimeMillis()); + List> expirations = getExpiredLeases(); + if (expirations.isEmpty()) { + return; + } - for (Lease lease : expirations) { - Lease doubleCheck = getLease(lease.getRenewal()); - // at this point of view, entry might be deleted through cancel method - if (doubleCheck == null) { - continue; - } - if (doubleCheck.isExpired()) { - logger - .warn("[evict] node evict [{}], cancel it and refresh epoch", doubleCheck); - try { - cancel(lease); - } catch (Throwable th) { - logger.error("[evict] node cancel failure", th); - } - } + for (Lease lease : expirations) { + Lease doubleCheck = getLease(lease.getRenewal()); + // at this point of view, entry might be deleted through cancel method + if (doubleCheck == null) { + continue; + } + if (doubleCheck.isExpired()) { + logger.warn("[evict] node evict [{}], cancel it and refresh epoch", doubleCheck); + try { + cancel(lease); + } catch (Throwable th) { + logger.error("[evict] node cancel failure", th); } + } } + } - protected List> getExpiredLeases() { - List> expires = Lists.newLinkedList(); - for (Lease lease : getLeaseMeta().getClusterMembers()) { - if (lease.isExpired()) { - expires.add(lease); - } - } - return expires; + protected List> getExpiredLeases() { + List> expires = Lists.newLinkedList(); + for (Lease lease : getLeaseMeta().getClusterMembers()) { + if (lease.isExpired()) { + expires.add(lease); + } } + return expires; + } - protected abstract long getEvictBetweenMilli(); + protected abstract long getEvictBetweenMilli(); - protected abstract long getIntervalMilli(); + protected abstract long getIntervalMilli(); - private final class EvictTask extends WakeUpLoopRunnable { + private final class EvictTask extends WakeUpLoopRunnable { - @Override - public int getWaitingMillis() { - return (int) getIntervalMilli(); - } + @Override + public int getWaitingMillis() { + return (int) getIntervalMilli(); + } - @Override - public void runUnthrowable() { - if (metaLeaderService.amIStableAsLeader()) { - logger.debug("[evict] begin"); - evict(); - logger.debug("[evict] end"); - } - } + @Override + public void runUnthrowable() { + if (metaLeaderService.amIStableAsLeader()) { + logger.debug("[evict] begin"); + evict(); + logger.debug("[evict] end"); + } } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/DefaultCrossDcMetaServerManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/DefaultCrossDcMetaServerManager.java index 2ec98dffe..96d1cfe0d 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/DefaultCrossDcMetaServerManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/DefaultCrossDcMetaServerManager.java @@ -16,6 +16,9 @@ */ package com.alipay.sofa.registry.server.meta.lease.impl; +import static com.alipay.sofa.registry.server.meta.bootstrap.MetaServerConfiguration.GLOBAL_EXECUTOR; +import static com.alipay.sofa.registry.server.meta.bootstrap.MetaServerConfiguration.SHARED_SCHEDULE_EXECUTOR; + import com.alipay.sofa.registry.exception.*; import com.alipay.sofa.registry.lifecycle.impl.AbstractLifecycle; import com.alipay.sofa.registry.lifecycle.impl.LifecycleHelper; @@ -29,184 +32,177 @@ import com.alipay.sofa.registry.util.ConcurrentUtils; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import javax.annotation.Resource; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; - -import static com.alipay.sofa.registry.server.meta.bootstrap.MetaServerConfiguration.GLOBAL_EXECUTOR; -import static com.alipay.sofa.registry.server.meta.bootstrap.MetaServerConfiguration.SHARED_SCHEDULE_EXECUTOR; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import javax.annotation.Resource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * @author chen.zhu - *

- * Nov 23, 2020 + *

Nov 23, 2020 */ /** - * Unique entrance for all "Cross-Dc-MetaServer" instances - * As while as a LeaderAware object, which watches leader event and trigger cross-dc-metaservers' refresh job when leader term - * and stop all of them when it's not a raft-cluster leader - * */ + * Unique entrance for all "Cross-Dc-MetaServer" instances As while as a LeaderAware object, which + * watches leader event and trigger cross-dc-metaservers' refresh job when leader term and stop all + * of them when it's not a raft-cluster leader + */ @Component -//@Profile(value = "cloud") -public class DefaultCrossDcMetaServerManager extends AbstractLifecycle implements CrossDcMetaServerManager { +// @Profile(value = "cloud") +public class DefaultCrossDcMetaServerManager extends AbstractLifecycle + implements CrossDcMetaServerManager { - /** - * Map[DataCenter(String), CrossDcMetaServer] - * */ - private ConcurrentMap crossDcMetaServers = Maps.newConcurrentMap(); + /** Map[DataCenter(String), CrossDcMetaServer] */ + private ConcurrentMap crossDcMetaServers = Maps.newConcurrentMap(); - @Autowired - private NodeConfig nodeConfig; + @Autowired private NodeConfig nodeConfig; - @Autowired - private MetaServerConfig metaServerConfig; + @Autowired private MetaServerConfig metaServerConfig; - @Autowired - private MetaLeaderService metaLeaderService; + @Autowired private MetaLeaderService metaLeaderService; - @Resource(name = SHARED_SCHEDULE_EXECUTOR) - private ScheduledExecutorService scheduled; + @Resource(name = SHARED_SCHEDULE_EXECUTOR) + private ScheduledExecutorService scheduled; - @Resource(name = GLOBAL_EXECUTOR) - private ExecutorService executors; + @Resource(name = GLOBAL_EXECUTOR) + private ExecutorService executors; - @Autowired - private BoltExchange boltExchange; + @Autowired private BoltExchange boltExchange; - @PostConstruct - public void postConstruct() throws Exception { - LifecycleHelper.initializeIfPossible(this); - } + @PostConstruct + public void postConstruct() throws Exception { + LifecycleHelper.initializeIfPossible(this); + } - @PreDestroy - public void preDestory() throws Exception { - LifecycleHelper.stopIfPossible(this); - LifecycleHelper.disposeIfPossible(this); - } + @PreDestroy + public void preDestory() throws Exception { + LifecycleHelper.stopIfPossible(this); + LifecycleHelper.disposeIfPossible(this); + } - @Override - public CrossDcMetaServer getOrCreate(String dcName) { - CrossDcMetaServer metaServer = crossDcMetaServers.get(dcName); + @Override + public CrossDcMetaServer getOrCreate(String dcName) { + CrossDcMetaServer metaServer = crossDcMetaServers.get(dcName); + if (metaServer == null) { + synchronized (this) { + metaServer = crossDcMetaServers.get(dcName); if (metaServer == null) { - synchronized (this) { - metaServer = crossDcMetaServers.get(dcName); - if (metaServer == null) { - metaServer = new DefaultCrossDcMetaServer(dcName, - nodeConfig.getDataCenterMetaServers(dcName), scheduled, boltExchange, - metaLeaderService, metaServerConfig); - try { - LifecycleHelper.initializeIfPossible(metaServer); - } catch (Throwable e) { - logger - .error( - "[getOrCreate][{}]Cross-Dc-MetaServer create err, stop register to map", - dcName, e); - throw new SofaRegistryRuntimeException(e); - } - crossDcMetaServers.put(dcName, metaServer); - } - } - } - return metaServer; - } - - @Override - protected void doInitialize() throws InitializeException { - super.doInitialize(); - for (Map.Entry> entry : nodeConfig.getMetaNodeIP().entrySet()) { - if (entry.getKey().equalsIgnoreCase(nodeConfig.getLocalDataCenter())) { - continue; - } - getOrCreate(entry.getKey()); + metaServer = + new DefaultCrossDcMetaServer( + dcName, + nodeConfig.getDataCenterMetaServers(dcName), + scheduled, + boltExchange, + metaLeaderService, + metaServerConfig); + try { + LifecycleHelper.initializeIfPossible(metaServer); + } catch (Throwable e) { + logger.error( + "[getOrCreate][{}]Cross-Dc-MetaServer create err, stop register to map", dcName, e); + throw new SofaRegistryRuntimeException(e); + } + crossDcMetaServers.put(dcName, metaServer); } + } } - - @Override - protected void doStart() throws StartException { - super.doStart(); - new ConcurrentUtils.SafeParaLoop(executors, crossDcMetaServers.values()) { - @Override - protected void doRun0(CrossDcMetaServer metaServer) throws Exception { - LifecycleHelper.startIfPossible(metaServer); - } - }.run(); - } - - @Override - protected void doStop() throws StopException { - new ConcurrentUtils.SafeParaLoop(executors, crossDcMetaServers.values()) { - @Override - protected void doRun0(CrossDcMetaServer metaServer) throws Exception { - LifecycleHelper.stopIfPossible(metaServer); - } - }.run(); - super.doStop(); - } - - @Override - protected void doDispose() throws DisposeException { - this.crossDcMetaServers = Maps.newConcurrentMap(); - super.doDispose(); - } - - @VisibleForTesting - DefaultCrossDcMetaServerManager setNodeConfig(NodeConfig nodeConfig) { - this.nodeConfig = nodeConfig; - return this; - } - - @VisibleForTesting - DefaultCrossDcMetaServerManager setMetaServerConfig(MetaServerConfig metaServerConfig) { - this.metaServerConfig = metaServerConfig; - return this; - } - - @VisibleForTesting - DefaultCrossDcMetaServerManager setScheduled(ScheduledExecutorService scheduled) { - this.scheduled = scheduled; - return this; - } - - @VisibleForTesting - DefaultCrossDcMetaServerManager setExecutors(ExecutorService executors) { - this.executors = executors; - return this; + return metaServer; + } + + @Override + protected void doInitialize() throws InitializeException { + super.doInitialize(); + for (Map.Entry> entry : nodeConfig.getMetaNodeIP().entrySet()) { + if (entry.getKey().equalsIgnoreCase(nodeConfig.getLocalDataCenter())) { + continue; + } + getOrCreate(entry.getKey()); } - - @VisibleForTesting - DefaultCrossDcMetaServerManager setBoltExchange(BoltExchange boltExchange) { - this.boltExchange = boltExchange; - return this; - } - - @VisibleForTesting - ConcurrentMap getCrossDcMetaServers() { - return crossDcMetaServers; + } + + @Override + protected void doStart() throws StartException { + super.doStart(); + new ConcurrentUtils.SafeParaLoop(executors, crossDcMetaServers.values()) { + @Override + protected void doRun0(CrossDcMetaServer metaServer) throws Exception { + LifecycleHelper.startIfPossible(metaServer); + } + }.run(); + } + + @Override + protected void doStop() throws StopException { + new ConcurrentUtils.SafeParaLoop(executors, crossDcMetaServers.values()) { + @Override + protected void doRun0(CrossDcMetaServer metaServer) throws Exception { + LifecycleHelper.stopIfPossible(metaServer); + } + }.run(); + super.doStop(); + } + + @Override + protected void doDispose() throws DisposeException { + this.crossDcMetaServers = Maps.newConcurrentMap(); + super.doDispose(); + } + + @VisibleForTesting + DefaultCrossDcMetaServerManager setNodeConfig(NodeConfig nodeConfig) { + this.nodeConfig = nodeConfig; + return this; + } + + @VisibleForTesting + DefaultCrossDcMetaServerManager setMetaServerConfig(MetaServerConfig metaServerConfig) { + this.metaServerConfig = metaServerConfig; + return this; + } + + @VisibleForTesting + DefaultCrossDcMetaServerManager setScheduled(ScheduledExecutorService scheduled) { + this.scheduled = scheduled; + return this; + } + + @VisibleForTesting + DefaultCrossDcMetaServerManager setExecutors(ExecutorService executors) { + this.executors = executors; + return this; + } + + @VisibleForTesting + DefaultCrossDcMetaServerManager setBoltExchange(BoltExchange boltExchange) { + this.boltExchange = boltExchange; + return this; + } + + @VisibleForTesting + ConcurrentMap getCrossDcMetaServers() { + return crossDcMetaServers; + } + + @Override + public void becomeLeader() { + try { + LifecycleHelper.startIfPossible(this); + } catch (Throwable th) { + logger.error("[becomeLeader]", th); } - - @Override - public void becomeLeader() { - try { - LifecycleHelper.startIfPossible(this); - } catch (Throwable th) { - logger.error("[becomeLeader]", th); - } - } - - @Override - public void loseLeader() { - try { - LifecycleHelper.stopIfPossible(this); - } catch (Throwable th) { - logger.error("[loseLeader]", th); - } + } + + @Override + public void loseLeader() { + try { + LifecycleHelper.stopIfPossible(this); + } catch (Throwable th) { + logger.error("[loseLeader]", th); } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/LeaderAwareLeaseManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/LeaderAwareLeaseManager.java index bd2ec0b67..e4432cd11 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/LeaderAwareLeaseManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/LeaderAwareLeaseManager.java @@ -24,61 +24,58 @@ /** * @author chen.zhu - *

- * Mar 09, 2021 + *

Mar 09, 2021 */ public class LeaderAwareLeaseManager extends SimpleLeaseManager { - @Autowired - protected MetaLeaderService metaLeaderService; + @Autowired protected MetaLeaderService metaLeaderService; - /** - * Register. - * - * @param lease the lease - */ - @Override - public void register(Lease lease) { - if (!amILeader()) { - throw new SofaRegistryMetaLeaderException(metaLeaderService.getLeader(), metaLeaderService.getLeaderEpoch(), - "leader mismatch"); - } - super.register(lease); + /** + * Register. + * + * @param lease the lease + */ + @Override + public void register(Lease lease) { + if (!amILeader()) { + throw new SofaRegistryMetaLeaderException( + metaLeaderService.getLeader(), metaLeaderService.getLeaderEpoch(), "leader mismatch"); } + super.register(lease); + } - /** - * Cancel boolean. - * - * @param lease the lease - * @return the boolean - */ - @Override - public boolean cancel(Lease lease) { - if (!amILeader()) { - throw new SofaRegistryMetaLeaderException(metaLeaderService.getLeader(), metaLeaderService.getLeaderEpoch(), - "leader mismatch"); - } - return super.cancel(lease); + /** + * Cancel boolean. + * + * @param lease the lease + * @return the boolean + */ + @Override + public boolean cancel(Lease lease) { + if (!amILeader()) { + throw new SofaRegistryMetaLeaderException( + metaLeaderService.getLeader(), metaLeaderService.getLeaderEpoch(), "leader mismatch"); } + return super.cancel(lease); + } - /** - * Renew boolean. - * - * @param renewal the renewal - * @param leaseDuration the lease duration - * @return the boolean - */ - @Override - public boolean renew(T renewal, int leaseDuration) { - if (!amILeader()) { - throw new SofaRegistryMetaLeaderException(metaLeaderService.getLeader(), metaLeaderService.getLeaderEpoch(), - "leader mismatch"); - } - return super.renew(renewal, leaseDuration); - } - - protected boolean amILeader() { - return metaLeaderService.amILeader(); + /** + * Renew boolean. + * + * @param renewal the renewal + * @param leaseDuration the lease duration + * @return the boolean + */ + @Override + public boolean renew(T renewal, int leaseDuration) { + if (!amILeader()) { + throw new SofaRegistryMetaLeaderException( + metaLeaderService.getLeader(), metaLeaderService.getLeaderEpoch(), "leader mismatch"); } + return super.renew(renewal, leaseDuration); + } + protected boolean amILeader() { + return metaLeaderService.amILeader(); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/SimpleLeaseManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/SimpleLeaseManager.java index 7a4475954..e65a5cc72 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/SimpleLeaseManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/impl/SimpleLeaseManager.java @@ -27,7 +27,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.collect.Maps; - import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicLong; @@ -35,121 +34,127 @@ /** * @author chen.zhu - *

- * Mar 09, 2021 + *

Mar 09, 2021 */ -public class SimpleLeaseManager extends AbstractLifecycleObservable implements LeaseManager { - - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - protected final AtomicLong currentEpoch = new AtomicLong(); - //Map[ip-address, Lease{node, duration, timestamp}] - protected final ConcurrentMap> localRepo = Maps.newConcurrentMap(); - - protected final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - - protected void register(Lease lease) { - if (lease == null) { - throw new IllegalArgumentException("[register]NullPointer of lease"); - } - logger.info("[register] register node: {}", lease.getRenewal()); - - lock.writeLock().lock(); - try { - String nodeIp = lease.getRenewal().getNodeUrl().getIpAddress(); - localRepo.putIfAbsent(nodeIp, lease); - refreshEpoch(DatumVersionUtil.nextId()); - } finally { - lock.writeLock().unlock(); - } - } +public class SimpleLeaseManager extends AbstractLifecycleObservable + implements LeaseManager { - protected boolean cancel(Lease lease) { - if (lease == null) { - throw new IllegalArgumentException("[cancel]NullPointer of renewal"); - } - // read lock for concurrent modification, and mutext for renew/register operations - lock.writeLock().lock(); - boolean result = true; - try { - logger.info("[cancel][begin] {}", lease); - result = localRepo.remove(lease.getRenewal().getNodeUrl().getIpAddress(), lease); - logger.info("[cancel][end] {}", result); - refreshEpoch(DatumVersionUtil.nextId()); - } finally { - lock.writeLock().unlock(); - } - return result; - } + protected final Logger logger = LoggerFactory.getLogger(getClass()); - @Override - public boolean renew(T renewal, int leaseDuration) { - if (renewal == null) { - throw new IllegalArgumentException("[renew]NullPointer of renewal"); - } - int validLeaseDuration = leaseDuration > 0 ? leaseDuration : Lease.DEFAULT_DURATION_SECS; - - lock.writeLock().lock(); - try { - Lease lease = localRepo.get(renewal.getNodeUrl().getIpAddress()); - if (lease == null) { - logger.warn("[renew][node not exist, register: {}-{}]", renewal.getNodeType(), - renewal.getNodeUrl().getIpAddress()); - - register(new Lease<>(renewal, validLeaseDuration)); - return false; - } - logger.info("[renew][renew lease] node: {}-{}, extends: {}s", - renewal.getNodeType(), renewal.getNodeUrl().getIpAddress(), validLeaseDuration); - - lease.renew(validLeaseDuration); - } finally { - lock.writeLock().unlock(); - } - return true; - } + protected final AtomicLong currentEpoch = new AtomicLong(); + // Map[ip-address, Lease{node, duration, timestamp}] + protected final ConcurrentMap> localRepo = Maps.newConcurrentMap(); - @Override - public Lease getLease(T renewal) { - return localRepo.get(renewal.getNodeUrl().getIpAddress()); - } + protected final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - @Override - public VersionedList> getLeaseMeta() { - lock.readLock().lock(); - try { - return new VersionedList<>(getEpoch(), getClusterMembers()); - } finally { - lock.readLock().unlock(); - } + protected void register(Lease lease) { + if (lease == null) { + throw new IllegalArgumentException("[register]NullPointer of lease"); } - - @VisibleForTesting - protected boolean refreshEpoch(long newEpoch) { - if (currentEpoch.get() < newEpoch) { - logger.info("[refreshEpoch] epoch change from {} to {}", currentEpoch.get(), - newEpoch); - currentEpoch.set(newEpoch); - return true; - } else { - logger.info("[refreshEpoch] epoch change not able, current {}, request {}", - currentEpoch.get(), newEpoch); - return false; - } + logger.info("[register] register node: {}", lease.getRenewal()); + + lock.writeLock().lock(); + try { + String nodeIp = lease.getRenewal().getNodeUrl().getIpAddress(); + localRepo.putIfAbsent(nodeIp, lease); + refreshEpoch(DatumVersionUtil.nextId()); + } finally { + lock.writeLock().unlock(); } + } - private long getEpoch() { - return currentEpoch.get(); + protected boolean cancel(Lease lease) { + if (lease == null) { + throw new IllegalArgumentException("[cancel]NullPointer of renewal"); } + // read lock for concurrent modification, and mutext for renew/register operations + lock.writeLock().lock(); + boolean result = true; + try { + logger.info("[cancel][begin] {}", lease); + result = localRepo.remove(lease.getRenewal().getNodeUrl().getIpAddress(), lease); + logger.info("[cancel][end] {}", result); + refreshEpoch(DatumVersionUtil.nextId()); + } finally { + lock.writeLock().unlock(); + } + return result; + } - private List> getClusterMembers() { - List> result = Lists.newArrayList(); - try { - lock.readLock().lock(); - result.addAll(localRepo.values()); - return result; - } finally { - lock.readLock().unlock(); - } + @Override + public boolean renew(T renewal, int leaseDuration) { + if (renewal == null) { + throw new IllegalArgumentException("[renew]NullPointer of renewal"); + } + int validLeaseDuration = leaseDuration > 0 ? leaseDuration : Lease.DEFAULT_DURATION_SECS; + + lock.writeLock().lock(); + try { + Lease lease = localRepo.get(renewal.getNodeUrl().getIpAddress()); + if (lease == null) { + logger.warn( + "[renew][node not exist, register: {}-{}]", + renewal.getNodeType(), + renewal.getNodeUrl().getIpAddress()); + + register(new Lease<>(renewal, validLeaseDuration)); + return false; + } + logger.info( + "[renew][renew lease] node: {}-{}, extends: {}s", + renewal.getNodeType(), + renewal.getNodeUrl().getIpAddress(), + validLeaseDuration); + + lease.renew(validLeaseDuration); + } finally { + lock.writeLock().unlock(); + } + return true; + } + + @Override + public Lease getLease(T renewal) { + return localRepo.get(renewal.getNodeUrl().getIpAddress()); + } + + @Override + public VersionedList> getLeaseMeta() { + lock.readLock().lock(); + try { + return new VersionedList<>(getEpoch(), getClusterMembers()); + } finally { + lock.readLock().unlock(); + } + } + + @VisibleForTesting + protected boolean refreshEpoch(long newEpoch) { + if (currentEpoch.get() < newEpoch) { + logger.info("[refreshEpoch] epoch change from {} to {}", currentEpoch.get(), newEpoch); + currentEpoch.set(newEpoch); + return true; + } else { + logger.info( + "[refreshEpoch] epoch change not able, current {}, request {}", + currentEpoch.get(), + newEpoch); + return false; + } + } + + private long getEpoch() { + return currentEpoch.get(); + } + + private List> getClusterMembers() { + List> result = Lists.newArrayList(); + try { + lock.readLock().lock(); + result.addAll(localRepo.values()); + return result; + } finally { + lock.readLock().unlock(); } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/DefaultSessionServerManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/DefaultSessionServerManager.java index 6071c3f27..6a66e2998 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/DefaultSessionServerManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/DefaultSessionServerManager.java @@ -31,119 +31,123 @@ import com.alipay.sofa.registry.server.meta.slot.SlotManager; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import java.util.List; import java.util.Objects; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * @author chen.zhu - *

- * Nov 24, 2020 + *

Nov 24, 2020 */ @Component public class DefaultSessionServerManager extends AbstractEvictableLeaseManager - implements SessionServerManager { - - @Autowired - private MetaServerConfig metaServerConfig; - - @Autowired - private SlotManager slotManager; - - @PostConstruct - public void postConstruct() throws Exception { - LifecycleHelper.initializeIfPossible(this); - LifecycleHelper.startIfPossible(this); - } - - @PreDestroy - public void preDestory() throws Exception { - LifecycleHelper.stopIfPossible(this); - LifecycleHelper.disposeIfPossible(this); - } - - @Override - public void register(Lease lease) { - super.register(lease); - notifyObservers(new NodeAdded<>(lease.getRenewal())); - } - /** - * Different from data server, session node maintains a 'ProcessId' to be as unique Id for Session Process(not server) - * - * Once a restart event happened on the same session-server, an notification will be sent - * */ - @Override - public boolean renew(SessionNode renewal, int duration) { - Metrics.Heartbeat.onSessionHeartbeat(renewal.getIp()); - Lease lease = getLease(renewal); - if (renewal.getProcessId() != null && lease != null && lease.getRenewal() != null - && !Objects.equals(lease.getRenewal().getProcessId(), renewal.getProcessId())) { - logger.warn("[renew] session node is restart, as process-Id change from {} to {}", - lease.getRenewal().getProcessId(), renewal.getProcessId()); - // replace the session node, as it has changed process-id already - lease.setRenewal(renewal); - super.register(new Lease<>(renewal, duration)); - notifyObservers(new NodeModified<>(lease.getRenewal(), renewal)); - return false; - } else { - return super.renew(renewal, duration); - } - } - - @Override - public boolean cancel(Lease lease) { - boolean result = super.cancel(lease); - if (result) { - Metrics.Heartbeat.onSessionEvict(lease.getRenewal().getIp()); - notifyObservers(new NodeRemoved<>(lease.getRenewal())); - } - return result; + implements SessionServerManager { + + @Autowired private MetaServerConfig metaServerConfig; + + @Autowired private SlotManager slotManager; + + @PostConstruct + public void postConstruct() throws Exception { + LifecycleHelper.initializeIfPossible(this); + LifecycleHelper.startIfPossible(this); + } + + @PreDestroy + public void preDestory() throws Exception { + LifecycleHelper.stopIfPossible(this); + LifecycleHelper.disposeIfPossible(this); + } + + @Override + public void register(Lease lease) { + super.register(lease); + notifyObservers(new NodeAdded<>(lease.getRenewal())); + } + /** + * Different from data server, session node maintains a 'ProcessId' to be as unique Id for Session + * Process(not server) + * + *

Once a restart event happened on the same session-server, an notification will be sent + */ + @Override + public boolean renew(SessionNode renewal, int duration) { + Metrics.Heartbeat.onSessionHeartbeat(renewal.getIp()); + Lease lease = getLease(renewal); + if (renewal.getProcessId() != null + && lease != null + && lease.getRenewal() != null + && !Objects.equals(lease.getRenewal().getProcessId(), renewal.getProcessId())) { + logger.warn( + "[renew] session node is restart, as process-Id change from {} to {}", + lease.getRenewal().getProcessId(), + renewal.getProcessId()); + // replace the session node, as it has changed process-id already + lease.setRenewal(renewal); + super.register(new Lease<>(renewal, duration)); + notifyObservers(new NodeModified<>(lease.getRenewal(), renewal)); + return false; + } else { + return super.renew(renewal, duration); } - - @Override - protected long getIntervalMilli() { - return metaServerConfig.getExpireCheckIntervalMilli(); - } - - @Override - protected long getEvictBetweenMilli() { - return metaServerConfig.getExpireCheckIntervalMilli(); + } + + @Override + public boolean cancel(Lease lease) { + boolean result = super.cancel(lease); + if (result) { + Metrics.Heartbeat.onSessionEvict(lease.getRenewal().getIp()); + notifyObservers(new NodeRemoved<>(lease.getRenewal())); } - - @VisibleForTesting - DefaultSessionServerManager setMetaServerConfig(MetaServerConfig metaServerConfig) { - this.metaServerConfig = metaServerConfig; - return this; + return result; + } + + @Override + protected long getIntervalMilli() { + return metaServerConfig.getExpireCheckIntervalMilli(); + } + + @Override + protected long getEvictBetweenMilli() { + return metaServerConfig.getExpireCheckIntervalMilli(); + } + + @VisibleForTesting + DefaultSessionServerManager setMetaServerConfig(MetaServerConfig metaServerConfig) { + this.metaServerConfig = metaServerConfig; + return this; + } + + @Override + public VersionedList getSessionServerMetaInfo() { + VersionedList> leaseMetaInfo = getLeaseMeta(); + List sessionNodes = Lists.newArrayList(); + leaseMetaInfo + .getClusterMembers() + .forEach( + lease -> { + sessionNodes.add(lease.getRenewal()); + }); + return new VersionedList<>(leaseMetaInfo.getEpoch(), sessionNodes); + } + + @Override + public long getEpoch() { + return currentEpoch.get(); + } + + @Override + public void onHeartbeat(HeartbeatRequest heartbeat) { + if (amILeader() && metaLeaderService.isWarmup()) { + learnFromSession(heartbeat); } + } - @Override - public VersionedList getSessionServerMetaInfo() { - VersionedList> leaseMetaInfo = getLeaseMeta(); - List sessionNodes = Lists.newArrayList(); - leaseMetaInfo.getClusterMembers().forEach(lease -> { - sessionNodes.add(lease.getRenewal()); - }); - return new VersionedList<>(leaseMetaInfo.getEpoch(), sessionNodes); - } - - @Override - public long getEpoch() { - return currentEpoch.get(); - } - - @Override - public void onHeartbeat(HeartbeatRequest heartbeat) { - if (amILeader() && metaLeaderService.isWarmup()) { - learnFromSession(heartbeat); - } - } - - protected void learnFromSession(HeartbeatRequest heartbeat) { - SlotTable slotTable = heartbeat.getSlotTable(); - slotManager.refresh(slotTable); - } + protected void learnFromSession(HeartbeatRequest heartbeat) { + SlotTable slotTable = heartbeat.getSlotTable(); + slotManager.refresh(slotTable); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/SessionManagerObserver.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/SessionManagerObserver.java index 394677984..47b77a49f 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/SessionManagerObserver.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/SessionManagerObserver.java @@ -20,8 +20,6 @@ /** * @author chen.zhu - *

- * Dec 15, 2020 + *

Dec 15, 2020 */ -public interface SessionManagerObserver extends UnblockingObserver { -} +public interface SessionManagerObserver extends UnblockingObserver {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/SessionServerManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/SessionServerManager.java index 9046e73eb..77643b8a3 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/SessionServerManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/lease/session/SessionServerManager.java @@ -25,12 +25,12 @@ /** * @author chen.zhu - *

- * Nov 23, 2020 + *

Nov 23, 2020 */ -public interface SessionServerManager extends Observable, Lifecycle, LeaseManager, SessionMessageListener { +public interface SessionServerManager + extends Observable, Lifecycle, LeaseManager, SessionMessageListener { - VersionedList getSessionServerMetaInfo(); + VersionedList getSessionServerMetaInfo(); - long getEpoch(); + long getEpoch(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CrossDcMetaServer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CrossDcMetaServer.java index c7ddf3b1b..124d6b08f 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CrossDcMetaServer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CrossDcMetaServer.java @@ -24,10 +24,7 @@ /** * @author chen.zhu - *

- * Nov 20, 2020 + *

Nov 20, 2020 */ -public interface CrossDcMetaServer extends DataCenterAware, NodeCluster, - RemoteServers, MetaServer { - -} +public interface CrossDcMetaServer + extends DataCenterAware, NodeCluster, RemoteServers, MetaServer {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CrossDcMetaServerManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CrossDcMetaServerManager.java index 48f16e0c2..cff3151c4 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CrossDcMetaServerManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CrossDcMetaServerManager.java @@ -22,21 +22,16 @@ /** * @author chen.zhu - *

- * Nov 19, 2020 + *

Nov 19, 2020 */ public interface CrossDcMetaServerManager - extends - Lifecycle, - MetaLeaderService.MetaLeaderElectorListener { - - /** - * Gets get or create. - * - * @param dc - * the dc - * @return the get or create - */ - MetaServer getOrCreate(String dc); + extends Lifecycle, MetaLeaderService.MetaLeaderElectorListener { + /** + * Gets get or create. + * + * @param dc the dc + * @return the get or create + */ + MetaServer getOrCreate(String dc); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CurrentDcMetaServer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CurrentDcMetaServer.java index 0958e122b..4ca1f352c 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CurrentDcMetaServer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/CurrentDcMetaServer.java @@ -26,19 +26,17 @@ /** * @author chen.zhu - *

- * Nov 23, 2020 + *

Nov 23, 2020 */ public interface CurrentDcMetaServer extends MetaServer, NodeCluster, Observable { - void renew(MetaNode metaNode); + void renew(MetaNode metaNode); - void cancel(MetaNode metaNode); + void cancel(MetaNode metaNode); - void updateClusterMembers(VersionedList metaNodes); + void updateClusterMembers(VersionedList metaNodes); - DataServerManager getDataServerManager(); - - SessionServerManager getSessionServerManager(); + DataServerManager getDataServerManager(); + SessionServerManager getSessionServerManager(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/MetaServerObserver.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/MetaServerObserver.java index fd40f0c7a..ce815db4a 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/MetaServerObserver.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/MetaServerObserver.java @@ -20,8 +20,6 @@ /** * @author chen.zhu - *

- * Dec 15, 2020 + *

Dec 15, 2020 */ -public interface MetaServerObserver extends UnblockingObserver { -} +public interface MetaServerObserver extends UnblockingObserver {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/AbstractMetaServer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/AbstractMetaServer.java index 220be2048..8db321a82 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/AbstractMetaServer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/AbstractMetaServer.java @@ -20,20 +20,17 @@ import com.alipay.sofa.registry.observer.impl.AbstractLifecycleObservable; import com.alipay.sofa.registry.server.meta.MetaServer; import com.google.common.collect.Sets; - import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @author chen.zhu - *

- * Nov 20, 2020 + *

Nov 20, 2020 */ public abstract class AbstractMetaServer extends AbstractLifecycleObservable implements MetaServer { - protected volatile Set metaServers = Sets.newHashSet(); - - protected final ReadWriteLock lock = new ReentrantReadWriteLock(); + protected volatile Set metaServers = Sets.newHashSet(); + protected final ReadWriteLock lock = new ReentrantReadWriteLock(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCrossDcMetaServer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCrossDcMetaServer.java index d4818c652..fc0cc2a9d 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCrossDcMetaServer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCrossDcMetaServer.java @@ -39,8 +39,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import org.springframework.aop.target.dynamic.Refreshable; - import java.util.Collection; import java.util.List; import java.util.Set; @@ -50,291 +48,309 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; +import org.springframework.aop.target.dynamic.Refreshable; /** * @author chen.zhu - *

- * Nov 20, 2020 - - * Generated through Factory - * CrossDcMetaServer is an object(could be as many as data centers we replicates data) that managing corresponding meta-server infos, as: - * 1. meta server list (here we consider cross-dc meta-servers as one virtual meta-server, as it supports nothing but slot-table) - * 2. slot table - * - * Scheduled Job is running inside meta-server object for high-cohesion perspective - * Other objects should not and must not have the privilege to care about updating slot-table or meta-server list - * What other objects needs to know is "Hey, I got the picture of other data-center's slot view and meta-server list" - * - * See @doRefresh for meta server list update - * See @refreshSlotTable for slot table update - * */ -public class DefaultCrossDcMetaServer extends AbstractMetaServer implements CrossDcMetaServer, - Refreshable { - - private final String dcName; + *

Nov 20, 2020 + *

Generated through Factory CrossDcMetaServer is an object(could be as many as data centers + * we replicates data) that managing corresponding meta-server infos, as: 1. meta server list + * (here we consider cross-dc meta-servers as one virtual meta-server, as it supports nothing + * but slot-table) 2. slot table + *

Scheduled Job is running inside meta-server object for high-cohesion perspective Other + * objects should not and must not have the privilege to care about updating slot-table or + * meta-server list What other objects needs to know is "Hey, I got the picture of other + * data-center's slot view and meta-server list" + *

See @doRefresh for meta server list update See @refreshSlotTable for slot table update + */ +public class DefaultCrossDcMetaServer extends AbstractMetaServer + implements CrossDcMetaServer, Refreshable { - private final List initMetaAddresses; + private final String dcName; - private final AtomicLong currentVersion = new AtomicLong(); + private final List initMetaAddresses; - private final ScheduledExecutorService scheduled; + private final AtomicLong currentVersion = new AtomicLong(); - private volatile ScheduledFuture future; + private final ScheduledExecutorService scheduled; - private final AtomicLong counter = new AtomicLong(); + private volatile ScheduledFuture future; - private final AtomicLong timestamp = new AtomicLong(); + private final AtomicLong counter = new AtomicLong(); - private final MetaLeaderService metaLeaderService; + private final AtomicLong timestamp = new AtomicLong(); - private SlotAllocator allocator; + private final MetaLeaderService metaLeaderService; - private final Exchange exchange; + private SlotAllocator allocator; - private final AtomicInteger requestMetaNodeIndex = new AtomicInteger(0); + private final Exchange exchange; - private final MetaServerConfig metaServerConfig; + private final AtomicInteger requestMetaNodeIndex = new AtomicInteger(0); - public DefaultCrossDcMetaServer(String dcName, Collection metaServerIpAddresses, - ScheduledExecutorService scheduled, Exchange exchange, - MetaLeaderService metaLeaderService, MetaServerConfig metaServerConfig) { - this.dcName = dcName; - this.initMetaAddresses = Lists.newArrayList(metaServerIpAddresses); - this.scheduled = scheduled; - this.exchange = exchange; - this.metaLeaderService = metaLeaderService; - this.metaServerConfig = metaServerConfig; - } + private final MetaServerConfig metaServerConfig; - @Override - protected void doInitialize() throws InitializeException { - super.doInitialize(); - initMetaNodes(); - initSlotAllocator(); - } + public DefaultCrossDcMetaServer( + String dcName, + Collection metaServerIpAddresses, + ScheduledExecutorService scheduled, + Exchange exchange, + MetaLeaderService metaLeaderService, + MetaServerConfig metaServerConfig) { + this.dcName = dcName; + this.initMetaAddresses = Lists.newArrayList(metaServerIpAddresses); + this.scheduled = scheduled; + this.exchange = exchange; + this.metaLeaderService = metaLeaderService; + this.metaServerConfig = metaServerConfig; + } - private void initMetaNodes() { - Set metaNodes = Sets.newHashSet(); - for (String ip : initMetaAddresses) { - metaNodes.add(new MetaNode(new URL(ip), dcName)); - } - this.metaServers = metaNodes; - } + @Override + protected void doInitialize() throws InitializeException { + super.doInitialize(); + initMetaNodes(); + initSlotAllocator(); + } - private void initSlotAllocator() throws InitializeException { - this.allocator = new CrossDcSlotAllocator(dcName, scheduled, exchange, this, metaLeaderService); - LifecycleHelper.initializeIfPossible(allocator); + private void initMetaNodes() { + Set metaNodes = Sets.newHashSet(); + for (String ip : initMetaAddresses) { + metaNodes.add(new MetaNode(new URL(ip), dcName)); } - - @Override - protected void doStart() throws StartException { - super.doStart(); - future = scheduled.scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { + this.metaServers = metaNodes; + } + + private void initSlotAllocator() throws InitializeException { + this.allocator = new CrossDcSlotAllocator(dcName, scheduled, exchange, this, metaLeaderService); + LifecycleHelper.initializeIfPossible(allocator); + } + + @Override + protected void doStart() throws StartException { + super.doStart(); + future = + scheduled.scheduleWithFixedDelay( + new Runnable() { + @Override + public void run() { if (metaLeaderService.amIStableAsLeader()) { - refresh(); + refresh(); } - } - }, getIntervalMilli(), getIntervalMilli(), TimeUnit.MILLISECONDS); - // start allocator for slot purpose - LifecycleHelper.startIfPossible(allocator); + } + }, + getIntervalMilli(), + getIntervalMilli(), + TimeUnit.MILLISECONDS); + // start allocator for slot purpose + LifecycleHelper.startIfPossible(allocator); + } + + @Override + protected void doStop() throws StopException { + // stop allocator for slot purpose + try { + LifecycleHelper.stopIfPossible(allocator); + } catch (StopException e) { + logger.error("[stop][stop allocator error]", e); } - - @Override - protected void doStop() throws StopException { - // stop allocator for slot purpose - try { - LifecycleHelper.stopIfPossible(allocator); - } catch (StopException e) { - logger.error("[stop][stop allocator error]", e); - } - if (future != null) { - future.cancel(true); - future = null; - } - super.doStop(); + if (future != null) { + future.cancel(true); + future = null; } - - @Override - protected void doDispose() throws DisposeException { - LifecycleHelper.disposeIfPossible(allocator); - super.doDispose(); + super.doStop(); + } + + @Override + protected void doDispose() throws DisposeException { + LifecycleHelper.disposeIfPossible(allocator); + super.doDispose(); + } + + @Override + public String getDc() { + return dcName; + } + + @Override + public SlotTable getSlotTable() { + if (!getLifecycleState().isStarted()) { + throw new IllegalStateException("[DefaultCrossDcMetaServer] not started yet"); } - - @Override - public String getDc() { - return dcName; + return allocator.getSlotTable(); + } + + public long getEpoch() { + return currentVersion.get(); + } + + @Override + public List getClusterMembers() { + return Lists.newArrayList(metaServers); + } + + private int getIntervalMilli() { + return metaServerConfig.getCrossDcMetaSyncIntervalMilli(); + } + + @VisibleForTesting + protected void doRefresh(int retryTimes) { + if (retryTimes >= 3) { + logger.warn("[doRefresh]retries more than {} times, stop", 3); + return; } - - @Override - public SlotTable getSlotTable() { - if (!getLifecycleState().isStarted()) { - throw new IllegalStateException("[DefaultCrossDcMetaServer] not started yet"); - } - return allocator.getSlotTable(); - } - - public long getEpoch() { - return currentVersion.get(); - } - - @Override - public List getClusterMembers() { - return Lists.newArrayList(metaServers); - } - - private int getIntervalMilli() { - return metaServerConfig.getCrossDcMetaSyncIntervalMilli(); + NodeClusterViewRequest request = new NodeClusterViewRequest(Node.NodeType.META, getDc()); + MetaNode metaServer = getRemoteMetaServer(); + if (metaServer == null) { + logger.warn("[doRefresh] no meta-server available"); + return; } - - @VisibleForTesting - protected void doRefresh(int retryTimes) { - if (retryTimes >= 3) { - logger.warn("[doRefresh]retries more than {} times, stop", 3); - return; - } - NodeClusterViewRequest request = new NodeClusterViewRequest(Node.NodeType.META, getDc()); - MetaNode metaServer = getRemoteMetaServer(); - if (metaServer == null) { - logger.warn("[doRefresh] no meta-server available"); - return; - } - exchange.getClient(Exchange.META_SERVER_TYPE).sendCallback(metaServer.getNodeUrl(), - request, new CallbackHandler() { - @Override - @SuppressWarnings("unchecked") - public void onCallback(Channel channel, Object message) { - if (message instanceof DataCenterNodes) { - tryUpdateRemoteDcMetaServerList((DataCenterNodes) message); - } else { - logger.error("[doRefresh][onCallback]unknown type from response: {}", - message); - } + exchange + .getClient(Exchange.META_SERVER_TYPE) + .sendCallback( + metaServer.getNodeUrl(), + request, + new CallbackHandler() { + @Override + @SuppressWarnings("unchecked") + public void onCallback(Channel channel, Object message) { + if (message instanceof DataCenterNodes) { + tryUpdateRemoteDcMetaServerList((DataCenterNodes) message); + } else { + logger.error("[doRefresh][onCallback]unknown type from response: {}", message); } - - @Override - public void onException(Channel channel, Throwable exception) { - if (logger.isErrorEnabled()) { - logger - .error( - "[doRefresh][onException][{}]Bolt Request Failure, remote: {}, will try other meta-server", - getDc(), channel != null ? channel.getRemoteAddress().getHostName() - : "unknown", exception); - } - List metaNodes = getClusterMembers(); - if (metaNodes == null || metaNodes.isEmpty()) { - logger.warn("[doRefresh][onException] no meta-servers available"); - return; - } - requestMetaNodeIndex.set(requestMetaNodeIndex.incrementAndGet() - % getClusterMembers().size()); - // if failure, try again with another meta server. - // good luck with that. :) - doRefresh(retryTimes + 1); + } + + @Override + public void onException(Channel channel, Throwable exception) { + if (logger.isErrorEnabled()) { + logger.error( + "[doRefresh][onException][{}]Bolt Request Failure, remote: {}, will try other meta-server", + getDc(), + channel != null ? channel.getRemoteAddress().getHostName() : "unknown", + exception); } - - @Override - public Executor getExecutor() { - return scheduled; + List metaNodes = getClusterMembers(); + if (metaNodes == null || metaNodes.isEmpty()) { + logger.warn("[doRefresh][onException] no meta-servers available"); + return; } - }, 5000); + requestMetaNodeIndex.set( + requestMetaNodeIndex.incrementAndGet() % getClusterMembers().size()); + // if failure, try again with another meta server. + // good luck with that. :) + doRefresh(retryTimes + 1); + } + + @Override + public Executor getExecutor() { + return scheduled; + } + }, + 5000); + } + + @Override + public void refresh() { + if (!(getLifecycleState().isStarting() || getLifecycleState().isStarted())) { + if (logger.isWarnEnabled()) { + logger.warn("[refresh][not started yet]{}", getDc()); + } + return; } - - @Override - public void refresh() { - if (!(getLifecycleState().isStarting() || getLifecycleState().isStarted())) { - if (logger.isWarnEnabled()) { - logger.warn("[refresh][not started yet]{}", getDc()); - } - return; - } - counter.incrementAndGet(); - timestamp.set(System.currentTimeMillis()); - if (logger.isInfoEnabled()) { - logger.info("[refresh][{}][times-{}] start", getDc(), getRefreshCount()); - } - doRefresh(0); - if (logger.isInfoEnabled()) { - logger.info("[refresh][{}][times-{}] end", getDc(), getRefreshCount()); - } + counter.incrementAndGet(); + timestamp.set(System.currentTimeMillis()); + if (logger.isInfoEnabled()) { + logger.info("[refresh][{}][times-{}] start", getDc(), getRefreshCount()); } - - @Override - public long getRefreshCount() { - return counter.get(); + doRefresh(0); + if (logger.isInfoEnabled()) { + logger.info("[refresh][{}][times-{}] end", getDc(), getRefreshCount()); } - - @Override - public long getLastRefreshTime() { - return timestamp.get(); + } + + @Override + public long getRefreshCount() { + return counter.get(); + } + + @Override + public long getLastRefreshTime() { + return timestamp.get(); + } + + private MetaNode getRemoteMetaServer() { + List metaServers = getClusterMembers(); + return metaServers.isEmpty() + ? null + : metaServers.get(requestMetaNodeIndex.get() % getClusterMembers().size()); + } + + @VisibleForTesting + protected DefaultCrossDcMetaServer setMetaServer(SlotAllocator allocator) { + if (getLifecycleState().isStarted()) { + throw new IllegalStateException("cannot reset meta-server instance while started"); } - - private MetaNode getRemoteMetaServer() { - List metaServers = getClusterMembers(); - return metaServers.isEmpty() ? null : metaServers.get(requestMetaNodeIndex.get() - % getClusterMembers().size()); + this.allocator = allocator; + return this; + } + + @Override + public VersionedList getClusterMeta() { + return new VersionedList<>(getEpoch(), getClusterMembers()); + } + + public void tryUpdateRemoteDcMetaServerList(DataCenterNodes response) { + String remoteDc = response.getDataCenterId(); + if (!getDc().equalsIgnoreCase(remoteDc)) { + throw new IllegalArgumentException( + String.format( + "MetaServer List Response not correct, ask [%s], received [%s]", getDc(), remoteDc)); } - - @VisibleForTesting - protected DefaultCrossDcMetaServer setMetaServer(SlotAllocator allocator) { - if (getLifecycleState().isStarted()) { - throw new IllegalStateException("cannot reset meta-server instance while started"); + DefaultCrossDcMetaServer.this.lock.writeLock().lock(); + try { + Long remoteVersion = response.getVersion(); + if (remoteVersion <= currentVersion.get()) { + if (logger.isDebugEnabled()) { + logger.debug( + "[tryUpdateRemoteDcMetaServerList]shall ignore as version is left behind, " + + "remote[{}], current[{}]", + remoteVersion, + currentVersion.get()); } - this.allocator = allocator; - return this; - } - - @Override - public VersionedList getClusterMeta() { - return new VersionedList<>(getEpoch(), getClusterMembers()); - } - - public void tryUpdateRemoteDcMetaServerList(DataCenterNodes response) { - String remoteDc = response.getDataCenterId(); - if (!getDc().equalsIgnoreCase(remoteDc)) { - throw new IllegalArgumentException(String.format( - "MetaServer List Response not correct, ask [%s], received [%s]", getDc(), - remoteDc)); - } - DefaultCrossDcMetaServer.this.lock.writeLock().lock(); - try { - Long remoteVersion = response.getVersion(); - if (remoteVersion <= currentVersion.get()) { - if (logger.isDebugEnabled()) { - logger.debug( - "[tryUpdateRemoteDcMetaServerList]shall ignore as version is left behind, " - + "remote[{}], current[{}]", remoteVersion, - currentVersion.get()); - } - return; - } - if (logger.isWarnEnabled()) { - logger - .warn( - "[tryUpdateRemoteDcMetaServerList][{}] remote meta server changed, \nbefore: {}, \nafter: {}", - getDc(), DefaultCrossDcMetaServer.this.metaServers, - response.getNodes() != null ? response.getNodes().values() : "None"); - } - currentVersion.set(remoteVersion); - if (response.getNodes() != null) { - metaServers = Sets.newHashSet(response.getNodes().values()); - } - } finally { - DefaultCrossDcMetaServer.this.lock.writeLock().unlock(); - } - - } - - @VisibleForTesting - DefaultCrossDcMetaServer setAllocator(SlotAllocator allocator) { - this.allocator = allocator; - return this; - } - - @Override - public String toString() { - return "DefaultCrossDcMetaServer{" + "dcName='" + dcName + '\'' + ", initMetaAddresses=" - + initMetaAddresses + ", lastRefreshTime=" + timestamp + '}'; + return; + } + if (logger.isWarnEnabled()) { + logger.warn( + "[tryUpdateRemoteDcMetaServerList][{}] remote meta server changed, \nbefore: {}, \nafter: {}", + getDc(), + DefaultCrossDcMetaServer.this.metaServers, + response.getNodes() != null ? response.getNodes().values() : "None"); + } + currentVersion.set(remoteVersion); + if (response.getNodes() != null) { + metaServers = Sets.newHashSet(response.getNodes().values()); + } + } finally { + DefaultCrossDcMetaServer.this.lock.writeLock().unlock(); } + } + + @VisibleForTesting + DefaultCrossDcMetaServer setAllocator(SlotAllocator allocator) { + this.allocator = allocator; + return this; + } + + @Override + public String toString() { + return "DefaultCrossDcMetaServer{" + + "dcName='" + + dcName + + '\'' + + ", initMetaAddresses=" + + initMetaAddresses + + ", lastRefreshTime=" + + timestamp + + '}'; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCurrentDcMetaServer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCurrentDcMetaServer.java index 0a6723817..0caf12254 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCurrentDcMetaServer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCurrentDcMetaServer.java @@ -32,105 +32,102 @@ import com.alipay.sofa.registry.util.DatumVersionUtil; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import java.util.Collection; import java.util.List; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * @author chen.zhu - *

- * Nov 23, 2020 + *

Nov 23, 2020 */ @Component public class DefaultCurrentDcMetaServer extends LocalMetaServer implements CurrentDcMetaServer { - @Autowired - private NodeConfig nodeConfig; - - public DefaultCurrentDcMetaServer() { - } - - public DefaultCurrentDcMetaServer(SlotManager slotManager, - DataServerManager dataServerManager, - SessionServerManager sessionServerManager) { - super(slotManager, dataServerManager, sessionServerManager); - } - - @PostConstruct - public void postConstruct() throws Exception { - LifecycleHelper.initializeIfPossible(this); - LifecycleHelper.startIfPossible(this); - } - - @PreDestroy - public void preDestory() throws Exception { - LifecycleHelper.stopIfPossible(this); - LifecycleHelper.disposeIfPossible(this); - } - - @Override - protected void doInitialize() throws InitializeException { - super.doInitialize(); - initMetaServers(); - } - - private void initMetaServers() { - Collection metaIpAddresses = nodeConfig.getMetaNodeIP().get( - nodeConfig.getLocalDataCenter()); - List metaNodes = Lists.newArrayList(); - for (String ip : metaIpAddresses) { - metaNodes.add(new MetaNode(new URL(ip), nodeConfig.getLocalDataCenter())); - } - updateClusterMembers(new VersionedList<>(DatumVersionUtil.nextId(), metaNodes)); - } - - @Override - protected void doDispose() throws DisposeException { - super.doDispose(); - } - - @Override - public void renew(MetaNode metaNode) { - super.renew(metaNode); - notifyObservers(new NodeAdded<>(metaNode)); - } - - @Override - public void cancel(MetaNode metaNode) { - super.cancel(metaNode); - notifyObservers(new NodeRemoved(metaNode)); - } - - @VisibleForTesting - DefaultCurrentDcMetaServer setSessionManager(SessionServerManager sessionServerManager) { - this.sessionServerManager = sessionServerManager; - return this; - } - - @VisibleForTesting - DefaultCurrentDcMetaServer setDataServerManager(DataServerManager dataServerManager) { - this.dataServerManager = dataServerManager; - return this; - } - - @VisibleForTesting - DefaultCurrentDcMetaServer setNodeConfig(NodeConfig nodeConfig) { - this.nodeConfig = nodeConfig; - return this; - } - - @VisibleForTesting - DefaultCurrentDcMetaServer setSlotManager(SlotManager slotManager) { - this.slotManager = slotManager; - return this; - } - - @Override - public VersionedList getClusterMeta() { - return new VersionedList<>(getEpoch(), getClusterMembers()); + @Autowired private NodeConfig nodeConfig; + + public DefaultCurrentDcMetaServer() {} + + public DefaultCurrentDcMetaServer( + SlotManager slotManager, + DataServerManager dataServerManager, + SessionServerManager sessionServerManager) { + super(slotManager, dataServerManager, sessionServerManager); + } + + @PostConstruct + public void postConstruct() throws Exception { + LifecycleHelper.initializeIfPossible(this); + LifecycleHelper.startIfPossible(this); + } + + @PreDestroy + public void preDestory() throws Exception { + LifecycleHelper.stopIfPossible(this); + LifecycleHelper.disposeIfPossible(this); + } + + @Override + protected void doInitialize() throws InitializeException { + super.doInitialize(); + initMetaServers(); + } + + private void initMetaServers() { + Collection metaIpAddresses = + nodeConfig.getMetaNodeIP().get(nodeConfig.getLocalDataCenter()); + List metaNodes = Lists.newArrayList(); + for (String ip : metaIpAddresses) { + metaNodes.add(new MetaNode(new URL(ip), nodeConfig.getLocalDataCenter())); } + updateClusterMembers(new VersionedList<>(DatumVersionUtil.nextId(), metaNodes)); + } + + @Override + protected void doDispose() throws DisposeException { + super.doDispose(); + } + + @Override + public void renew(MetaNode metaNode) { + super.renew(metaNode); + notifyObservers(new NodeAdded<>(metaNode)); + } + + @Override + public void cancel(MetaNode metaNode) { + super.cancel(metaNode); + notifyObservers(new NodeRemoved(metaNode)); + } + + @VisibleForTesting + DefaultCurrentDcMetaServer setSessionManager(SessionServerManager sessionServerManager) { + this.sessionServerManager = sessionServerManager; + return this; + } + + @VisibleForTesting + DefaultCurrentDcMetaServer setDataServerManager(DataServerManager dataServerManager) { + this.dataServerManager = dataServerManager; + return this; + } + + @VisibleForTesting + DefaultCurrentDcMetaServer setNodeConfig(NodeConfig nodeConfig) { + this.nodeConfig = nodeConfig; + return this; + } + + @VisibleForTesting + DefaultCurrentDcMetaServer setSlotManager(SlotManager slotManager) { + this.slotManager = slotManager; + return this; + } + + @Override + public VersionedList getClusterMeta() { + return new VersionedList<>(getEpoch(), getClusterMembers()); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaLeaderElector.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaLeaderElector.java index 57ebaba4c..777be2824 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaLeaderElector.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaLeaderElector.java @@ -25,129 +25,128 @@ import com.alipay.sofa.registry.server.meta.bootstrap.config.MetaServerConfig; import com.alipay.sofa.registry.store.api.elector.LeaderAware; import com.alipay.sofa.registry.store.api.elector.LeaderElector; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * @author chen.zhu - *

- * Mar 10, 2021 + *

Mar 10, 2021 */ @Component -public class DefaultMetaLeaderElector extends AbstractLifecycleObservable implements MetaLeaderService, LeaderAware { +public class DefaultMetaLeaderElector extends AbstractLifecycleObservable + implements MetaLeaderService, LeaderAware { - private final Logger logger = LoggerFactory.getLogger(DefaultMetaLeaderElector.class); + private final Logger logger = LoggerFactory.getLogger(DefaultMetaLeaderElector.class); - @Autowired - private LeaderElector leaderElector; + @Autowired private LeaderElector leaderElector; - @Autowired - private MetaServerConfig metaServerConfig; + @Autowired private MetaServerConfig metaServerConfig; - @Autowired(required = false) - private List listeners; + @Autowired(required = false) + private List listeners; - private final AtomicBoolean wasLeader = new AtomicBoolean(false); + private final AtomicBoolean wasLeader = new AtomicBoolean(false); - private final AtomicReference leaderState = new AtomicReference<>(); + private final AtomicReference leaderState = new AtomicReference<>(); - @PostConstruct - public void postConstruct() throws Exception { - LifecycleHelper.initializeIfPossible(this); - LifecycleHelper.startIfPossible(this); - leaderElector.registerLeaderAware(this); + @PostConstruct + public void postConstruct() throws Exception { + LifecycleHelper.initializeIfPossible(this); + LifecycleHelper.startIfPossible(this); + leaderElector.registerLeaderAware(this); + } - } + @Override + protected void doInitialize() throws InitializeException { + super.doInitialize(); + } - @Override - protected void doInitialize() throws InitializeException { - super.doInitialize(); - } + @Override + public boolean isWarmup() { + return leaderState.get() != null + && System.currentTimeMillis() - leaderState.get().getStartTime() > getWarmupMilli(); + } - @Override - public boolean isWarmup() { - return leaderState.get() != null - && System.currentTimeMillis() - leaderState.get().getStartTime() > getWarmupMilli(); - } + @Override + public boolean amILeader() { + return leaderElector.amILeader(); + } - @Override - public boolean amILeader() { - return leaderElector.amILeader(); - } + @Override + public String getLeader() { + return leaderElector.getLeader(); + } - @Override - public String getLeader() { - return leaderElector.getLeader(); - } + @Override + public long getLeaderEpoch() { + return leaderElector.getLeaderEpoch(); + } - @Override - public long getLeaderEpoch() { - return leaderElector.getLeaderEpoch(); + @Override + public void leaderNotify() { + if (wasLeader.compareAndSet(false, true)) { + leaderState.set( + new LeaderState(LeaderElector.ElectorRole.LEADER, System.currentTimeMillis())); + becomeLeader(); } - - - @Override - public void leaderNotify() { - if (wasLeader.compareAndSet(false, true)) { - leaderState.set(new LeaderState(LeaderElector.ElectorRole.LEADER, System.currentTimeMillis())); - becomeLeader(); - } + } + + @Override + public void followNotify() { + if (wasLeader.compareAndSet(true, false)) { + leaderState.set( + new LeaderState(LeaderElector.ElectorRole.FOLLOWER, System.currentTimeMillis())); + loseLeader(); } + } - @Override - public void followNotify() { - if (wasLeader.compareAndSet(true, false)) { - leaderState.set(new LeaderState(LeaderElector.ElectorRole.FOLLOWER, System.currentTimeMillis())); - loseLeader(); - } + protected void becomeLeader() { + if (logger.isInfoEnabled()) { + logger.info("[becomeLeader] change from follower to elector"); } - - protected void becomeLeader() { - if (logger.isInfoEnabled()) { - logger.info("[becomeLeader] change from follower to elector"); - } - if (listeners != null && !listeners.isEmpty()) { - listeners.forEach(listener -> { - listener.becomeLeader(); - }); - } + if (listeners != null && !listeners.isEmpty()) { + listeners.forEach( + listener -> { + listener.becomeLeader(); + }); } + } - private long getWarmupMilli() { - return metaServerConfig.getMetaLeaderWarmupMilli(); - } + private long getWarmupMilli() { + return metaServerConfig.getMetaLeaderWarmupMilli(); + } - protected void loseLeader() { - if (logger.isInfoEnabled()) { - logger.info("[becomeFollow] change from elector to follower"); - } - if (listeners != null && !listeners.isEmpty()) { - listeners.forEach(listener -> { - listener.loseLeader(); - }); - } + protected void loseLeader() { + if (logger.isInfoEnabled()) { + logger.info("[becomeFollow] change from elector to follower"); + } + if (listeners != null && !listeners.isEmpty()) { + listeners.forEach( + listener -> { + listener.loseLeader(); + }); } + } - private static final class LeaderState { - private final LeaderElector.ElectorRole state; - private final long startTime; + private static final class LeaderState { + private final LeaderElector.ElectorRole state; + private final long startTime; - public LeaderState(LeaderElector.ElectorRole state, long startTime) { - this.state = state; - this.startTime = startTime; - } + public LeaderState(LeaderElector.ElectorRole state, long startTime) { + this.state = state; + this.startTime = startTime; + } - public LeaderElector.ElectorRole getState() { - return state; - } + public LeaderElector.ElectorRole getState() { + return state; + } - public long getStartTime() { - return startTime; - } + public long getStartTime() { + return startTime; } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaServerManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaServerManager.java index 9707d97c1..ed730de1a 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaServerManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaServerManager.java @@ -28,131 +28,127 @@ import com.alipay.sofa.registry.server.meta.metaserver.CurrentDcMetaServer; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import java.util.List; import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * @author chen.zhu - *

- * Nov 25, 2020 + *

Nov 25, 2020 */ @Component public class DefaultMetaServerManager { - @Autowired - private DefaultCrossDcMetaServerManager crossDcMetaServerManager; - - @Autowired - private CurrentDcMetaServer currentDcMetaServer; - - @Autowired - private SessionServerManager sessionServerManager; - - @Autowired - private DataServerManager dataServerManager; - - @Autowired - private NodeConfig nodeConfig; - - public NodeChangeResult getSummary(Node.NodeType type) { - switch (type) { - case META: - return (NodeChangeResult) getMetaServerLists(); - case DATA: - return getDataServerLists(); - case SESSION: - return getSessionServerLists(); - default: - break; - } - return null; - } - - private NodeChangeResult getMetaServerLists() { - NodeChangeResult result = new NodeChangeResult<>(Node.NodeType.META); - result.setLocalDataCenter(nodeConfig.getLocalDataCenter()); - Map> nodeMap = Maps.newHashMap(); - Map epochMap = Maps.newHashMap(); - for (String dcName : nodeConfig.getMetaNodeIP().keySet()) { - List metaNodeList = crossDcMetaServerManager.getOrCreate(dcName) - .getClusterMembers(); - nodeMap.put(dcName, transform(metaNodeList)); - epochMap.put(dcName, crossDcMetaServerManager.getOrCreate(dcName).getEpoch()); - } - nodeMap.put(nodeConfig.getLocalDataCenter(), - transform(currentDcMetaServer.getClusterMembers())); - epochMap.put(nodeConfig.getLocalDataCenter(), currentDcMetaServer.getEpoch()); - result.setNodes(nodeMap); - result.setDataCenterListVersions(epochMap); - - result.setVersion(currentDcMetaServer.getEpoch()); - return result; - } - - private NodeChangeResult getSessionServerLists() { - NodeChangeResult result = new NodeChangeResult<>(Node.NodeType.SESSION); - result.setLocalDataCenter(nodeConfig.getLocalDataCenter()); - Map> nodeMap = Maps.newHashMap(); - Map epochMap = Maps.newHashMap(); - nodeMap.put(nodeConfig.getLocalDataCenter(), - transform(sessionServerManager.getSessionServerMetaInfo().getClusterMembers())); - result.setNodes(nodeMap); - result.setVersion(sessionServerManager.getEpoch()); - result.setDataCenterListVersions(epochMap); - return result; - } + @Autowired private DefaultCrossDcMetaServerManager crossDcMetaServerManager; - private NodeChangeResult getDataServerLists() { - NodeChangeResult result = new NodeChangeResult<>(Node.NodeType.DATA); - result.setLocalDataCenter(nodeConfig.getLocalDataCenter()); - Map> nodeMap = Maps.newHashMap(); - Map epochMap = Maps.newHashMap(); - nodeMap.put(nodeConfig.getLocalDataCenter(), - transform(dataServerManager.getDataServerMetaInfo().getClusterMembers())); - result.setNodes(nodeMap); - result.setVersion(dataServerManager.getEpoch()); - result.setDataCenterListVersions(epochMap); - return result; - } + @Autowired private CurrentDcMetaServer currentDcMetaServer; - private Map transform(List nodes) { - Map map = Maps.newHashMap(); - for (T node : nodes) { - map.put(node.getNodeUrl().getIpAddress(), node); - } - return map; - } + @Autowired private SessionServerManager sessionServerManager; - @VisibleForTesting - DefaultMetaServerManager setCrossDcMetaServerManager(DefaultCrossDcMetaServerManager crossDcMetaServerManager) { - this.crossDcMetaServerManager = crossDcMetaServerManager; - return this; - } + @Autowired private DataServerManager dataServerManager; - @VisibleForTesting - DefaultMetaServerManager setCurrentDcMetaServer(CurrentDcMetaServer currentDcMetaServer) { - this.currentDcMetaServer = currentDcMetaServer; - return this; - } + @Autowired private NodeConfig nodeConfig; - @VisibleForTesting - DefaultMetaServerManager setSessionManager(SessionServerManager sessionServerManager) { - this.sessionServerManager = sessionServerManager; - return this; + public NodeChangeResult getSummary(Node.NodeType type) { + switch (type) { + case META: + return (NodeChangeResult) getMetaServerLists(); + case DATA: + return getDataServerLists(); + case SESSION: + return getSessionServerLists(); + default: + break; } - - @VisibleForTesting - DefaultMetaServerManager setDataServerManager(DataServerManager dataServerManager) { - this.dataServerManager = dataServerManager; - return this; + return null; + } + + private NodeChangeResult getMetaServerLists() { + NodeChangeResult result = new NodeChangeResult<>(Node.NodeType.META); + result.setLocalDataCenter(nodeConfig.getLocalDataCenter()); + Map> nodeMap = Maps.newHashMap(); + Map epochMap = Maps.newHashMap(); + for (String dcName : nodeConfig.getMetaNodeIP().keySet()) { + List metaNodeList = + crossDcMetaServerManager.getOrCreate(dcName).getClusterMembers(); + nodeMap.put(dcName, transform(metaNodeList)); + epochMap.put(dcName, crossDcMetaServerManager.getOrCreate(dcName).getEpoch()); } - - @VisibleForTesting - DefaultMetaServerManager setNodeConfig(NodeConfig nodeConfig) { - this.nodeConfig = nodeConfig; - return this; + nodeMap.put( + nodeConfig.getLocalDataCenter(), transform(currentDcMetaServer.getClusterMembers())); + epochMap.put(nodeConfig.getLocalDataCenter(), currentDcMetaServer.getEpoch()); + result.setNodes(nodeMap); + result.setDataCenterListVersions(epochMap); + + result.setVersion(currentDcMetaServer.getEpoch()); + return result; + } + + private NodeChangeResult getSessionServerLists() { + NodeChangeResult result = new NodeChangeResult<>(Node.NodeType.SESSION); + result.setLocalDataCenter(nodeConfig.getLocalDataCenter()); + Map> nodeMap = Maps.newHashMap(); + Map epochMap = Maps.newHashMap(); + nodeMap.put( + nodeConfig.getLocalDataCenter(), + transform(sessionServerManager.getSessionServerMetaInfo().getClusterMembers())); + result.setNodes(nodeMap); + result.setVersion(sessionServerManager.getEpoch()); + result.setDataCenterListVersions(epochMap); + return result; + } + + private NodeChangeResult getDataServerLists() { + NodeChangeResult result = new NodeChangeResult<>(Node.NodeType.DATA); + result.setLocalDataCenter(nodeConfig.getLocalDataCenter()); + Map> nodeMap = Maps.newHashMap(); + Map epochMap = Maps.newHashMap(); + nodeMap.put( + nodeConfig.getLocalDataCenter(), + transform(dataServerManager.getDataServerMetaInfo().getClusterMembers())); + result.setNodes(nodeMap); + result.setVersion(dataServerManager.getEpoch()); + result.setDataCenterListVersions(epochMap); + return result; + } + + private Map transform(List nodes) { + Map map = Maps.newHashMap(); + for (T node : nodes) { + map.put(node.getNodeUrl().getIpAddress(), node); } + return map; + } + + @VisibleForTesting + DefaultMetaServerManager setCrossDcMetaServerManager( + DefaultCrossDcMetaServerManager crossDcMetaServerManager) { + this.crossDcMetaServerManager = crossDcMetaServerManager; + return this; + } + + @VisibleForTesting + DefaultMetaServerManager setCurrentDcMetaServer(CurrentDcMetaServer currentDcMetaServer) { + this.currentDcMetaServer = currentDcMetaServer; + return this; + } + + @VisibleForTesting + DefaultMetaServerManager setSessionManager(SessionServerManager sessionServerManager) { + this.sessionServerManager = sessionServerManager; + return this; + } + + @VisibleForTesting + DefaultMetaServerManager setDataServerManager(DataServerManager dataServerManager) { + this.dataServerManager = dataServerManager; + return this; + } + + @VisibleForTesting + DefaultMetaServerManager setNodeConfig(NodeConfig nodeConfig) { + this.nodeConfig = nodeConfig; + return this; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/LocalMetaServer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/LocalMetaServer.java index 8550bf93e..8efc19c75 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/LocalMetaServer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/metaserver/impl/LocalMetaServer.java @@ -25,105 +25,107 @@ import com.alipay.sofa.registry.server.meta.slot.SlotManager; import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.List; import java.util.concurrent.atomic.AtomicLong; +import org.springframework.beans.factory.annotation.Autowired; /** * @author chen.zhu - *

- * Dec 14, 2020 + *

Dec 14, 2020 */ public class LocalMetaServer extends AbstractMetaServer implements CurrentDcMetaServer { - private final AtomicLong currentEpoch = new AtomicLong(); + private final AtomicLong currentEpoch = new AtomicLong(); - @Autowired - protected SlotManager slotManager; + @Autowired protected SlotManager slotManager; - @Autowired - protected DataServerManager dataServerManager; + @Autowired protected DataServerManager dataServerManager; - @Autowired - protected SessionServerManager sessionServerManager; + @Autowired protected SessionServerManager sessionServerManager; - public LocalMetaServer() { - } + public LocalMetaServer() {} - public LocalMetaServer(SlotManager slotManager, DataServerManager dataServerManager, - SessionServerManager sessionServerManager) { - this.slotManager = slotManager; - this.dataServerManager = dataServerManager; - this.sessionServerManager = sessionServerManager; - } - - @Override - public SlotTable getSlotTable() { - return slotManager.getSlotTable(); - } + public LocalMetaServer( + SlotManager slotManager, + DataServerManager dataServerManager, + SessionServerManager sessionServerManager) { + this.slotManager = slotManager; + this.dataServerManager = dataServerManager; + this.sessionServerManager = sessionServerManager; + } - public long getEpoch() { - return currentEpoch.get(); - } + @Override + public SlotTable getSlotTable() { + return slotManager.getSlotTable(); + } - @Override - public List getClusterMembers() { - return Lists.newArrayList(metaServers); - } + public long getEpoch() { + return currentEpoch.get(); + } - @Override - public void updateClusterMembers(VersionedList versionedMetaNodes) { - if (versionedMetaNodes.getEpoch() <= currentEpoch.get()) { - logger.warn("[updateClusterMembers]Epoch[{}] is less than current[{}], ignore: {}", - currentEpoch.get(), versionedMetaNodes.getEpoch(), versionedMetaNodes.getClusterMembers()); - } - lock.writeLock().lock(); - try { - logger.warn( - "[updateClusterMembers] update meta-servers, \nprevious[{}]: {} \ncurrent[{}]: {}", - currentEpoch.get(), getClusterMembers(), versionedMetaNodes.getEpoch(), versionedMetaNodes.getClusterMembers()); - currentEpoch.set(versionedMetaNodes.getEpoch()); - metaServers = Sets.newHashSet(versionedMetaNodes.getClusterMembers()); - } finally { - lock.writeLock().unlock(); - } - } + @Override + public List getClusterMembers() { + return Lists.newArrayList(metaServers); + } - @Override - public DataServerManager getDataServerManager() { - return dataServerManager; + @Override + public void updateClusterMembers(VersionedList versionedMetaNodes) { + if (versionedMetaNodes.getEpoch() <= currentEpoch.get()) { + logger.warn( + "[updateClusterMembers]Epoch[{}] is less than current[{}], ignore: {}", + currentEpoch.get(), + versionedMetaNodes.getEpoch(), + versionedMetaNodes.getClusterMembers()); } - - @Override - public SessionServerManager getSessionServerManager() { - return sessionServerManager; + lock.writeLock().lock(); + try { + logger.warn( + "[updateClusterMembers] update meta-servers, \nprevious[{}]: {} \ncurrent[{}]: {}", + currentEpoch.get(), + getClusterMembers(), + versionedMetaNodes.getEpoch(), + versionedMetaNodes.getClusterMembers()); + currentEpoch.set(versionedMetaNodes.getEpoch()); + metaServers = Sets.newHashSet(versionedMetaNodes.getClusterMembers()); + } finally { + lock.writeLock().unlock(); } - - @Override - public void renew(MetaNode metaNode) { - lock.writeLock().lock(); - try { - logger.info("[renew]meta node [{}] renewed", metaNode); - metaServers.add(metaNode); - } finally { - lock.writeLock().unlock(); - } + } + + @Override + public DataServerManager getDataServerManager() { + return dataServerManager; + } + + @Override + public SessionServerManager getSessionServerManager() { + return sessionServerManager; + } + + @Override + public void renew(MetaNode metaNode) { + lock.writeLock().lock(); + try { + logger.info("[renew]meta node [{}] renewed", metaNode); + metaServers.add(metaNode); + } finally { + lock.writeLock().unlock(); } - - @Override - public void cancel(MetaNode renewal) { - lock.writeLock().lock(); - try { - logger.info("[cancel]meta node [{}] removed", renewal); - metaServers.remove(renewal); - } finally { - lock.writeLock().unlock(); - } + } + + @Override + public void cancel(MetaNode renewal) { + lock.writeLock().lock(); + try { + logger.info("[cancel]meta node [{}] removed", renewal); + metaServers.remove(renewal); + } finally { + lock.writeLock().unlock(); } + } - @Override - public VersionedList getClusterMeta() { - return new VersionedList<>(getEpoch(), getClusterMembers()); - } + @Override + public VersionedList getClusterMeta() { + return new VersionedList<>(getEpoch(), getClusterMembers()); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/Metrics.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/Metrics.java index 5b787e151..f4a788366 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/Metrics.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/Metrics.java @@ -23,279 +23,318 @@ /** * @author chen.zhu - *

- * Mar 03, 2021 + *

Mar 03, 2021 */ public class Metrics { - public static final class SlotArrange { - - private static final Logger LOGGER = LoggerFactory - .getLogger(SlotArrange.class); - - private static long start = -1L; - - private static final Histogram SLOT_ARRANGE_HISTOGRAM = Histogram - .build().namespace("meta").subsystem("slot_arrange") - .name("leader_migrating_secs").help("migrating in seconds.") - .buckets(3, 5, 10, 20, 30, 60, 120, 180, 240).register(); - - public static void begin() { - start = System.currentTimeMillis(); - } - - public static void end() { - try { - SLOT_ARRANGE_HISTOGRAM.observe(System.currentTimeMillis() - - start); - } catch (Throwable throwable) { - LOGGER.error("[end]", throwable); - } - } - } - - public static final class Heartbeat { - - private static final Logger LOGGER = LoggerFactory - .getLogger(Heartbeat.class); - - private static final Gauge DATA_HEART_BEAT_GUAGE = Gauge.build() - .namespace("meta").subsystem("heartbeat") - .name("data_heartbeat").help("data heartbeat times") - .labelNames("data_server").register(); - - private static final Gauge SESSION_HEART_BEAT_GUAGE = Gauge.build() - .namespace("meta").subsystem("heartbeat") - .name("session_heartbeat").help("session heartbeat times") - .labelNames("session_server").register(); - - public static void onDataHeartbeat(String dataServer) { - try { - DATA_HEART_BEAT_GUAGE.labels(dataServer).set(1); - } catch (Throwable th) { - LOGGER.error("[onDataHeartbeat]", th); - } - } - - public static void onDataEvict(String dataServer) { - try { - DATA_HEART_BEAT_GUAGE.labels(dataServer).set(0); - } catch (Throwable th) { - LOGGER.error("[onDataEvict]", th); - } - } - - public static void onSessionHeartbeat(String session) { - try { - SESSION_HEART_BEAT_GUAGE.labels(session).set(1); - } catch (Throwable th) { - LOGGER.error("[onSessionHeartbeat]", th); - } - } - - public static void onSessionEvict(String session) { - try { - SESSION_HEART_BEAT_GUAGE.labels(session).set(0); - } catch (Throwable th) { - LOGGER.error("[onSessionEvict]", th); - } - } - - } - - public static final class SlotBalance { - - private static final Logger LOGGER = LoggerFactory - .getLogger(SlotBalance.class); - - private static final Gauge HIGH_LEADER_MIGRATE = Gauge.build() - .namespace("meta").subsystem("slot_balancer") - .name("high_leader_migrate").help("high leader migrate gauge") - .labelNames("from", "to", "slot").register(); - - private static final Gauge HIGH_LEADER_UPGRADE = Gauge.build() - .namespace("meta").subsystem("slot_balancer") - .name("high_leader_upgrade").help("high leader upgrade gauge") - .labelNames("from", "to", "slot").register(); - - private static final Gauge HIGH_FOLLOWER_BALANCE = Gauge.build() - .namespace("meta").subsystem("slot_balancer") - .name("high_follower_balance") - .help("data to swap slot follower out") - .labelNames("from", "to", "slot").register(); - - private static final Gauge LOW_FOLLOWER_BALANCE = Gauge.build() - .namespace("meta").subsystem("slot_balancer") - .name("low_follower_balance") - .help("data to swap slot follower in") - .labelNames("from", "to", "slot").register(); - - private static final Gauge LOW_LEADER_BALANCE = Gauge.build() - .namespace("meta").subsystem("slot_balancer") - .name("low_leader_balance") - .help("data to swap slot leader out") - .labelNames("from", "to", "slot").register(); - - public static void onLeaderUpgrade(String from, String to, int slotId) { - try { - HIGH_LEADER_MIGRATE.labels(from, to, String.valueOf(slotId)) - .inc(); - } catch (Throwable throwable) { - LOGGER.error("[onLeaderUpgrade]", throwable); - } - } - - public static void onLeaderMigrate(String from, String to, int slotId) { - try { - HIGH_LEADER_UPGRADE.labels(from, to, String.valueOf(slotId)) - .inc(); - } catch (Throwable throwable) { - LOGGER.error("[onLeaderMigrate]", throwable); - } - } - - public static void onHighFollowerMigrate(String from, String to, - int slotId) { - try { - HIGH_FOLLOWER_BALANCE.labels(from, to, String.valueOf(slotId)) - .inc(); - } catch (Throwable throwable) { - LOGGER.error("[onHighFollowerMigrate]", throwable); - } - } - - public static void onLowFollowerMigrate(String from, String to, - int slotId) { - try { - LOW_FOLLOWER_BALANCE.labels(from, to, String.valueOf(slotId)) - .inc(); - } catch (Throwable throwable) { - LOGGER.error("[onLowFollowerMigrate]", throwable); - } - } - - public static void onLowLeaderReplace(String from, String to, int slotId) { - try { - LOW_LEADER_BALANCE.labels(from, to, String.valueOf(slotId)) - .inc(); - } catch (Throwable throwable) { - LOGGER.error("[onLowLeaderReplace]", throwable); - } - } - } - - public static final class SlotAssign { - - private static final Logger LOGGER = LoggerFactory - .getLogger(SlotAssign.class); - - private static final Gauge LEADER_ASSIGN_GAUGE = Gauge.build() - .namespace("meta").subsystem("slot_assigner") - .name("assign_leader").help("leader assign") - .labelNames("leader", "slot").register(); - - private static final Gauge FOLLOWER_ASSIGN_GAUGE = Gauge.build() - .namespace("meta").subsystem("slot_assigner") - .name("assign_follower").help("follower assign") - .labelNames("follower", "slot").register(); - - public static void onSlotLeaderAssign(String dataServer, int slotId) { - try { - LEADER_ASSIGN_GAUGE.labels(dataServer, String.valueOf(slotId)) - .inc(); - } catch (Throwable throwable) { - LOGGER.error("[onSlotLeaderAssign]", throwable); - } - } - - public static void onSlotFollowerAssign(String dataServer, int slotId) { - try { - FOLLOWER_ASSIGN_GAUGE - .labels(dataServer, String.valueOf(slotId)).inc(); - } catch (Throwable throwable) { - LOGGER.error("[onSlotFollowerAssign]", throwable); - } - } - } - - public static final class DataSlot { - - private static final Logger LOGGER = LoggerFactory - .getLogger(DataSlot.class); - - private static final Gauge LEADER_ASSIGN_GAUGE = Gauge.build() - .namespace("meta").subsystem("data").name("leader_slot_number") - .help("leader slot number").labelNames("data_server") - .register(); - - private static final Gauge FOLLOWER_ASSIGN_GAUGE = Gauge.build() - .namespace("meta").subsystem("data") - .name("follower_slot_number").help("follower slot number") - .labelNames("data_server").register(); - - private static final Gauge DATA_SLOT_TABLE_LAG_TIMES = Gauge.build() - .namespace("meta").subsystem("data") - .name("data_server_slot_lag").help("data server slot is behind meta") - .labelNames("data_server").register(); - - private static final Gauge DATA_SLOT_GREATER_THAN_META = Gauge.build() - .namespace("meta").subsystem("data") - .name("data_slot_greater_than_meta").help("data server slot epoch greater than meta") - .labelNames("data_server", "slotId").register(); - - private static final Gauge DATA_SLOT_NOT_EQUALS_META = Gauge.build() - .namespace("meta").subsystem("data") - .name("data_slot_not_equals_meta").help("data server slot is not as expected as meta") - .labelNames("data_server").register(); - - public static void setLeaderNumbers(String dataServer, int leaderNum) { - try { - LEADER_ASSIGN_GAUGE.labels(dataServer).set(leaderNum); - } catch (Throwable throwable) { - LOGGER.error("[setLeaderNumbers]", throwable); - } - } - - public static void setFollowerNumbers(String dataServer, int followerNum) { - try { - FOLLOWER_ASSIGN_GAUGE.labels(dataServer).set(followerNum); - } catch (Throwable throwable) { - LOGGER.error("[setFollowerNumbers]", throwable); - } - } - - public static void setDataServerSlotLagTimes(String dataServer, int times) { - try { - DATA_SLOT_TABLE_LAG_TIMES.labels(dataServer).set(times); - } catch (Throwable throwable) { - LOGGER.error("[setDataServerSlotLagTimes]", throwable); - } - } - - public static long getDataServerSlotLagTimes(String dataServer) { - try { - return (long) DATA_SLOT_TABLE_LAG_TIMES.labels(dataServer).get(); - } catch (Throwable throwable) { - LOGGER.error("[setDataServerSlotLagTimes]", throwable); - } - return 0; - } - - public static void setDataSlotGreaterThanMeta(String dataServer, int slotId) { - try { - DATA_SLOT_GREATER_THAN_META.labels(dataServer, String.valueOf(slotId)).set(1); - } catch (Throwable throwable) { - LOGGER.error("[setDataServerSlotLagTimes]", throwable); - } - } - - public static void setDataReportNotStable(String dataServer, int slotId) { - try { - DATA_SLOT_NOT_EQUALS_META.labels(dataServer, String.valueOf(slotId)).set(1); - } catch (Throwable throwable) { - LOGGER.error("[setDataServerSlotLagTimes]", throwable); - } - } - } - + public static final class SlotArrange { + + private static final Logger LOGGER = LoggerFactory.getLogger(SlotArrange.class); + + private static long start = -1L; + + private static final Histogram SLOT_ARRANGE_HISTOGRAM = + Histogram.build() + .namespace("meta") + .subsystem("slot_arrange") + .name("leader_migrating_secs") + .help("migrating in seconds.") + .buckets(3, 5, 10, 20, 30, 60, 120, 180, 240) + .register(); + + public static void begin() { + start = System.currentTimeMillis(); + } + + public static void end() { + try { + SLOT_ARRANGE_HISTOGRAM.observe(System.currentTimeMillis() - start); + } catch (Throwable throwable) { + LOGGER.error("[end]", throwable); + } + } + } + + public static final class Heartbeat { + + private static final Logger LOGGER = LoggerFactory.getLogger(Heartbeat.class); + + private static final Gauge DATA_HEART_BEAT_GUAGE = + Gauge.build() + .namespace("meta") + .subsystem("heartbeat") + .name("data_heartbeat") + .help("data heartbeat times") + .labelNames("data_server") + .register(); + + private static final Gauge SESSION_HEART_BEAT_GUAGE = + Gauge.build() + .namespace("meta") + .subsystem("heartbeat") + .name("session_heartbeat") + .help("session heartbeat times") + .labelNames("session_server") + .register(); + + public static void onDataHeartbeat(String dataServer) { + try { + DATA_HEART_BEAT_GUAGE.labels(dataServer).set(1); + } catch (Throwable th) { + LOGGER.error("[onDataHeartbeat]", th); + } + } + + public static void onDataEvict(String dataServer) { + try { + DATA_HEART_BEAT_GUAGE.labels(dataServer).set(0); + } catch (Throwable th) { + LOGGER.error("[onDataEvict]", th); + } + } + + public static void onSessionHeartbeat(String session) { + try { + SESSION_HEART_BEAT_GUAGE.labels(session).set(1); + } catch (Throwable th) { + LOGGER.error("[onSessionHeartbeat]", th); + } + } + + public static void onSessionEvict(String session) { + try { + SESSION_HEART_BEAT_GUAGE.labels(session).set(0); + } catch (Throwable th) { + LOGGER.error("[onSessionEvict]", th); + } + } + } + + public static final class SlotBalance { + + private static final Logger LOGGER = LoggerFactory.getLogger(SlotBalance.class); + + private static final Gauge HIGH_LEADER_MIGRATE = + Gauge.build() + .namespace("meta") + .subsystem("slot_balancer") + .name("high_leader_migrate") + .help("high leader migrate gauge") + .labelNames("from", "to", "slot") + .register(); + + private static final Gauge HIGH_LEADER_UPGRADE = + Gauge.build() + .namespace("meta") + .subsystem("slot_balancer") + .name("high_leader_upgrade") + .help("high leader upgrade gauge") + .labelNames("from", "to", "slot") + .register(); + + private static final Gauge HIGH_FOLLOWER_BALANCE = + Gauge.build() + .namespace("meta") + .subsystem("slot_balancer") + .name("high_follower_balance") + .help("data to swap slot follower out") + .labelNames("from", "to", "slot") + .register(); + + private static final Gauge LOW_FOLLOWER_BALANCE = + Gauge.build() + .namespace("meta") + .subsystem("slot_balancer") + .name("low_follower_balance") + .help("data to swap slot follower in") + .labelNames("from", "to", "slot") + .register(); + + private static final Gauge LOW_LEADER_BALANCE = + Gauge.build() + .namespace("meta") + .subsystem("slot_balancer") + .name("low_leader_balance") + .help("data to swap slot leader out") + .labelNames("from", "to", "slot") + .register(); + + public static void onLeaderUpgrade(String from, String to, int slotId) { + try { + HIGH_LEADER_MIGRATE.labels(from, to, String.valueOf(slotId)).inc(); + } catch (Throwable throwable) { + LOGGER.error("[onLeaderUpgrade]", throwable); + } + } + + public static void onLeaderMigrate(String from, String to, int slotId) { + try { + HIGH_LEADER_UPGRADE.labels(from, to, String.valueOf(slotId)).inc(); + } catch (Throwable throwable) { + LOGGER.error("[onLeaderMigrate]", throwable); + } + } + + public static void onHighFollowerMigrate(String from, String to, int slotId) { + try { + HIGH_FOLLOWER_BALANCE.labels(from, to, String.valueOf(slotId)).inc(); + } catch (Throwable throwable) { + LOGGER.error("[onHighFollowerMigrate]", throwable); + } + } + + public static void onLowFollowerMigrate(String from, String to, int slotId) { + try { + LOW_FOLLOWER_BALANCE.labels(from, to, String.valueOf(slotId)).inc(); + } catch (Throwable throwable) { + LOGGER.error("[onLowFollowerMigrate]", throwable); + } + } + + public static void onLowLeaderReplace(String from, String to, int slotId) { + try { + LOW_LEADER_BALANCE.labels(from, to, String.valueOf(slotId)).inc(); + } catch (Throwable throwable) { + LOGGER.error("[onLowLeaderReplace]", throwable); + } + } + } + + public static final class SlotAssign { + + private static final Logger LOGGER = LoggerFactory.getLogger(SlotAssign.class); + + private static final Gauge LEADER_ASSIGN_GAUGE = + Gauge.build() + .namespace("meta") + .subsystem("slot_assigner") + .name("assign_leader") + .help("leader assign") + .labelNames("leader", "slot") + .register(); + + private static final Gauge FOLLOWER_ASSIGN_GAUGE = + Gauge.build() + .namespace("meta") + .subsystem("slot_assigner") + .name("assign_follower") + .help("follower assign") + .labelNames("follower", "slot") + .register(); + + public static void onSlotLeaderAssign(String dataServer, int slotId) { + try { + LEADER_ASSIGN_GAUGE.labels(dataServer, String.valueOf(slotId)).inc(); + } catch (Throwable throwable) { + LOGGER.error("[onSlotLeaderAssign]", throwable); + } + } + + public static void onSlotFollowerAssign(String dataServer, int slotId) { + try { + FOLLOWER_ASSIGN_GAUGE.labels(dataServer, String.valueOf(slotId)).inc(); + } catch (Throwable throwable) { + LOGGER.error("[onSlotFollowerAssign]", throwable); + } + } + } + + public static final class DataSlot { + + private static final Logger LOGGER = LoggerFactory.getLogger(DataSlot.class); + + private static final Gauge LEADER_ASSIGN_GAUGE = + Gauge.build() + .namespace("meta") + .subsystem("data") + .name("leader_slot_number") + .help("leader slot number") + .labelNames("data_server") + .register(); + + private static final Gauge FOLLOWER_ASSIGN_GAUGE = + Gauge.build() + .namespace("meta") + .subsystem("data") + .name("follower_slot_number") + .help("follower slot number") + .labelNames("data_server") + .register(); + + private static final Gauge DATA_SLOT_TABLE_LAG_TIMES = + Gauge.build() + .namespace("meta") + .subsystem("data") + .name("data_server_slot_lag") + .help("data server slot is behind meta") + .labelNames("data_server") + .register(); + + private static final Gauge DATA_SLOT_GREATER_THAN_META = + Gauge.build() + .namespace("meta") + .subsystem("data") + .name("data_slot_greater_than_meta") + .help("data server slot epoch greater than meta") + .labelNames("data_server", "slotId") + .register(); + + private static final Gauge DATA_SLOT_NOT_EQUALS_META = + Gauge.build() + .namespace("meta") + .subsystem("data") + .name("data_slot_not_equals_meta") + .help("data server slot is not as expected as meta") + .labelNames("data_server") + .register(); + + public static void setLeaderNumbers(String dataServer, int leaderNum) { + try { + LEADER_ASSIGN_GAUGE.labels(dataServer).set(leaderNum); + } catch (Throwable throwable) { + LOGGER.error("[setLeaderNumbers]", throwable); + } + } + + public static void setFollowerNumbers(String dataServer, int followerNum) { + try { + FOLLOWER_ASSIGN_GAUGE.labels(dataServer).set(followerNum); + } catch (Throwable throwable) { + LOGGER.error("[setFollowerNumbers]", throwable); + } + } + + public static void setDataServerSlotLagTimes(String dataServer, int times) { + try { + DATA_SLOT_TABLE_LAG_TIMES.labels(dataServer).set(times); + } catch (Throwable throwable) { + LOGGER.error("[setDataServerSlotLagTimes]", throwable); + } + } + + public static long getDataServerSlotLagTimes(String dataServer) { + try { + return (long) DATA_SLOT_TABLE_LAG_TIMES.labels(dataServer).get(); + } catch (Throwable throwable) { + LOGGER.error("[setDataServerSlotLagTimes]", throwable); + } + return 0; + } + + public static void setDataSlotGreaterThanMeta(String dataServer, int slotId) { + try { + DATA_SLOT_GREATER_THAN_META.labels(dataServer, String.valueOf(slotId)).set(1); + } catch (Throwable throwable) { + LOGGER.error("[setDataServerSlotLagTimes]", throwable); + } + } + + public static void setDataReportNotStable(String dataServer, int slotId) { + try { + DATA_SLOT_NOT_EQUALS_META.labels(dataServer, String.valueOf(slotId)).set(1); + } catch (Throwable throwable) { + LOGGER.error("[setDataServerSlotLagTimes]", throwable); + } + } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotStats.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotStats.java index 1af4761f2..8d92d8801 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotStats.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotStats.java @@ -22,20 +22,19 @@ /** * @author chen.zhu - *

- * Jan 28, 2021 + *

Jan 28, 2021 */ public interface SlotStats { - Slot getSlot(); + Slot getSlot(); - boolean isLeaderStable(); + boolean isLeaderStable(); - boolean isFollowersStable(); + boolean isFollowersStable(); - boolean isFollowerStable(String dataServer); + boolean isFollowerStable(String dataServer); - void updateLeaderState(LeaderSlotStatus leaderSlotStatus); + void updateLeaderState(LeaderSlotStatus leaderSlotStatus); - void updateFollowerState(FollowerSlotStatus followerSlotStatus); + void updateFollowerState(FollowerSlotStatus followerSlotStatus); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotTableMonitor.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotTableMonitor.java index 5c0525672..f63d8c57f 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotTableMonitor.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotTableMonitor.java @@ -21,13 +21,11 @@ /** * @author chen.zhu - *

- * Dec 25, 2020 + *

Dec 25, 2020 */ public interface SlotTableMonitor extends DataMessageListener, UnblockingObserver { - void recordSlotTable(); - - boolean isStableTableStable(); + void recordSlotTable(); + boolean isStableTableStable(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotTableStats.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotTableStats.java index da218f4d0..30a39f9cb 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotTableStats.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/SlotTableStats.java @@ -20,21 +20,19 @@ import com.alipay.sofa.registry.common.model.slot.BaseSlotStatus; import com.alipay.sofa.registry.common.model.slot.SlotTable; import com.alipay.sofa.registry.lifecycle.Initializable; - import java.util.List; /** * @author chen.zhu - *

- * Jan 28, 2021 + *

Jan 28, 2021 */ public interface SlotTableStats extends Initializable { - boolean isSlotLeadersStable(); + boolean isSlotLeadersStable(); - boolean isSlotFollowersStable(); + boolean isSlotFollowersStable(); - void updateSlotTable(SlotTable slotTable); + void updateSlotTable(SlotTable slotTable); - void checkSlotStatuses(DataNode node, List slotStatuses); + void checkSlotStatuses(DataNode node, List slotStatuses); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataMessageListener.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataMessageListener.java index 1ba376e4a..32339f2d1 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataMessageListener.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataMessageListener.java @@ -21,9 +21,6 @@ /** * @author chen.zhu - *

- * Feb 23, 2021 + *

Feb 23, 2021 */ -public interface DataMessageListener extends HeartbeatListener { - -} +public interface DataMessageListener extends HeartbeatListener {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataServerStats.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataServerStats.java index 7135b977b..3300702c8 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataServerStats.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataServerStats.java @@ -17,57 +17,56 @@ package com.alipay.sofa.registry.server.meta.monitor.data; import com.alipay.sofa.registry.common.model.slot.BaseSlotStatus; - import java.util.List; /** * @author chen.zhu - *

- * Feb 24, 2021 + *

Feb 24, 2021 */ public class DataServerStats { - private final String dataServer; - private final long slotTableEpoch; - private final List slotStatuses; + private final String dataServer; + private final long slotTableEpoch; + private final List slotStatuses; - /** - * Constructor. - * - * @param dataServer - * @param slotTableEpoch the slot table epoch - * @param slotStatuses the slot status - */ - public DataServerStats(String dataServer, long slotTableEpoch, List slotStatuses) { - this.dataServer = dataServer; - this.slotTableEpoch = slotTableEpoch; - this.slotStatuses = slotStatuses; - } + /** + * Constructor. + * + * @param dataServer + * @param slotTableEpoch the slot table epoch + * @param slotStatuses the slot status + */ + public DataServerStats( + String dataServer, long slotTableEpoch, List slotStatuses) { + this.dataServer = dataServer; + this.slotTableEpoch = slotTableEpoch; + this.slotStatuses = slotStatuses; + } - /** - * Gets get slot table epoch. - * - * @return the get slot table epoch - */ - public long getSlotTableEpoch() { - return slotTableEpoch; - } + /** + * Gets get slot table epoch. + * + * @return the get slot table epoch + */ + public long getSlotTableEpoch() { + return slotTableEpoch; + } - /** - * Gets get slot status. - * - * @return the get slot status - */ - public List getSlotStatus() { - return slotStatuses; - } + /** + * Gets get slot status. + * + * @return the get slot status + */ + public List getSlotStatus() { + return slotStatuses; + } - /** - * Gets get data server. - * - * @return the get data server - */ - public String getDataServer() { - return dataServer; - } + /** + * Gets get data server. + * + * @return the get data server + */ + public String getDataServer() { + return dataServer; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataSlotMetricsRecorder.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataSlotMetricsRecorder.java index 82c656e93..e45af0725 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataSlotMetricsRecorder.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/data/DataSlotMetricsRecorder.java @@ -20,21 +20,22 @@ import com.alipay.sofa.registry.common.model.slot.SlotTable; import com.alipay.sofa.registry.server.meta.monitor.Metrics; import com.alipay.sofa.registry.server.shared.slot.SlotTableRecorder; - import java.util.List; /** * @author chen.zhu - *

- * Mar 03, 2021 + *

Mar 03, 2021 */ public class DataSlotMetricsRecorder implements SlotTableRecorder { - @Override - public void record(SlotTable slotTable) { - List dataNodeSlots = slotTable.transfer(null, false); - dataNodeSlots.forEach(dataNodeSlot -> { - Metrics.DataSlot.setLeaderNumbers(dataNodeSlot.getDataNode(), dataNodeSlot.getLeaders().size()); - Metrics.DataSlot.setFollowerNumbers(dataNodeSlot.getDataNode(), dataNodeSlot.getFollowers().size()); + @Override + public void record(SlotTable slotTable) { + List dataNodeSlots = slotTable.transfer(null, false); + dataNodeSlots.forEach( + dataNodeSlot -> { + Metrics.DataSlot.setLeaderNumbers( + dataNodeSlot.getDataNode(), dataNodeSlot.getLeaders().size()); + Metrics.DataSlot.setFollowerNumbers( + dataNodeSlot.getDataNode(), dataNodeSlot.getFollowers().size()); }); - } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/heartbeat/HeartbeatListener.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/heartbeat/HeartbeatListener.java index e6bbb9435..2ae8ec088 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/heartbeat/HeartbeatListener.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/heartbeat/HeartbeatListener.java @@ -21,9 +21,8 @@ /** * @author chen.zhu - *

- * Feb 24, 2021 + *

Feb 24, 2021 */ public interface HeartbeatListener { - void onHeartbeat(HeartbeatRequest heartbeat); + void onHeartbeat(HeartbeatRequest heartbeat); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotStats.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotStats.java index 2e0f9f27d..328f0e7eb 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotStats.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotStats.java @@ -22,153 +22,152 @@ import com.alipay.sofa.registry.common.model.slot.Slot; import com.alipay.sofa.registry.server.meta.monitor.SlotStats; import com.google.common.collect.Maps; -import org.apache.commons.lang.StringUtils; - import java.util.Map; import java.util.Objects; +import org.apache.commons.lang.StringUtils; /** * @author chen.zhu - *

- * Jan 28, 2021 + *

Jan 28, 2021 */ public class DefaultSlotStats implements SlotStats { - public final static long MAX_SYNC_GAP = Long - .getLong( - "data.replicate.max.gap", - 3 * 60 * 1000); - - private final Slot slot; - - private volatile BaseSlotStatus.LeaderStatus leaderStatus = BaseSlotStatus.LeaderStatus.INIT; - - /** - * offsets: follower replicate offset against the leader. - * Current implementation is as simple as no incremental data replication - * Under this circumstances, offset stands for the last successful sync task execute time - * */ - private final Map followerLastSyncTimes = Maps.newConcurrentMap(); - - /** - * Constructor. - * - * @param slot the slot - */ - public DefaultSlotStats(Slot slot) { - this.slot = slot; - } - - /** - * Gets get slot. - * - * @return the get slot - */ - @Override - public Slot getSlot() { - return slot; - } - - /** - * Is leader stable boolean. - * - * @return the boolean - */ - @Override - public boolean isLeaderStable() { - return leaderStatus.isHealthy(); - } - - /** - * Is followers stable boolean. - * - * @return the boolean - */ - @Override - public boolean isFollowersStable() { - for (String dataServer : slot.getFollowers()) { - if (!isFollowerStable(dataServer)) { - return false; - } - } - return true; - } - - /** - * Is follower stable boolean. - * - * @param dataServer the data server - * - * Calculate the replicate gap between leader and followers, check if it's legal - * Current implementation is as simple as no incremental data replication - * Under this circumstances, offset stands for the last successful sync task execute time - * @return the boolean - */ - @Override - public boolean isFollowerStable(String dataServer) { - if (StringUtils.isEmpty(dataServer)) { - return false; - } - Long offset = followerLastSyncTimes.get(dataServer); - return offset != null && System.currentTimeMillis() - offset < MAX_SYNC_GAP; - } - - /** - * Update leader state. - * - * @param leaderSlotStatus the leader slot status - */ - @Override - public void updateLeaderState(LeaderSlotStatus leaderSlotStatus) { - this.leaderStatus = leaderSlotStatus.getLeaderStatus(); - } - - /** - * Update follower state. - * - * @param followerSlotStatus the follower slot status - */ - @Override - public void updateFollowerState(FollowerSlotStatus followerSlotStatus) { - followerLastSyncTimes.put(followerSlotStatus.getServer(), - followerSlotStatus.getLastLeaderSyncTime()); + public static final long MAX_SYNC_GAP = Long.getLong("data.replicate.max.gap", 3 * 60 * 1000); + + private final Slot slot; + + private volatile BaseSlotStatus.LeaderStatus leaderStatus = BaseSlotStatus.LeaderStatus.INIT; + + /** + * offsets: follower replicate offset against the leader. Current implementation is as simple as + * no incremental data replication Under this circumstances, offset stands for the last successful + * sync task execute time + */ + private final Map followerLastSyncTimes = Maps.newConcurrentMap(); + + /** + * Constructor. + * + * @param slot the slot + */ + public DefaultSlotStats(Slot slot) { + this.slot = slot; + } + + /** + * Gets get slot. + * + * @return the get slot + */ + @Override + public Slot getSlot() { + return slot; + } + + /** + * Is leader stable boolean. + * + * @return the boolean + */ + @Override + public boolean isLeaderStable() { + return leaderStatus.isHealthy(); + } + + /** + * Is followers stable boolean. + * + * @return the boolean + */ + @Override + public boolean isFollowersStable() { + for (String dataServer : slot.getFollowers()) { + if (!isFollowerStable(dataServer)) { + return false; + } } - - /** - * To string string. - * - * @return the string - */ - @Override - public String toString() { - return "DefaultSlotStats{" + "slot=" + slot + ", leaderStatus=" + leaderStatus - + ", followerOffsets=" + followerLastSyncTimes + '}'; - } - - /** - * Equals boolean. - * - * @param o the o - * @return the boolean - */ - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - DefaultSlotStats that = (DefaultSlotStats) o; - return Objects.equals(slot, that.slot) && leaderStatus == that.leaderStatus - && Objects.equals(followerLastSyncTimes, that.followerLastSyncTimes); - } - - /** - * Hash code int. - * - * @return the int - */ - @Override - public int hashCode() { - return Objects.hash(slot, leaderStatus, followerLastSyncTimes); + return true; + } + + /** + * Is follower stable boolean. + * + * @param dataServer the data server + *

Calculate the replicate gap between leader and followers, check if it's legal Current + * implementation is as simple as no incremental data replication Under this circumstances, + * offset stands for the last successful sync task execute time + * @return the boolean + */ + @Override + public boolean isFollowerStable(String dataServer) { + if (StringUtils.isEmpty(dataServer)) { + return false; } + Long offset = followerLastSyncTimes.get(dataServer); + return offset != null && System.currentTimeMillis() - offset < MAX_SYNC_GAP; + } + + /** + * Update leader state. + * + * @param leaderSlotStatus the leader slot status + */ + @Override + public void updateLeaderState(LeaderSlotStatus leaderSlotStatus) { + this.leaderStatus = leaderSlotStatus.getLeaderStatus(); + } + + /** + * Update follower state. + * + * @param followerSlotStatus the follower slot status + */ + @Override + public void updateFollowerState(FollowerSlotStatus followerSlotStatus) { + followerLastSyncTimes.put( + followerSlotStatus.getServer(), followerSlotStatus.getLastLeaderSyncTime()); + } + + /** + * To string string. + * + * @return the string + */ + @Override + public String toString() { + return "DefaultSlotStats{" + + "slot=" + + slot + + ", leaderStatus=" + + leaderStatus + + ", followerOffsets=" + + followerLastSyncTimes + + '}'; + } + + /** + * Equals boolean. + * + * @param o the o + * @return the boolean + */ + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + DefaultSlotStats that = (DefaultSlotStats) o; + return Objects.equals(slot, that.slot) + && leaderStatus == that.leaderStatus + && Objects.equals(followerLastSyncTimes, that.followerLastSyncTimes); + } + + /** + * Hash code int. + * + * @return the int + */ + @Override + public int hashCode() { + return Objects.hash(slot, leaderStatus, followerLastSyncTimes); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableMonitor.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableMonitor.java index 0de00a7b6..2fbe87140 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableMonitor.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableMonitor.java @@ -39,138 +39,137 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import java.util.List; import java.util.Map; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * @author chen.zhu - *

- * Dec 25, 2020 + *

Dec 25, 2020 */ @Component -public class DefaultSlotTableMonitor extends AbstractLifecycle implements SlotTableMonitor, - UnblockingObserver { - - @Autowired - private SlotManager slotManager; - - @Autowired - private SlotGenericResource slotGenericResource; - - private final Map dataServerLagCounter = Maps.newConcurrentMap(); - - private SlotTableStats slotTableStats; - - private List recorders; - - private WakeUpLoopRunnable scheduledTask; - - @PostConstruct - public void postConstruct() throws Exception { - LifecycleHelper.initializeIfPossible(this); - LifecycleHelper.startIfPossible(this); - } - - @PreDestroy - public void preDestroy() throws Exception { - LifecycleHelper.stopIfPossible(this); - LifecycleHelper.disposeIfPossible(this); - } - - @Override - protected void doInitialize() throws InitializeException { - super.doInitialize(); - recorders = Lists.newArrayList(new DiskSlotTableRecorder(), slotGenericResource, - new DataSlotMetricsRecorder()); - slotTableStats = new DefaultSlotTableStats(slotManager); - slotTableStats.initialize(); - scheduledTask = new WakeUpLoopRunnable() { - @Override - public int getWaitingMillis() { - return 10 * 60 * 1000; - } - - @Override - public void runUnthrowable() { - recordSlotTable(); - } +public class DefaultSlotTableMonitor extends AbstractLifecycle + implements SlotTableMonitor, UnblockingObserver { + + @Autowired private SlotManager slotManager; + + @Autowired private SlotGenericResource slotGenericResource; + + private final Map dataServerLagCounter = Maps.newConcurrentMap(); + + private SlotTableStats slotTableStats; + + private List recorders; + + private WakeUpLoopRunnable scheduledTask; + + @PostConstruct + public void postConstruct() throws Exception { + LifecycleHelper.initializeIfPossible(this); + LifecycleHelper.startIfPossible(this); + } + + @PreDestroy + public void preDestroy() throws Exception { + LifecycleHelper.stopIfPossible(this); + LifecycleHelper.disposeIfPossible(this); + } + + @Override + protected void doInitialize() throws InitializeException { + super.doInitialize(); + recorders = + Lists.newArrayList( + new DiskSlotTableRecorder(), slotGenericResource, new DataSlotMetricsRecorder()); + slotTableStats = new DefaultSlotTableStats(slotManager); + slotTableStats.initialize(); + scheduledTask = + new WakeUpLoopRunnable() { + @Override + public int getWaitingMillis() { + return 10 * 60 * 1000; + } + + @Override + public void runUnthrowable() { + recordSlotTable(); + } }; + } + + @Override + protected void doStart() throws StartException { + super.doStart(); + slotManager.addObserver(this); + ConcurrentUtils.createDaemonThread(DefaultSlotTableMonitor.class.getSimpleName(), scheduledTask) + .start(); + } + + @Override + protected void doStop() throws StopException { + slotManager.removeObserver(this); + if (scheduledTask != null) { + scheduledTask.close(); } - - @Override - protected void doStart() throws StartException { - super.doStart(); - slotManager.addObserver(this); - ConcurrentUtils.createDaemonThread(DefaultSlotTableMonitor.class.getSimpleName(), - scheduledTask).start(); - } - - @Override - protected void doStop() throws StopException { - slotManager.removeObserver(this); - if (scheduledTask != null) { - scheduledTask.close(); - } - super.doStop(); - } - - @Override - public void recordSlotTable() { - recorders.forEach(recorder -> { - if(recorder != null) { - recorder.record(slotManager.getSlotTable()); - } - }); - } - - @Override - public boolean isStableTableStable() { - return slotTableStats.isSlotLeadersStable() && slotTableStats.isSlotFollowersStable(); - } - - @Override - public void update(Observable source, Object message) { - if (message instanceof SlotTable) { - logger.warn("[update] slot-table changed, current epoch: [{}]", - ((SlotTable) message).getEpoch()); - recordSlotTable(); - slotTableStats.updateSlotTable((SlotTable) message); - } + super.doStop(); + } + + @Override + public void recordSlotTable() { + recorders.forEach( + recorder -> { + if (recorder != null) { + recorder.record(slotManager.getSlotTable()); + } + }); + } + + @Override + public boolean isStableTableStable() { + return slotTableStats.isSlotLeadersStable() && slotTableStats.isSlotFollowersStable(); + } + + @Override + public void update(Observable source, Object message) { + if (message instanceof SlotTable) { + logger.warn( + "[update] slot-table changed, current epoch: [{}]", ((SlotTable) message).getEpoch()); + recordSlotTable(); + slotTableStats.updateSlotTable((SlotTable) message); } - - @VisibleForTesting - public DefaultSlotTableMonitor setSlotManager(SlotManager slotManager) { - this.slotManager = slotManager; - return this; + } + + @VisibleForTesting + public DefaultSlotTableMonitor setSlotManager(SlotManager slotManager) { + this.slotManager = slotManager; + return this; + } + + @Override + public void onHeartbeat(HeartbeatRequest heartbeat) { + long slotTableEpoch = heartbeat.getSlotTableEpoch(); + if (slotTableEpoch < slotManager.getSlotTable().getEpoch()) { + // after slot-table changed, first time data-server report heartbeat, the epoch is less than + // meta servers + // it is ok with that + // but the second time should be ok, otherwise, data has something un-common + int times = dataServerLagCounter.getOrDefault(heartbeat.getNode().getIp(), 0) + 1; + if (times > 1) { + logger.error("[onHeartbeatLag] data[{}] lag", heartbeat.getNode().getIp()); + } + Metrics.DataSlot.setDataServerSlotLagTimes(heartbeat.getNode().getIp(), times); + dataServerLagCounter.put(heartbeat.getNode().getIp(), times); + return; } - - @Override - public void onHeartbeat(HeartbeatRequest heartbeat) { - long slotTableEpoch = heartbeat.getSlotTableEpoch(); - if (slotTableEpoch < slotManager.getSlotTable().getEpoch()) { - // after slot-table changed, first time data-server report heartbeat, the epoch is less than meta servers - // it is ok with that - // but the second time should be ok, otherwise, data has something un-common - int times = dataServerLagCounter.getOrDefault(heartbeat.getNode().getIp(), 0) + 1; - if (times > 1) { - logger.error("[onHeartbeatLag] data[{}] lag", heartbeat.getNode().getIp()); - } - Metrics.DataSlot - .setDataServerSlotLagTimes(heartbeat.getNode().getIp(), times); - dataServerLagCounter.put(heartbeat.getNode().getIp(), times); - return; - } - if (heartbeat.getSlotStatus() == null) { - logger.warn("[onHeartbeatEmpty] empty heartbeat"); - return; - } - dataServerLagCounter.put(heartbeat.getNode().getIp(), 0); - Metrics.DataSlot.setDataServerSlotLagTimes(heartbeat.getNode().getIp(), 0); - slotTableStats.checkSlotStatuses(heartbeat.getNode(), heartbeat.getSlotStatus()); + if (heartbeat.getSlotStatus() == null) { + logger.warn("[onHeartbeatEmpty] empty heartbeat"); + return; } + dataServerLagCounter.put(heartbeat.getNode().getIp(), 0); + Metrics.DataSlot.setDataServerSlotLagTimes(heartbeat.getNode().getIp(), 0); + slotTableStats.checkSlotStatuses(heartbeat.getNode(), heartbeat.getSlotStatus()); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableStats.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableStats.java index bd6bd3d94..27d248cbf 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableStats.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableStats.java @@ -26,7 +26,6 @@ import com.alipay.sofa.registry.server.meta.slot.SlotManager; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Maps; - import java.util.Collections; import java.util.List; import java.util.Map; @@ -36,156 +35,160 @@ /** * @author chen.zhu - *

- * Jan 28, 2021 + *

Jan 28, 2021 */ public class DefaultSlotTableStats extends AbstractLifecycle implements SlotTableStats { - private final SlotManager slotManager; + private final SlotManager slotManager; - private final Map slotStatses = Maps.newConcurrentMap(); + private final Map slotStatses = Maps.newConcurrentMap(); - private final ReadWriteLock lock = new ReentrantReadWriteLock(); + private final ReadWriteLock lock = new ReentrantReadWriteLock(); - public DefaultSlotTableStats(SlotManager slotManager) { - this.slotManager = slotManager; - } + public DefaultSlotTableStats(SlotManager slotManager) { + this.slotManager = slotManager; + } - @Override - protected void doInitialize() throws InitializeException { - super.doInitialize(); - for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { - Slot slot = slotManager.getSlotTable().getSlot(slotId); - if (slot == null) { - slot = new Slot(slotId, null, 0L, Collections.emptyList()); - } - slotStatses.put(slotId, new DefaultSlotStats(slot)); - } + @Override + protected void doInitialize() throws InitializeException { + super.doInitialize(); + for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { + Slot slot = slotManager.getSlotTable().getSlot(slotId); + if (slot == null) { + slot = new Slot(slotId, null, 0L, Collections.emptyList()); + } + slotStatses.put(slotId, new DefaultSlotStats(slot)); } + } - @Override - public boolean isSlotLeadersStable() { - try { - lock.readLock().lock(); - for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { - String leader = slotManager.getSlotTable().getSlot(slotId).getLeader(); - SlotStats slotStats = slotStatses.get(slotId); - if (!slotStats.getSlot().getLeader().equals(leader) - || !slotStatses.get(slotId).isLeaderStable()) { - logger.warn("[isSlotLeadersStable]slot[{}] leader[{}] not stable", slotId, - leader); - return false; - } - } - return true; - } finally { - lock.readLock().unlock(); + @Override + public boolean isSlotLeadersStable() { + try { + lock.readLock().lock(); + for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { + String leader = slotManager.getSlotTable().getSlot(slotId).getLeader(); + SlotStats slotStats = slotStatses.get(slotId); + if (!slotStats.getSlot().getLeader().equals(leader) + || !slotStatses.get(slotId).isLeaderStable()) { + logger.warn("[isSlotLeadersStable]slot[{}] leader[{}] not stable", slotId, leader); + return false; } + } + return true; + } finally { + lock.readLock().unlock(); } + } - @Override - public boolean isSlotFollowersStable() { - try { - lock.readLock().lock(); - for (Map.Entry entry : slotStatses.entrySet()) { - Set followers = slotManager.getSlotTable().getSlot(entry.getKey()) - .getFollowers(); - for (String follower : followers) { - if (!entry.getValue().isFollowerStable(follower)) { - logger.warn("[isSlotFollowersStable]slot[{}] follower not stable {}", - entry.getKey(), entry.getValue()); - return false; - } - } - } - return true; - } finally { - lock.readLock().unlock(); + @Override + public boolean isSlotFollowersStable() { + try { + lock.readLock().lock(); + for (Map.Entry entry : slotStatses.entrySet()) { + Set followers = slotManager.getSlotTable().getSlot(entry.getKey()).getFollowers(); + for (String follower : followers) { + if (!entry.getValue().isFollowerStable(follower)) { + logger.warn( + "[isSlotFollowersStable]slot[{}] follower not stable {}", + entry.getKey(), + entry.getValue()); + return false; + } } + } + return true; + } finally { + lock.readLock().unlock(); } + } - @Override - public void checkSlotStatuses(DataNode node, List slotStatuses) { - try { - lock.writeLock().lock(); - for (BaseSlotStatus slotStatus : slotStatuses) { - int slotId = slotStatus.getSlotId(); - SlotStats slotStats = slotStatses.get(slotId); - if (slotStats == null || slotStats.getSlot() == null) { - continue; - } - if (slotStats.getSlot().getLeaderEpoch() > slotStatus.getSlotLeaderEpoch()) { - logger - .warn( - "[checkSlotStatuses] won't update slot status, slot[{}] leader-epoch[{}] is less than current[{}]", - slotId, slotStatus.getSlotLeaderEpoch(), slotStats.getSlot() - .getLeaderEpoch()); - continue; - } else if (slotStats.getSlot().getLeaderEpoch() < slotStatus.getSlotLeaderEpoch()) { - Metrics.DataSlot.setDataSlotGreaterThanMeta(node.getIp(), slotId); - logger - .error( - "[checkSlotStatuses] won't update slot status, slot[{}] leader-epoch[{}] reported by data({}) is more than current[{}]", - slotId, slotStatus.getSlotLeaderEpoch(), node.getIp(), slotStats - .getSlot().getLeaderEpoch()); - continue; - } - if (!slotStats.getSlot().equals(slotManager.getSlotTable().getSlot(slotId))) { - logger - .error( - "[checkSlotStatuses] slot reported by data({}) is not equals with mine({}), not update", - slotStats.getSlot(), slotManager.getSlotTable().getSlot(slotId)); - continue; - } + @Override + public void checkSlotStatuses(DataNode node, List slotStatuses) { + try { + lock.writeLock().lock(); + for (BaseSlotStatus slotStatus : slotStatuses) { + int slotId = slotStatus.getSlotId(); + SlotStats slotStats = slotStatses.get(slotId); + if (slotStats == null || slotStats.getSlot() == null) { + continue; + } + if (slotStats.getSlot().getLeaderEpoch() > slotStatus.getSlotLeaderEpoch()) { + logger.warn( + "[checkSlotStatuses] won't update slot status, slot[{}] leader-epoch[{}] is less than current[{}]", + slotId, + slotStatus.getSlotLeaderEpoch(), + slotStats.getSlot().getLeaderEpoch()); + continue; + } else if (slotStats.getSlot().getLeaderEpoch() < slotStatus.getSlotLeaderEpoch()) { + Metrics.DataSlot.setDataSlotGreaterThanMeta(node.getIp(), slotId); + logger.error( + "[checkSlotStatuses] won't update slot status, slot[{}] leader-epoch[{}] reported by data({}) is more than current[{}]", + slotId, + slotStatus.getSlotLeaderEpoch(), + node.getIp(), + slotStats.getSlot().getLeaderEpoch()); + continue; + } + if (!slotStats.getSlot().equals(slotManager.getSlotTable().getSlot(slotId))) { + logger.error( + "[checkSlotStatuses] slot reported by data({}) is not equals with mine({}), not update", + slotStats.getSlot(), + slotManager.getSlotTable().getSlot(slotId)); + continue; + } - if (slotStatus.getRole() == Slot.Role.Leader) { - if (!slotStats.getSlot().getLeader().equals(node.getIp())) { - logger - .error( - "[checkSlotStatuses] slot leader({}) is not equal with reported data-server({})", - slotStats.getSlot().getLeader(), node.getIp()); - Metrics.DataSlot.setDataReportNotStable(node.getIp(), slotId); - continue; - } - slotStats.updateLeaderState((LeaderSlotStatus) slotStatus); - } else { - if (!slotStats.getSlot().getFollowers().contains(node.getIp())) { - logger - .error( - "[checkSlotStatuses] slot follower({}) is not containing reported data-server({})", - slotStats.getSlot().getFollowers(), node.getIp()); - Metrics.DataSlot.setDataReportNotStable(node.getIp(), slotId); - continue; - } - slotStats.updateFollowerState((FollowerSlotStatus) slotStatus); - } - } - } finally { - lock.writeLock().unlock(); + if (slotStatus.getRole() == Slot.Role.Leader) { + if (!slotStats.getSlot().getLeader().equals(node.getIp())) { + logger.error( + "[checkSlotStatuses] slot leader({}) is not equal with reported data-server({})", + slotStats.getSlot().getLeader(), + node.getIp()); + Metrics.DataSlot.setDataReportNotStable(node.getIp(), slotId); + continue; + } + slotStats.updateLeaderState((LeaderSlotStatus) slotStatus); + } else { + if (!slotStats.getSlot().getFollowers().contains(node.getIp())) { + logger.error( + "[checkSlotStatuses] slot follower({}) is not containing reported data-server({})", + slotStats.getSlot().getFollowers(), + node.getIp()); + Metrics.DataSlot.setDataReportNotStable(node.getIp(), slotId); + continue; + } + slotStats.updateFollowerState((FollowerSlotStatus) slotStatus); } + } + } finally { + lock.writeLock().unlock(); } + } - @Override - public void updateSlotTable(SlotTable slotTable) { - try { - lock.writeLock().lock(); - slotTable.getSlotMap().forEach((slotId, slot) -> { + @Override + public void updateSlotTable(SlotTable slotTable) { + try { + lock.writeLock().lock(); + slotTable + .getSlotMap() + .forEach( + (slotId, slot) -> { SlotStats slotStats = slotStatses.get(slotId); if (slotStats.getSlot().getLeaderEpoch() < slot.getLeaderEpoch()) { - slotStatses.put(slotId, new DefaultSlotStats(slot)); - } else if (slotStats.getSlot().getLeaderEpoch() == slot.getLeaderEpoch() && !slotStats.getSlot().equals(slot)) { - slotStatses.put(slotId, new DefaultSlotStats(slot)); + slotStatses.put(slotId, new DefaultSlotStats(slot)); + } else if (slotStats.getSlot().getLeaderEpoch() == slot.getLeaderEpoch() + && !slotStats.getSlot().equals(slot)) { + slotStatses.put(slotId, new DefaultSlotStats(slot)); } else { - logger.warn("[updateSlotTable]skip slot[{}]", slotId); + logger.warn("[updateSlotTable]skip slot[{}]", slotId); } - }); - } finally { - lock.writeLock().unlock(); - } + }); + } finally { + lock.writeLock().unlock(); } + } - @VisibleForTesting - public SlotStats getSlotStats(int slotId) { - return slotStatses.get(slotId); - } + @VisibleForTesting + public SlotStats getSlotStats(int slotId) { + return slotStatses.get(slotId); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/session/SessionMessageListener.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/session/SessionMessageListener.java index 2e9f0b54b..3e408a029 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/session/SessionMessageListener.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/monitor/session/SessionMessageListener.java @@ -21,9 +21,6 @@ /** * @author chen.zhu - *

- * Feb 24, 2021 + *

Feb 24, 2021 */ -public interface SessionMessageListener extends HeartbeatListener { - -} +public interface SessionMessageListener extends HeartbeatListener {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/DefaultProvideDataNotifier.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/DefaultProvideDataNotifier.java index f00add4f0..67d40dc1d 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/DefaultProvideDataNotifier.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/DefaultProvideDataNotifier.java @@ -21,53 +21,49 @@ import com.alipay.sofa.registry.server.meta.remoting.data.DefaultDataServerService; import com.alipay.sofa.registry.server.meta.remoting.session.DefaultSessionServerService; import com.google.common.annotations.VisibleForTesting; +import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.Set; - /** * @author chen.zhu - *

- * Dec 03, 2020 - *

- * Provide Data is designed for two scenerio, as below: - * 1. Dynamic Configs inside Sofa-Registry itself - * 2. Service Gaven (or say 'Watcher') are subscring messages through Session-Server - *

- * All above user cases stages a Config Center role by Sofa-Registry - * And all these infos are madantorily persistenced to disk - * So, by leveraging meta server's JRaft feature, infos are reliable and stable to be stored on MetaServer + *

Dec 03, 2020 + *

Provide Data is designed for two scenerio, as below: 1. Dynamic Configs inside + * Sofa-Registry itself 2. Service Gaven (or say 'Watcher') are subscring messages through + * Session-Server + *

All above user cases stages a Config Center role by Sofa-Registry And all these infos are + * madantorily persistenced to disk So, by leveraging meta server's JRaft feature, infos are + * reliable and stable to be stored on MetaServer */ @Component public class DefaultProvideDataNotifier implements ProvideDataNotifier { - @Autowired - private DefaultDataServerService defaultDataServerService; + @Autowired private DefaultDataServerService defaultDataServerService; - @Autowired - private DefaultSessionServerService defaultSessionServerService; + @Autowired private DefaultSessionServerService defaultSessionServerService; - @Override - public void notifyProvideDataChange(ProvideDataChangeEvent event) { - Set notifyTypes = event.getNodeTypes(); - if (notifyTypes.contains(Node.NodeType.DATA)) { - defaultDataServerService.notifyProvideDataChange(event); - } - if (notifyTypes.contains(Node.NodeType.SESSION)) { - defaultSessionServerService.notifyProvideDataChange(event); - } + @Override + public void notifyProvideDataChange(ProvideDataChangeEvent event) { + Set notifyTypes = event.getNodeTypes(); + if (notifyTypes.contains(Node.NodeType.DATA)) { + defaultDataServerService.notifyProvideDataChange(event); } - - @VisibleForTesting - DefaultProvideDataNotifier setDataServerProvideDataNotifier(DefaultDataServerService defaultDataServerService) { - this.defaultDataServerService = defaultDataServerService; - return this; + if (notifyTypes.contains(Node.NodeType.SESSION)) { + defaultSessionServerService.notifyProvideDataChange(event); } + } - @VisibleForTesting - DefaultProvideDataNotifier setSessionServerProvideDataNotifier(DefaultSessionServerService defaultSessionServerService) { - this.defaultSessionServerService = defaultSessionServerService; - return this; - } + @VisibleForTesting + DefaultProvideDataNotifier setDataServerProvideDataNotifier( + DefaultDataServerService defaultDataServerService) { + this.defaultDataServerService = defaultDataServerService; + return this; + } + + @VisibleForTesting + DefaultProvideDataNotifier setSessionServerProvideDataNotifier( + DefaultSessionServerService defaultSessionServerService) { + this.defaultSessionServerService = defaultSessionServerService; + return this; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/ProvideDataNotifier.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/ProvideDataNotifier.java index dff6497e4..64c755f75 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/ProvideDataNotifier.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/ProvideDataNotifier.java @@ -20,11 +20,9 @@ /** * @author chen.zhu - *

- * Dec 03, 2020 + *

Dec 03, 2020 */ public interface ProvideDataNotifier { - void notifyProvideDataChange(ProvideDataChangeEvent event); - + void notifyProvideDataChange(ProvideDataChangeEvent event); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/package-info.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/package-info.java index 1e6882db8..ce0761ad8 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/package-info.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/provide/data/package-info.java @@ -17,18 +17,18 @@ package com.alipay.sofa.registry.server.meta.provide.data; /** - * The so called "Provide Data" is designed for two scenario, as below: - * 1. Dynamic Configurations inter-active between Sofa-Registry system - * 2. Service Gaven (or say 'Watcher') are subscribing/watching messages through Session-Server - *

- * All above user cases stage a Config Center role by Sofa-Registry - * And all these infos are mandatory being persistence to disk - * The idea is simple, leveraging meta server's JRaft feature, infos are reliable and stable to be stored on MetaServer - *

- * So, besides meta-info control, another functionality has been assigned to MetaServer, that it holds some dynamic configs - * or receive changes from session. - * And then send out a notification to data-servers/session servers, so that these two buddy could come and take some stuff - * it needs - *

- * Not a big deal, but it's a 'must' feature for MetaServer, be careful if you want to refactor this feature + * The so called "Provide Data" is designed for two scenario, as below: 1. Dynamic Configurations + * inter-active between Sofa-Registry system 2. Service Gaven (or say 'Watcher') are + * subscribing/watching messages through Session-Server + * + *

All above user cases stage a Config Center role by Sofa-Registry And all these infos are + * mandatory being persistence to disk The idea is simple, leveraging meta server's JRaft feature, + * infos are reliable and stable to be stored on MetaServer + * + *

So, besides meta-info control, another functionality has been assigned to MetaServer, that it + * holds some dynamic configs or receive changes from session. And then send out a notification to + * data-servers/session servers, so that these two buddy could come and take some stuff it needs + * + *

Not a big deal, but it's a 'must' feature for MetaServer, be careful if you want to refactor + * this feature */ diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/DataNodeExchanger.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/DataNodeExchanger.java index b5e612e81..38e07dea0 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/DataNodeExchanger.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/DataNodeExchanger.java @@ -24,35 +24,33 @@ import org.springframework.stereotype.Component; /** - * * @author shangyu.wh * @version $Id: DataNodeExchanger.java, v 0.1 2018-01-23 19:18 shangyu.wh Exp $ */ @Component public class DataNodeExchanger extends ServerSideExchanger { - @Autowired - private MetaServerConfig metaServerConfig; + @Autowired private MetaServerConfig metaServerConfig; - @Override - public int getRpcTimeoutMillis() { - return metaServerConfig.getDataNodeExchangeTimeout(); - } + @Override + public int getRpcTimeoutMillis() { + return metaServerConfig.getDataNodeExchangeTimeout(); + } - @Override - public int getServerPort() { - return metaServerConfig.getDataServerPort(); - } + @Override + public int getServerPort() { + return metaServerConfig.getDataServerPort(); + } - @VisibleForTesting - public DataNodeExchanger setMetaServerConfig(MetaServerConfig metaServerConfig) { - this.metaServerConfig = metaServerConfig; - return this; - } + @VisibleForTesting + public DataNodeExchanger setMetaServerConfig(MetaServerConfig metaServerConfig) { + this.metaServerConfig = metaServerConfig; + return this; + } - @VisibleForTesting - public DataNodeExchanger setBoltExchange(Exchange boltExchange) { - this.boltExchange = boltExchange; - return this; - } -} \ No newline at end of file + @VisibleForTesting + public DataNodeExchanger setBoltExchange(Exchange boltExchange) { + this.boltExchange = boltExchange; + return this; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/MetaServerExchanger.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/MetaServerExchanger.java index 40d0ab105..2c33b343f 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/MetaServerExchanger.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/MetaServerExchanger.java @@ -22,23 +22,21 @@ import org.springframework.stereotype.Component; /** - * * @author shangyu.wh * @version $Id: MetaNodeExchanger.java, v 0.1 2018-02-12 14:22 shangyu.wh Exp $ */ @Component public class MetaServerExchanger extends ServerSideExchanger { - @Autowired - private MetaServerConfig metaServerConfig; + @Autowired private MetaServerConfig metaServerConfig; - @Override - public int getRpcTimeoutMillis() { - return metaServerConfig.getMetaNodeExchangeTimeout(); - } + @Override + public int getRpcTimeoutMillis() { + return metaServerConfig.getMetaNodeExchangeTimeout(); + } - @Override - public int getServerPort() { - return metaServerConfig.getMetaServerPort(); - } -} \ No newline at end of file + @Override + public int getServerPort() { + return metaServerConfig.getMetaServerPort(); + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/SessionNodeExchanger.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/SessionNodeExchanger.java index 27b151d73..f2b281ffa 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/SessionNodeExchanger.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/SessionNodeExchanger.java @@ -22,23 +22,21 @@ import org.springframework.stereotype.Component; /** - * * @author shangyu.wh * @version $Id: SessionNodeExchanger.java, v 0.1 2018-01-15 21:21 shangyu.wh Exp $ */ @Component public class SessionNodeExchanger extends ServerSideExchanger { - @Autowired - private MetaServerConfig metaServerConfig; + @Autowired private MetaServerConfig metaServerConfig; - @Override - public int getRpcTimeoutMillis() { - return metaServerConfig.getSessionNodeExchangeTimeout(); - } + @Override + public int getRpcTimeoutMillis() { + return metaServerConfig.getSessionNodeExchangeTimeout(); + } - @Override - public int getServerPort() { - return metaServerConfig.getSessionServerPort(); - } -} \ No newline at end of file + @Override + public int getServerPort() { + return metaServerConfig.getSessionServerPort(); + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/DataConnectionHandler.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/DataConnectionHandler.java index 990a5db44..24900cfaa 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/DataConnectionHandler.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/DataConnectionHandler.java @@ -21,12 +21,11 @@ import com.alipay.sofa.registry.remoting.Channel; import com.alipay.sofa.registry.server.meta.bootstrap.handler.DataServerHandler; import com.alipay.sofa.registry.server.shared.remoting.ListenServerChannelHandler; -import org.springframework.stereotype.Component; - import java.net.InetSocketAddress; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.springframework.stereotype.Component; /** * Handle data node's connect request @@ -35,48 +34,46 @@ * @version $Id: DataConnectionHandler.java, v 0.1 2018-01-24 16:04 shangyu.wh Exp $ */ @Component -public class DataConnectionHandler extends ListenServerChannelHandler implements NodeConnectManager, DataServerHandler { +public class DataConnectionHandler extends ListenServerChannelHandler + implements NodeConnectManager, DataServerHandler { - /** - * key: connectId - * value: InetSocketAddress - * */ - private final Map connections = new ConcurrentHashMap<>(); + /** key: connectId value: InetSocketAddress */ + private final Map connections = new ConcurrentHashMap<>(); - @Override - public void connected(Channel channel) { - super.connected(channel); - addConnection(channel); - } + @Override + public void connected(Channel channel) { + super.connected(channel); + addConnection(channel); + } - @Override - public void disconnected(Channel channel) { - super.disconnected(channel); - removeConnection(channel); - } + @Override + public void disconnected(Channel channel) { + super.disconnected(channel); + removeConnection(channel); + } - @Override - public void addConnection(Channel channel) { - InetSocketAddress remoteAddress = channel.getRemoteAddress(); - String connectId = NetUtil.toAddressString(remoteAddress); - connections.putIfAbsent(connectId, remoteAddress); - } + @Override + public void addConnection(Channel channel) { + InetSocketAddress remoteAddress = channel.getRemoteAddress(); + String connectId = NetUtil.toAddressString(remoteAddress); + connections.putIfAbsent(connectId, remoteAddress); + } - @Override - public boolean removeConnection(Channel channel) { - InetSocketAddress remoteAddress = channel.getRemoteAddress(); - String connectId = NetUtil.toAddressString(remoteAddress); + @Override + public boolean removeConnection(Channel channel) { + InetSocketAddress remoteAddress = channel.getRemoteAddress(); + String connectId = NetUtil.toAddressString(remoteAddress); - return connections.remove(connectId) != null; - } + return connections.remove(connectId) != null; + } - @Override - public Collection getConnections(String dataCenter) { - return connections.values(); - } + @Override + public Collection getConnections(String dataCenter) { + return connections.values(); + } - @Override - public NodeType getConnectNodeType() { - return NodeType.DATA; - } -} \ No newline at end of file + @Override + public NodeType getConnectNodeType() { + return NodeType.DATA; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/MetaConnectionHandler.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/MetaConnectionHandler.java index 7d27e6389..19a5a45f2 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/MetaConnectionHandler.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/MetaConnectionHandler.java @@ -24,92 +24,91 @@ import com.alipay.sofa.registry.server.meta.bootstrap.config.NodeConfig; import com.alipay.sofa.registry.server.meta.bootstrap.handler.MetaServerHandler; import com.alipay.sofa.registry.server.shared.remoting.ListenServerChannelHandler; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - import java.net.InetSocketAddress; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * Handle meta node's connect request + * * @author shangyu.wh * @version $Id: MetaConnectionHandler.java, v 0.1 2018-02-12 15:01 shangyu.wh Exp $ */ @Component -public class MetaConnectionHandler extends ListenServerChannelHandler implements NodeConnectManager, MetaServerHandler { +public class MetaConnectionHandler extends ListenServerChannelHandler + implements NodeConnectManager, MetaServerHandler { - private static final Logger LOGGER = LoggerFactory - .getLogger(MetaConnectionHandler.class); + private static final Logger LOGGER = LoggerFactory.getLogger(MetaConnectionHandler.class); - @Autowired - private NodeConfig nodeConfig; + @Autowired private NodeConfig nodeConfig; - private final Map> connections = new ConcurrentHashMap<>(); + private final Map> + connections = new ConcurrentHashMap<>(); - @Override - public void connected(Channel channel) { - super.connected(channel); - addConnection(channel); - } + @Override + public void connected(Channel channel) { + super.connected(channel); + addConnection(channel); + } - @Override - public void disconnected(Channel channel) { - super.disconnected(channel); - removeConnection(channel); - } + @Override + public void disconnected(Channel channel) { + super.disconnected(channel); + removeConnection(channel); + } - @Override - public void addConnection(Channel channel) { - InetSocketAddress remoteAddress = channel.getRemoteAddress(); - String connectId = NetUtil.toAddressString(remoteAddress); - String ipAddress = remoteAddress.getAddress().getHostAddress(); + @Override + public void addConnection(Channel channel) { + InetSocketAddress remoteAddress = channel.getRemoteAddress(); + String connectId = NetUtil.toAddressString(remoteAddress); + String ipAddress = remoteAddress.getAddress().getHostAddress(); - String dataCenter = nodeConfig.getMetaDataCenter(ipAddress); - if (dataCenter != null) { - Map connectMap = connections.get(dataCenter); - if (connectMap == null) { - final Map newMap = new ConcurrentHashMap<>(); - connectMap = connections.putIfAbsent(dataCenter, newMap); - if (connectMap == null) { - connectMap = newMap; - } - } - connectMap.putIfAbsent(connectId, remoteAddress); + String dataCenter = nodeConfig.getMetaDataCenter(ipAddress); + if (dataCenter != null) { + Map connectMap = connections.get(dataCenter); + if (connectMap == null) { + final Map newMap = new ConcurrentHashMap<>(); + connectMap = connections.putIfAbsent(dataCenter, newMap); + if (connectMap == null) { + connectMap = newMap; } + } + connectMap.putIfAbsent(connectId, remoteAddress); } + } - @Override - public boolean removeConnection(Channel channel) { - InetSocketAddress remoteAddress = channel.getRemoteAddress(); - String connectId = NetUtil.toAddressString(remoteAddress); - String ipAddress = remoteAddress.getAddress().getHostAddress(); - - String dataCenter = nodeConfig.getMetaDataCenter(ipAddress); - if (dataCenter != null) { - Map connectMap = connections.get(dataCenter); - if (connectMap != null) { - connectMap.remove(connectId); - return true; - } - } - return false; - } + @Override + public boolean removeConnection(Channel channel) { + InetSocketAddress remoteAddress = channel.getRemoteAddress(); + String connectId = NetUtil.toAddressString(remoteAddress); + String ipAddress = remoteAddress.getAddress().getHostAddress(); - @Override - public Collection getConnections(String dataCenter) { - Map connectMap = connections.get(dataCenter); - if (connectMap == null || connectMap.isEmpty()) { - LOGGER.error("Can not find connection of dataCenter {}", dataCenter); - throw new RuntimeException("Can not find connection of dataCenter:" + dataCenter); - } - return connectMap.values(); + String dataCenter = nodeConfig.getMetaDataCenter(ipAddress); + if (dataCenter != null) { + Map connectMap = connections.get(dataCenter); + if (connectMap != null) { + connectMap.remove(connectId); + return true; + } } + return false; + } - @Override - public NodeType getConnectNodeType() { - return NodeType.META; + @Override + public Collection getConnections(String dataCenter) { + Map connectMap = connections.get(dataCenter); + if (connectMap == null || connectMap.isEmpty()) { + LOGGER.error("Can not find connection of dataCenter {}", dataCenter); + throw new RuntimeException("Can not find connection of dataCenter:" + dataCenter); } + return connectMap.values(); + } -} \ No newline at end of file + @Override + public NodeType getConnectNodeType() { + return NodeType.META; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/NodeConnectManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/NodeConnectManager.java index 74ecaf99b..67f1d6ba5 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/NodeConnectManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/NodeConnectManager.java @@ -18,22 +18,20 @@ import com.alipay.sofa.registry.common.model.Node.NodeType; import com.alipay.sofa.registry.remoting.Channel; - import java.net.InetSocketAddress; import java.util.Collection; /** - * * @author shangyu.wh * @version $Id: NodeConnectManager.java, v 0.1 2018-01-24 10:57 shangyu.wh Exp $ */ public interface NodeConnectManager { - void addConnection(Channel channel); + void addConnection(Channel channel); - boolean removeConnection(Channel channel); + boolean removeConnection(Channel channel); - Collection getConnections(String dataCenter); + Collection getConnections(String dataCenter); - NodeType getConnectNodeType(); -} \ No newline at end of file + NodeType getConnectNodeType(); +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/SessionConnectionHandler.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/SessionConnectionHandler.java index 67a15c7a1..1cd2cd391 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/SessionConnectionHandler.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/connection/SessionConnectionHandler.java @@ -21,56 +21,57 @@ import com.alipay.sofa.registry.remoting.Channel; import com.alipay.sofa.registry.server.meta.bootstrap.handler.SessionServerHandler; import com.alipay.sofa.registry.server.shared.remoting.ListenServerChannelHandler; -import org.springframework.stereotype.Component; - import java.net.InetSocketAddress; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.springframework.stereotype.Component; /** * Handle session node's connect request + * * @author shangyu.wh * @version $Id: ServerConnectionHandler.java, v 0.1 2018-01-24 11:42 shangyu.wh Exp $ */ @Component -public class SessionConnectionHandler extends ListenServerChannelHandler implements - NodeConnectManager, SessionServerHandler { +public class SessionConnectionHandler extends ListenServerChannelHandler + implements NodeConnectManager, SessionServerHandler { - private final Map connections = new ConcurrentHashMap<>(); + private final Map connections = + new ConcurrentHashMap<>(); - @Override - public void connected(Channel channel) { - super.connected(channel); - addConnection(channel); - } + @Override + public void connected(Channel channel) { + super.connected(channel); + addConnection(channel); + } - @Override - public void disconnected(Channel channel) { - super.disconnected(channel); - removeConnection(channel); - } + @Override + public void disconnected(Channel channel) { + super.disconnected(channel); + removeConnection(channel); + } - @Override - public NodeType getConnectNodeType() { - return NodeType.SESSION; - } + @Override + public NodeType getConnectNodeType() { + return NodeType.SESSION; + } - @Override - public void addConnection(Channel channel) { - InetSocketAddress remoteAddress = channel.getRemoteAddress(); - String connectId = NetUtil.toAddressString(remoteAddress); - connections.putIfAbsent(connectId, remoteAddress); - } + @Override + public void addConnection(Channel channel) { + InetSocketAddress remoteAddress = channel.getRemoteAddress(); + String connectId = NetUtil.toAddressString(remoteAddress); + connections.putIfAbsent(connectId, remoteAddress); + } - @Override - public boolean removeConnection(Channel channel) { - String connectId = NetUtil.toAddressString(channel.getRemoteAddress()); - return connections.remove(connectId) != null; - } + @Override + public boolean removeConnection(Channel channel) { + String connectId = NetUtil.toAddressString(channel.getRemoteAddress()); + return connections.remove(connectId) != null; + } - @Override - public Collection getConnections(String dataCenter) { - return connections.values(); - } -} \ No newline at end of file + @Override + public Collection getConnections(String dataCenter) { + return connections.values(); + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/data/DataServerService.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/data/DataServerService.java index 0f25546f7..d69b5ef13 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/data/DataServerService.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/data/DataServerService.java @@ -20,9 +20,6 @@ /** * @author chen.zhu - *

- * Feb 23, 2021 + *

Feb 23, 2021 */ -public interface DataServerService extends Notifier { - -} +public interface DataServerService extends Notifier {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/data/DefaultDataServerService.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/data/DefaultDataServerService.java index 774d4ef4a..7053b29c2 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/data/DefaultDataServerService.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/data/DefaultDataServerService.java @@ -25,65 +25,60 @@ import com.alipay.sofa.registry.server.meta.remoting.notifier.AbstractNotifier; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; import com.google.common.annotations.VisibleForTesting; +import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.List; - /** * @author chen.zhu - *

- * Dec 03, 2020 + *

Dec 03, 2020 */ @Component -public class DefaultDataServerService extends AbstractNotifier implements - DataServerService { +public class DefaultDataServerService extends AbstractNotifier + implements DataServerService { - @Autowired - private DataNodeExchanger dataNodeExchanger; + @Autowired private DataNodeExchanger dataNodeExchanger; - @Autowired - private AbstractServerHandler dataConnectionHandler; + @Autowired private AbstractServerHandler dataConnectionHandler; - @Autowired - private DataServerManager dataServerManager; - - @Override - protected NodeExchanger getNodeExchanger() { - return dataNodeExchanger; - } + @Autowired private DataServerManager dataServerManager; - @Override - protected List getNodes() { - return dataServerManager.getDataServerMetaInfo().getClusterMembers(); - } + @Override + protected NodeExchanger getNodeExchanger() { + return dataNodeExchanger; + } - @Override - protected NodeConnectManager getNodeConnectManager() { - if (!(dataConnectionHandler instanceof NodeConnectManager)) { - logger.error("dataConnectionHandler inject is not NodeConnectManager instance!"); - throw new SofaRegistryRuntimeException( - "dataConnectionHandler inject is not NodeConnectManager instance!"); - } + @Override + protected List getNodes() { + return dataServerManager.getDataServerMetaInfo().getClusterMembers(); + } - return (NodeConnectManager) dataConnectionHandler; + @Override + protected NodeConnectManager getNodeConnectManager() { + if (!(dataConnectionHandler instanceof NodeConnectManager)) { + logger.error("dataConnectionHandler inject is not NodeConnectManager instance!"); + throw new SofaRegistryRuntimeException( + "dataConnectionHandler inject is not NodeConnectManager instance!"); } - @VisibleForTesting - DefaultDataServerService setDataNodeExchanger(DataNodeExchanger dataNodeExchanger) { - this.dataNodeExchanger = dataNodeExchanger; - return this; - } + return (NodeConnectManager) dataConnectionHandler; + } - @VisibleForTesting - DefaultDataServerService setDataConnectionHandler(AbstractServerHandler dataConnectionHandler) { - this.dataConnectionHandler = dataConnectionHandler; - return this; - } + @VisibleForTesting + DefaultDataServerService setDataNodeExchanger(DataNodeExchanger dataNodeExchanger) { + this.dataNodeExchanger = dataNodeExchanger; + return this; + } - @VisibleForTesting - DefaultDataServerService setDataServerManager(DataServerManager dataServerManager) { - this.dataServerManager = dataServerManager; - return this; - } + @VisibleForTesting + DefaultDataServerService setDataConnectionHandler(AbstractServerHandler dataConnectionHandler) { + this.dataConnectionHandler = dataConnectionHandler; + return this; + } + + @VisibleForTesting + DefaultDataServerService setDataServerManager(DataServerManager dataServerManager) { + this.dataServerManager = dataServerManager; + return this; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/BaseMetaServerHandler.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/BaseMetaServerHandler.java index 775b24202..2e19b4b35 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/BaseMetaServerHandler.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/BaseMetaServerHandler.java @@ -18,10 +18,9 @@ import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; +import org.springframework.beans.factory.annotation.Autowired; /** * @author shangyu.wh @@ -29,16 +28,15 @@ */ public abstract class BaseMetaServerHandler extends AbstractServerHandler { - @Autowired - private ThreadPoolExecutor defaultRequestExecutor; + @Autowired private ThreadPoolExecutor defaultRequestExecutor; - @Override - public Executor getExecutor() { - return defaultRequestExecutor; - } + @Override + public Executor getExecutor() { + return defaultRequestExecutor; + } - @Override - protected Node.NodeType getConnectNodeType() { - return null; - } -} \ No newline at end of file + @Override + protected Node.NodeType getConnectNodeType() { + return null; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/FetchProvideDataRequestHandler.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/FetchProvideDataRequestHandler.java index 764f76645..a99322c4b 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/FetchProvideDataRequestHandler.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/FetchProvideDataRequestHandler.java @@ -41,54 +41,56 @@ */ @Component public class FetchProvideDataRequestHandler extends BaseMetaServerHandler - implements SessionServerHandler, DataServerHandler { + implements SessionServerHandler, DataServerHandler { - private static final Logger DB_LOGGER = LoggerFactory.getLogger( - FetchProvideDataRequestHandler.class, "[DBService]"); + private static final Logger DB_LOGGER = + LoggerFactory.getLogger(FetchProvideDataRequestHandler.class, "[DBService]"); - @Autowired - private ProvideDataRepository provideDataRepository; + @Autowired private ProvideDataRepository provideDataRepository; - @Autowired - private NodeConfig nodeConfig; + @Autowired private NodeConfig nodeConfig; - @Override - public Object doHandle(Channel channel, FetchProvideDataRequest fetchProvideDataRequest) { - try { - DBResponse ret = provideDataRepository.get(nodeConfig.getLocalDataCenter(), fetchProvideDataRequest.getDataInfoId()); - if (ret == null) { - DB_LOGGER.error("get null Data from db!"); - throw new RuntimeException("Get null Data from db!"); - } + @Override + public Object doHandle(Channel channel, FetchProvideDataRequest fetchProvideDataRequest) { + try { + DBResponse ret = + provideDataRepository.get( + nodeConfig.getLocalDataCenter(), fetchProvideDataRequest.getDataInfoId()); + if (ret == null) { + DB_LOGGER.error("get null Data from db!"); + throw new RuntimeException("Get null Data from db!"); + } - if (ret.getOperationStatus() == OperationStatus.SUCCESS) { - PersistenceData data = JsonUtils.read((String) ret.getEntity(), PersistenceData.class); - ProvideData provideData = new ProvideData(new ServerDataBox(data.getData()), - fetchProvideDataRequest.getDataInfoId(), data.getVersion()); - DB_LOGGER.info("get ProvideData {} from DB success!", provideData); - return provideData; - } else if (ret.getOperationStatus() == OperationStatus.NOTFOUND) { - ProvideData provideData = new ProvideData(null, - fetchProvideDataRequest.getDataInfoId(), null); - DB_LOGGER.warn("has not found data from DB dataInfoId:{}", - fetchProvideDataRequest.getDataInfoId()); - return provideData; - } else { - DB_LOGGER.error("get Data DB status error!"); - throw new RuntimeException("Get Data DB status error!"); - } + if (ret.getOperationStatus() == OperationStatus.SUCCESS) { + PersistenceData data = JsonUtils.read((String) ret.getEntity(), PersistenceData.class); + ProvideData provideData = + new ProvideData( + new ServerDataBox(data.getData()), + fetchProvideDataRequest.getDataInfoId(), + data.getVersion()); + DB_LOGGER.info("get ProvideData {} from DB success!", provideData); + return provideData; + } else if (ret.getOperationStatus() == OperationStatus.NOTFOUND) { + ProvideData provideData = + new ProvideData(null, fetchProvideDataRequest.getDataInfoId(), null); + DB_LOGGER.warn( + "has not found data from DB dataInfoId:{}", fetchProvideDataRequest.getDataInfoId()); + return provideData; + } else { + DB_LOGGER.error("get Data DB status error!"); + throw new RuntimeException("Get Data DB status error!"); + } - } catch (Exception e) { - DB_LOGGER.error("get persistence Data dataInfoId {} from db error!", - fetchProvideDataRequest.getDataInfoId()); - throw new RuntimeException("Get persistence Data from db error!", e); - } - - } - - @Override - public Class interest() { - return FetchProvideDataRequest.class; + } catch (Exception e) { + DB_LOGGER.error( + "get persistence Data dataInfoId {} from db error!", + fetchProvideDataRequest.getDataInfoId()); + throw new RuntimeException("Get persistence Data from db error!", e); } + } -} \ No newline at end of file + @Override + public Class interest() { + return FetchProvideDataRequest.class; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/GetSlotTableRequestHandler.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/GetSlotTableRequestHandler.java index fd945d2b6..dd088af62 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/GetSlotTableRequestHandler.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/GetSlotTableRequestHandler.java @@ -25,12 +25,10 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.remoting.Channel; import com.alipay.sofa.registry.server.meta.metaserver.CurrentDcMetaServer; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-11 11:23 yuzhi.lyz Exp $ */ @@ -38,37 +36,39 @@ // for cross-dc sync use only public final class GetSlotTableRequestHandler extends BaseMetaServerHandler { - private static final Logger LOGGER = LoggerFactory.getLogger("META-SLOT"); + private static final Logger LOGGER = LoggerFactory.getLogger("META-SLOT"); - @Autowired - private CurrentDcMetaServer currentDcMetaServer; + @Autowired private CurrentDcMetaServer currentDcMetaServer; - @Override - public Object doHandle(Channel channel, GetSlotTableRequest getNodesRequest) { - final long epochOfNode = getNodesRequest.getEpochOfNode(); - final SlotTable currentTable = currentDcMetaServer.getSlotTable(); - if (epochOfNode == currentTable.getEpoch()) { - // not change, return null - return new GenericResponse().fillSucceed(null); - } - if (epochOfNode > currentTable.getEpoch()) { - // should not happen - LOGGER.error("[SLOT-EPOCH] meta's epoch={} should not less than node's epoch={}, {}", - currentTable.getEpoch(), epochOfNode, channel.getRemoteAddress().getAddress() - .getHostAddress()); - return new GenericResponse().fillFailed("illegal epoch of node"); - } - if (getNodesRequest.getTargetDataNode() == null) { - return new GenericResponse().fillSucceed(currentTable); - } - List dataNodeSlots = currentTable.transfer( - getNodesRequest.getTargetDataNode(), getNodesRequest.isIgnoredFollowers()); - return new GenericResponse().fillSucceed(new GetSlotTableResult(currentTable.getEpoch(), - dataNodeSlots)); + @Override + public Object doHandle(Channel channel, GetSlotTableRequest getNodesRequest) { + final long epochOfNode = getNodesRequest.getEpochOfNode(); + final SlotTable currentTable = currentDcMetaServer.getSlotTable(); + if (epochOfNode == currentTable.getEpoch()) { + // not change, return null + return new GenericResponse().fillSucceed(null); } - - @Override - public Class interest() { - return GetSlotTableRequest.class; + if (epochOfNode > currentTable.getEpoch()) { + // should not happen + LOGGER.error( + "[SLOT-EPOCH] meta's epoch={} should not less than node's epoch={}, {}", + currentTable.getEpoch(), + epochOfNode, + channel.getRemoteAddress().getAddress().getHostAddress()); + return new GenericResponse().fillFailed("illegal epoch of node"); + } + if (getNodesRequest.getTargetDataNode() == null) { + return new GenericResponse().fillSucceed(currentTable); } + List dataNodeSlots = + currentTable.transfer( + getNodesRequest.getTargetDataNode(), getNodesRequest.isIgnoredFollowers()); + return new GenericResponse() + .fillSucceed(new GetSlotTableResult(currentTable.getEpoch(), dataNodeSlots)); + } + + @Override + public Class interest() { + return GetSlotTableRequest.class; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/HeartbeatRequestHandler.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/HeartbeatRequestHandler.java index 999011e54..44379c83c 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/HeartbeatRequestHandler.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/handler/HeartbeatRequestHandler.java @@ -44,333 +44,349 @@ import com.alipay.sofa.registry.server.meta.slot.SlotManager; import com.alipay.sofa.registry.server.meta.slot.manager.DefaultSlotManager; import com.alipay.sofa.registry.server.shared.slot.SlotTableUtils; +import java.util.List; +import java.util.Set; import org.glassfish.jersey.internal.guava.Sets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.List; -import java.util.Set; - /** * Handle session/data node's heartbeat request + * * @author shangyu.wh * @version $Id: RenewNodesRequestHandler.java, v 0.1 2018-03-30 19:58 shangyu.wh Exp $ */ @Component public class HeartbeatRequestHandler extends BaseMetaServerHandler> - implements SessionServerHandler, DataServerHandler { - - private static final Logger logger = LoggerFactory - .getLogger(HeartbeatRequestHandler.class); - - @Autowired - private DefaultCurrentDcMetaServer currentDcMetaServer; - - @Autowired - private SlotManager slotManager; - - @Autowired - private MetaLeaderService metaLeaderService; - - @Autowired(required = false) - private List dataMessageListeners; - - @Autowired(required = false) - private List sessionMessageListeners; - - @Autowired - private NodeConfig nodeConfig; - - /** - * Do handle object. - * - * @param channel the channel - * @param heartbeat the heartbeat - * @return the object - */ - @Override - public Object doHandle(Channel channel, HeartbeatRequest heartbeat) { - Node renewNode = null; - try { - renewNode = heartbeat.getNode(); - onHeartbeat(heartbeat, channel); - - SlotTable slotTable = currentDcMetaServer.getSlotTable(); - if (!SlotTableUtils.isValidSlotTable(slotTable)) { - return new GenericResponse() - .fillFailed("slot-table not valid, check meta-server log for detail"); - } - BaseHeartBeatResponse response = null; - - final VersionedList metaServerInfo = currentDcMetaServer.getClusterMeta(); - final VersionedList sessionMetaInfo = currentDcMetaServer.getSessionServerManager() - .getSessionServerMetaInfo(); - - switch (renewNode.getNodeType()) { - case SESSION: - response = new SessionHeartBeatResponse(metaServerInfo, slotTable, sessionMetaInfo, - metaLeaderService.getLeader(), metaLeaderService.getLeaderEpoch()); - break; - case DATA: - slotTable = transferDataNodeSlotToSlotTable((DataNode) renewNode, slotTable); - response = new DataHeartBeatResponse(metaServerInfo, slotTable, sessionMetaInfo, - metaLeaderService.getLeader(), metaLeaderService.getLeaderEpoch()); - break; - case META: - response = new BaseHeartBeatResponse(metaServerInfo, slotTable, - metaLeaderService.getLeader(), metaLeaderService.getLeaderEpoch()); - break; - default: - break; - } - - return new GenericResponse().fillSucceed(response); - } catch (Throwable e) { - logger.error("Node {} renew error!", renewNode, e); - return new GenericResponse().fillFailed("Node " + renewNode - + "renew error!"); - } + implements SessionServerHandler, DataServerHandler { + + private static final Logger logger = LoggerFactory.getLogger(HeartbeatRequestHandler.class); + + @Autowired private DefaultCurrentDcMetaServer currentDcMetaServer; + + @Autowired private SlotManager slotManager; + + @Autowired private MetaLeaderService metaLeaderService; + + @Autowired(required = false) + private List dataMessageListeners; + + @Autowired(required = false) + private List sessionMessageListeners; + + @Autowired private NodeConfig nodeConfig; + + /** + * Do handle object. + * + * @param channel the channel + * @param heartbeat the heartbeat + * @return the object + */ + @Override + public Object doHandle(Channel channel, HeartbeatRequest heartbeat) { + Node renewNode = null; + try { + renewNode = heartbeat.getNode(); + onHeartbeat(heartbeat, channel); + + SlotTable slotTable = currentDcMetaServer.getSlotTable(); + if (!SlotTableUtils.isValidSlotTable(slotTable)) { + return new GenericResponse() + .fillFailed("slot-table not valid, check meta-server log for detail"); + } + BaseHeartBeatResponse response = null; + + final VersionedList metaServerInfo = currentDcMetaServer.getClusterMeta(); + final VersionedList sessionMetaInfo = + currentDcMetaServer.getSessionServerManager().getSessionServerMetaInfo(); + + switch (renewNode.getNodeType()) { + case SESSION: + response = + new SessionHeartBeatResponse( + metaServerInfo, + slotTable, + sessionMetaInfo, + metaLeaderService.getLeader(), + metaLeaderService.getLeaderEpoch()); + break; + case DATA: + slotTable = transferDataNodeSlotToSlotTable((DataNode) renewNode, slotTable); + response = + new DataHeartBeatResponse( + metaServerInfo, + slotTable, + sessionMetaInfo, + metaLeaderService.getLeader(), + metaLeaderService.getLeaderEpoch()); + break; + case META: + response = + new BaseHeartBeatResponse( + metaServerInfo, + slotTable, + metaLeaderService.getLeader(), + metaLeaderService.getLeaderEpoch()); + break; + default: + break; + } + + return new GenericResponse().fillSucceed(response); + } catch (Throwable e) { + logger.error("Node {} renew error!", renewNode, e); + return new GenericResponse() + .fillFailed("Node " + renewNode + "renew error!"); } - - @SuppressWarnings("unchecked") - private void onHeartbeat(HeartbeatRequest heartbeat, Channel channel) { - new DefaultHeartbeatListener(nodeConfig.getLocalDataCenter(), channel) - .onHeartbeat(heartbeat); - Node node = heartbeat.getNode(); - switch (node.getNodeType()) { - case SESSION: - currentDcMetaServer.getSessionServerManager().renew((SessionNode) node, - heartbeat.getDuration()); - onSessionHeartbeat(heartbeat); - return; - case DATA: - currentDcMetaServer.getDataServerManager().renew((DataNode) node, - heartbeat.getDuration()); - onDataHeartbeat(heartbeat); - return; - case META: - throw new IllegalArgumentException("node type not correct: " + node.getNodeType()); - default: - break; - } + } + + @SuppressWarnings("unchecked") + private void onHeartbeat(HeartbeatRequest heartbeat, Channel channel) { + new DefaultHeartbeatListener(nodeConfig.getLocalDataCenter(), channel).onHeartbeat(heartbeat); + Node node = heartbeat.getNode(); + switch (node.getNodeType()) { + case SESSION: + currentDcMetaServer + .getSessionServerManager() + .renew((SessionNode) node, heartbeat.getDuration()); + onSessionHeartbeat(heartbeat); + return; + case DATA: + currentDcMetaServer.getDataServerManager().renew((DataNode) node, heartbeat.getDuration()); + onDataHeartbeat(heartbeat); + return; + case META: throw new IllegalArgumentException("node type not correct: " + node.getNodeType()); + default: + break; } + throw new IllegalArgumentException("node type not correct: " + node.getNodeType()); + } - private void onSessionHeartbeat(HeartbeatRequest heartbeat) { - if(sessionMessageListeners == null || sessionMessageListeners.isEmpty()) { - return; - } - sessionMessageListeners.forEach(listener -> { - try { - listener.onHeartbeat(heartbeat); - } catch (Throwable th) { - logger.error("[onDataHeartbeat]", th); - } - }); + private void onSessionHeartbeat(HeartbeatRequest heartbeat) { + if (sessionMessageListeners == null || sessionMessageListeners.isEmpty()) { + return; } - - private void onDataHeartbeat(HeartbeatRequest heartbeat) { - if(dataMessageListeners == null || dataMessageListeners.isEmpty()) { - return; - } - dataMessageListeners.forEach(listener -> { - try { - listener.onHeartbeat(heartbeat); - } catch (Throwable th) { - logger.error("[onDataHeartbeat]", th); - } + sessionMessageListeners.forEach( + listener -> { + try { + listener.onHeartbeat(heartbeat); + } catch (Throwable th) { + logger.error("[onDataHeartbeat]", th); + } }); - } + } - private SlotTable transferDataNodeSlotToSlotTable(DataNode node, SlotTable slotTable) { - DataNodeSlot dataNodeSlot = slotManager.getDataNodeManagedSlot(node.getIp(), false); - Set result = Sets.newHashSet(); - dataNodeSlot.getLeaders().forEach(leaderSlotId->result.add(slotTable.getSlot(leaderSlotId))); - dataNodeSlot.getFollowers().forEach(followerSlotId->result.add(slotTable.getSlot(followerSlotId))); - return new SlotTable(slotTable.getEpoch(), result); + private void onDataHeartbeat(HeartbeatRequest heartbeat) { + if (dataMessageListeners == null || dataMessageListeners.isEmpty()) { + return; } + dataMessageListeners.forEach( + listener -> { + try { + listener.onHeartbeat(heartbeat); + } catch (Throwable th) { + logger.error("[onDataHeartbeat]", th); + } + }); + } - /** - * Interest class. - * - * @return the class - */ - @Override - public Class interest() { - return HeartbeatRequest.class; - } + private SlotTable transferDataNodeSlotToSlotTable(DataNode node, SlotTable slotTable) { + DataNodeSlot dataNodeSlot = slotManager.getDataNodeManagedSlot(node.getIp(), false); + Set result = Sets.newHashSet(); + dataNodeSlot.getLeaders().forEach(leaderSlotId -> result.add(slotTable.getSlot(leaderSlotId))); + dataNodeSlot + .getFollowers() + .forEach(followerSlotId -> result.add(slotTable.getSlot(followerSlotId))); + return new SlotTable(slotTable.getEpoch(), result); + } - public static class DefaultHeartbeatListener implements HeartbeatListener { - - private static final Logger logger = LoggerFactory - .getLogger(DefaultHeartbeatListener.class); - - public static final String KEY_TIMESTAMP_GAP_THRESHOLD = "timestamp.gap.threshold"; - - private static final long timeGapThreshold = Long.getLong( - KEY_TIMESTAMP_GAP_THRESHOLD, - 2000); - - private final String dataCenter; - - private final Channel channel; - - private volatile boolean isValidChannel = true; - - /** - * Constructor. - * - * @param dataCenter the data center - * @param channel the channel - */ - public DefaultHeartbeatListener(String dataCenter, Channel channel) { - this.dataCenter = dataCenter; - this.channel = channel; - } - - /** - * On heartbeat. - * - * @param heartbeat the heartbeat - */ - @Override - public void onHeartbeat(HeartbeatRequest heartbeat) { - checkIfDataCenterMatched(heartbeat); - checkIfTimeSynced(heartbeat); - checkIfSlotBasicInfoMatched(heartbeat); - closeIfChannelNotValid(); - } - - private void closeIfChannelNotValid() { - if (!isValidChannel) { - - channel.close(); - } - } - - private void checkIfTimeSynced(HeartbeatRequest heartbeat) { - long timestamp = heartbeat.getTimestamp(); - if (System.currentTimeMillis() - timestamp > timeGapThreshold) { - logger.error("[checkIfTimeSynced] {} timestamp[{}] is far behind mine[{}]", - heartbeat.getNode(), timestamp, System.currentTimeMillis()); - } - } - - private void checkIfSlotBasicInfoMatched(HeartbeatRequest heartbeat) { - - SlotConfig.SlotBasicInfo slotBasicInfo = heartbeat.getSlotBasicInfo(); - if (!SlotConfig.FUNC.equals(slotBasicInfo.getSlotFunc())) { - logger - .error( - "[checkIfSlotBasicInfoMatched] {} slot function not match(meta-server: [{}], receive: [{}]", - heartbeat.getNode(), SlotConfig.FUNC, slotBasicInfo.getSlotFunc()); - isValidChannel = false; - } - if (SlotConfig.SLOT_NUM != slotBasicInfo.getSlotNum()) { - logger - .error( - "[checkIfSlotBasicInfoMatched] {} slot number not match(meta-server: [{}], receive: [{}]", - heartbeat.getNode(), SlotConfig.SLOT_NUM, slotBasicInfo.getSlotNum()); - isValidChannel = false; - } - if (SlotConfig.SLOT_REPLICAS != slotBasicInfo.getSlotReplicas()) { - logger - .error( - "[checkIfSlotBasicInfoMatched] {} slot replicas not match(meta-server: [{}], receive: [{}]", - heartbeat.getNode(), SlotConfig.SLOT_REPLICAS, - slotBasicInfo.getSlotReplicas()); - isValidChannel = false; - } - - } - - private void checkIfDataCenterMatched(HeartbeatRequest heartbeat) { - String dc = heartbeat.getDataCenter(); - if (!this.dataCenter.equalsIgnoreCase(dc)) { - logger - .error( - "[checkIfDataCenterMatched] {} datacenter not match(meta-server: [{}], node: [{}]", - heartbeat.getNode(), this.dataCenter, dc); - isValidChannel = false; - } - } + /** + * Interest class. + * + * @return the class + */ + @Override + public Class interest() { + return HeartbeatRequest.class; + } - } + public static class DefaultHeartbeatListener implements HeartbeatListener { - /** - * Sets set current dc meta server. - * - * @param currentDcMetaServer the current dc meta server - * @return the set current dc meta server - */ - public HeartbeatRequestHandler setCurrentDcMetaServer(DefaultCurrentDcMetaServer currentDcMetaServer) { - this.currentDcMetaServer = currentDcMetaServer; - return this; - } + private static final Logger logger = LoggerFactory.getLogger(DefaultHeartbeatListener.class); + + public static final String KEY_TIMESTAMP_GAP_THRESHOLD = "timestamp.gap.threshold"; + + private static final long timeGapThreshold = Long.getLong(KEY_TIMESTAMP_GAP_THRESHOLD, 2000); + + private final String dataCenter; + + private final Channel channel; + + private volatile boolean isValidChannel = true; /** - * Sets set default slot manager. + * Constructor. * - * @param defaultSlotManager the default slot manager - * @return the set default slot manager + * @param dataCenter the data center + * @param channel the channel */ - public HeartbeatRequestHandler setDefaultSlotManager(DefaultSlotManager defaultSlotManager) { - this.slotManager = defaultSlotManager; - return this; + public DefaultHeartbeatListener(String dataCenter, Channel channel) { + this.dataCenter = dataCenter; + this.channel = channel; } /** - * Sets set data message listeners. + * On heartbeat. * - * @param dataMessageListeners the data message listeners - * @return the set data message listeners + * @param heartbeat the heartbeat */ - public HeartbeatRequestHandler setDataMessageListeners(List dataMessageListeners) { - this.dataMessageListeners = dataMessageListeners; - return this; + @Override + public void onHeartbeat(HeartbeatRequest heartbeat) { + checkIfDataCenterMatched(heartbeat); + checkIfTimeSynced(heartbeat); + checkIfSlotBasicInfoMatched(heartbeat); + closeIfChannelNotValid(); } - /** - * Sets set session message listeners. - * - * @param sessionMessageListeners the session message listeners - * @return the set session message listeners - */ - public HeartbeatRequestHandler setSessionMessageListeners(List sessionMessageListeners) { - this.sessionMessageListeners = sessionMessageListeners; - return this; + private void closeIfChannelNotValid() { + if (!isValidChannel) { + + channel.close(); + } } - /** - * Sets set node config. - * - * @param nodeConfig the node config - * @return the set node config - */ - public HeartbeatRequestHandler setNodeConfig(NodeConfig nodeConfig) { - this.nodeConfig = nodeConfig; - return this; + private void checkIfTimeSynced(HeartbeatRequest heartbeat) { + long timestamp = heartbeat.getTimestamp(); + if (System.currentTimeMillis() - timestamp > timeGapThreshold) { + logger.error( + "[checkIfTimeSynced] {} timestamp[{}] is far behind mine[{}]", + heartbeat.getNode(), + timestamp, + System.currentTimeMillis()); + } } - /** - * Sets set slot manager. - * - * @param slotManager the slot manager - * @return the set slot manager - */ - public HeartbeatRequestHandler setSlotManager(SlotManager slotManager) { - this.slotManager = slotManager; - return this; + private void checkIfSlotBasicInfoMatched(HeartbeatRequest heartbeat) { + + SlotConfig.SlotBasicInfo slotBasicInfo = heartbeat.getSlotBasicInfo(); + if (!SlotConfig.FUNC.equals(slotBasicInfo.getSlotFunc())) { + logger.error( + "[checkIfSlotBasicInfoMatched] {} slot function not match(meta-server: [{}], receive: [{}]", + heartbeat.getNode(), + SlotConfig.FUNC, + slotBasicInfo.getSlotFunc()); + isValidChannel = false; + } + if (SlotConfig.SLOT_NUM != slotBasicInfo.getSlotNum()) { + logger.error( + "[checkIfSlotBasicInfoMatched] {} slot number not match(meta-server: [{}], receive: [{}]", + heartbeat.getNode(), + SlotConfig.SLOT_NUM, + slotBasicInfo.getSlotNum()); + isValidChannel = false; + } + if (SlotConfig.SLOT_REPLICAS != slotBasicInfo.getSlotReplicas()) { + logger.error( + "[checkIfSlotBasicInfoMatched] {} slot replicas not match(meta-server: [{}], receive: [{}]", + heartbeat.getNode(), + SlotConfig.SLOT_REPLICAS, + slotBasicInfo.getSlotReplicas()); + isValidChannel = false; + } } - /** - * Sets set meta leader elector. - * - * @param metaLeaderElector the meta leader elector - * @return the set meta leader elector - */ - public HeartbeatRequestHandler setMetaLeaderElector(MetaLeaderService metaLeaderElector) { - this.metaLeaderService = metaLeaderElector; - return this; + private void checkIfDataCenterMatched(HeartbeatRequest heartbeat) { + String dc = heartbeat.getDataCenter(); + if (!this.dataCenter.equalsIgnoreCase(dc)) { + logger.error( + "[checkIfDataCenterMatched] {} datacenter not match(meta-server: [{}], node: [{}]", + heartbeat.getNode(), + this.dataCenter, + dc); + isValidChannel = false; + } } -} \ No newline at end of file + } + + /** + * Sets set current dc meta server. + * + * @param currentDcMetaServer the current dc meta server + * @return the set current dc meta server + */ + public HeartbeatRequestHandler setCurrentDcMetaServer( + DefaultCurrentDcMetaServer currentDcMetaServer) { + this.currentDcMetaServer = currentDcMetaServer; + return this; + } + + /** + * Sets set default slot manager. + * + * @param defaultSlotManager the default slot manager + * @return the set default slot manager + */ + public HeartbeatRequestHandler setDefaultSlotManager(DefaultSlotManager defaultSlotManager) { + this.slotManager = defaultSlotManager; + return this; + } + + /** + * Sets set data message listeners. + * + * @param dataMessageListeners the data message listeners + * @return the set data message listeners + */ + public HeartbeatRequestHandler setDataMessageListeners( + List dataMessageListeners) { + this.dataMessageListeners = dataMessageListeners; + return this; + } + + /** + * Sets set session message listeners. + * + * @param sessionMessageListeners the session message listeners + * @return the set session message listeners + */ + public HeartbeatRequestHandler setSessionMessageListeners( + List sessionMessageListeners) { + this.sessionMessageListeners = sessionMessageListeners; + return this; + } + + /** + * Sets set node config. + * + * @param nodeConfig the node config + * @return the set node config + */ + public HeartbeatRequestHandler setNodeConfig(NodeConfig nodeConfig) { + this.nodeConfig = nodeConfig; + return this; + } + + /** + * Sets set slot manager. + * + * @param slotManager the slot manager + * @return the set slot manager + */ + public HeartbeatRequestHandler setSlotManager(SlotManager slotManager) { + this.slotManager = slotManager; + return this; + } + + /** + * Sets set meta leader elector. + * + * @param metaLeaderElector the meta leader elector + * @return the set meta leader elector + */ + public HeartbeatRequestHandler setMetaLeaderElector(MetaLeaderService metaLeaderElector) { + this.metaLeaderService = metaLeaderElector; + return this; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/notifier/AbstractNotifier.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/notifier/AbstractNotifier.java index 1b5a30fff..fadb03cc9 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/notifier/AbstractNotifier.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/notifier/AbstractNotifier.java @@ -33,7 +33,6 @@ import com.alipay.sofa.registry.util.OsUtils; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Sets; - import java.net.InetSocketAddress; import java.util.Collection; import java.util.List; @@ -44,126 +43,129 @@ /** * @author chen.zhu - *

- * Feb 23, 2021 + *

Feb 23, 2021 */ public abstract class AbstractNotifier implements Notifier { - protected final Logger logger = LoggerFactory.getLogger(getClass()); + protected final Logger logger = LoggerFactory.getLogger(getClass()); - private Executor executors = DefaultExecutorFactory.createCachedThreadPoolFactory( - getClass().getSimpleName(), - Math.min(4, OsUtils.getCpuCount()), 60 * 1000, - TimeUnit.MILLISECONDS).create(); + private Executor executors = + DefaultExecutorFactory.createCachedThreadPoolFactory( + getClass().getSimpleName(), + Math.min(4, OsUtils.getCpuCount()), + 60 * 1000, + TimeUnit.MILLISECONDS) + .create(); - @Override - public void notifySlotTableChange(SlotTable slotTable) { - new NotifyTemplate().broadcast(new SlotTableChangeEvent(slotTable - .getEpoch())); - } + @Override + public void notifySlotTableChange(SlotTable slotTable) { + new NotifyTemplate() + .broadcast(new SlotTableChangeEvent(slotTable.getEpoch())); + } - @Override - public void notifyProvideDataChange(ProvideDataChangeEvent event) { - new NotifyTemplate().broadcast(event); + @Override + public void notifyProvideDataChange(ProvideDataChangeEvent event) { + new NotifyTemplate().broadcast(event); + } - } + @VisibleForTesting + public AbstractNotifier setExecutors(Executor executors) { + this.executors = executors; + return this; + } - @VisibleForTesting - public AbstractNotifier setExecutors(Executor executors) { - this.executors = executors; - return this; - } + protected abstract NodeExchanger getNodeExchanger(); - protected abstract NodeExchanger getNodeExchanger(); + protected abstract List getNodes(); - protected abstract List getNodes(); + protected abstract NodeConnectManager getNodeConnectManager(); - protected abstract NodeConnectManager getNodeConnectManager(); + public final class NotifyTemplate { - public final class NotifyTemplate { + public void broadcast(E event) { + NodeConnectManager nodeConnectManager = getNodeConnectManager(); + Collection connections = nodeConnectManager.getConnections(null); - public void broadcast(E event) { - NodeConnectManager nodeConnectManager = getNodeConnectManager(); - Collection connections = nodeConnectManager.getConnections(null); + if (connections == null || connections.isEmpty()) { + logger.error("Push Node list error! No node connected!"); + return; + } - if (connections == null || connections.isEmpty()) { - logger.error("Push Node list error! No node connected!"); - return; - } + List nodes = getNodes(); - List nodes = getNodes(); - - if (nodes == null || nodes.isEmpty()) { - logger.error("Node list error! No node registered!"); - return; - } - Set ipAddresses = Sets.newHashSet(); - nodes.forEach(node -> ipAddresses.add(node.getNodeUrl().getIpAddress())); - new ConcurrentUtils.SafeParaLoop(executors, connections) { - @Override - protected void doRun0(InetSocketAddress connection) throws Exception { - if (!ipAddresses.contains(connection.getAddress().getHostAddress())) { - return; - } - getNodeExchanger().request(new SimpleRequest(event, connection, executors)); - } - }.run(); + if (nodes == null || nodes.isEmpty()) { + logger.error("Node list error! No node registered!"); + return; + } + Set ipAddresses = Sets.newHashSet(); + nodes.forEach(node -> ipAddresses.add(node.getNodeUrl().getIpAddress())); + new ConcurrentUtils.SafeParaLoop(executors, connections) { + @Override + protected void doRun0(InetSocketAddress connection) throws Exception { + if (!ipAddresses.contains(connection.getAddress().getHostAddress())) { + return; + } + getNodeExchanger().request(new SimpleRequest(event, connection, executors)); } + }.run(); } + } - private final static class SimpleRequest implements Request { + private static final class SimpleRequest implements Request { - private final static Logger logger = LoggerFactory.getLogger(SimpleRequest.class); + private static final Logger logger = LoggerFactory.getLogger(SimpleRequest.class); - private final E event; + private final E event; - private final InetSocketAddress connection; + private final InetSocketAddress connection; - private final Executor executors; + private final Executor executors; - public SimpleRequest(E event, InetSocketAddress connection, Executor executors) { - this.event = event; - this.connection = connection; - this.executors = executors; - } + public SimpleRequest(E event, InetSocketAddress connection, Executor executors) { + this.event = event; + this.connection = connection; + this.executors = executors; + } - @Override - public E getRequestBody() { - return event; - } + @Override + public E getRequestBody() { + return event; + } + + @Override + public URL getRequestUrl() { + return new URL(connection); + } + @Override + public CallbackHandler getCallBackHandler() { + return new CallbackHandler() { @Override - public URL getRequestUrl() { - return new URL(connection); + public void onCallback(Channel channel, Object message) { + logger.info( + "[onCallback] notify slot-change succeed, ({}): [{}]", + channel != null ? channel.getRemoteAddress() : "unknown channel", + message); } @Override - public CallbackHandler getCallBackHandler() { - return new CallbackHandler() { - @Override - public void onCallback(Channel channel, Object message) { - logger.info("[onCallback] notify slot-change succeed, ({}): [{}]", - channel != null ? channel.getRemoteAddress() : "unknown channel", message); - } - - @Override - public void onException(Channel channel, Throwable exception) { - logger - .error("[onException] notify slot-change failed, ({})", - channel != null ? channel.getRemoteAddress() : "unknown channel", - exception); - } - - @Override - public Executor getExecutor() { - return executors; - } - }; + public void onException(Channel channel, Throwable exception) { + logger.error( + "[onException] notify slot-change failed, ({})", + channel != null ? channel.getRemoteAddress() : "unknown channel", + exception); } @Override - public AtomicInteger getRetryTimes() { - return new AtomicInteger(3); + public Executor getExecutor() { + return executors; } + }; + } + + @Override + public AtomicInteger getRetryTimes() { + return new AtomicInteger(3); } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/notifier/Notifier.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/notifier/Notifier.java index d866c86a4..5cdb45cbf 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/notifier/Notifier.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/notifier/Notifier.java @@ -21,12 +21,11 @@ /** * @author chen.zhu - *

- * Feb 23, 2021 + *

Feb 23, 2021 */ public interface Notifier { - void notifySlotTableChange(SlotTable slotTable); + void notifySlotTableChange(SlotTable slotTable); - void notifyProvideDataChange(ProvideDataChangeEvent event); + void notifyProvideDataChange(ProvideDataChangeEvent event); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/session/DefaultSessionServerService.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/session/DefaultSessionServerService.java index ea28c1054..4d9c5cdaf 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/session/DefaultSessionServerService.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/session/DefaultSessionServerService.java @@ -24,59 +24,55 @@ import com.alipay.sofa.registry.server.meta.remoting.connection.SessionConnectionHandler; import com.alipay.sofa.registry.server.meta.remoting.notifier.AbstractNotifier; import com.google.common.annotations.VisibleForTesting; +import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import java.util.List; - /** * @author chen.zhu - *

- * Dec 03, 2020 + *

Dec 03, 2020 */ @Component -public class DefaultSessionServerService extends AbstractNotifier implements - SessionServerService { +public class DefaultSessionServerService extends AbstractNotifier + implements SessionServerService { - @Autowired - private SessionNodeExchanger sessionNodeExchanger; + @Autowired private SessionNodeExchanger sessionNodeExchanger; - @Autowired - private SessionConnectionHandler sessionConnectionHandler; + @Autowired private SessionConnectionHandler sessionConnectionHandler; - @Autowired - private SessionServerManager sessionServerManager; + @Autowired private SessionServerManager sessionServerManager; - @Override - protected NodeExchanger getNodeExchanger() { - return sessionNodeExchanger; - } + @Override + protected NodeExchanger getNodeExchanger() { + return sessionNodeExchanger; + } - @Override - protected List getNodes() { - return sessionServerManager.getSessionServerMetaInfo().getClusterMembers(); - } + @Override + protected List getNodes() { + return sessionServerManager.getSessionServerMetaInfo().getClusterMembers(); + } - @Override - protected NodeConnectManager getNodeConnectManager() { - return sessionConnectionHandler; - } + @Override + protected NodeConnectManager getNodeConnectManager() { + return sessionConnectionHandler; + } - @VisibleForTesting - DefaultSessionServerService setSessionNodeExchanger(SessionNodeExchanger sessionNodeExchanger) { - this.sessionNodeExchanger = sessionNodeExchanger; - return this; - } + @VisibleForTesting + DefaultSessionServerService setSessionNodeExchanger(SessionNodeExchanger sessionNodeExchanger) { + this.sessionNodeExchanger = sessionNodeExchanger; + return this; + } - @VisibleForTesting - DefaultSessionServerService setSessionConnectionHandler(SessionConnectionHandler sessionConnectionHandler) { - this.sessionConnectionHandler = sessionConnectionHandler; - return this; - } + @VisibleForTesting + DefaultSessionServerService setSessionConnectionHandler( + SessionConnectionHandler sessionConnectionHandler) { + this.sessionConnectionHandler = sessionConnectionHandler; + return this; + } - @VisibleForTesting - DefaultSessionServerService setSessionServerManager(SessionServerManager sessionServerManager) { - this.sessionServerManager = sessionServerManager; - return this; - } + @VisibleForTesting + DefaultSessionServerService setSessionServerManager(SessionServerManager sessionServerManager) { + this.sessionServerManager = sessionServerManager; + return this; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/session/SessionServerService.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/session/SessionServerService.java index 86e2ecd37..4451033c0 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/session/SessionServerService.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/remoting/session/SessionServerService.java @@ -20,9 +20,6 @@ /** * @author chen.zhu - *

- * Feb 23, 2021 + *

Feb 23, 2021 */ -public interface SessionServerService extends Notifier { - -} +public interface SessionServerService extends Notifier {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/BlacklistDataResource.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/BlacklistDataResource.java index 013a4c76a..cb329d91d 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/BlacklistDataResource.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/BlacklistDataResource.java @@ -29,15 +29,13 @@ import com.alipay.sofa.registry.server.meta.resource.filter.LeaderAwareRestController; import com.alipay.sofa.registry.store.api.meta.ProvideDataRepository; import com.alipay.sofa.registry.util.JsonUtils; -import org.springframework.beans.factory.annotation.Autowired; - import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: StopPushDataResource.java, v 0.1 2018-07-25 11:40 shangyu.wh Exp $ */ @@ -45,68 +43,68 @@ @LeaderAwareRestController public class BlacklistDataResource { - private static final Logger DB_LOGGER = LoggerFactory.getLogger( - BlacklistDataResource.class, "[DBService]"); + private static final Logger DB_LOGGER = + LoggerFactory.getLogger(BlacklistDataResource.class, "[DBService]"); - private static final Logger TASK_LOGGER = LoggerFactory.getLogger( - BlacklistDataResource.class, "[Task]"); + private static final Logger TASK_LOGGER = + LoggerFactory.getLogger(BlacklistDataResource.class, "[Task]"); - @Autowired - private ProvideDataRepository provideDataRepository; + @Autowired private ProvideDataRepository provideDataRepository; - @Autowired - private DefaultProvideDataNotifier provideDataNotifier; + @Autowired private DefaultProvideDataNotifier provideDataNotifier; - @Autowired - private NodeConfig nodeConfig; + @Autowired private NodeConfig nodeConfig; - /** - * update blacklist - * e.g. curl -d '{"FORBIDDEN_PUB":{"IP_FULL":["1.1.1.1","10.15.233.150"]},"FORBIDDEN_SUB_BY_PREFIX":{"IP_FULL":["1.1.1.1"]}}' -H "Content-Type: application/json" -X POST http://localhost:9615/blacklist/update - */ - @POST - @Path("update") - @Produces(MediaType.APPLICATION_JSON) - public Result blacklistPush(String config) { - PersistenceData persistenceData = createDataInfo(); - persistenceData.setData(config); - try { - boolean ret = provideDataRepository.put(nodeConfig.getLocalDataCenter(), ValueConstants.BLACK_LIST_DATA_ID, - JsonUtils.writeValueAsString(persistenceData)); - DB_LOGGER.info("Success update blacklist to DB result {}!", ret); - } catch (Throwable e) { - DB_LOGGER.error("Error update blacklist to DB!", e); - throw new RuntimeException("Update blacklist to error!", e); - } + /** + * update blacklist e.g. curl -d + * '{"FORBIDDEN_PUB":{"IP_FULL":["1.1.1.1","10.15.233.150"]},"FORBIDDEN_SUB_BY_PREFIX":{"IP_FULL":["1.1.1.1"]}}' + * -H "Content-Type: application/json" -X POST http://localhost:9615/blacklist/update + */ + @POST + @Path("update") + @Produces(MediaType.APPLICATION_JSON) + public Result blacklistPush(String config) { + PersistenceData persistenceData = createDataInfo(); + persistenceData.setData(config); + try { + boolean ret = + provideDataRepository.put( + nodeConfig.getLocalDataCenter(), + ValueConstants.BLACK_LIST_DATA_ID, + JsonUtils.writeValueAsString(persistenceData)); + DB_LOGGER.info("Success update blacklist to DB result {}!", ret); + } catch (Throwable e) { + DB_LOGGER.error("Error update blacklist to DB!", e); + throw new RuntimeException("Update blacklist to error!", e); + } - fireDataChangeNotify(persistenceData.getVersion(), ValueConstants.BLACK_LIST_DATA_ID, - DataOperator.UPDATE); + fireDataChangeNotify( + persistenceData.getVersion(), ValueConstants.BLACK_LIST_DATA_ID, DataOperator.UPDATE); - Result result = new Result(); - result.setSuccess(true); - return result; - } + Result result = new Result(); + result.setSuccess(true); + return result; + } - private PersistenceData createDataInfo() { - DataInfo dataInfo = DataInfo.valueOf(ValueConstants.BLACK_LIST_DATA_ID); - PersistenceData persistenceData = new PersistenceData(); - persistenceData.setDataId(dataInfo.getDataId()); - persistenceData.setGroup(dataInfo.getGroup()); - persistenceData.setInstanceId(dataInfo.getInstanceId()); - persistenceData.setVersion(System.currentTimeMillis()); - return persistenceData; - } + private PersistenceData createDataInfo() { + DataInfo dataInfo = DataInfo.valueOf(ValueConstants.BLACK_LIST_DATA_ID); + PersistenceData persistenceData = new PersistenceData(); + persistenceData.setDataId(dataInfo.getDataId()); + persistenceData.setGroup(dataInfo.getGroup()); + persistenceData.setInstanceId(dataInfo.getInstanceId()); + persistenceData.setVersion(System.currentTimeMillis()); + return persistenceData; + } - private void fireDataChangeNotify(Long version, String dataInfoId, DataOperator dataOperator) { + private void fireDataChangeNotify(Long version, String dataInfoId, DataOperator dataOperator) { - ProvideDataChangeEvent provideDataChangeEvent = new ProvideDataChangeEvent(dataInfoId, - version, dataOperator); - if (TASK_LOGGER.isInfoEnabled()) { - TASK_LOGGER.info( - "send PERSISTENCE_DATA_CHANGE_NOTIFY_TASK notifyProvideDataChange: {}", - provideDataChangeEvent); - } - provideDataNotifier.notifyProvideDataChange(provideDataChangeEvent); + ProvideDataChangeEvent provideDataChangeEvent = + new ProvideDataChangeEvent(dataInfoId, version, dataOperator); + if (TASK_LOGGER.isInfoEnabled()) { + TASK_LOGGER.info( + "send PERSISTENCE_DATA_CHANGE_NOTIFY_TASK notifyProvideDataChange: {}", + provideDataChangeEvent); } - -} \ No newline at end of file + provideDataNotifier.notifyProvideDataChange(provideDataChangeEvent); + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/HealthResource.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/HealthResource.java index e17376d12..fdb175c36 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/HealthResource.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/HealthResource.java @@ -25,8 +25,6 @@ import com.alipay.sofa.registry.store.api.elector.LeaderElector; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; -import org.springframework.beans.factory.annotation.Autowired; - import javax.annotation.PostConstruct; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -35,82 +33,78 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: PushSwitchResource.java, v 0.1 2018-10-29 16:51 shangyu.wh Exp $ */ @Path("health") public class HealthResource { - @Autowired - private MetaServerBootstrap metaServerBootstrap; + @Autowired private MetaServerBootstrap metaServerBootstrap; - @Autowired - private MetaLeaderService metaLeaderService; + @Autowired private MetaLeaderService metaLeaderService; - @Autowired - private CurrentDcMetaServer currentDcMetaServer; + @Autowired private CurrentDcMetaServer currentDcMetaServer; - @Autowired - private LeaderElector leaderElector; + @Autowired private LeaderElector leaderElector; - @PostConstruct - public void init() { - MetricRegistry metrics = new MetricRegistry(); - metrics.register("healthCheck", (Gauge) () -> getHealthCheckResult()); - ReporterUtils.startSlf4jReporter(60, metrics); - } + @PostConstruct + public void init() { + MetricRegistry metrics = new MetricRegistry(); + metrics.register("healthCheck", (Gauge) () -> getHealthCheckResult()); + ReporterUtils.startSlf4jReporter(60, metrics); + } - @GET - @Path("check") - @Produces(MediaType.APPLICATION_JSON) - public Response checkHealth() { - ResponseBuilder builder = Response.status(Response.Status.OK); - CommonResponse response = getHealthCheckResult(); - builder.entity(response); - if (!response.isSuccess()) { - builder.status(Status.INTERNAL_SERVER_ERROR); - } - return builder.build(); + @GET + @Path("check") + @Produces(MediaType.APPLICATION_JSON) + public Response checkHealth() { + ResponseBuilder builder = Response.status(Response.Status.OK); + CommonResponse response = getHealthCheckResult(); + builder.entity(response); + if (!response.isSuccess()) { + builder.status(Status.INTERNAL_SERVER_ERROR); } + return builder.build(); + } - private CommonResponse getHealthCheckResult() { - CommonResponse response; + private CommonResponse getHealthCheckResult() { + CommonResponse response; - StringBuilder sb = new StringBuilder("MetaServerBoot "); + StringBuilder sb = new StringBuilder("MetaServerBoot "); - boolean start = metaServerBootstrap.getSessionStart(); - boolean ret = start; - sb.append("sessionRegisterServer:").append(start); + boolean start = metaServerBootstrap.getSessionStart(); + boolean ret = start; + sb.append("sessionRegisterServer:").append(start); - start = metaServerBootstrap.getDataStart(); - ret = ret && start; - sb.append(", dataRegisterServerStart:").append(start); + start = metaServerBootstrap.getDataStart(); + ret = ret && start; + sb.append(", dataRegisterServerStart:").append(start); - start = metaServerBootstrap.getMetaStart(); - ret = ret && start; - sb.append(", otherMetaRegisterServerStart:").append(start); + start = metaServerBootstrap.getMetaStart(); + ret = ret && start; + sb.append(", otherMetaRegisterServerStart:").append(start); - start = metaServerBootstrap.getHttpStart(); - ret = ret && start; + start = metaServerBootstrap.getHttpStart(); + ret = ret && start; - boolean leaderNotEmpty = StringUtil.isNotBlank(leaderElector.getLeader()); - ret = ret && leaderNotEmpty; + boolean leaderNotEmpty = StringUtil.isNotBlank(leaderElector.getLeader()); + ret = ret && leaderNotEmpty; - sb.append(", httpServerStart:").append(start); + sb.append(", httpServerStart:").append(start); - sb.append(", role:").append(metaLeaderService.amILeader() ? "leader" : "follower"); - sb.append(", leader:").append(metaLeaderService.getLeader()); - sb.append(", meta-servers:").append(currentDcMetaServer.getClusterMembers()); - sb.append(", leader:").append(leaderElector.getLeader()); + sb.append(", role:").append(metaLeaderService.amILeader() ? "leader" : "follower"); + sb.append(", leader:").append(metaLeaderService.getLeader()); + sb.append(", meta-servers:").append(currentDcMetaServer.getClusterMembers()); + sb.append(", leader:").append(leaderElector.getLeader()); - if (ret) { - response = CommonResponse.buildSuccessResponse(sb.toString()); - } else { - response = CommonResponse.buildFailedResponse(sb.toString()); - } - return response; + if (ret) { + response = CommonResponse.buildSuccessResponse(sb.toString()); + } else { + response = CommonResponse.buildFailedResponse(sb.toString()); } -} \ No newline at end of file + return response; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/MetaDigestResource.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/MetaDigestResource.java index b452aa066..5e1495b91 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/MetaDigestResource.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/MetaDigestResource.java @@ -31,19 +31,17 @@ import com.alipay.sofa.registry.util.JsonUtils; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; -import org.springframework.beans.factory.annotation.Autowired; - +import java.util.HashMap; +import java.util.Map; import javax.annotation.PostConstruct; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import java.util.HashMap; -import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: MetaDigestResource.java, v 0.1 2018-06-25 21:13 shangyu.wh Exp $ */ @@ -51,92 +49,92 @@ @LeaderAwareRestController public class MetaDigestResource { - private static final Logger TASK_LOGGER = LoggerFactory.getLogger( - MetaDigestResource.class, "[Resource]"); + private static final Logger TASK_LOGGER = + LoggerFactory.getLogger(MetaDigestResource.class, "[Resource]"); - private static final Logger DB_LOGGER = LoggerFactory.getLogger( - MetaDigestResource.class, "[DBService]"); + private static final Logger DB_LOGGER = + LoggerFactory.getLogger(MetaDigestResource.class, "[DBService]"); - @Autowired - private DefaultMetaServerManager metaServerManager; + @Autowired private DefaultMetaServerManager metaServerManager; - @Autowired - private ProvideDataRepository provideDataRepository; + @Autowired private ProvideDataRepository provideDataRepository; - @Autowired - private NodeConfig nodeConfig; + @Autowired private NodeConfig nodeConfig; - @PostConstruct - public void init() { - MetricRegistry metrics = new MetricRegistry(); - metrics.register("metaNodeList", (Gauge) () -> getRegisterNodeByType(NodeType.META.name())); - metrics.register("dataNodeList", (Gauge) () -> getRegisterNodeByType(NodeType.DATA.name())); - metrics.register("sessionNodeList", (Gauge) () -> getRegisterNodeByType(NodeType.SESSION.name())); - metrics.register("pushSwitch", (Gauge) () -> getPushSwitch()); - ReporterUtils.startSlf4jReporter(60, metrics); - } + @PostConstruct + public void init() { + MetricRegistry metrics = new MetricRegistry(); + metrics.register( + "metaNodeList", (Gauge) () -> getRegisterNodeByType(NodeType.META.name())); + metrics.register( + "dataNodeList", (Gauge) () -> getRegisterNodeByType(NodeType.DATA.name())); + metrics.register( + "sessionNodeList", (Gauge) () -> getRegisterNodeByType(NodeType.SESSION.name())); + metrics.register("pushSwitch", (Gauge) () -> getPushSwitch()); + ReporterUtils.startSlf4jReporter(60, metrics); + } - @GET - @Path("{type}/node/query") - @Produces(MediaType.APPLICATION_JSON) - public Map getRegisterNodeByType(@PathParam("type") String type) { - try { - return metaServerManager.getSummary(NodeType.valueOf(type.toUpperCase())).getNodes(); - } catch (Exception e) { - TASK_LOGGER.error("Fail get Register Node By Type:{}", type, e); - throw new RuntimeException("Fail get Register Node By Type:" + type, e); - } + @GET + @Path("{type}/node/query") + @Produces(MediaType.APPLICATION_JSON) + public Map getRegisterNodeByType(@PathParam("type") String type) { + try { + return metaServerManager.getSummary(NodeType.valueOf(type.toUpperCase())).getNodes(); + } catch (Exception e) { + TASK_LOGGER.error("Fail get Register Node By Type:{}", type, e); + throw new RuntimeException("Fail get Register Node By Type:" + type, e); } + } - /** - * return true mean push switch on - */ - @GET - @Path("pushSwitch") - @Produces(MediaType.APPLICATION_JSON) - public Map getPushSwitch() { - Map resultMap = new HashMap<>(1); - try { - DBResponse ret = provideDataRepository - .get(nodeConfig.getLocalDataCenter(), ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID); + /** return true mean push switch on */ + @GET + @Path("pushSwitch") + @Produces(MediaType.APPLICATION_JSON) + public Map getPushSwitch() { + Map resultMap = new HashMap<>(1); + try { + DBResponse ret = + provideDataRepository.get( + nodeConfig.getLocalDataCenter(), ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID); - if (ret == null) { - //default push switch on - resultMap.put("pushSwitch", "open"); - resultMap.put("msg", "get null Data from db!"); - } else { - if (ret.getOperationStatus() == OperationStatus.SUCCESS) { - String result = getEntityData(ret); - if (result != null && !result.isEmpty()) { - resultMap.put("pushSwitch", "false".equalsIgnoreCase(result) ? "open" - : "closed"); - } else { - resultMap.put("pushSwitch", "open"); - resultMap.put("msg", "data is empty"); - } - } else if (ret.getOperationStatus() == OperationStatus.NOTFOUND) { - resultMap.put("pushSwitch", "open"); - resultMap.put("msg", "OperationStatus is NOTFOUND"); - } else { - DB_LOGGER.error("get Data DB status error!"); - throw new RuntimeException("Get Data DB status error!"); - } - } - DB_LOGGER.info("getPushSwitch: {}", resultMap); - } catch (Exception e) { - DB_LOGGER.error("get persistence Data dataInfoId {} from db error!", - ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID, e); - throw new RuntimeException("Get persistence Data from db error!", e); + if (ret == null) { + // default push switch on + resultMap.put("pushSwitch", "open"); + resultMap.put("msg", "get null Data from db!"); + } else { + if (ret.getOperationStatus() == OperationStatus.SUCCESS) { + String result = getEntityData(ret); + if (result != null && !result.isEmpty()) { + resultMap.put("pushSwitch", "false".equalsIgnoreCase(result) ? "open" : "closed"); + } else { + resultMap.put("pushSwitch", "open"); + resultMap.put("msg", "data is empty"); + } + } else if (ret.getOperationStatus() == OperationStatus.NOTFOUND) { + resultMap.put("pushSwitch", "open"); + resultMap.put("msg", "OperationStatus is NOTFOUND"); + } else { + DB_LOGGER.error("get Data DB status error!"); + throw new RuntimeException("Get Data DB status error!"); } - - return resultMap; + } + DB_LOGGER.info("getPushSwitch: {}", resultMap); + } catch (Exception e) { + DB_LOGGER.error( + "get persistence Data dataInfoId {} from db error!", + ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID, + e); + throw new RuntimeException("Get persistence Data from db error!", e); } - private static String getEntityData(DBResponse resp) { - if (resp != null && resp.getEntity() != null) { - PersistenceData data = JsonUtils.read((String) resp.getEntity(), PersistenceData.class); - return data.getData(); - } - return null; + return resultMap; + } + + private static String getEntityData(DBResponse resp) { + if (resp != null && resp.getEntity() != null) { + PersistenceData data = JsonUtils.read((String) resp.getEntity(), PersistenceData.class); + return data.getData(); } -} \ No newline at end of file + return null; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/ProvideDataResource.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/ProvideDataResource.java index a82ab9d64..a003fe8dd 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/ProvideDataResource.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/ProvideDataResource.java @@ -28,15 +28,13 @@ import com.alipay.sofa.registry.server.meta.resource.filter.LeaderAwareRestController; import com.alipay.sofa.registry.store.api.meta.ProvideDataRepository; import com.alipay.sofa.registry.util.JsonUtils; -import org.springframework.beans.factory.annotation.Autowired; - import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: DecisionModeResource.java, v 0.1 2018-02-01 16:50 shangyu.wh Exp $ */ @@ -44,95 +42,95 @@ @LeaderAwareRestController public class ProvideDataResource { - private static final Logger DB_LOGGER = LoggerFactory.getLogger( - ProvideDataResource.class, "[DBService]"); + private static final Logger DB_LOGGER = + LoggerFactory.getLogger(ProvideDataResource.class, "[DBService]"); - private static final Logger taskLogger = LoggerFactory.getLogger( - ProvideDataResource.class, "[Task]"); + private static final Logger taskLogger = + LoggerFactory.getLogger(ProvideDataResource.class, "[Task]"); - @Autowired - private ProvideDataRepository provideDataRepository; + @Autowired private ProvideDataRepository provideDataRepository; - @Autowired - private DefaultProvideDataNotifier provideDataNotifier; + @Autowired private DefaultProvideDataNotifier provideDataNotifier; - @Autowired - private NodeConfig nodeConfig; + @Autowired private NodeConfig nodeConfig; - @POST - @Path("put") - @Produces(MediaType.APPLICATION_JSON) - public Result put(PersistenceData data) { + @POST + @Path("put") + @Produces(MediaType.APPLICATION_JSON) + public Result put(PersistenceData data) { - checkObj(data, "PersistenceData"); - checkString(data.getData()); - checkObj(data.getVersion(), "version"); + checkObj(data, "PersistenceData"); + checkString(data.getData()); + checkObj(data.getVersion(), "version"); - String dataInfoId = DataInfo.toDataInfoId(data.getDataId(), data.getInstanceId(), - data.getGroup()); + String dataInfoId = + DataInfo.toDataInfoId(data.getDataId(), data.getInstanceId(), data.getGroup()); - try { - boolean ret = provideDataRepository.put(nodeConfig.getLocalDataCenter(), dataInfoId, JsonUtils.writeValueAsString(data)); - DB_LOGGER.info("put Persistence Data {} to DB result {}!", data, ret); - } catch (Throwable e) { - DB_LOGGER.error("error put Persistence Data {} to DB!", data, e); - throw new RuntimeException("Put Persistence Data " + data + " to DB error!", e); - } - - fireDataChangeNotify(data.getVersion(), dataInfoId, DataOperator.ADD); - - Result result = new Result(); - result.setSuccess(true); - return result; + try { + boolean ret = + provideDataRepository.put( + nodeConfig.getLocalDataCenter(), dataInfoId, JsonUtils.writeValueAsString(data)); + DB_LOGGER.info("put Persistence Data {} to DB result {}!", data, ret); + } catch (Throwable e) { + DB_LOGGER.error("error put Persistence Data {} to DB!", data, e); + throw new RuntimeException("Put Persistence Data " + data + " to DB error!", e); } - @POST - @Path("remove") - @Produces(MediaType.APPLICATION_JSON) - public Result remove(PersistenceData data) { + fireDataChangeNotify(data.getVersion(), dataInfoId, DataOperator.ADD); - checkObj(data, "PersistenceData"); - checkObj(data.getVersion(), "version"); + Result result = new Result(); + result.setSuccess(true); + return result; + } - String dataInfoId = DataInfo.toDataInfoId(data.getDataId(), data.getInstanceId(), - data.getGroup()); + @POST + @Path("remove") + @Produces(MediaType.APPLICATION_JSON) + public Result remove(PersistenceData data) { - try { - boolean ret = provideDataRepository.remove(nodeConfig.getLocalDataCenter(), dataInfoId); - DB_LOGGER.info("remove Persistence Data {} from DB result {}!", data, ret); - } catch (Exception e) { - DB_LOGGER.error("error remove Persistence Data {} from DB!", data); - throw new RuntimeException("Remove Persistence Data " + data + " from DB error!"); - } + checkObj(data, "PersistenceData"); + checkObj(data.getVersion(), "version"); - fireDataChangeNotify(data.getVersion(), dataInfoId, DataOperator.REMOVE); + String dataInfoId = + DataInfo.toDataInfoId(data.getDataId(), data.getInstanceId(), data.getGroup()); - Result result = new Result(); - result.setSuccess(true); - return result; + try { + boolean ret = provideDataRepository.remove(nodeConfig.getLocalDataCenter(), dataInfoId); + DB_LOGGER.info("remove Persistence Data {} from DB result {}!", data, ret); + } catch (Exception e) { + DB_LOGGER.error("error remove Persistence Data {} from DB!", data); + throw new RuntimeException("Remove Persistence Data " + data + " from DB error!"); } - private void fireDataChangeNotify(Long version, String dataInfoId, DataOperator dataOperator) { + fireDataChangeNotify(data.getVersion(), dataInfoId, DataOperator.REMOVE); + + Result result = new Result(); + result.setSuccess(true); + return result; + } + + private void fireDataChangeNotify(Long version, String dataInfoId, DataOperator dataOperator) { - ProvideDataChangeEvent provideDataChangeEvent = new ProvideDataChangeEvent(dataInfoId, - version, dataOperator); + ProvideDataChangeEvent provideDataChangeEvent = + new ProvideDataChangeEvent(dataInfoId, version, dataOperator); - if (taskLogger.isInfoEnabled()) { - taskLogger.info("send PERSISTENCE_DATA_CHANGE_NOTIFY_TASK notifyProvideDataChange: {}", - provideDataChangeEvent); - } - provideDataNotifier.notifyProvideDataChange(provideDataChangeEvent); + if (taskLogger.isInfoEnabled()) { + taskLogger.info( + "send PERSISTENCE_DATA_CHANGE_NOTIFY_TASK notifyProvideDataChange: {}", + provideDataChangeEvent); } + provideDataNotifier.notifyProvideDataChange(provideDataChangeEvent); + } - private void checkString(String input) { - if (input == null || input.isEmpty()) { - throw new IllegalArgumentException("Error String data input:" + input); - } + private void checkString(String input) { + if (input == null || input.isEmpty()) { + throw new IllegalArgumentException("Error String data input:" + input); } + } - private void checkObj(Object input, String objName) { - if (input == null) { - throw new IllegalArgumentException("Error null Object " + objName + " data input!"); - } + private void checkObj(Object input, String objName) { + if (input == null) { + throw new IllegalArgumentException("Error null Object " + objName + " data input!"); } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/SlotSyncResource.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/SlotSyncResource.java index e837ec19a..bc636c88f 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/SlotSyncResource.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/SlotSyncResource.java @@ -23,17 +23,15 @@ import com.alipay.sofa.registry.store.api.DBResponse; import com.alipay.sofa.registry.store.api.meta.ProvideDataRepository; import com.alipay.sofa.registry.util.JsonUtils; -import org.springframework.beans.factory.annotation.Autowired; - +import java.util.HashMap; +import java.util.Map; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import java.util.HashMap; -import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: RenewSwitchResource.java, v 0.1 2018-07-25 11:40 shangyu.wh Exp $ */ @@ -41,36 +39,33 @@ @LeaderAwareRestController public class SlotSyncResource { - @Autowired - private ProvideDataRepository provideDataRepository; + @Autowired private ProvideDataRepository provideDataRepository; - @Autowired - private NodeConfig nodeConfig; + @Autowired private NodeConfig nodeConfig; - /** - * get - */ - @GET - @Path("get") - @Produces(MediaType.APPLICATION_JSON) - public Map getSlotSync() throws Exception { - Map resultMap = new HashMap<>(2); - DBResponse syncSessionIntervalSec = provideDataRepository - .get(nodeConfig.getLocalDataCenter(), ValueConstants.DATA_DATUM_SYNC_SESSION_INTERVAL_SEC); - DBResponse dataDatumExpire = provideDataRepository - .get(nodeConfig.getLocalDataCenter(), ValueConstants.DATA_SESSION_LEASE_SEC); + /** get */ + @GET + @Path("get") + @Produces(MediaType.APPLICATION_JSON) + public Map getSlotSync() throws Exception { + Map resultMap = new HashMap<>(2); + DBResponse syncSessionIntervalSec = + provideDataRepository.get( + nodeConfig.getLocalDataCenter(), ValueConstants.DATA_DATUM_SYNC_SESSION_INTERVAL_SEC); + DBResponse dataDatumExpire = + provideDataRepository.get( + nodeConfig.getLocalDataCenter(), ValueConstants.DATA_SESSION_LEASE_SEC); - resultMap.put("syncSessionIntervalSec", getEntityData(syncSessionIntervalSec)); - resultMap.put("dataDatumExpire", getEntityData(dataDatumExpire)); - return resultMap; - } + resultMap.put("syncSessionIntervalSec", getEntityData(syncSessionIntervalSec)); + resultMap.put("dataDatumExpire", getEntityData(dataDatumExpire)); + return resultMap; + } - private static String getEntityData(DBResponse resp) { - if (resp != null && resp.getEntity() != null) { - PersistenceData data = JsonUtils.read((String) resp.getEntity(), PersistenceData.class); - return data.getData(); - } - return "null"; + private static String getEntityData(DBResponse resp) { + if (resp != null && resp.getEntity() != null) { + PersistenceData data = JsonUtils.read((String) resp.getEntity(), PersistenceData.class); + return data.getData(); } - -} \ No newline at end of file + return "null"; + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/SlotTableResource.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/SlotTableResource.java index b4be8d4fb..314086fab 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/SlotTableResource.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/SlotTableResource.java @@ -27,138 +27,130 @@ import com.alipay.sofa.registry.server.meta.slot.SlotManager; import com.alipay.sofa.registry.server.meta.slot.arrange.ScheduledSlotArranger; import com.alipay.sofa.registry.server.meta.slot.tasks.BalanceTask; -import org.springframework.beans.factory.annotation.Autowired; - import javax.ws.rs.GET; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; +import org.springframework.beans.factory.annotation.Autowired; /** * @author chen.zhu - *

- * Jan 08, 2021 + *

Jan 08, 2021 */ @Path("openapi/v1/slot/table") public class SlotTableResource { - private final Logger logger = LoggerFactory.getLogger(getClass()); - - @Autowired - private SlotManager slotManager; + private final Logger logger = LoggerFactory.getLogger(getClass()); - @Autowired - private DataServerManager dataServerManager; + @Autowired private SlotManager slotManager; - @Autowired - private ScheduledSlotArranger slotArranger; + @Autowired private DataServerManager dataServerManager; - @Autowired - private MetaLeaderService metaLeaderService; + @Autowired private ScheduledSlotArranger slotArranger; - @PUT - @Path("force/refresh") - @Produces(MediaType.APPLICATION_JSON) - @LeaderAwareRestController - public GenericResponse forceRefreshSlotTable() { - logger.info("[forceRefreshSlotTable] begin"); - if (metaLeaderService.amILeader()) { - if (slotArranger.tryLock()) { - try { - BalanceTask task = new BalanceTask(slotManager, dataServerManager); - task.run(); - logger.info("[forceRefreshSlotTable] end with succeed"); - return new GenericResponse().fillSucceed(slotManager.getSlotTable()); - } finally { - slotArranger.unlock(); - } - } else { - logger.info("[forceRefreshSlotTable] end, fail to get the lock"); - return new GenericResponse() - .fillFailed("scheduled slot arrangement is running"); - } - } else { - logger.info("[forceRefreshSlotTable] end, not meta-server leader"); - return new GenericResponse().fillFailed("not the meta-server leader"); - } - } + @Autowired private MetaLeaderService metaLeaderService; - @PUT - @Path("/reconcile/stop") - @Produces(MediaType.APPLICATION_JSON) - public CommonResponse stopSlotTableReconcile() { - logger.info("[stopSlotTableReconcile] begin"); + @PUT + @Path("force/refresh") + @Produces(MediaType.APPLICATION_JSON) + @LeaderAwareRestController + public GenericResponse forceRefreshSlotTable() { + logger.info("[forceRefreshSlotTable] begin"); + if (metaLeaderService.amILeader()) { + if (slotArranger.tryLock()) { try { - slotArranger.suspend(); - logger.info("[stopSlotTableReconcile] end with succeed"); - return GenericResponse.buildSuccessResponse("succeed"); - } catch (Throwable throwable) { - logger.error("[stopSlotTableReconcile] end", throwable); - return GenericResponse.buildFailedResponse(throwable.getMessage()); + BalanceTask task = new BalanceTask(slotManager, dataServerManager); + task.run(); + logger.info("[forceRefreshSlotTable] end with succeed"); + return new GenericResponse().fillSucceed(slotManager.getSlotTable()); + } finally { + slotArranger.unlock(); } + } else { + logger.info("[forceRefreshSlotTable] end, fail to get the lock"); + return new GenericResponse().fillFailed("scheduled slot arrangement is running"); + } + } else { + logger.info("[forceRefreshSlotTable] end, not meta-server leader"); + return new GenericResponse().fillFailed("not the meta-server leader"); } + } - @PUT - @Path("/reconcile/start") - @Produces(MediaType.APPLICATION_JSON) - public CommonResponse startSlotTableReconcile() { - logger.info("[startSlotTableReconcile] begin"); - try { - slotArranger.resume(); - logger.info("[startSlotTableReconcile] end with succeed"); - return GenericResponse.buildSuccessResponse("succeed"); - } catch (Throwable throwable) { - logger.error("[startSlotTableReconcile] end", throwable); - return GenericResponse.buildFailedResponse(throwable.getMessage()); - } + @PUT + @Path("/reconcile/stop") + @Produces(MediaType.APPLICATION_JSON) + public CommonResponse stopSlotTableReconcile() { + logger.info("[stopSlotTableReconcile] begin"); + try { + slotArranger.suspend(); + logger.info("[stopSlotTableReconcile] end with succeed"); + return GenericResponse.buildSuccessResponse("succeed"); + } catch (Throwable throwable) { + logger.error("[stopSlotTableReconcile] end", throwable); + return GenericResponse.buildFailedResponse(throwable.getMessage()); } + } - @GET - @Path("/reconcile/status") - @Produces(MediaType.APPLICATION_JSON) - public CommonResponse getReconcileStatus() { - logger.info("[getReconcileStatus] begin"); - try { - boolean result = slotArranger.getLifecycleState().isStarted() - && !slotArranger.isSuspended(); - logger.info("[getReconcileStatus] end with succeed"); - if (result) { - return GenericResponse.buildSuccessResponse("running"); - } else { - return GenericResponse.buildSuccessResponse("stopped"); - } - } catch (Throwable throwable) { - logger.error("[getReconcileStatus] end", throwable); - return GenericResponse.buildFailedResponse(throwable.getMessage()); - } + @PUT + @Path("/reconcile/start") + @Produces(MediaType.APPLICATION_JSON) + public CommonResponse startSlotTableReconcile() { + logger.info("[startSlotTableReconcile] begin"); + try { + slotArranger.resume(); + logger.info("[startSlotTableReconcile] end with succeed"); + return GenericResponse.buildSuccessResponse("succeed"); + } catch (Throwable throwable) { + logger.error("[startSlotTableReconcile] end", throwable); + return GenericResponse.buildFailedResponse(throwable.getMessage()); } + } - @GET - @Path("/data/slot/status") - @Produces(MediaType.APPLICATION_JSON) - @LeaderAwareRestController - public GenericResponse getDataSlotStatuses() { - logger.info("[getDataSlotStatuses] begin"); - try { - return new GenericResponse<>().fillSucceed(dataServerManager.getDataServersStats()); - } catch (Throwable throwable) { - return new GenericResponse<>().fillFailed(throwable.getMessage()); - } finally { - logger.info("[getDataSlotStatuses] end"); - } + @GET + @Path("/reconcile/status") + @Produces(MediaType.APPLICATION_JSON) + public CommonResponse getReconcileStatus() { + logger.info("[getReconcileStatus] begin"); + try { + boolean result = slotArranger.getLifecycleState().isStarted() && !slotArranger.isSuspended(); + logger.info("[getReconcileStatus] end with succeed"); + if (result) { + return GenericResponse.buildSuccessResponse("running"); + } else { + return GenericResponse.buildSuccessResponse("stopped"); + } + } catch (Throwable throwable) { + logger.error("[getReconcileStatus] end", throwable); + return GenericResponse.buildFailedResponse(throwable.getMessage()); } + } - public SlotTableResource() { + @GET + @Path("/data/slot/status") + @Produces(MediaType.APPLICATION_JSON) + @LeaderAwareRestController + public GenericResponse getDataSlotStatuses() { + logger.info("[getDataSlotStatuses] begin"); + try { + return new GenericResponse<>().fillSucceed(dataServerManager.getDataServersStats()); + } catch (Throwable throwable) { + return new GenericResponse<>().fillFailed(throwable.getMessage()); + } finally { + logger.info("[getDataSlotStatuses] end"); } + } - public SlotTableResource(SlotManager slotManager, - DataServerManager dataServerManager, - ScheduledSlotArranger slotArranger, - MetaLeaderService metaLeaderService) { - this.slotManager = slotManager; - this.dataServerManager = dataServerManager; - this.slotArranger = slotArranger; - this.metaLeaderService = metaLeaderService; - } + public SlotTableResource() {} + + public SlotTableResource( + SlotManager slotManager, + DataServerManager dataServerManager, + ScheduledSlotArranger slotArranger, + MetaLeaderService metaLeaderService) { + this.slotManager = slotManager; + this.dataServerManager = dataServerManager; + this.slotArranger = slotArranger; + this.metaLeaderService = metaLeaderService; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/StopPushDataResource.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/StopPushDataResource.java index 37e4166ca..37c0870a5 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/StopPushDataResource.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/StopPushDataResource.java @@ -31,16 +31,14 @@ import com.alipay.sofa.registry.store.api.meta.ProvideDataRepository; import com.alipay.sofa.registry.util.JsonUtils; import com.google.common.collect.Sets; -import org.springframework.beans.factory.annotation.Autowired; - +import java.util.Set; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import java.util.Set; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: StopPushDataResource.java, v 0.1 2018-07-25 11:40 shangyu.wh Exp $ */ @@ -48,98 +46,100 @@ @LeaderAwareRestController public class StopPushDataResource { - private static final Logger DB_LOGGER = LoggerFactory.getLogger( - StopPushDataResource.class, "[DBService]"); - - private static final Logger TASK_LOGGER = LoggerFactory.getLogger( - StopPushDataResource.class, "[Task]"); - - @Autowired - private ProvideDataRepository provideDataRepository; - - @Autowired - private DefaultProvideDataNotifier provideDataNotifier; - - @Autowired - private NodeConfig nodeConfig; - - /** - * close push - */ - @GET - @Path("open") - @Produces(MediaType.APPLICATION_JSON) - public Result closePush() { - PersistenceData persistenceData = createPushDataInfo(); - persistenceData.setData("true"); - - try { - boolean ret = provideDataRepository.put(nodeConfig.getLocalDataCenter(), - ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID, JsonUtils.writeValueAsString(persistenceData)); - DB_LOGGER.info("open stop push data switch to DB result {}!", ret); - } catch (Throwable e) { - DB_LOGGER.error("error open stop push data switch to DB!", e); - throw new RuntimeException("open stop push data switch to DB error!", e); - } - - fireDataChangeNotify(persistenceData.getVersion(), - ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID, DataOperator.ADD); - - Result result = new Result(); - result.setSuccess(true); - return result; - } + private static final Logger DB_LOGGER = + LoggerFactory.getLogger(StopPushDataResource.class, "[DBService]"); - /** - * open push - */ - @GET - @Path("close") - @Produces(MediaType.APPLICATION_JSON) - public Result openPush() { - PersistenceData persistenceData = createPushDataInfo(); - persistenceData.setData("false"); - try { - boolean ret = provideDataRepository.put(nodeConfig.getLocalDataCenter(), - ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID, JsonUtils.writeValueAsString(persistenceData)); - DB_LOGGER.info("close stop push data switch to DB result {}!", ret); - } catch (Exception e) { - DB_LOGGER.error("error close stop push data switch from DB!"); - throw new RuntimeException("Close stop push data switch from DB error!"); - } - - fireDataChangeNotify(persistenceData.getVersion(), - ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID, DataOperator.UPDATE); - - Result result = new Result(); - result.setSuccess(true); - return result; - } + private static final Logger TASK_LOGGER = + LoggerFactory.getLogger(StopPushDataResource.class, "[Task]"); - private PersistenceData createPushDataInfo() { - DataInfo dataInfo = DataInfo.valueOf(ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID); - PersistenceData persistenceData = new PersistenceData(); - persistenceData.setDataId(dataInfo.getDataId()); - persistenceData.setGroup(dataInfo.getGroup()); - persistenceData.setInstanceId(dataInfo.getInstanceId()); - persistenceData.setVersion(System.currentTimeMillis()); - return persistenceData; - } + @Autowired private ProvideDataRepository provideDataRepository; + + @Autowired private DefaultProvideDataNotifier provideDataNotifier; - private void fireDataChangeNotify(Long version, String dataInfoId, DataOperator dataOperator) { + @Autowired private NodeConfig nodeConfig; + + /** close push */ + @GET + @Path("open") + @Produces(MediaType.APPLICATION_JSON) + public Result closePush() { + PersistenceData persistenceData = createPushDataInfo(); + persistenceData.setData("true"); + + try { + boolean ret = + provideDataRepository.put( + nodeConfig.getLocalDataCenter(), + ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID, + JsonUtils.writeValueAsString(persistenceData)); + DB_LOGGER.info("open stop push data switch to DB result {}!", ret); + } catch (Throwable e) { + DB_LOGGER.error("error open stop push data switch to DB!", e); + throw new RuntimeException("open stop push data switch to DB error!", e); + } - ProvideDataChangeEvent provideDataChangeEvent = new ProvideDataChangeEvent(dataInfoId, - version, dataOperator, getNodeTypes()); - if (TASK_LOGGER.isInfoEnabled()) { - TASK_LOGGER.info( - "send PERSISTENCE_DATA_CHANGE_NOTIFY_TASK notifyProvideDataChange: {}", - provideDataChangeEvent); - } - provideDataNotifier.notifyProvideDataChange(provideDataChangeEvent); + fireDataChangeNotify( + persistenceData.getVersion(), + ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID, + DataOperator.ADD); + + Result result = new Result(); + result.setSuccess(true); + return result; + } + + /** open push */ + @GET + @Path("close") + @Produces(MediaType.APPLICATION_JSON) + public Result openPush() { + PersistenceData persistenceData = createPushDataInfo(); + persistenceData.setData("false"); + try { + boolean ret = + provideDataRepository.put( + nodeConfig.getLocalDataCenter(), + ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID, + JsonUtils.writeValueAsString(persistenceData)); + DB_LOGGER.info("close stop push data switch to DB result {}!", ret); + } catch (Exception e) { + DB_LOGGER.error("error close stop push data switch from DB!"); + throw new RuntimeException("Close stop push data switch from DB error!"); } - protected Set getNodeTypes() { - return Sets.newHashSet(NodeType.SESSION); + fireDataChangeNotify( + persistenceData.getVersion(), + ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID, + DataOperator.UPDATE); + + Result result = new Result(); + result.setSuccess(true); + return result; + } + + private PersistenceData createPushDataInfo() { + DataInfo dataInfo = DataInfo.valueOf(ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID); + PersistenceData persistenceData = new PersistenceData(); + persistenceData.setDataId(dataInfo.getDataId()); + persistenceData.setGroup(dataInfo.getGroup()); + persistenceData.setInstanceId(dataInfo.getInstanceId()); + persistenceData.setVersion(System.currentTimeMillis()); + return persistenceData; + } + + private void fireDataChangeNotify(Long version, String dataInfoId, DataOperator dataOperator) { + + ProvideDataChangeEvent provideDataChangeEvent = + new ProvideDataChangeEvent(dataInfoId, version, dataOperator, getNodeTypes()); + if (TASK_LOGGER.isInfoEnabled()) { + TASK_LOGGER.info( + "send PERSISTENCE_DATA_CHANGE_NOTIFY_TASK notifyProvideDataChange: {}", + provideDataChangeEvent); } + provideDataNotifier.notifyProvideDataChange(provideDataChangeEvent); + } -} \ No newline at end of file + protected Set getNodeTypes() { + return Sets.newHashSet(NodeType.SESSION); + } +} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareFilter.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareFilter.java index 8fe716caf..051f6b66b 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareFilter.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareFilter.java @@ -20,66 +20,73 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.server.meta.MetaLeaderService; import com.alipay.sofa.registry.server.meta.bootstrap.config.MetaServerConfig; -import org.apache.commons.lang.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; - +import java.io.IOException; +import java.net.URI; import javax.annotation.Priority; -import javax.servlet.http.HttpServletRequest; import javax.ws.rs.Priorities; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerRequestFilter; -import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import javax.ws.rs.ext.Provider; -import java.io.IOException; -import java.net.URI; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; /** * @author chen.zhu - *

- * Mar 17, 2021 + *

Mar 17, 2021 */ @Provider @LeaderAwareRestController @Priority(Priorities.USER) public class LeaderAwareFilter implements ContainerRequestFilter { - private static final Logger LOGGER = LoggerFactory.getLogger(LeaderAwareFilter.class); + private static final Logger LOGGER = LoggerFactory.getLogger(LeaderAwareFilter.class); - @Autowired - private MetaLeaderService metaLeaderService; + @Autowired private MetaLeaderService metaLeaderService; - @Autowired - private MetaServerConfig metaServerConfig; + @Autowired private MetaServerConfig metaServerConfig; - @Override - public void filter(ContainerRequestContext context) throws IOException { - if (!metaLeaderService.amILeader()) { - Response response; - String leaderIp = metaLeaderService.getLeader(); - if (StringUtils.isEmpty(leaderIp)) { - response = Response.status(Response.Status.BAD_REQUEST).header("reason", "no leader found").build(); - } else { - try { - LOGGER.warn("[filter]request: [{}][{}] need to redirect to {}", - getRemortIP(context), context.getMethod(), leaderIp); - response = Response.temporaryRedirect( - new URI("http://" + leaderIp + ":" + metaServerConfig.getHttpServerPort() + "/" + context.getUriInfo().getPath())) - .build(); - } catch (Throwable e) { - LOGGER.error("[filter]", e); - response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); - } - } - context.abortWith(response); + @Override + public void filter(ContainerRequestContext context) throws IOException { + if (!metaLeaderService.amILeader()) { + Response response; + String leaderIp = metaLeaderService.getLeader(); + if (StringUtils.isEmpty(leaderIp)) { + response = + Response.status(Response.Status.BAD_REQUEST) + .header("reason", "no leader found") + .build(); + } else { + try { + LOGGER.warn( + "[filter]request: [{}][{}] need to redirect to {}", + getRemortIP(context), + context.getMethod(), + leaderIp); + response = + Response.temporaryRedirect( + new URI( + "http://" + + leaderIp + + ":" + + metaServerConfig.getHttpServerPort() + + "/" + + context.getUriInfo().getPath())) + .build(); + } catch (Throwable e) { + LOGGER.error("[filter]", e); + response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } + } + context.abortWith(response); } + } - public String getRemortIP(ContainerRequestContext context) { - String remote = context.getHeaderString("x-forwarded-for"); - if (StringUtils.isNotBlank(remote)) { - return remote; - } - return "unknown"; + public String getRemortIP(ContainerRequestContext context) { + String remote = context.getHeaderString("x-forwarded-for"); + if (StringUtils.isNotBlank(remote)) { + return remote; } + return "unknown"; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareRestController.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareRestController.java index 3462d4626..ee7e33334 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareRestController.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareRestController.java @@ -16,14 +16,13 @@ */ package com.alipay.sofa.registry.server.meta.resource.filter; -import javax.ws.rs.NameBinding; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import javax.ws.rs.NameBinding; -@NameBinding //标识名称绑定的注解 -@Target({ElementType.TYPE, ElementType.METHOD}) //表示该注解可以使用在类和方法上。 +@NameBinding // 标识名称绑定的注解 +@Target({ElementType.TYPE, ElementType.METHOD}) // 表示该注解可以使用在类和方法上。 @Retention(value = RetentionPolicy.RUNTIME) -public @interface LeaderAwareRestController { -} +public @interface LeaderAwareRestController {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/RebalanceTask.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/RebalanceTask.java index f4a5d7cad..de8f6038d 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/RebalanceTask.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/RebalanceTask.java @@ -18,8 +18,6 @@ /** * @author chen.zhu - *

- * Nov 25, 2020 + *

Nov 25, 2020 */ -public interface RebalanceTask extends Runnable { -} +public interface RebalanceTask extends Runnable {} diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotAllocator.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotAllocator.java index 0782130d7..a348094d3 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotAllocator.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotAllocator.java @@ -19,10 +19,9 @@ import com.alipay.sofa.registry.common.model.slot.SlotTable; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-11 11:31 yuzhi.lyz Exp $ */ public interface SlotAllocator { - SlotTable getSlotTable(); + SlotTable getSlotTable(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotAssigner.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotAssigner.java index 354b85104..d9a9ca98f 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotAssigner.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotAssigner.java @@ -20,11 +20,9 @@ /** * @author chen.zhu - *

- * Jan 15, 2021 + *

Jan 15, 2021 */ public interface SlotAssigner { - SlotTable assign(); - + SlotTable assign(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotBalancer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotBalancer.java index f881dd18d..ba24fa774 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotBalancer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotBalancer.java @@ -20,10 +20,9 @@ /** * @author chen.zhu - *

- * Jan 15, 2021 + *

Jan 15, 2021 */ public interface SlotBalancer { - SlotTable balance(); + SlotTable balance(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotManager.java index 240583992..0c0260458 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotManager.java @@ -22,42 +22,37 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public interface SlotManager extends SlotTableAware, Observable { - /** - * Refresh. - * - * @param slotTable - * the slot table - */ - void refresh(SlotTable slotTable); + /** + * Refresh. + * + * @param slotTable the slot table + */ + void refresh(SlotTable slotTable); - /** - * Gets get slot nums. - * - * @return the get slot nums - */ - int getSlotNums(); + /** + * Gets get slot nums. + * + * @return the get slot nums + */ + int getSlotNums(); - /** - * Gets get slot replica nums. - * - * @return the get slot replica nums - */ - int getSlotReplicaNums(); - - /** - * Gets get data node managed slot. - * - * @param dataNode - * the data node - * @param ignoreFollowers - * the ignore followers - * @return the get data node managed slot - */ - DataNodeSlot getDataNodeManagedSlot(String dataNode, boolean ignoreFollowers); + /** + * Gets get slot replica nums. + * + * @return the get slot replica nums + */ + int getSlotReplicaNums(); + /** + * Gets get data node managed slot. + * + * @param dataNode the data node + * @param ignoreFollowers the ignore followers + * @return the get data node managed slot + */ + DataNodeSlot getDataNodeManagedSlot(String dataNode, boolean ignoreFollowers); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotTableAware.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotTableAware.java index b41be2c82..19061ba08 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotTableAware.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/SlotTableAware.java @@ -21,17 +21,15 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public interface SlotTableAware { - /** - * Gets get slot table. - * - * @return the get slot table - */ - @ReadOnLeader - SlotTable getSlotTable(); - + /** + * Gets get slot table. + * + * @return the get slot table + */ + @ReadOnLeader + SlotTable getSlotTable(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/arrange/CrossDcSlotAllocator.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/arrange/CrossDcSlotAllocator.java index 543f70a58..2d5faac65 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/arrange/CrossDcSlotAllocator.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/arrange/CrossDcSlotAllocator.java @@ -33,7 +33,6 @@ import com.alipay.sofa.registry.server.meta.slot.SlotAllocator; import com.alipay.sofa.registry.server.meta.slot.SlotTableAware; import com.google.common.annotations.VisibleForTesting; - import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; @@ -45,181 +44,200 @@ /** * @author chen.zhu - *

- * Nov 20, 2020 + *

Nov 20, 2020 */ -public class CrossDcSlotAllocator extends AbstractLifecycle implements SlotAllocator, - DataCenterAware, SlotTableAware { - - private final String dcName; - - private final ScheduledExecutorService scheduled; - - private final CrossDcMetaServer metaServer; - - private volatile ScheduledFuture future; - - private final AtomicReference currentSlotTable = new AtomicReference<>(); - - private final Exchange exchange; - - private final MetaLeaderService metaLeaderService; - - private final AtomicInteger index = new AtomicInteger(0); - - private final ReadWriteLock lock = new ReentrantReadWriteLock(); - - /** - * Constructor. - * - * @param dcName the dc name - * @param scheduled the scheduled - * @param exchange the exchange - * @param metaServer the meta server - */ - public CrossDcSlotAllocator(String dcName, ScheduledExecutorService scheduled, - Exchange exchange, CrossDcMetaServer metaServer, - MetaLeaderService metaLeaderService) { - this.dcName = dcName; - this.scheduled = scheduled; - this.exchange = exchange; - this.metaServer = metaServer; - this.metaLeaderService = metaLeaderService; +public class CrossDcSlotAllocator extends AbstractLifecycle + implements SlotAllocator, DataCenterAware, SlotTableAware { + + private final String dcName; + + private final ScheduledExecutorService scheduled; + + private final CrossDcMetaServer metaServer; + + private volatile ScheduledFuture future; + + private final AtomicReference currentSlotTable = new AtomicReference<>(); + + private final Exchange exchange; + + private final MetaLeaderService metaLeaderService; + + private final AtomicInteger index = new AtomicInteger(0); + + private final ReadWriteLock lock = new ReentrantReadWriteLock(); + + /** + * Constructor. + * + * @param dcName the dc name + * @param scheduled the scheduled + * @param exchange the exchange + * @param metaServer the meta server + */ + public CrossDcSlotAllocator( + String dcName, + ScheduledExecutorService scheduled, + Exchange exchange, + CrossDcMetaServer metaServer, + MetaLeaderService metaLeaderService) { + this.dcName = dcName; + this.scheduled = scheduled; + this.exchange = exchange; + this.metaServer = metaServer; + this.metaLeaderService = metaLeaderService; + } + + /** + * Gets get slot table. + * + * @return the get slot table + */ + @Override + public SlotTable getSlotTable() { + if (!getLifecycleState().isStarted() && !getLifecycleState().isStarting()) { + throw new IllegalStateException("[RemoteDcSlotAllocator]not available not"); } - - /** - * Gets get slot table. - * - * @return the get slot table - */ - @Override - public SlotTable getSlotTable() { - if (!getLifecycleState().isStarted() && !getLifecycleState().isStarting()) { - throw new IllegalStateException("[RemoteDcSlotAllocator]not available not"); - } - return currentSlotTable.get(); - } - - /** - * Gets get dc. - * - * @return the get dc - */ - @Override - public String getDc() { - return dcName; - } - - @Override - protected void doInitialize() throws InitializeException { - super.doInitialize(); - } - - @Override - protected void doStart() throws StartException { - future = scheduled.scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { + return currentSlotTable.get(); + } + + /** + * Gets get dc. + * + * @return the get dc + */ + @Override + public String getDc() { + return dcName; + } + + @Override + protected void doInitialize() throws InitializeException { + super.doInitialize(); + } + + @Override + protected void doStart() throws StartException { + future = + scheduled.scheduleWithFixedDelay( + new Runnable() { + @Override + public void run() { if (metaLeaderService.amIStableAsLeader()) { - refreshSlotTable(0); + refreshSlotTable(0); } - } - }, getIntervalMilli(), getIntervalMilli(), TimeUnit.MILLISECONDS); + } + }, + getIntervalMilli(), + getIntervalMilli(), + TimeUnit.MILLISECONDS); + } + + @Override + protected void doStop() throws StopException { + if (future != null) { + future.cancel(true); + future = null; } - - @Override - protected void doStop() throws StopException { - if (future != null) { - future.cancel(true); - future = null; - } - } - - @Override - protected void doDispose() throws DisposeException { - super.doDispose(); - } - - /** - * Sets slot table. - * - * @param slotTable the slot table - */ - public void setSlotTable(SlotTable slotTable) { - currentSlotTable.set(slotTable); + } + + @Override + protected void doDispose() throws DisposeException { + super.doDispose(); + } + + /** + * Sets slot table. + * + * @param slotTable the slot table + */ + public void setSlotTable(SlotTable slotTable) { + currentSlotTable.set(slotTable); + } + + @VisibleForTesting + protected long getIntervalMilli() { + return 60 * 1000; + } + + @VisibleForTesting + protected void refreshSlotTable(int retryTimes) { + if (retryTimes > 3) { + logger.warn("[refreshSlotTable]try timeout, more than {} times", 3); + return; } - - @VisibleForTesting - protected long getIntervalMilli() { - return 60 * 1000; - } - - @VisibleForTesting - protected void refreshSlotTable(int retryTimes) { - if (retryTimes > 3) { - logger.warn("[refreshSlotTable]try timeout, more than {} times", 3); - return; - } - final long currentEpoch = currentSlotTable.get() == null ? -1 : currentSlotTable.get() - .getEpoch(); - GetSlotTableRequest request = new GetSlotTableRequest(currentEpoch, null, false); - MetaNode metaNode = getRemoteMetaServer(); - exchange.getClient(Exchange.META_SERVER_TYPE).sendCallback(metaNode.getNodeUrl(), request, + final long currentEpoch = + currentSlotTable.get() == null ? -1 : currentSlotTable.get().getEpoch(); + GetSlotTableRequest request = new GetSlotTableRequest(currentEpoch, null, false); + MetaNode metaNode = getRemoteMetaServer(); + exchange + .getClient(Exchange.META_SERVER_TYPE) + .sendCallback( + metaNode.getNodeUrl(), + request, new CallbackHandler() { - @Override - @SuppressWarnings("unchecked") - public void onCallback(Channel channel, Object message) { - if (!(message instanceof SlotTable)) { - logger.error("[refreshSlotTable]wanted SlotTable, but receive: [{}]{}", - message.getClass(), message); - return; - } - SlotTable slotTable = (SlotTable) message; - lock.writeLock().lock(); - try { - if (currentEpoch < slotTable.getEpoch()) { - if (logger.isWarnEnabled()) { - logger - .warn( - "[refreshSlotTable] remote slot table changed, \n prev: {} \n change to: {}", - currentSlotTable.get(), slotTable); - } - currentSlotTable.set(slotTable); - } - } finally { - lock.writeLock().unlock(); - } + @Override + @SuppressWarnings("unchecked") + public void onCallback(Channel channel, Object message) { + if (!(message instanceof SlotTable)) { + logger.error( + "[refreshSlotTable]wanted SlotTable, but receive: [{}]{}", + message.getClass(), + message); + return; } - - @Override - public void onException(Channel channel, Throwable exception) { - if (logger.isErrorEnabled()) { - logger - .error( - "[refreshSlotTable][{}]Bolt Request Failure, remote: {}, will try other meta-server", - getDc(), channel == null ? "unknown" : channel.getRemoteAddress() - .getHostName(), exception); + SlotTable slotTable = (SlotTable) message; + lock.writeLock().lock(); + try { + if (currentEpoch < slotTable.getEpoch()) { + if (logger.isWarnEnabled()) { + logger.warn( + "[refreshSlotTable] remote slot table changed, \n prev: {} \n change to: {}", + currentSlotTable.get(), + slotTable); } - index.set(index.incrementAndGet() % metaServer.getClusterMembers().size()); - // if failure, try again with another meta server. - // good luck with that. :) - refreshSlotTable(retryTimes + 1); + currentSlotTable.set(slotTable); + } + } finally { + lock.writeLock().unlock(); } - - @Override - public Executor getExecutor() { - return scheduled; + } + + @Override + public void onException(Channel channel, Throwable exception) { + if (logger.isErrorEnabled()) { + logger.error( + "[refreshSlotTable][{}]Bolt Request Failure, remote: {}, will try other meta-server", + getDc(), + channel == null ? "unknown" : channel.getRemoteAddress().getHostName(), + exception); } - }, 5000); - } - - private MetaNode getRemoteMetaServer() { - return metaServer.getClusterMembers().get(index.get()); - } - - @Override - public String toString() { - return "CrossDcSlotAllocator{" + "dcName='" + dcName + '\'' + ", metaServer=" + metaServer - + '}'; - } + index.set(index.incrementAndGet() % metaServer.getClusterMembers().size()); + // if failure, try again with another meta server. + // good luck with that. :) + refreshSlotTable(retryTimes + 1); + } + + @Override + public Executor getExecutor() { + return scheduled; + } + }, + 5000); + } + + private MetaNode getRemoteMetaServer() { + return metaServer.getClusterMembers().get(index.get()); + } + + @Override + public String toString() { + return "CrossDcSlotAllocator{" + + "dcName='" + + dcName + + '\'' + + ", metaServer=" + + metaServer + + '}'; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/arrange/ScheduledSlotArranger.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/arrange/ScheduledSlotArranger.java index 38048c18e..4225002bc 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/arrange/ScheduledSlotArranger.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/arrange/ScheduledSlotArranger.java @@ -45,235 +45,243 @@ import com.alipay.sofa.registry.util.JsonUtils; import com.alipay.sofa.registry.util.WakeUpLoopRunnable; import com.google.common.annotations.VisibleForTesting; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import java.util.Collection; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * @author chen.zhu - *

- * Jan 14, 2021 + *

Jan 14, 2021 */ @Component -public class ScheduledSlotArranger extends AbstractLifecycleObservable implements - DataManagerObserver, - Suspendable { - - private DefaultDataServerManager dataServerManager; - - private SlotManager slotManager; - - private SlotTableMonitor slotTableMonitor; - - private MetaLeaderService metaLeaderService; - - private final Arranger arranger = new Arranger(); - - private final Lock lock = new ReentrantLock(); - - public ScheduledSlotArranger() { - } - - @Autowired - public ScheduledSlotArranger(DefaultDataServerManager dataServerManager, - SlotManager slotManager, - SlotTableMonitor slotTableMonitor, - MetaLeaderService metaLeaderService) { - this.dataServerManager = dataServerManager; - this.slotManager = slotManager; - this.slotTableMonitor = slotTableMonitor; - this.metaLeaderService = metaLeaderService; - } - - @PostConstruct - public void postConstruct() throws Exception { - LifecycleHelper.initializeIfPossible(this); - LifecycleHelper.startIfPossible(this); - } - - @PreDestroy - public void preDestroy() throws Exception { - LifecycleHelper.stopIfPossible(this); - LifecycleHelper.disposeIfPossible(this); - } - - @Override - protected void doInitialize() throws InitializeException { - super.doInitialize(); - dataServerManager.addObserver(this); - Thread executor = ConcurrentUtils.createDaemonThread(getClass().getSimpleName(), arranger); - executor.start(); +public class ScheduledSlotArranger extends AbstractLifecycleObservable + implements DataManagerObserver, Suspendable { + + private DefaultDataServerManager dataServerManager; + + private SlotManager slotManager; + + private SlotTableMonitor slotTableMonitor; + + private MetaLeaderService metaLeaderService; + + private final Arranger arranger = new Arranger(); + + private final Lock lock = new ReentrantLock(); + + public ScheduledSlotArranger() {} + + @Autowired + public ScheduledSlotArranger( + DefaultDataServerManager dataServerManager, + SlotManager slotManager, + SlotTableMonitor slotTableMonitor, + MetaLeaderService metaLeaderService) { + this.dataServerManager = dataServerManager; + this.slotManager = slotManager; + this.slotTableMonitor = slotTableMonitor; + this.metaLeaderService = metaLeaderService; + } + + @PostConstruct + public void postConstruct() throws Exception { + LifecycleHelper.initializeIfPossible(this); + LifecycleHelper.startIfPossible(this); + } + + @PreDestroy + public void preDestroy() throws Exception { + LifecycleHelper.stopIfPossible(this); + LifecycleHelper.disposeIfPossible(this); + } + + @Override + protected void doInitialize() throws InitializeException { + super.doInitialize(); + dataServerManager.addObserver(this); + Thread executor = ConcurrentUtils.createDaemonThread(getClass().getSimpleName(), arranger); + executor.start(); + } + + @Override + protected void doDispose() throws DisposeException { + arranger.close(); + dataServerManager.removeObserver(this); + super.doDispose(); + } + + @Override + public void update(Observable source, Object message) { + logger.warn("[update] receive from [{}], message: {}", source, message); + if (message instanceof NodeRemoved) { + arranger.wakeup(); } - - @Override - protected void doDispose() throws DisposeException { - arranger.close(); - dataServerManager.removeObserver(this); - super.doDispose(); + if (message instanceof NodeAdded) { + arranger.wakeup(); } - - @Override - public void update(Observable source, Object message) { - logger.warn("[update] receive from [{}], message: {}", source, message); - if (message instanceof NodeRemoved) { - arranger.wakeup(); - } - if (message instanceof NodeAdded) { - arranger.wakeup(); - } + } + + public boolean tryLock() { + return lock.tryLock(); + } + + public void unlock() { + lock.unlock(); + } + + private SlotTableBuilder createSlotTableBuilder( + SlotTable slotTable, List currentDataNodeIps, int slotNum, int replicas) { + NodeComparator comparator = new NodeComparator(slotTable.getDataServers(), currentDataNodeIps); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, slotNum, replicas); + slotTableBuilder.init(currentDataNodeIps); + + comparator.getRemoved().forEach(slotTableBuilder::removeDataServerSlots); + return slotTableBuilder; + } + + protected void assignSlots( + SlotTableBuilder slotTableBuilder, Collection currentDataServers) { + SlotTable slotTable = createSlotAssigner(slotTableBuilder, currentDataServers).assign(); + refreshSlotTable(slotTable); + } + + protected SlotAssigner createSlotAssigner( + SlotTableBuilder slotTableBuilder, Collection currentDataServers) { + return new DefaultSlotAssigner(slotTableBuilder, currentDataServers); + } + + protected void balanceSlots( + SlotTableBuilder slotTableBuilder, Collection currentDataServers) { + SlotTable slotTable = createSlotBalancer(slotTableBuilder, currentDataServers).balance(); + refreshSlotTable(slotTable); + } + + private void refreshSlotTable(SlotTable slotTable) { + if (slotTable == null) { + logger.info("[refreshSlotTable] slot-table not change"); + return; } - - public boolean tryLock() { - return lock.tryLock(); + if (!SlotTableUtils.isValidSlotTable(slotTable)) { + throw new SofaRegistrySlotTableException( + "slot table is not valid: \n" + JsonUtils.writeValueAsString(slotTable)); } - - public void unlock() { - lock.unlock(); + if (slotTable.getEpoch() > slotManager.getSlotTable().getEpoch()) { + slotManager.refresh(slotTable); + } else { + logger.warn( + "[refreshSlotTable] slot-table epoch not change: {}", + JsonUtils.writeValueAsString(slotTable)); } + } - private SlotTableBuilder createSlotTableBuilder(SlotTable slotTable, List currentDataNodeIps, - int slotNum, int replicas) { - NodeComparator comparator = new NodeComparator(slotTable.getDataServers(), currentDataNodeIps); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, slotNum, replicas); - slotTableBuilder.init(currentDataNodeIps); - - comparator.getRemoved().forEach(slotTableBuilder::removeDataServerSlots); - return slotTableBuilder; - } + protected SlotBalancer createSlotBalancer( + SlotTableBuilder slotTableBuilder, Collection currentDataServers) { + return new DefaultSlotBalancer(slotTableBuilder, currentDataServers); + } - protected void assignSlots(SlotTableBuilder slotTableBuilder, - Collection currentDataServers) { - SlotTable slotTable = createSlotAssigner(slotTableBuilder, currentDataServers).assign(); - refreshSlotTable(slotTable); - } + @Override + public void suspend() { + arranger.suspend(); + } - protected SlotAssigner createSlotAssigner(SlotTableBuilder slotTableBuilder, - Collection currentDataServers) { - return new DefaultSlotAssigner(slotTableBuilder, currentDataServers); - } + @Override + public void resume() { + arranger.resume(); + } - protected void balanceSlots(SlotTableBuilder slotTableBuilder, - Collection currentDataServers) { - SlotTable slotTable = createSlotBalancer(slotTableBuilder, currentDataServers).balance(); - refreshSlotTable(slotTable); - } + @Override + public boolean isSuspended() { + return arranger.isSuspended(); + } - private void refreshSlotTable(SlotTable slotTable) { - if (slotTable == null) { - logger.info("[refreshSlotTable] slot-table not change"); - return; - } - if (!SlotTableUtils.isValidSlotTable(slotTable)) { - throw new SofaRegistrySlotTableException("slot table is not valid: \n" - + JsonUtils.writeValueAsString(slotTable)); - } - if (slotTable.getEpoch() > slotManager.getSlotTable().getEpoch()) { - slotManager.refresh(slotTable); - } else { - logger.warn("[refreshSlotTable] slot-table epoch not change: {}", - JsonUtils.writeValueAsString(slotTable)); - } - } + private final class Arranger extends WakeUpLoopRunnable { - protected SlotBalancer createSlotBalancer(SlotTableBuilder slotTableBuilder, - Collection currentDataServers) { - return new DefaultSlotBalancer(slotTableBuilder, currentDataServers); - } + private final int waitingMillis = Integer.getInteger("slot.arrange.interval.milli", 1000); @Override - public void suspend() { - arranger.suspend(); + public int getWaitingMillis() { + return waitingMillis; } @Override - public void resume() { - arranger.resume(); + public void runUnthrowable() { + try { + arrangeSync(); + } catch (Throwable e) { + logger.error("failed to arrange", e); + } } + } - @Override - public boolean isSuspended() { - return arranger.isSuspended(); + private boolean tryArrangeSlots(List dataNodes) { + if (!tryLock()) { + logger.warn("[tryArrangeSlots] tryLock failed"); + return false; } - - private final class Arranger extends WakeUpLoopRunnable { - - private final int waitingMillis = Integer.getInteger("slot.arrange.interval.milli", 1000); - - @Override - public int getWaitingMillis() { - return waitingMillis; - } - - @Override - public void runUnthrowable() { - try { - arrangeSync(); - } catch (Throwable e) { - logger.error("failed to arrange", e); - } - } + try { + List currentDataNodeIps = NodeUtils.transferNodeToIpList(dataNodes); + logger.info( + "[tryArrangeSlots][begin]arrange slot with DataNode, size={}, {}", + currentDataNodeIps.size(), + currentDataNodeIps); + final SlotTable curSlotTable = slotManager.getSlotTable(); + SlotTableBuilder tableBuilder = + createSlotTableBuilder( + curSlotTable, + currentDataNodeIps, + slotManager.getSlotNums(), + slotManager.getSlotReplicaNums()); + + if (tableBuilder.hasNoAssignedSlots()) { + logger.info("[re-assign][begin] assign slots to data-server"); + assignSlots(tableBuilder, currentDataNodeIps); + logger.info("[re-assign][end]"); + + } else if (slotTableMonitor.isStableTableStable()) { + logger.info("[balance][begin] balance slots to data-server"); + balanceSlots(tableBuilder, currentDataNodeIps); + logger.info("[balance][end]"); + + } else { + logger.info("[tryArrangeSlots][end] no arrangement"); + } + } finally { + unlock(); } - - private boolean tryArrangeSlots(List dataNodes) { - if (!tryLock()) { - logger.warn("[tryArrangeSlots] tryLock failed"); - return false; - } - try { - List currentDataNodeIps = NodeUtils.transferNodeToIpList(dataNodes); - logger.info("[tryArrangeSlots][begin]arrange slot with DataNode, size={}, {}", - currentDataNodeIps.size(), currentDataNodeIps); - final SlotTable curSlotTable = slotManager.getSlotTable(); - SlotTableBuilder tableBuilder = createSlotTableBuilder(curSlotTable, - currentDataNodeIps, slotManager.getSlotNums(), slotManager.getSlotReplicaNums()); - - if (tableBuilder.hasNoAssignedSlots()) { - logger.info("[re-assign][begin] assign slots to data-server"); - assignSlots(tableBuilder, currentDataNodeIps); - logger.info("[re-assign][end]"); - - } else if (slotTableMonitor.isStableTableStable()) { - logger.info("[balance][begin] balance slots to data-server"); - balanceSlots(tableBuilder, currentDataNodeIps); - logger.info("[balance][end]"); - - } else { - logger.info("[tryArrangeSlots][end] no arrangement"); - } - } finally { - unlock(); - } + return true; + } + + public void arrangeAsync() { + arranger.wakeup(); + } + + @VisibleForTesting + public boolean arrangeSync() { + if (metaLeaderService.amIStableAsLeader()) { + + // the start arrange with the dataNodes snapshot + final List dataNodes = + dataServerManager.getDataServerMetaInfo().getClusterMembers(); + if (dataNodes.isEmpty()) { + logger.warn("[Arranger] empty data server list, continue"); return true; + } else { + Metrics.SlotArrange.begin(); + boolean result = tryArrangeSlots(dataNodes); + Metrics.SlotArrange.end(); + return result; + } + } else { + logger.info( + "not leader for arrange, leader:{}, isWarmup:{}", + metaLeaderService.getLeader(), + metaLeaderService.isWarmup()); + return false; } - - public void arrangeAsync() { - arranger.wakeup(); - } - - @VisibleForTesting - public boolean arrangeSync() { - if (metaLeaderService.amIStableAsLeader()) { - - // the start arrange with the dataNodes snapshot - final List dataNodes = dataServerManager.getDataServerMetaInfo().getClusterMembers(); - if (dataNodes.isEmpty()) { - logger.warn("[Arranger] empty data server list, continue"); - return true; - } else { - Metrics.SlotArrange.begin(); - boolean result = tryArrangeSlots(dataNodes); - Metrics.SlotArrange.end(); - return result; - } - } else { - logger.info("not leader for arrange, leader:{}, isWarmup:{}", metaLeaderService.getLeader(), metaLeaderService.isWarmup()); - return false; - } - } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/assigner/DefaultSlotAssigner.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/assigner/DefaultSlotAssigner.java index f62b652f1..5310e766d 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/assigner/DefaultSlotAssigner.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/assigner/DefaultSlotAssigner.java @@ -31,7 +31,6 @@ import com.alipay.sofa.registry.server.meta.slot.util.selector.Selectors; import com.google.common.collect.Lists; import com.google.common.collect.Sets; - import java.util.Collection; import java.util.Collections; import java.util.List; @@ -39,172 +38,168 @@ /** * @author chen.zhu - *

- * Jan 15, 2021 + *

Jan 15, 2021 */ public class DefaultSlotAssigner implements SlotAssigner { - private static final Logger logger = LoggerFactory.getLogger(DefaultSlotAssigner.class); - - private final Set currentDataServers; + private static final Logger logger = LoggerFactory.getLogger(DefaultSlotAssigner.class); - protected final SlotTableBuilder slotTableBuilder; - private final MigrateSlotGroup migrateSlotGroup; + private final Set currentDataServers; - public DefaultSlotAssigner(SlotTableBuilder slotTableBuilder, - Collection currentDataServers) { - this.slotTableBuilder = slotTableBuilder; - this.currentDataServers = Collections.unmodifiableSet(Sets.newTreeSet(currentDataServers)); - this.migrateSlotGroup = slotTableBuilder.getNoAssignedSlots(); - } + protected final SlotTableBuilder slotTableBuilder; + private final MigrateSlotGroup migrateSlotGroup; - @Override - public SlotTable assign() { - if (migrateSlotGroup.isEmpty() || currentDataServers.isEmpty()) { - throw new SofaRegistryRuntimeException( - "no pending slot or available dataServers for reassignment"); - } - logger.info("[assign][assignLeaderSlots] begin, migrate={}", migrateSlotGroup); - if (tryAssignLeaderSlots()) { - logger.info("[assign][after assignLeaderSlots] end -- leader changed"); - slotTableBuilder.incrEpoch(); - } else { - logger.info("[assign][after assignLeaderSlots] end -- no changes"); - } + public DefaultSlotAssigner( + SlotTableBuilder slotTableBuilder, Collection currentDataServers) { + this.slotTableBuilder = slotTableBuilder; + this.currentDataServers = Collections.unmodifiableSet(Sets.newTreeSet(currentDataServers)); + this.migrateSlotGroup = slotTableBuilder.getNoAssignedSlots(); + } - logger.info("[assign][assignLeaderSlots] begin"); - if (assignFollowerSlots()) { - logger.info("[assign][after assignLeaderSlots] end -- follower changed"); - slotTableBuilder.incrEpoch(); - } else { - logger.info("[assign][assignLeaderSlots] end -- no changes"); - } - return slotTableBuilder.build(); + @Override + public SlotTable assign() { + if (migrateSlotGroup.isEmpty() || currentDataServers.isEmpty()) { + throw new SofaRegistryRuntimeException( + "no pending slot or available dataServers for reassignment"); } - - private boolean tryAssignLeaderSlots() { - /** our strategy(assign leader) is to swap follower to leader when follower is enabled - * if no followers, we select a new data-server to assign, that's simple and low prioritized - * so, leaders are resolved in an order that who has least followers first - * (as we wish to satisfy these nodes first) - * leaders with no follower is lowest priority, as whatever we did, it will pick up a candidate - * that is not its follower - */ - List leaders = migrateSlotGroup.getLeadersByScore(new FewerFollowerFirstStrategy( - slotTableBuilder)); - if (leaders.isEmpty()) { - logger.info("[assignLeaderSlots] no slot leader needs assign, quit"); - return false; - } - for (int slotId : leaders) { - List currentDataNodes = Lists.newArrayList(currentDataServers); - String nextLeader = Selectors.slotLeaderSelector(slotTableBuilder, slotId).select( - currentDataNodes); - logger.info("[assignLeaderSlots]assign slot[{}] leader as [{}], dataServers={}", - slotId, nextLeader, currentDataServers.size()); - boolean nextLeaderWasFollower = isNextLeaderFollowerOfSlot(slotId, nextLeader); - slotTableBuilder.replaceLeader(slotId, nextLeader); - Metrics.SlotAssign.onSlotLeaderAssign(nextLeader, slotId); - if (nextLeaderWasFollower) { - migrateSlotGroup.addFollower(slotId); - } - } - return true; + logger.info("[assign][assignLeaderSlots] begin, migrate={}", migrateSlotGroup); + if (tryAssignLeaderSlots()) { + logger.info("[assign][after assignLeaderSlots] end -- leader changed"); + slotTableBuilder.incrEpoch(); + } else { + logger.info("[assign][after assignLeaderSlots] end -- no changes"); } - private boolean isNextLeaderFollowerOfSlot(int slotId, String nextLeader) { - return slotTableBuilder.getOrCreate(slotId).containsFollower(nextLeader); - } - - private boolean assignFollowerSlots() { - List followerToAssigns = migrateSlotGroup - .getFollowersByScore(new FollowerEmergentScoreJury()); - if (followerToAssigns.isEmpty()) { - logger.info("[assignFollowerSlots] no follower slots need to assign, quit"); - return false; - } - int assignCount = 0; - for (MigrateSlotGroup.FollowerToAssign followerToAssign : followerToAssigns) { - final int slotId = followerToAssign.getSlotId(); - for (int i = 0; i < followerToAssign.getAssigneeNums(); i++) { - List candidates = Lists.newArrayList(currentDataServers); - candidates.sort(Comparators.leastFollowersFirst(slotTableBuilder)); - boolean assigned = false; - for (String candidate : candidates) { - DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(candidate); - if (dataNodeSlot.containsFollower(slotId) - || dataNodeSlot.containsLeader(slotId)) { - continue; - } - slotTableBuilder.addFollower(slotId, candidate); - Metrics.SlotAssign.onSlotFollowerAssign(candidate, slotId); - assigned = true; - assignCount++; - logger - .info( - "[assignFollowerSlots]assign slot[{}] add follower as [{}], dataServers={}", - slotId, candidate, currentDataServers.size()); - break; - } - if (!assigned) { - logger - .warn( - "[assignFollowerSlots]assign slot[{}] no dataServer to assign, dataServers={}", - slotId, currentDataServers.size()); - } - } - } - return assignCount != 0; + logger.info("[assign][assignLeaderSlots] begin"); + if (assignFollowerSlots()) { + logger.info("[assign][after assignLeaderSlots] end -- follower changed"); + slotTableBuilder.incrEpoch(); + } else { + logger.info("[assign][assignLeaderSlots] end -- no changes"); } + return slotTableBuilder.build(); + } + private boolean tryAssignLeaderSlots() { /** - * ================================== Getters ====================================== * + * our strategy(assign leader) is to swap follower to leader when follower is enabled if no + * followers, we select a new data-server to assign, that's simple and low prioritized so, + * leaders are resolved in an order that who has least followers first (as we wish to satisfy + * these nodes first) leaders with no follower is lowest priority, as whatever we did, it will + * pick up a candidate that is not its follower */ - - public Set getCurrentDataServers() { - return currentDataServers; + List leaders = + migrateSlotGroup.getLeadersByScore(new FewerFollowerFirstStrategy(slotTableBuilder)); + if (leaders.isEmpty()) { + logger.info("[assignLeaderSlots] no slot leader needs assign, quit"); + return false; } - - public SlotTableBuilder getSlotTableBuilder() { - return slotTableBuilder; + for (int slotId : leaders) { + List currentDataNodes = Lists.newArrayList(currentDataServers); + String nextLeader = + Selectors.slotLeaderSelector(slotTableBuilder, slotId).select(currentDataNodes); + logger.info( + "[assignLeaderSlots]assign slot[{}] leader as [{}], dataServers={}", + slotId, + nextLeader, + currentDataServers.size()); + boolean nextLeaderWasFollower = isNextLeaderFollowerOfSlot(slotId, nextLeader); + slotTableBuilder.replaceLeader(slotId, nextLeader); + Metrics.SlotAssign.onSlotLeaderAssign(nextLeader, slotId); + if (nextLeaderWasFollower) { + migrateSlotGroup.addFollower(slotId); + } } - - public MigrateSlotGroup getMigrateSlotGroup() { - return migrateSlotGroup; + return true; + } + + private boolean isNextLeaderFollowerOfSlot(int slotId, String nextLeader) { + return slotTableBuilder.getOrCreate(slotId).containsFollower(nextLeader); + } + + private boolean assignFollowerSlots() { + List followerToAssigns = + migrateSlotGroup.getFollowersByScore(new FollowerEmergentScoreJury()); + if (followerToAssigns.isEmpty()) { + logger.info("[assignFollowerSlots] no follower slots need to assign, quit"); + return false; + } + int assignCount = 0; + for (MigrateSlotGroup.FollowerToAssign followerToAssign : followerToAssigns) { + final int slotId = followerToAssign.getSlotId(); + for (int i = 0; i < followerToAssign.getAssigneeNums(); i++) { + List candidates = Lists.newArrayList(currentDataServers); + candidates.sort(Comparators.leastFollowersFirst(slotTableBuilder)); + boolean assigned = false; + for (String candidate : candidates) { + DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(candidate); + if (dataNodeSlot.containsFollower(slotId) || dataNodeSlot.containsLeader(slotId)) { + continue; + } + slotTableBuilder.addFollower(slotId, candidate); + Metrics.SlotAssign.onSlotFollowerAssign(candidate, slotId); + assigned = true; + assignCount++; + logger.info( + "[assignFollowerSlots]assign slot[{}] add follower as [{}], dataServers={}", + slotId, + candidate, + currentDataServers.size()); + break; + } + if (!assigned) { + logger.warn( + "[assignFollowerSlots]assign slot[{}] no dataServer to assign, dataServers={}", + slotId, + currentDataServers.size()); + } + } } + return assignCount != 0; + } - /** - * ================================== Classes ====================================== * - */ + /** ================================== Getters ====================================== * */ + public Set getCurrentDataServers() { + return currentDataServers; + } - static class FewerFollowerFirstStrategy implements ScoreStrategy { + public SlotTableBuilder getSlotTableBuilder() { + return slotTableBuilder; + } - final SlotTableBuilder slotTableBuilder; + public MigrateSlotGroup getMigrateSlotGroup() { + return migrateSlotGroup; + } - FewerFollowerFirstStrategy(SlotTableBuilder slotTableBuilder) { - this.slotTableBuilder = slotTableBuilder; - } + /** ================================== Classes ====================================== * */ + static class FewerFollowerFirstStrategy implements ScoreStrategy { - @Override - public int score(Integer slotId) { - SlotBuilder slotBuilder = slotTableBuilder.getOrCreate(slotId); - int followerNums = slotBuilder.getFollowers().size(); - // if no followers, we leave it the least priority - // because our strategy(assign leader) is to swap follower to leader when follower is enabled - // if no followers, we select a new data-server to assign, that's simple and low prioritized - if (followerNums == 0) { - return Integer.MAX_VALUE; - } - return SortType.ASC.getScore(slotBuilder.getFollowers().size()); - } + final SlotTableBuilder slotTableBuilder; + + FewerFollowerFirstStrategy(SlotTableBuilder slotTableBuilder) { + this.slotTableBuilder = slotTableBuilder; } - public static class FollowerEmergentScoreJury implements - ScoreStrategy { + @Override + public int score(Integer slotId) { + SlotBuilder slotBuilder = slotTableBuilder.getOrCreate(slotId); + int followerNums = slotBuilder.getFollowers().size(); + // if no followers, we leave it the least priority + // because our strategy(assign leader) is to swap follower to leader when follower is enabled + // if no followers, we select a new data-server to assign, that's simple and low prioritized + if (followerNums == 0) { + return Integer.MAX_VALUE; + } + return SortType.ASC.getScore(slotBuilder.getFollowers().size()); + } + } - @Override - public int score(MigrateSlotGroup.FollowerToAssign followerToAssign) { - return SortType.DES.getScore(followerToAssign.getAssigneeNums()); - } + public static class FollowerEmergentScoreJury + implements ScoreStrategy { + + @Override + public int score(MigrateSlotGroup.FollowerToAssign followerToAssign) { + return SortType.DES.getScore(followerToAssign.getAssigneeNums()); } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/assigner/ScoreStrategy.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/assigner/ScoreStrategy.java index 98c2cdca4..f117ab92d 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/assigner/ScoreStrategy.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/assigner/ScoreStrategy.java @@ -18,11 +18,9 @@ /** * @author chen.zhu - *

- * Jan 15, 2021 + *

Jan 15, 2021 */ public interface ScoreStrategy { - int score(T t); - + int score(T t); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/BalancePolicy.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/BalancePolicy.java index c52f3799c..c597a7699 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/BalancePolicy.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/BalancePolicy.java @@ -18,52 +18,47 @@ /** * @author chen.zhu - *

- * Jan 20, 2021 + *

Jan 20, 2021 */ public interface BalancePolicy { - /** - * Gets get low water mark slot leader nums. low watermark means the - * threshold we could endure with, that once the slot leader numbers on a - * data-server is under the low water mark, we need to rebalance the - * slot-table - * - * @param average - * the average - * @return the get low water mark slot leader nums - */ - int getLowWaterMarkSlotLeaderNums(int average); + /** + * Gets get low water mark slot leader nums. low watermark means the threshold we could endure + * with, that once the slot leader numbers on a data-server is under the low water mark, we need + * to rebalance the slot-table + * + * @param average the average + * @return the get low water mark slot leader nums + */ + int getLowWaterMarkSlotLeaderNums(int average); - int getHighWaterMarkSlotLeaderNums(int average); + int getHighWaterMarkSlotLeaderNums(int average); - /** - * Gets get low water mark of follower slot nums. low watermark means the - * threshold we could endure with, that once the follower slot numbers on a - * data-server is under the low water mark, we need to rebalance the - * slot-table - * - * @param average - * the average - * @return the get low water mark of slot follower nums - */ - int getLowWaterMarkSlotFollowerNums(int average); + /** + * Gets get low water mark of follower slot nums. low watermark means the threshold we could + * endure with, that once the follower slot numbers on a data-server is under the low water mark, + * we need to rebalance the slot-table + * + * @param average the average + * @return the get low water mark of slot follower nums + */ + int getLowWaterMarkSlotFollowerNums(int average); - int getHighWaterMarkSlotFollowerNums(int average); + int getHighWaterMarkSlotFollowerNums(int average); - /** - * Gets get max move leader slots. max move means the maximum number of - * slots' leader we are good to migrate per balance time - * - * @return the get max move leader slots - */ - int getMaxMoveLeaderSlots(); + /** + * Gets get max move leader slots. max move means the maximum number of slots' leader we are good + * to migrate per balance time + * + * @return the get max move leader slots + */ + int getMaxMoveLeaderSlots(); - /** - * Gets get max move follower slots. max move means the maximum number of - * slots' followers we are good to migrate per balance time - * - * @return the get max move follower slots - */ - int getMaxMoveFollowerSlots(); + /** + * Gets get max move follower slots. max move means the maximum number of slots' followers we are + * good to migrate per balance time + * + * @return the get max move follower slots + */ + int getMaxMoveFollowerSlots(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/DefaultSlotBalancer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/DefaultSlotBalancer.java index 9f6b0e95a..bb3dc8d31 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/DefaultSlotBalancer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/DefaultSlotBalancer.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.slot.balance; +import static com.alipay.sofa.registry.server.meta.slot.balance.LeaderOnlyBalancer.TRIGGER_THESHOLD; + import com.alipay.sofa.registry.common.model.Triple; import com.alipay.sofa.registry.common.model.Tuple; import com.alipay.sofa.registry.common.model.slot.DataNodeSlot; @@ -31,558 +33,602 @@ import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; -import org.apache.commons.lang.StringUtils; - import java.util.*; - -import static com.alipay.sofa.registry.server.meta.slot.balance.LeaderOnlyBalancer.TRIGGER_THESHOLD; +import org.apache.commons.lang.StringUtils; /** * @author chen.zhu - *

- * Jan 15, 2021 + *

Jan 15, 2021 */ public class DefaultSlotBalancer implements SlotBalancer { - private static final Logger LOGGER = LoggerFactory - .getLogger(DefaultSlotBalancer.class); - - private final Set currentDataServers; - - protected final SlotTableBuilder slotTableBuilder; - private final BalancePolicy balancePolicy = new NaiveBalancePolicy(); - private final int slotNum; - private final int slotReplicas; - - public DefaultSlotBalancer(SlotTableBuilder slotTableBuilder, - Collection currentDataServers) { - this.currentDataServers = Collections.unmodifiableSet(Sets.newTreeSet(currentDataServers)); - this.slotTableBuilder = slotTableBuilder; - this.slotNum = slotTableBuilder.getSlotNums(); - this.slotReplicas = slotTableBuilder.getSlotReplicas(); + private static final Logger LOGGER = LoggerFactory.getLogger(DefaultSlotBalancer.class); + + private final Set currentDataServers; + + protected final SlotTableBuilder slotTableBuilder; + private final BalancePolicy balancePolicy = new NaiveBalancePolicy(); + private final int slotNum; + private final int slotReplicas; + + public DefaultSlotBalancer( + SlotTableBuilder slotTableBuilder, Collection currentDataServers) { + this.currentDataServers = Collections.unmodifiableSet(Sets.newTreeSet(currentDataServers)); + this.slotTableBuilder = slotTableBuilder; + this.slotNum = slotTableBuilder.getSlotNums(); + this.slotReplicas = slotTableBuilder.getSlotReplicas(); + } + + @Override + public SlotTable balance() { + if (currentDataServers.isEmpty()) { + LOGGER.error("[no available data-servers] quit"); + throw new SofaRegistryRuntimeException( + "no available data-servers for slot-table reassignment"); } - - @Override - public SlotTable balance() { - if (currentDataServers.isEmpty()) { - LOGGER.error("[no available data-servers] quit"); - throw new SofaRegistryRuntimeException( - "no available data-servers for slot-table reassignment"); - } - if (slotReplicas < TRIGGER_THESHOLD) { - LOGGER.warn("[balance] slot replica[{}] means no followers, balance leader only", - slotTableBuilder.getSlotReplicas()); - return new LeaderOnlyBalancer(slotTableBuilder, currentDataServers).balance(); - } - if (balanceLeaderSlots()) { - LOGGER.info("[balanceLeaderSlots] end"); - slotTableBuilder.incrEpoch(); - return slotTableBuilder.build(); - } - if (balanceHighFollowerSlots()) { - LOGGER.info("[balanceHighFollowerSlots] end"); - slotTableBuilder.incrEpoch(); - return slotTableBuilder.build(); - } - if (balanceLowFollowerSlots()) { - LOGGER.info("[balanceLowFollowerSlots] end"); - slotTableBuilder.incrEpoch(); - return slotTableBuilder.build(); - } - // check the low watermark leader, the follower has balanced - // just upgrade the followers in low data server - if (balanceLowLeaders()) { - LOGGER.info("[balanceLowLeaders] end"); - slotTableBuilder.incrEpoch(); - return slotTableBuilder.build(); - } - LOGGER.info("[balance] do nothing"); - return null; + if (slotReplicas < TRIGGER_THESHOLD) { + LOGGER.warn( + "[balance] slot replica[{}] means no followers, balance leader only", + slotTableBuilder.getSlotReplicas()); + return new LeaderOnlyBalancer(slotTableBuilder, currentDataServers).balance(); } - - private boolean balanceLeaderSlots() { - // ceil avg, find the high water mark - final int leaderCeilAvg = MathUtils.divideCeil(slotNum, currentDataServers.size()); - if (upgradeHighLeaders(leaderCeilAvg)) { - return true; - } - if (migrateHighLeaders(leaderCeilAvg)) { - return true; - } - return false; + if (balanceLeaderSlots()) { + LOGGER.info("[balanceLeaderSlots] end"); + slotTableBuilder.incrEpoch(); + return slotTableBuilder.build(); } - - private boolean upgradeHighLeaders(int ceilAvg) { - // smoothly, find the dataNode which owners the target slot's follower - // and upgrade the follower to leader - final int maxMove = balancePolicy.getMaxMoveLeaderSlots(); - final int threshold = balancePolicy.getHighWaterMarkSlotLeaderNums(ceilAvg); - int balanced = 0; - Set notSatisfies = Sets.newHashSet(); - - while (balanced < maxMove) { - // 1. find the dataNode which has leaders more than high water mark - // and sorted by leaders.num desc - final List highDataServers = findDataServersLeaderHighWaterMark(threshold); - if (highDataServers.isEmpty()) { - break; - } - // could not found any follower to upgrade - if (notSatisfies.containsAll(highDataServers)) { - LOGGER.info("[upgradeHighLeaders] could not found followers to upgrade for {}", - highDataServers); - break; - } - // 2. find the dataNode which could own a new leader - // exclude the high - final Set excludes = Sets.newHashSet(highDataServers); - // exclude the dataNode which could not add any leader - excludes.addAll(findDataServersLeaderHighWaterMark(threshold - 1)); - for (String highDataServer : highDataServers) { - if (notSatisfies.contains(highDataServer)) { - continue; - } - Tuple selected = selectFollower4LeaderUpgradeOut(highDataServer, - excludes); - if (selected == null) { - notSatisfies.add(highDataServer); - continue; - } - final int slotId = selected.o2; - final String newLeaderDataServer = selected.o1; - slotTableBuilder.replaceLeader(slotId, newLeaderDataServer); - LOGGER.info("[upgradeHighLeaders] slotId={} leader balance from {} to {}", slotId, - highDataServer, newLeaderDataServer); - Metrics.SlotBalance.onLeaderUpgrade(highDataServer, newLeaderDataServer, - slotId); - balanced++; - break; - } - } - return balanced != 0; + if (balanceHighFollowerSlots()) { + LOGGER.info("[balanceHighFollowerSlots] end"); + slotTableBuilder.incrEpoch(); + return slotTableBuilder.build(); } - - private boolean migrateHighLeaders(int ceilAvg) { - // could not found the follower to upgrade, migrate follower first - final int maxMove = balancePolicy.getMaxMoveFollowerSlots(); - final int threshold = balancePolicy.getHighWaterMarkSlotLeaderNums(ceilAvg); - - // 1. find the dataNode which has leaders more than high water mark - // and sorted by leaders.num desc - final List highDataServers = findDataServersLeaderHighWaterMark(threshold); - if (highDataServers.isEmpty()) { - return false; - } - // 2. find the dataNode which could own a new leader - // exclude the high - final Set excludes = Sets.newHashSet(highDataServers); - // exclude the dataNode which could not add any leader - excludes.addAll(findDataServersLeaderHighWaterMark(threshold - 1)); - int balanced = 0; - final Set newFollowerDataServers = Sets.newHashSet(); - // only balance highDataServer once at one round, avoid the follower moves multi times - for (String highDataServer : highDataServers) { - Triple selected = selectFollower4LeaderMigrate(highDataServer, - excludes, newFollowerDataServers); - if (selected == null) { - LOGGER.warn( - "[migrateHighLeaders] could not find dataServer to migrate follower for {}", - highDataServer); - continue; - } - final String oldFollower = selected.getFirst(); - final int slotId = selected.getMiddle(); - final String newFollower = selected.getLast(); - slotTableBuilder.removeFollower(slotId, oldFollower); - slotTableBuilder.addFollower(slotId, newFollower); - newFollowerDataServers.add(newFollower); - LOGGER.info("[migrateHighLeaders] slotId={}, follower balance from {} to {}", slotId, - oldFollower, newFollower); - Metrics.SlotBalance.onLeaderMigrate(oldFollower, newFollower, slotId); - - balanced++; - if (balanced >= maxMove) { - break; - } - } - return balanced != 0; + if (balanceLowFollowerSlots()) { + LOGGER.info("[balanceLowFollowerSlots] end"); + slotTableBuilder.incrEpoch(); + return slotTableBuilder.build(); } - - private boolean balanceLowLeaders() { - final int leaderFloorAvg = Math.floorDiv(slotNum, currentDataServers.size()); - final int maxMove = balancePolicy.getMaxMoveLeaderSlots(); - final int threshold = balancePolicy.getLowWaterMarkSlotLeaderNums(leaderFloorAvg); - int balanced = 0; - Set notSatisfies = Sets.newHashSet(); - - while (balanced < maxMove) { - // 1. find the dataNode which has leaders less than low water mark - // and sorted by leaders.num asc - final List lowDataServers = findDataServersLeaderLowWaterMark(threshold); - if (lowDataServers.isEmpty()) { - break; - } - // could not found any follower to upgrade - if (notSatisfies.containsAll(lowDataServers)) { - LOGGER.info("[upgradeLowLeaders] could not found followers to upgrade for {}", - lowDataServers); - break; - } - // 2. find the dataNode which could not remove a leader - // exclude the low - final Set excludes = Sets.newHashSet(lowDataServers); - // exclude the dataNode which could not remove any leader - excludes.addAll(findDataServersLeaderLowWaterMark(threshold + 1)); - for (String lowDataServer : lowDataServers) { - if (notSatisfies.contains(lowDataServer)) { - continue; - } - Tuple selected = selectFollower4LeaderUpgradeIn(lowDataServer, - excludes); - if (selected == null) { - notSatisfies.add(lowDataServer); - continue; - } - final int slotId = selected.o2; - final String oldLeaderDataServer = selected.o1; - final String replaceLeader = slotTableBuilder.replaceLeader(slotId, lowDataServer); - if (!StringUtils.equals(oldLeaderDataServer, replaceLeader)) { - LOGGER - .error( - "[upgradeLowLeaders] conflict leader, slotId={} leader balance from {}/{} to {}", - slotId, oldLeaderDataServer, replaceLeader, lowDataServer); - throw new SofaRegistryRuntimeException(String.format( - "upgradeLowLeaders, conflict leader=%d of %s and %s", slotId, - oldLeaderDataServer, replaceLeader)); - } - Metrics.SlotBalance.onLowLeaderReplace(oldLeaderDataServer, - replaceLeader, slotId); - LOGGER.info("[upgradeLowLeaders] slotId={} leader balance from {} to {}", slotId, - oldLeaderDataServer, lowDataServer); - balanced++; - break; - } - } - return balanced != 0; + // check the low watermark leader, the follower has balanced + // just upgrade the followers in low data server + if (balanceLowLeaders()) { + LOGGER.info("[balanceLowLeaders] end"); + slotTableBuilder.incrEpoch(); + return slotTableBuilder.build(); } - - private Triple selectFollower4LeaderMigrate(String leaderDataServer, Set excludes, - Set newFollowerDataServers) { - final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(leaderDataServer); - Set leaderSlots = dataNodeSlot.getLeaders(); - Map> dataServersWithFollowers = Maps.newHashMap(); - for (int slot : leaderSlots) { - List followerDataServers = slotTableBuilder.getDataServersOwnsFollower(slot); - for (String followerDataServer : followerDataServers) { - if (newFollowerDataServers.contains(followerDataServer)) { - // the followerDataServer contains move in follower, could not be move out candidates - continue; - } - List followerSlots = dataServersWithFollowers.computeIfAbsent(followerDataServer, - k -> Lists.newArrayList()); - followerSlots.add(slot); - } + LOGGER.info("[balance] do nothing"); + return null; + } + + private boolean balanceLeaderSlots() { + // ceil avg, find the high water mark + final int leaderCeilAvg = MathUtils.divideCeil(slotNum, currentDataServers.size()); + if (upgradeHighLeaders(leaderCeilAvg)) { + return true; + } + if (migrateHighLeaders(leaderCeilAvg)) { + return true; + } + return false; + } + + private boolean upgradeHighLeaders(int ceilAvg) { + // smoothly, find the dataNode which owners the target slot's follower + // and upgrade the follower to leader + final int maxMove = balancePolicy.getMaxMoveLeaderSlots(); + final int threshold = balancePolicy.getHighWaterMarkSlotLeaderNums(ceilAvg); + int balanced = 0; + Set notSatisfies = Sets.newHashSet(); + + while (balanced < maxMove) { + // 1. find the dataNode which has leaders more than high water mark + // and sorted by leaders.num desc + final List highDataServers = findDataServersLeaderHighWaterMark(threshold); + if (highDataServers.isEmpty()) { + break; + } + // could not found any follower to upgrade + if (notSatisfies.containsAll(highDataServers)) { + LOGGER.info( + "[upgradeHighLeaders] could not found followers to upgrade for {}", highDataServers); + break; + } + // 2. find the dataNode which could own a new leader + // exclude the high + final Set excludes = Sets.newHashSet(highDataServers); + // exclude the dataNode which could not add any leader + excludes.addAll(findDataServersLeaderHighWaterMark(threshold - 1)); + for (String highDataServer : highDataServers) { + if (notSatisfies.contains(highDataServer)) { + continue; } - LOGGER.info("[selectFollower4LeaderMigrate] {} owns leader slots={}, slotIds={}, migrate candidates {}, newFollowers={}", - leaderDataServer, leaderSlots.size(), leaderSlots, dataServersWithFollowers, newFollowerDataServers); - // sort the dataServer by follower.num desc - List migrateDataServers = Lists.newArrayList(dataServersWithFollowers.keySet()); - migrateDataServers.sort(Comparators.mostFollowersFirst(slotTableBuilder)); - for (String migrateDataServer : migrateDataServers) { - final List selectedFollowers = dataServersWithFollowers.get(migrateDataServer); - for (Integer selectedFollower : selectedFollowers) { - // chose the dataServer which own least leaders - List candidates = getCandidateDataServers(excludes, - Comparators.leastLeadersFirst(slotTableBuilder), currentDataServers); - for (String candidate : candidates) { - if (candidate.equals(migrateDataServer)) { - // the same, skip - continue; - } - DataNodeSlot candidateDataNodeSlot = slotTableBuilder.getDataNodeSlot(candidate); - if (candidateDataNodeSlot.containsFollower(selectedFollower)) { - LOGGER.error("[selectFollower4LeaderMigrate] slotId={}, follower conflict with migrate from {} to {}", - selectedFollower, migrateDataServer, candidateDataNodeSlot); - continue; - } - return Triple.from(migrateDataServer, selectedFollower, candidate); - } - } - + Tuple selected = selectFollower4LeaderUpgradeOut(highDataServer, excludes); + if (selected == null) { + notSatisfies.add(highDataServer); + continue; } - return null; + final int slotId = selected.o2; + final String newLeaderDataServer = selected.o1; + slotTableBuilder.replaceLeader(slotId, newLeaderDataServer); + LOGGER.info( + "[upgradeHighLeaders] slotId={} leader balance from {} to {}", + slotId, + highDataServer, + newLeaderDataServer); + Metrics.SlotBalance.onLeaderUpgrade(highDataServer, newLeaderDataServer, slotId); + balanced++; + break; + } } - - private Tuple selectFollower4LeaderUpgradeOut(String leaderDataServer, Set excludes) { - final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(leaderDataServer); - Set leaderSlots = dataNodeSlot.getLeaders(); - Map> dataServers2Followers = Maps.newHashMap(); - for (int slot : leaderSlots) { - List followerDataServers = slotTableBuilder.getDataServersOwnsFollower(slot); - followerDataServers = getCandidateDataServers(excludes, null, followerDataServers); - for (String followerDataServer : followerDataServers) { - List followerSlots = dataServers2Followers.computeIfAbsent(followerDataServer, - k -> Lists.newArrayList()); - followerSlots.add(slot); - } + return balanced != 0; + } + + private boolean migrateHighLeaders(int ceilAvg) { + // could not found the follower to upgrade, migrate follower first + final int maxMove = balancePolicy.getMaxMoveFollowerSlots(); + final int threshold = balancePolicy.getHighWaterMarkSlotLeaderNums(ceilAvg); + + // 1. find the dataNode which has leaders more than high water mark + // and sorted by leaders.num desc + final List highDataServers = findDataServersLeaderHighWaterMark(threshold); + if (highDataServers.isEmpty()) { + return false; + } + // 2. find the dataNode which could own a new leader + // exclude the high + final Set excludes = Sets.newHashSet(highDataServers); + // exclude the dataNode which could not add any leader + excludes.addAll(findDataServersLeaderHighWaterMark(threshold - 1)); + int balanced = 0; + final Set newFollowerDataServers = Sets.newHashSet(); + // only balance highDataServer once at one round, avoid the follower moves multi times + for (String highDataServer : highDataServers) { + Triple selected = + selectFollower4LeaderMigrate(highDataServer, excludes, newFollowerDataServers); + if (selected == null) { + LOGGER.warn( + "[migrateHighLeaders] could not find dataServer to migrate follower for {}", + highDataServer); + continue; + } + final String oldFollower = selected.getFirst(); + final int slotId = selected.getMiddle(); + final String newFollower = selected.getLast(); + slotTableBuilder.removeFollower(slotId, oldFollower); + slotTableBuilder.addFollower(slotId, newFollower); + newFollowerDataServers.add(newFollower); + LOGGER.info( + "[migrateHighLeaders] slotId={}, follower balance from {} to {}", + slotId, + oldFollower, + newFollower); + Metrics.SlotBalance.onLeaderMigrate(oldFollower, newFollower, slotId); + + balanced++; + if (balanced >= maxMove) { + break; + } + } + return balanced != 0; + } + + private boolean balanceLowLeaders() { + final int leaderFloorAvg = Math.floorDiv(slotNum, currentDataServers.size()); + final int maxMove = balancePolicy.getMaxMoveLeaderSlots(); + final int threshold = balancePolicy.getLowWaterMarkSlotLeaderNums(leaderFloorAvg); + int balanced = 0; + Set notSatisfies = Sets.newHashSet(); + + while (balanced < maxMove) { + // 1. find the dataNode which has leaders less than low water mark + // and sorted by leaders.num asc + final List lowDataServers = findDataServersLeaderLowWaterMark(threshold); + if (lowDataServers.isEmpty()) { + break; + } + // could not found any follower to upgrade + if (notSatisfies.containsAll(lowDataServers)) { + LOGGER.info( + "[upgradeLowLeaders] could not found followers to upgrade for {}", lowDataServers); + break; + } + // 2. find the dataNode which could not remove a leader + // exclude the low + final Set excludes = Sets.newHashSet(lowDataServers); + // exclude the dataNode which could not remove any leader + excludes.addAll(findDataServersLeaderLowWaterMark(threshold + 1)); + for (String lowDataServer : lowDataServers) { + if (notSatisfies.contains(lowDataServer)) { + continue; } - if (dataServers2Followers.isEmpty()) { - LOGGER.info("[LeaderUpgradeOut] {} owns leader slots={}, no dataServers could be upgrade, slotId={}", - leaderDataServer, leaderSlots.size(), leaderSlots); - return null; - } else { - LOGGER.info("[LeaderUpgradeOut] {} owns leader slots={}, slotIds={}, upgrade candidates {}", - leaderDataServer, leaderSlots.size(), leaderSlots, dataServers2Followers); + Tuple selected = selectFollower4LeaderUpgradeIn(lowDataServer, excludes); + if (selected == null) { + notSatisfies.add(lowDataServer); + continue; } - // sort the dataServer by leaders.num asc - List dataServers = Lists.newArrayList(dataServers2Followers.keySet()); - dataServers.sort(Comparators.leastLeadersFirst(slotTableBuilder)); - final String selectedDataServer = dataServers.get(0); - List followers = dataServers2Followers.get(selectedDataServer); - return Tuple.of(selectedDataServer, followers.get(0)); + final int slotId = selected.o2; + final String oldLeaderDataServer = selected.o1; + final String replaceLeader = slotTableBuilder.replaceLeader(slotId, lowDataServer); + if (!StringUtils.equals(oldLeaderDataServer, replaceLeader)) { + LOGGER.error( + "[upgradeLowLeaders] conflict leader, slotId={} leader balance from {}/{} to {}", + slotId, + oldLeaderDataServer, + replaceLeader, + lowDataServer); + throw new SofaRegistryRuntimeException( + String.format( + "upgradeLowLeaders, conflict leader=%d of %s and %s", + slotId, oldLeaderDataServer, replaceLeader)); + } + Metrics.SlotBalance.onLowLeaderReplace(oldLeaderDataServer, replaceLeader, slotId); + LOGGER.info( + "[upgradeLowLeaders] slotId={} leader balance from {} to {}", + slotId, + oldLeaderDataServer, + lowDataServer); + balanced++; + break; + } } - - private Tuple selectFollower4LeaderUpgradeIn(String followerDataServer, Set excludes) { - final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(followerDataServer); - Set followerSlots = dataNodeSlot.getFollowers(); - Map> dataServers2Leaders = Maps.newHashMap(); - for (int slot : followerSlots) { - final String leaderDataServers = slotTableBuilder.getDataServersOwnsLeader(slot); - if (StringUtils.isBlank(leaderDataServers)) { - // no leader, should not happen - LOGGER.error("[LeaderUpgradeIn] no leader for slotId={} in {}", slot, followerDataServer); - continue; - } - if (excludes.contains(leaderDataServers)) { - final DataNodeSlot leaderDataNodeSlot = slotTableBuilder.getDataNodeSlot(leaderDataServers); - LOGGER.info("[LeaderUpgradeIn] {} not owns enough leader to downgrade, leaderSize={}, leaders={}", - leaderDataServers, leaderDataNodeSlot.getLeaders().size(), leaderDataNodeSlot.getLeaders()); - continue; - } - - List leaders = dataServers2Leaders.computeIfAbsent(leaderDataServers, k -> Lists.newArrayList()); - leaders.add(slot); + return balanced != 0; + } + + private Triple selectFollower4LeaderMigrate( + String leaderDataServer, Set excludes, Set newFollowerDataServers) { + final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(leaderDataServer); + Set leaderSlots = dataNodeSlot.getLeaders(); + Map> dataServersWithFollowers = Maps.newHashMap(); + for (int slot : leaderSlots) { + List followerDataServers = slotTableBuilder.getDataServersOwnsFollower(slot); + for (String followerDataServer : followerDataServers) { + if (newFollowerDataServers.contains(followerDataServer)) { + // the followerDataServer contains move in follower, could not be move out candidates + continue; } - if (dataServers2Leaders.isEmpty()) { - LOGGER.info("[LeaderUpgradeIn] {} owns followerSize={}, no dataServers could be downgrade, slotId={}", - followerDataServer, followerSlots.size(), followerSlots); - return null; - } else { - LOGGER.info("[LeaderUpgradeIn] {} owns followerSize={}, slotIds={}, downgrade candidates {}", - followerDataServer, followerSlots.size(), followerSlots, dataServers2Leaders); + List followerSlots = + dataServersWithFollowers.computeIfAbsent(followerDataServer, k -> Lists.newArrayList()); + followerSlots.add(slot); + } + } + LOGGER.info( + "[selectFollower4LeaderMigrate] {} owns leader slots={}, slotIds={}, migrate candidates {}, newFollowers={}", + leaderDataServer, + leaderSlots.size(), + leaderSlots, + dataServersWithFollowers, + newFollowerDataServers); + // sort the dataServer by follower.num desc + List migrateDataServers = Lists.newArrayList(dataServersWithFollowers.keySet()); + migrateDataServers.sort(Comparators.mostFollowersFirst(slotTableBuilder)); + for (String migrateDataServer : migrateDataServers) { + final List selectedFollowers = dataServersWithFollowers.get(migrateDataServer); + for (Integer selectedFollower : selectedFollowers) { + // chose the dataServer which own least leaders + List candidates = + getCandidateDataServers( + excludes, Comparators.leastLeadersFirst(slotTableBuilder), currentDataServers); + for (String candidate : candidates) { + if (candidate.equals(migrateDataServer)) { + // the same, skip + continue; + } + DataNodeSlot candidateDataNodeSlot = slotTableBuilder.getDataNodeSlot(candidate); + if (candidateDataNodeSlot.containsFollower(selectedFollower)) { + LOGGER.error( + "[selectFollower4LeaderMigrate] slotId={}, follower conflict with migrate from {} to {}", + selectedFollower, + migrateDataServer, + candidateDataNodeSlot); + continue; + } + return Triple.from(migrateDataServer, selectedFollower, candidate); } - // sort the dataServer by leaders.num asc - List dataServers = Lists.newArrayList(dataServers2Leaders.keySet()); - dataServers.sort(Comparators.mostLeadersFirst(slotTableBuilder)); - final String selectedDataServer = dataServers.get(0); - List leaders = dataServers2Leaders.get(selectedDataServer); - return Tuple.of(selectedDataServer, leaders.get(0)); + } } - - private List findDataServersLeaderHighWaterMark(int threshold) { - List dataNodeSlots = slotTableBuilder.getDataNodeSlotsLeaderBeyond(threshold); - List dataServers = DataNodeSlot.collectDataNodes(dataNodeSlots); - dataServers.sort(Comparators.mostLeadersFirst(slotTableBuilder)); - LOGGER.info("[LeaderHighWaterMark] threshold={}, dataServers={}", threshold, dataServers); - return dataServers; + return null; + } + + private Tuple selectFollower4LeaderUpgradeOut( + String leaderDataServer, Set excludes) { + final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(leaderDataServer); + Set leaderSlots = dataNodeSlot.getLeaders(); + Map> dataServers2Followers = Maps.newHashMap(); + for (int slot : leaderSlots) { + List followerDataServers = slotTableBuilder.getDataServersOwnsFollower(slot); + followerDataServers = getCandidateDataServers(excludes, null, followerDataServers); + for (String followerDataServer : followerDataServers) { + List followerSlots = + dataServers2Followers.computeIfAbsent(followerDataServer, k -> Lists.newArrayList()); + followerSlots.add(slot); + } } - - private List findDataServersLeaderLowWaterMark(int threshold) { - List dataNodeSlots = slotTableBuilder.getDataNodeSlotsLeaderBelow(threshold); - List dataServers = DataNodeSlot.collectDataNodes(dataNodeSlots); - dataServers.sort(Comparators.leastLeadersFirst(slotTableBuilder)); - LOGGER.info("[LeaderLowWaterMark] threshold={}, dataServers={}", threshold, dataServers); - return dataServers; + if (dataServers2Followers.isEmpty()) { + LOGGER.info( + "[LeaderUpgradeOut] {} owns leader slots={}, no dataServers could be upgrade, slotId={}", + leaderDataServer, + leaderSlots.size(), + leaderSlots); + return null; + } else { + LOGGER.info( + "[LeaderUpgradeOut] {} owns leader slots={}, slotIds={}, upgrade candidates {}", + leaderDataServer, + leaderSlots.size(), + leaderSlots, + dataServers2Followers); } - - private List findDataServersFollowerHighWaterMark(int threshold) { - List dataNodeSlots = slotTableBuilder - .getDataNodeSlotsFollowerBeyond(threshold); - List dataServers = DataNodeSlot.collectDataNodes(dataNodeSlots); - dataServers.sort(Comparators.mostFollowersFirst(slotTableBuilder)); - LOGGER.info("[FollowerHighWaterMark] threshold={}, dataServers={}", threshold, dataServers); - return dataServers; + // sort the dataServer by leaders.num asc + List dataServers = Lists.newArrayList(dataServers2Followers.keySet()); + dataServers.sort(Comparators.leastLeadersFirst(slotTableBuilder)); + final String selectedDataServer = dataServers.get(0); + List followers = dataServers2Followers.get(selectedDataServer); + return Tuple.of(selectedDataServer, followers.get(0)); + } + + private Tuple selectFollower4LeaderUpgradeIn( + String followerDataServer, Set excludes) { + final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(followerDataServer); + Set followerSlots = dataNodeSlot.getFollowers(); + Map> dataServers2Leaders = Maps.newHashMap(); + for (int slot : followerSlots) { + final String leaderDataServers = slotTableBuilder.getDataServersOwnsLeader(slot); + if (StringUtils.isBlank(leaderDataServers)) { + // no leader, should not happen + LOGGER.error("[LeaderUpgradeIn] no leader for slotId={} in {}", slot, followerDataServer); + continue; + } + if (excludes.contains(leaderDataServers)) { + final DataNodeSlot leaderDataNodeSlot = slotTableBuilder.getDataNodeSlot(leaderDataServers); + LOGGER.info( + "[LeaderUpgradeIn] {} not owns enough leader to downgrade, leaderSize={}, leaders={}", + leaderDataServers, + leaderDataNodeSlot.getLeaders().size(), + leaderDataNodeSlot.getLeaders()); + continue; + } + + List leaders = + dataServers2Leaders.computeIfAbsent(leaderDataServers, k -> Lists.newArrayList()); + leaders.add(slot); } - - private List findDataServersFollowerLowWaterMark(int threshold) { - List dataNodeSlots = slotTableBuilder - .getDataNodeSlotsFollowerBelow(threshold); - List dataServers = DataNodeSlot.collectDataNodes(dataNodeSlots); - dataServers.sort(Comparators.leastFollowersFirst(slotTableBuilder)); - LOGGER.info("[FollowerLowWaterMark] threshold={}, dataServers={}", threshold, dataServers); - return dataServers; + if (dataServers2Leaders.isEmpty()) { + LOGGER.info( + "[LeaderUpgradeIn] {} owns followerSize={}, no dataServers could be downgrade, slotId={}", + followerDataServer, + followerSlots.size(), + followerSlots); + return null; + } else { + LOGGER.info( + "[LeaderUpgradeIn] {} owns followerSize={}, slotIds={}, downgrade candidates {}", + followerDataServer, + followerSlots.size(), + followerSlots, + dataServers2Leaders); } - - private boolean balanceHighFollowerSlots() { - final int followerCeilAvg = MathUtils.divideCeil(slotNum * (slotReplicas - 1), - currentDataServers.size()); - final int maxMove = balancePolicy.getMaxMoveFollowerSlots(); - final int threshold = balancePolicy.getHighWaterMarkSlotFollowerNums(followerCeilAvg); - int balanced = 0, prevBalanced = -1; - while (balanced < maxMove) { - final List highDataServers = findDataServersFollowerHighWaterMark(threshold); - if (highDataServers.isEmpty()) { - break; - } - - Set excludes = Sets.newHashSet(highDataServers); - excludes.addAll(findDataServersFollowerHighWaterMark(threshold - 1)); - - prevBalanced = balanced; - for (String highDataServer : highDataServers) { - Tuple selected = selectFollower4BalanceOut(highDataServer, - excludes); - if (selected == null) { - LOGGER.warn( - "[balanceHighFollowerSlots] could not find follower slot to balance: {}", - highDataServer); - continue; - } - final int followerSlot = selected.o2; - final String newFollowerDataServer = selected.o1; - slotTableBuilder.removeFollower(followerSlot, highDataServer); - slotTableBuilder.addFollower(followerSlot, newFollowerDataServer); - LOGGER.info("[balanceHighFollowerSlots] balance follower slotId={} from {} to {}", - followerSlot, highDataServer, newFollowerDataServer); - Metrics.SlotBalance.onHighFollowerMigrate(highDataServer, - newFollowerDataServer, followerSlot); - balanced++; - break; - } - /** - * avoid for infinity loop - * once the "prev-balanced == balanced", it means that we can't find any suitable candidate for migrate - * stop before we case an infinity loop - * */ - if (prevBalanced == balanced) { - LOGGER - .warn("[balanceHighFollowerSlots][prevBlanced == balanced]no more balance available"); - break; - } + // sort the dataServer by leaders.num asc + List dataServers = Lists.newArrayList(dataServers2Leaders.keySet()); + dataServers.sort(Comparators.mostLeadersFirst(slotTableBuilder)); + final String selectedDataServer = dataServers.get(0); + List leaders = dataServers2Leaders.get(selectedDataServer); + return Tuple.of(selectedDataServer, leaders.get(0)); + } + + private List findDataServersLeaderHighWaterMark(int threshold) { + List dataNodeSlots = slotTableBuilder.getDataNodeSlotsLeaderBeyond(threshold); + List dataServers = DataNodeSlot.collectDataNodes(dataNodeSlots); + dataServers.sort(Comparators.mostLeadersFirst(slotTableBuilder)); + LOGGER.info("[LeaderHighWaterMark] threshold={}, dataServers={}", threshold, dataServers); + return dataServers; + } + + private List findDataServersLeaderLowWaterMark(int threshold) { + List dataNodeSlots = slotTableBuilder.getDataNodeSlotsLeaderBelow(threshold); + List dataServers = DataNodeSlot.collectDataNodes(dataNodeSlots); + dataServers.sort(Comparators.leastLeadersFirst(slotTableBuilder)); + LOGGER.info("[LeaderLowWaterMark] threshold={}, dataServers={}", threshold, dataServers); + return dataServers; + } + + private List findDataServersFollowerHighWaterMark(int threshold) { + List dataNodeSlots = slotTableBuilder.getDataNodeSlotsFollowerBeyond(threshold); + List dataServers = DataNodeSlot.collectDataNodes(dataNodeSlots); + dataServers.sort(Comparators.mostFollowersFirst(slotTableBuilder)); + LOGGER.info("[FollowerHighWaterMark] threshold={}, dataServers={}", threshold, dataServers); + return dataServers; + } + + private List findDataServersFollowerLowWaterMark(int threshold) { + List dataNodeSlots = slotTableBuilder.getDataNodeSlotsFollowerBelow(threshold); + List dataServers = DataNodeSlot.collectDataNodes(dataNodeSlots); + dataServers.sort(Comparators.leastFollowersFirst(slotTableBuilder)); + LOGGER.info("[FollowerLowWaterMark] threshold={}, dataServers={}", threshold, dataServers); + return dataServers; + } + + private boolean balanceHighFollowerSlots() { + final int followerCeilAvg = + MathUtils.divideCeil(slotNum * (slotReplicas - 1), currentDataServers.size()); + final int maxMove = balancePolicy.getMaxMoveFollowerSlots(); + final int threshold = balancePolicy.getHighWaterMarkSlotFollowerNums(followerCeilAvg); + int balanced = 0, prevBalanced = -1; + while (balanced < maxMove) { + final List highDataServers = findDataServersFollowerHighWaterMark(threshold); + if (highDataServers.isEmpty()) { + break; + } + + Set excludes = Sets.newHashSet(highDataServers); + excludes.addAll(findDataServersFollowerHighWaterMark(threshold - 1)); + + prevBalanced = balanced; + for (String highDataServer : highDataServers) { + Tuple selected = selectFollower4BalanceOut(highDataServer, excludes); + if (selected == null) { + LOGGER.warn( + "[balanceHighFollowerSlots] could not find follower slot to balance: {}", + highDataServer); + continue; } - return balanced != 0; + final int followerSlot = selected.o2; + final String newFollowerDataServer = selected.o1; + slotTableBuilder.removeFollower(followerSlot, highDataServer); + slotTableBuilder.addFollower(followerSlot, newFollowerDataServer); + LOGGER.info( + "[balanceHighFollowerSlots] balance follower slotId={} from {} to {}", + followerSlot, + highDataServer, + newFollowerDataServer); + Metrics.SlotBalance.onHighFollowerMigrate( + highDataServer, newFollowerDataServer, followerSlot); + balanced++; + break; + } + /** + * avoid for infinity loop once the "prev-balanced == balanced", it means that we can't find + * any suitable candidate for migrate stop before we case an infinity loop + */ + if (prevBalanced == balanced) { + LOGGER.warn("[balanceHighFollowerSlots][prevBlanced == balanced]no more balance available"); + break; + } } - - private boolean balanceLowFollowerSlots() { - final int followerFloorAvg = Math.floorDiv(slotNum * (slotReplicas - 1), - currentDataServers.size()); - final int maxMove = balancePolicy.getMaxMoveFollowerSlots(); - final int threshold = balancePolicy.getLowWaterMarkSlotFollowerNums(followerFloorAvg); - int balanced = 0, prevBalanced = -1; - while (balanced < maxMove) { - final List lowDataServers = findDataServersFollowerLowWaterMark(threshold); - if (lowDataServers.isEmpty()) { - break; - } - - Set excludes = Sets.newHashSet(lowDataServers); - excludes.addAll(findDataServersFollowerLowWaterMark(threshold + 1)); - - prevBalanced = balanced; - for (String lowDataServer : lowDataServers) { - Tuple selected = selectFollower4BalanceIn(lowDataServer, excludes); - if (selected == null) { - LOGGER.warn( - "[balanceLowFollowerSlots] could not find follower slot to balance: {}", - lowDataServer); - continue; - } - final int followerSlot = selected.o2; - final String oldFollowerDataServer = selected.o1; - slotTableBuilder.removeFollower(followerSlot, oldFollowerDataServer); - slotTableBuilder.addFollower(followerSlot, lowDataServer); - LOGGER.info("[balanceLowFollowerSlots] balance follower slotId={} from {} to {}", - followerSlot, oldFollowerDataServer, lowDataServer); - Metrics.SlotBalance.onLowFollowerMigrate(oldFollowerDataServer, - lowDataServer, followerSlot); - balanced++; - break; - } - if (prevBalanced == balanced) { - LOGGER - .warn("[balanceLowFollowerSlots][prevBlanced == balanced]no more balance available"); - break; - } + return balanced != 0; + } + + private boolean balanceLowFollowerSlots() { + final int followerFloorAvg = + Math.floorDiv(slotNum * (slotReplicas - 1), currentDataServers.size()); + final int maxMove = balancePolicy.getMaxMoveFollowerSlots(); + final int threshold = balancePolicy.getLowWaterMarkSlotFollowerNums(followerFloorAvg); + int balanced = 0, prevBalanced = -1; + while (balanced < maxMove) { + final List lowDataServers = findDataServersFollowerLowWaterMark(threshold); + if (lowDataServers.isEmpty()) { + break; + } + + Set excludes = Sets.newHashSet(lowDataServers); + excludes.addAll(findDataServersFollowerLowWaterMark(threshold + 1)); + + prevBalanced = balanced; + for (String lowDataServer : lowDataServers) { + Tuple selected = selectFollower4BalanceIn(lowDataServer, excludes); + if (selected == null) { + LOGGER.warn( + "[balanceLowFollowerSlots] could not find follower slot to balance: {}", + lowDataServer); + continue; } - return balanced != 0; + final int followerSlot = selected.o2; + final String oldFollowerDataServer = selected.o1; + slotTableBuilder.removeFollower(followerSlot, oldFollowerDataServer); + slotTableBuilder.addFollower(followerSlot, lowDataServer); + LOGGER.info( + "[balanceLowFollowerSlots] balance follower slotId={} from {} to {}", + followerSlot, + oldFollowerDataServer, + lowDataServer); + Metrics.SlotBalance.onLowFollowerMigrate( + oldFollowerDataServer, lowDataServer, followerSlot); + balanced++; + break; + } + if (prevBalanced == balanced) { + LOGGER.warn("[balanceLowFollowerSlots][prevBlanced == balanced]no more balance available"); + break; + } } - - private Tuple selectFollower4BalanceIn(String followerDataServer, - Set excludes) { - final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(followerDataServer); - List candidates = getCandidateDataServers(excludes, - Comparators.mostFollowersFirst(slotTableBuilder), currentDataServers); - LOGGER.info("[selectFollower4BalanceIn] target={}, followerSize={}, candidates={}", - followerDataServer, dataNodeSlot.getFollowers().size(), candidates); - for (String candidate : candidates) { - DataNodeSlot candidateDataNodeSlot = slotTableBuilder.getDataNodeSlot(candidate); - Set candidateFollowerSlots = candidateDataNodeSlot.getFollowers(); - for (int candidateFollowerSlot : candidateFollowerSlots) { - if (dataNodeSlot.containsFollower(candidateFollowerSlot)) { - LOGGER - .info( - "[selectFollower4BalanceIn] skip, target {} contains follower {}, candidate={}", - followerDataServer, candidateFollowerSlot, candidate); - continue; - } - if (dataNodeSlot.containsLeader(candidateFollowerSlot)) { - LOGGER - .info( - "[selectFollower4BalanceIn] skip, target {} contains leader {}, candidate={}", - followerDataServer, candidateFollowerSlot, candidate); - continue; - } - return Tuple.of(candidate, candidateFollowerSlot); - } + return balanced != 0; + } + + private Tuple selectFollower4BalanceIn( + String followerDataServer, Set excludes) { + final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(followerDataServer); + List candidates = + getCandidateDataServers( + excludes, Comparators.mostFollowersFirst(slotTableBuilder), currentDataServers); + LOGGER.info( + "[selectFollower4BalanceIn] target={}, followerSize={}, candidates={}", + followerDataServer, + dataNodeSlot.getFollowers().size(), + candidates); + for (String candidate : candidates) { + DataNodeSlot candidateDataNodeSlot = slotTableBuilder.getDataNodeSlot(candidate); + Set candidateFollowerSlots = candidateDataNodeSlot.getFollowers(); + for (int candidateFollowerSlot : candidateFollowerSlots) { + if (dataNodeSlot.containsFollower(candidateFollowerSlot)) { + LOGGER.info( + "[selectFollower4BalanceIn] skip, target {} contains follower {}, candidate={}", + followerDataServer, + candidateFollowerSlot, + candidate); + continue; } - return null; - } - - private Tuple selectFollower4BalanceOut(String followerDataServer, - Set excludes) { - final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(followerDataServer); - Set followerSlots = dataNodeSlot.getFollowers(); - List candidates = getCandidateDataServers(excludes, - Comparators.leastFollowersFirst(slotTableBuilder), currentDataServers); - LOGGER.info("[selectFollower4BalanceOut] target={}, followerSize={}, candidates={}", - followerDataServer, followerSlots.size(), candidates); - for (Integer followerSlot : followerSlots) { - for (String candidate : candidates) { - DataNodeSlot candidateDataNodeSlot = slotTableBuilder.getDataNodeSlot(candidate); - if (candidateDataNodeSlot.containsLeader(followerSlot)) { - LOGGER - .info( - "[selectFollower4BalanceOut] skip, conflict leader, target={}, follower={}, candidate={}", - followerDataServer, followerSlot, candidate); - continue; - } - if (candidateDataNodeSlot.containsFollower(followerSlot)) { - LOGGER - .info( - "[selectFollower4BalanceOut] skip, conflict follower, target={}, follower={}, candidate={}", - followerDataServer, followerSlot, candidate); - continue; - } - return Tuple.of(candidate, followerSlot); - } + if (dataNodeSlot.containsLeader(candidateFollowerSlot)) { + LOGGER.info( + "[selectFollower4BalanceIn] skip, target {} contains leader {}, candidate={}", + followerDataServer, + candidateFollowerSlot, + candidate); + continue; } - return null; + return Tuple.of(candidate, candidateFollowerSlot); + } } - - public SlotTableBuilder getSlotTableBuilder() { - return slotTableBuilder; - } - - private List getCandidateDataServers(Collection excludes, - Comparator comp, - Collection candidateDataServers) { - Set candidates = Sets.newHashSet(candidateDataServers); - candidates.removeAll(excludes); - List ret = Lists.newArrayList(candidates); - if (comp != null) { - ret.sort(comp); + return null; + } + + private Tuple selectFollower4BalanceOut( + String followerDataServer, Set excludes) { + final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(followerDataServer); + Set followerSlots = dataNodeSlot.getFollowers(); + List candidates = + getCandidateDataServers( + excludes, Comparators.leastFollowersFirst(slotTableBuilder), currentDataServers); + LOGGER.info( + "[selectFollower4BalanceOut] target={}, followerSize={}, candidates={}", + followerDataServer, + followerSlots.size(), + candidates); + for (Integer followerSlot : followerSlots) { + for (String candidate : candidates) { + DataNodeSlot candidateDataNodeSlot = slotTableBuilder.getDataNodeSlot(candidate); + if (candidateDataNodeSlot.containsLeader(followerSlot)) { + LOGGER.info( + "[selectFollower4BalanceOut] skip, conflict leader, target={}, follower={}, candidate={}", + followerDataServer, + followerSlot, + candidate); + continue; } - return ret; + if (candidateDataNodeSlot.containsFollower(followerSlot)) { + LOGGER.info( + "[selectFollower4BalanceOut] skip, conflict follower, target={}, follower={}, candidate={}", + followerDataServer, + followerSlot, + candidate); + continue; + } + return Tuple.of(candidate, followerSlot); + } } - + return null; + } + + public SlotTableBuilder getSlotTableBuilder() { + return slotTableBuilder; + } + + private List getCandidateDataServers( + Collection excludes, + Comparator comp, + Collection candidateDataServers) { + Set candidates = Sets.newHashSet(candidateDataServers); + candidates.removeAll(excludes); + List ret = Lists.newArrayList(candidates); + if (comp != null) { + ret.sort(comp); + } + return ret; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/LeaderOnlyBalancer.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/LeaderOnlyBalancer.java index 54f81412c..4270be6cb 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/LeaderOnlyBalancer.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/LeaderOnlyBalancer.java @@ -28,106 +28,110 @@ import com.alipay.sofa.registry.util.MathUtils; import com.google.common.collect.Lists; import com.google.common.collect.Sets; - import java.util.*; /** * @author chen.zhu - *

- * Jan 21, 2021 + *

Jan 21, 2021 */ public class LeaderOnlyBalancer implements SlotBalancer { - private static final Logger logger = LoggerFactory - .getLogger(LeaderOnlyBalancer.class); + private static final Logger logger = LoggerFactory.getLogger(LeaderOnlyBalancer.class); - public static final int TRIGGER_THESHOLD = 2; + public static final int TRIGGER_THESHOLD = 2; - private final SlotTableBuilder slotTableBuilder; + private final SlotTableBuilder slotTableBuilder; - private final Set currentDataServers; + private final Set currentDataServers; - private final BalancePolicy balancePolicy = new NaiveBalancePolicy(); + private final BalancePolicy balancePolicy = new NaiveBalancePolicy(); - public LeaderOnlyBalancer(SlotTableBuilder slotTableBuilder, - Collection currentDataServers) { - this.slotTableBuilder = slotTableBuilder; - this.currentDataServers = Collections.unmodifiableSet(Sets.newTreeSet(currentDataServers)); - } + public LeaderOnlyBalancer( + SlotTableBuilder slotTableBuilder, Collection currentDataServers) { + this.slotTableBuilder = slotTableBuilder; + this.currentDataServers = Collections.unmodifiableSet(Sets.newTreeSet(currentDataServers)); + } - @Override - public SlotTable balance() { - final int leaderCeilAvg = MathUtils.divideCeil(slotTableBuilder.getSlotNums(), - currentDataServers.size()); - final int maxMove = balancePolicy.getMaxMoveLeaderSlots(); - int balanced = 0; - while (balanced < maxMove) { - List targetHighDataServers = findDataServersLeaderHighWaterMark(leaderCeilAvg); - if (targetHighDataServers.isEmpty()) { - logger.info("[balance]no data-servers needs leader balance"); - // no balance, return null - break; - } - final Set excludes = Sets.newHashSet(targetHighDataServers); - // exclude the dataNode which could not add any leader - excludes.addAll(findDataServersLeaderHighWaterMark(leaderCeilAvg - 1)); + @Override + public SlotTable balance() { + final int leaderCeilAvg = + MathUtils.divideCeil(slotTableBuilder.getSlotNums(), currentDataServers.size()); + final int maxMove = balancePolicy.getMaxMoveLeaderSlots(); + int balanced = 0; + while (balanced < maxMove) { + List targetHighDataServers = findDataServersLeaderHighWaterMark(leaderCeilAvg); + if (targetHighDataServers.isEmpty()) { + logger.info("[balance]no data-servers needs leader balance"); + // no balance, return null + break; + } + final Set excludes = Sets.newHashSet(targetHighDataServers); + // exclude the dataNode which could not add any leader + excludes.addAll(findDataServersLeaderHighWaterMark(leaderCeilAvg - 1)); - for (String target : targetHighDataServers) { - Tuple candidate = selectLeader(target, excludes); - if (candidate == null) { - continue; - } - final String newLeader = candidate.o1; - final int slotId = candidate.o2; - slotTableBuilder.replaceLeader(slotId, newLeader); - balanced++; - break; - } + for (String target : targetHighDataServers) { + Tuple candidate = selectLeader(target, excludes); + if (candidate == null) { + continue; } - if (balanced != 0) { - SlotTable slotTable = slotTableBuilder.build(); - logger.info("[balance][end] slot table leader stat: {}", - SlotTableUtils.getSlotTableLeaderCount(slotTable)); - logger.info("[balance][end] slot table slots stat: {}", - SlotTableUtils.getSlotTableSlotCount(slotTable)); - return slotTable; - } - return null; + final String newLeader = candidate.o1; + final int slotId = candidate.o2; + slotTableBuilder.replaceLeader(slotId, newLeader); + balanced++; + break; + } } - - private Tuple selectLeader(String leaderDataServer, Set excludes) { - final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(leaderDataServer); - List candidates = getCandidateDataServers(excludes, - Comparators.leastLeadersFirst(slotTableBuilder), currentDataServers); - logger.info("[selectLeader] target={}, leaders={}, candidates={}", leaderDataServer, - dataNodeSlot.getLeaders().size(), candidates); - for (int leader : dataNodeSlot.getLeaders()) { - for (String candidate : candidates) { - return Tuple.of(candidate, leader); - } - } - return null; + if (balanced != 0) { + SlotTable slotTable = slotTableBuilder.build(); + logger.info( + "[balance][end] slot table leader stat: {}", + SlotTableUtils.getSlotTableLeaderCount(slotTable)); + logger.info( + "[balance][end] slot table slots stat: {}", + SlotTableUtils.getSlotTableSlotCount(slotTable)); + return slotTable; } + return null; + } - private List findDataServersLeaderHighWaterMark(int avg) { - int threshold = balancePolicy.getHighWaterMarkSlotLeaderNums(avg); - List dataNodeSlots = slotTableBuilder.getDataNodeSlotsLeaderBeyond(threshold); - List dataServers = DataNodeSlot.collectDataNodes(dataNodeSlots); - dataServers.sort(Comparators.mostLeadersFirst(slotTableBuilder)); - logger.info("[LeaderHighWaterMark] avg={}, threshold={}, dataServers={}", avg, threshold, - dataServers); - return dataServers; + private Tuple selectLeader(String leaderDataServer, Set excludes) { + final DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(leaderDataServer); + List candidates = + getCandidateDataServers( + excludes, Comparators.leastLeadersFirst(slotTableBuilder), currentDataServers); + logger.info( + "[selectLeader] target={}, leaders={}, candidates={}", + leaderDataServer, + dataNodeSlot.getLeaders().size(), + candidates); + for (int leader : dataNodeSlot.getLeaders()) { + for (String candidate : candidates) { + return Tuple.of(candidate, leader); + } } + return null; + } - private List getCandidateDataServers(Collection excludes, - Comparator comp, - Collection candidateDataServers) { - Set candidates = Sets.newHashSet(candidateDataServers); - candidates.removeAll(excludes); - List ret = Lists.newArrayList(candidates); - if (comp != null) { - ret.sort(comp); - } - return ret; + private List findDataServersLeaderHighWaterMark(int avg) { + int threshold = balancePolicy.getHighWaterMarkSlotLeaderNums(avg); + List dataNodeSlots = slotTableBuilder.getDataNodeSlotsLeaderBeyond(threshold); + List dataServers = DataNodeSlot.collectDataNodes(dataNodeSlots); + dataServers.sort(Comparators.mostLeadersFirst(slotTableBuilder)); + logger.info( + "[LeaderHighWaterMark] avg={}, threshold={}, dataServers={}", avg, threshold, dataServers); + return dataServers; + } + + private List getCandidateDataServers( + Collection excludes, + Comparator comp, + Collection candidateDataServers) { + Set candidates = Sets.newHashSet(candidateDataServers); + candidates.removeAll(excludes); + List ret = Lists.newArrayList(candidates); + if (comp != null) { + ret.sort(comp); } + return ret; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/NaiveBalancePolicy.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/NaiveBalancePolicy.java index b9ed6deff..1a8cf7048 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/NaiveBalancePolicy.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/balance/NaiveBalancePolicy.java @@ -20,50 +20,49 @@ /** * @author chen.zhu - *

- * Jan 20, 2021 + *

Jan 20, 2021 */ public class NaiveBalancePolicy implements BalancePolicy { - // "final" instead of "static final" to make it dynamic and flexible - private final int threshold = Integer.getInteger("slot.threshold", 10); + // "final" instead of "static final" to make it dynamic and flexible + private final int threshold = Integer.getInteger("slot.threshold", 10); - // "final" instead of "static final" to make it dynamic and flexible - private final int maxMoveLeaderSlots = Integer.getInteger("slot.leader.max.move", 2); + // "final" instead of "static final" to make it dynamic and flexible + private final int maxMoveLeaderSlots = Integer.getInteger("slot.leader.max.move", 2); - private final int maxMoveFollowerSlots = Integer.getInteger("slot.follower.max.move", 10); + private final int maxMoveFollowerSlots = Integer.getInteger("slot.follower.max.move", 10); - @Override - public int getLowWaterMarkSlotLeaderNums(int average) { - // round down - return average * (100 - threshold) / 100; - } + @Override + public int getLowWaterMarkSlotLeaderNums(int average) { + // round down + return average * (100 - threshold) / 100; + } - @Override - public int getHighWaterMarkSlotLeaderNums(int average) { - // round up - return MathUtils.divideCeil(average * (100 + threshold), 100); - } + @Override + public int getHighWaterMarkSlotLeaderNums(int average) { + // round up + return MathUtils.divideCeil(average * (100 + threshold), 100); + } - @Override - public int getLowWaterMarkSlotFollowerNums(int average) { - // same as getLowWaterMarkSlotLeaderNums - return getLowWaterMarkSlotLeaderNums(average); - } + @Override + public int getLowWaterMarkSlotFollowerNums(int average) { + // same as getLowWaterMarkSlotLeaderNums + return getLowWaterMarkSlotLeaderNums(average); + } - @Override - public int getHighWaterMarkSlotFollowerNums(int average) { - // same as getHighWaterMarkSlotLeaderNums - return getHighWaterMarkSlotLeaderNums(average); - } + @Override + public int getHighWaterMarkSlotFollowerNums(int average) { + // same as getHighWaterMarkSlotLeaderNums + return getHighWaterMarkSlotLeaderNums(average); + } - @Override - public int getMaxMoveLeaderSlots() { - return maxMoveLeaderSlots; - } + @Override + public int getMaxMoveLeaderSlots() { + return maxMoveLeaderSlots; + } - @Override - public int getMaxMoveFollowerSlots() { - return maxMoveFollowerSlots; - } + @Override + public int getMaxMoveFollowerSlots() { + return maxMoveFollowerSlots; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/manager/DefaultSlotManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/manager/DefaultSlotManager.java index ce000755a..19ce6ed41 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/manager/DefaultSlotManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/manager/DefaultSlotManager.java @@ -25,75 +25,71 @@ import com.alipay.sofa.registry.server.meta.remoting.notifier.Notifier; import com.alipay.sofa.registry.server.meta.slot.SlotManager; import com.google.common.annotations.VisibleForTesting; +import java.util.List; +import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import javax.annotation.PostConstruct; -import java.util.List; - /** * @author chen.zhu - *

- * Dec 02, 2020 + *

Dec 02, 2020 */ @Component public class DefaultSlotManager extends SimpleSlotManager implements SlotManager { - @Autowired(required = false) - private List notifiers; + @Autowired(required = false) + private List notifiers; - @Autowired - private MetaLeaderService metaLeaderService; + @Autowired private MetaLeaderService metaLeaderService; - public DefaultSlotManager() { - } + public DefaultSlotManager() {} - public DefaultSlotManager(MetaLeaderService metaLeaderService) { - this.metaLeaderService = metaLeaderService; - } + public DefaultSlotManager(MetaLeaderService metaLeaderService) { + this.metaLeaderService = metaLeaderService; + } - @PostConstruct - public void postConstruct() throws Exception { - LifecycleHelper.initializeIfPossible(this); - } + @PostConstruct + public void postConstruct() throws Exception { + LifecycleHelper.initializeIfPossible(this); + } - @Override - protected void doInitialize() throws InitializeException { - super.doInitialize(); - addObserver(new SlotTableChangeNotification()); - } + @Override + protected void doInitialize() throws InitializeException { + super.doInitialize(); + addObserver(new SlotTableChangeNotification()); + } - @Override - public void refresh(SlotTable slotTable) { - super.refresh(slotTable); - if (metaLeaderService.amIStableAsLeader()) { - notifyObservers(slotTable); - } + @Override + public void refresh(SlotTable slotTable) { + super.refresh(slotTable); + if (metaLeaderService.amIStableAsLeader()) { + notifyObservers(slotTable); } + } - private final class SlotTableChangeNotification implements UnblockingObserver { + private final class SlotTableChangeNotification implements UnblockingObserver { - @Override - public void update(Observable source, Object message) { - if (message instanceof SlotTable) { - if (notifiers == null || notifiers.isEmpty()) { - return; - } - notifiers.forEach(notifier -> { - try { - notifier.notifySlotTableChange((SlotTable) message); - } catch (Throwable th) { - logger.error("[notify] notifier [{}]", notifier.getClass().getSimpleName(), th); - } - }); - } + @Override + public void update(Observable source, Object message) { + if (message instanceof SlotTable) { + if (notifiers == null || notifiers.isEmpty()) { + return; } + notifiers.forEach( + notifier -> { + try { + notifier.notifySlotTableChange((SlotTable) message); + } catch (Throwable th) { + logger.error("[notify] notifier [{}]", notifier.getClass().getSimpleName(), th); + } + }); + } } + } - @VisibleForTesting - public SimpleSlotManager setNotifiers(List notifiers) { - this.notifiers = notifiers; - return this; - } - + @VisibleForTesting + public SimpleSlotManager setNotifiers(List notifiers) { + this.notifiers = notifiers; + return this; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/manager/SimpleSlotManager.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/manager/SimpleSlotManager.java index 30354bd25..842fca9e8 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/manager/SimpleSlotManager.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/manager/SimpleSlotManager.java @@ -24,7 +24,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; - import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicReference; @@ -33,94 +32,95 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ public class SimpleSlotManager extends AbstractLifecycleObservable implements SlotManager { - public static final String LOCAL_SLOT_MANAGER = "LocalSlotManager"; + public static final String LOCAL_SLOT_MANAGER = "LocalSlotManager"; - private final ReadWriteLock lock = new ReentrantReadWriteLock(); + private final ReadWriteLock lock = new ReentrantReadWriteLock(); - private final AtomicReference localRepo = new AtomicReference<>(new SlotTableCacheWrapper(SlotTable.INIT, ImmutableMap.of())); + private final AtomicReference localRepo = + new AtomicReference<>(new SlotTableCacheWrapper(SlotTable.INIT, ImmutableMap.of())); - @Override - public SlotTable getSlotTable() { - lock.readLock().lock(); - try { - return localRepo.get().slotTable; - } finally { - lock.readLock().unlock(); - } + @Override + public SlotTable getSlotTable() { + lock.readLock().lock(); + try { + return localRepo.get().slotTable; + } finally { + lock.readLock().unlock(); } - - @Override - public void refresh(SlotTable slotTable) { - lock.writeLock().lock(); - try { - if (slotTable.getEpoch() <= localRepo.get().slotTable.getEpoch()) { - if (logger.isWarnEnabled()) { - logger.warn( - "[refresh]receive slot table,but epoch({}) is smaller than current({})", - slotTable.getEpoch(), localRepo.get().slotTable.getEpoch()); - } - return; - } - setSlotTableCacheWrapper(new SlotTableCacheWrapper(slotTable, refreshReverseMap(slotTable))); - } finally { - lock.writeLock().unlock(); + } + + @Override + public void refresh(SlotTable slotTable) { + lock.writeLock().lock(); + try { + if (slotTable.getEpoch() <= localRepo.get().slotTable.getEpoch()) { + if (logger.isWarnEnabled()) { + logger.warn( + "[refresh]receive slot table,but epoch({}) is smaller than current({})", + slotTable.getEpoch(), + localRepo.get().slotTable.getEpoch()); } + return; + } + setSlotTableCacheWrapper(new SlotTableCacheWrapper(slotTable, refreshReverseMap(slotTable))); + } finally { + lock.writeLock().unlock(); } + } - private Map refreshReverseMap(SlotTable slotTable) { - Map newMap = Maps.newHashMap(); - List dataNodeSlots = slotTable.transfer(null, false); - for(DataNodeSlot dataNodeSlot : dataNodeSlots) { - newMap.put(dataNodeSlot.getDataNode(), dataNodeSlot); - } - return ImmutableMap.copyOf(newMap); + private Map refreshReverseMap(SlotTable slotTable) { + Map newMap = Maps.newHashMap(); + List dataNodeSlots = slotTable.transfer(null, false); + for (DataNodeSlot dataNodeSlot : dataNodeSlots) { + newMap.put(dataNodeSlot.getDataNode(), dataNodeSlot); } - - @Override - public int getSlotNums() { - return SlotConfig.SLOT_NUM; + return ImmutableMap.copyOf(newMap); + } + + @Override + public int getSlotNums() { + return SlotConfig.SLOT_NUM; + } + + @Override + public int getSlotReplicaNums() { + return SlotConfig.SLOT_REPLICAS; + } + + @Override + public DataNodeSlot getDataNodeManagedSlot(String dataNode, boolean ignoreFollowers) { + lock.readLock().lock(); + try { + // here we ignore port for data-node, as when store the reverse-map, we lose the port + // information + // besides, port is not matter here + DataNodeSlot target = localRepo.get().reverseMap.get(dataNode); + if (target == null) { + return new DataNodeSlot(dataNode); + } + return target.fork(ignoreFollowers); + } finally { + lock.readLock().unlock(); } + } - @Override - public int getSlotReplicaNums() { - return SlotConfig.SLOT_REPLICAS; - } + @VisibleForTesting + protected void setSlotTableCacheWrapper(SlotTableCacheWrapper wrapper) { + this.localRepo.set(wrapper); + } - @Override - public DataNodeSlot getDataNodeManagedSlot(String dataNode, boolean ignoreFollowers) { - lock.readLock().lock(); - try { - // here we ignore port for data-node, as when store the reverse-map, we lose the port information - // besides, port is not matter here - DataNodeSlot target = localRepo.get().reverseMap.get(dataNode); - if (target == null) { - return new DataNodeSlot(dataNode); - } - return target.fork(ignoreFollowers); - } finally { - lock.readLock().unlock(); - } - } - - @VisibleForTesting - protected void setSlotTableCacheWrapper(SlotTableCacheWrapper wrapper) { - this.localRepo.set(wrapper); - } + private static final class SlotTableCacheWrapper { + private final SlotTable slotTable; - private static final class SlotTableCacheWrapper { - private final SlotTable slotTable; + private final Map reverseMap; - private final Map reverseMap; - - public SlotTableCacheWrapper(SlotTable slotTable, Map reverseMap) { - this.slotTable = slotTable; - this.reverseMap = reverseMap; - } + public SlotTableCacheWrapper(SlotTable slotTable, Map reverseMap) { + this.slotTable = slotTable; + this.reverseMap = reverseMap; } - + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/tasks/BalanceTask.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/tasks/BalanceTask.java index 818e6cae8..0ff5a3a23 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/tasks/BalanceTask.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/tasks/BalanceTask.java @@ -27,98 +27,94 @@ import com.alipay.sofa.registry.util.DatumVersionUtil; import com.google.common.collect.Lists; import com.google.common.collect.Maps; - import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; /** * @author chen.zhu - *

- * Dec 01, 2020 + *

Dec 01, 2020 */ public class BalanceTask implements RebalanceTask { - private static final Logger logger = LoggerFactory - .getLogger(BalanceTask.class); + private static final Logger logger = LoggerFactory.getLogger(BalanceTask.class); - private final SlotManager slotManager; + private final SlotManager slotManager; - private final DataServerManager dataServerManager; + private final DataServerManager dataServerManager; - private long nextEpoch; + private long nextEpoch; - private final AtomicInteger nextLeaderIndex = new AtomicInteger(); + private final AtomicInteger nextLeaderIndex = new AtomicInteger(); - private final AtomicInteger nextFollowerIndex = new AtomicInteger(1); + private final AtomicInteger nextFollowerIndex = new AtomicInteger(1); - private List dataNodes; + private List dataNodes; - public BalanceTask(SlotManager slotManager, - DataServerManager dataServerManager) { - this.slotManager = slotManager; - this.dataServerManager = dataServerManager; - } + public BalanceTask(SlotManager slotManager, DataServerManager dataServerManager) { + this.slotManager = slotManager; + this.dataServerManager = dataServerManager; + } - @Override - public void run() { - initParameters(); - if (dataNodes == null || dataNodes.isEmpty()) { - return; - } - if (logger.isInfoEnabled()) { - logger.info("[run] candidates({}): {}", dataNodes.size(), dataNodes); - } - - SlotTable slotTable = createSlotTable(); - if (logger.isInfoEnabled()) { - logger.info("[run] end to init slot table"); - } - - slotManager.refresh(slotTable); - if (logger.isInfoEnabled()) { - logger.info("[run] raft refreshed slot-table"); - } + @Override + public void run() { + initParameters(); + if (dataNodes == null || dataNodes.isEmpty()) { + return; } - - private void initParameters() { - dataNodes = dataServerManager.getDataServerMetaInfo().getClusterMembers(); - if (dataNodes.isEmpty()) { - if (logger.isInfoEnabled()) { - logger.info("[run] empty candidate, quit"); - } - return; - } - nextLeaderIndex.set(0); - nextFollowerIndex.set(dataNodes.size() - 1); - nextEpoch = DatumVersionUtil.nextId(); + if (logger.isInfoEnabled()) { + logger.info("[run] candidates({}): {}", dataNodes.size(), dataNodes); } - public SlotTable createSlotTable() { - Map slotMap = generateSlotMap(); - return new SlotTable(nextEpoch, slotMap.values()); + SlotTable slotTable = createSlotTable(); + if (logger.isInfoEnabled()) { + logger.info("[run] end to init slot table"); } - private Map generateSlotMap() { - Map slotMap = Maps.newHashMap(); - for (int i = 0; i < slotManager.getSlotNums(); i++) { - long epoch = DatumVersionUtil.nextId(); - String leader = getNextLeader().getIp(); - List followers = Lists.newArrayList(); - for (int j = 0; j < slotManager.getSlotReplicaNums() - 1; j++) { - followers.add(getNextFollower().getIp()); - } - Slot slot = new Slot(i, leader, epoch, followers); - slotMap.put(i, slot); - } - return slotMap; + slotManager.refresh(slotTable); + if (logger.isInfoEnabled()) { + logger.info("[run] raft refreshed slot-table"); } - - private DataNode getNextLeader() { - return dataNodes.get(nextLeaderIndex.getAndIncrement() % dataNodes.size()); + } + + private void initParameters() { + dataNodes = dataServerManager.getDataServerMetaInfo().getClusterMembers(); + if (dataNodes.isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("[run] empty candidate, quit"); + } + return; } - - private DataNode getNextFollower() { - return dataNodes.get(nextFollowerIndex.getAndIncrement() % dataNodes.size()); + nextLeaderIndex.set(0); + nextFollowerIndex.set(dataNodes.size() - 1); + nextEpoch = DatumVersionUtil.nextId(); + } + + public SlotTable createSlotTable() { + Map slotMap = generateSlotMap(); + return new SlotTable(nextEpoch, slotMap.values()); + } + + private Map generateSlotMap() { + Map slotMap = Maps.newHashMap(); + for (int i = 0; i < slotManager.getSlotNums(); i++) { + long epoch = DatumVersionUtil.nextId(); + String leader = getNextLeader().getIp(); + List followers = Lists.newArrayList(); + for (int j = 0; j < slotManager.getSlotReplicaNums() - 1; j++) { + followers.add(getNextFollower().getIp()); + } + Slot slot = new Slot(i, leader, epoch, followers); + slotMap.put(i, slot); } + return slotMap; + } + + private DataNode getNextLeader() { + return dataNodes.get(nextLeaderIndex.getAndIncrement() % dataNodes.size()); + } + + private DataNode getNextFollower() { + return dataNodes.get(nextFollowerIndex.getAndIncrement() % dataNodes.size()); + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/MigrateSlotGroup.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/MigrateSlotGroup.java index 23d464c96..45d00d5bc 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/MigrateSlotGroup.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/MigrateSlotGroup.java @@ -19,150 +19,143 @@ import com.alipay.sofa.registry.server.meta.slot.assigner.ScoreStrategy; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.glassfish.jersey.internal.guava.Sets; - import java.util.*; +import org.glassfish.jersey.internal.guava.Sets; /** * @author chen.zhu - *

- * Jan 12, 2021 - * - * MigrateSlotGroup is used as a model object to cache all slots we wish to migrate - * Separated through different roles(Leader/Follower) - * + *

Jan 12, 2021 + *

MigrateSlotGroup is used as a model object to cache all slots we wish to migrate Separated + * through different roles(Leader/Follower) */ public class MigrateSlotGroup { - /** slotId */ - private final Set leaders = Sets.newHashSet(); - /** key: slotId, value: counter (one slot could has multi followers to migrate) */ - private final Map lackFollowers = Maps.newHashMap(); - - /** - * Add leader migrate slot group. - * - * @param slotId the slot id - * @return the migrate slot group - */ - public MigrateSlotGroup addLeader(int slotId) { - leaders.add(slotId); - return this; - } - - public boolean isEmpty() { - return leaders.isEmpty() && lackFollowers.isEmpty(); - } - - /** - * Add follower migrate slot group. - * - * @param slotId the slot id - * @return the migrate slot group - */ - public MigrateSlotGroup addFollower(int slotId) { - lackFollowers.put(slotId, lackFollowers.getOrDefault(slotId, 0) + 1); - return this; - } - - public MigrateSlotGroup addFollower(int slotId, int num) { - lackFollowers.put(slotId, lackFollowers.getOrDefault(slotId, 0) + num); - return this; - } - - public List getLeadersByScore(ScoreStrategy scoreStrategy) { - List leaders = Lists.newArrayList(this.leaders); - leaders.sort(new Comparator() { - @Override - public int compare(Integer slotId1, Integer slotId2) { - return scoreStrategy.score(slotId1) - scoreStrategy.score(slotId2); - } + /** slotId */ + private final Set leaders = Sets.newHashSet(); + /** key: slotId, value: counter (one slot could has multi followers to migrate) */ + private final Map lackFollowers = Maps.newHashMap(); + + /** + * Add leader migrate slot group. + * + * @param slotId the slot id + * @return the migrate slot group + */ + public MigrateSlotGroup addLeader(int slotId) { + leaders.add(slotId); + return this; + } + + public boolean isEmpty() { + return leaders.isEmpty() && lackFollowers.isEmpty(); + } + + /** + * Add follower migrate slot group. + * + * @param slotId the slot id + * @return the migrate slot group + */ + public MigrateSlotGroup addFollower(int slotId) { + lackFollowers.put(slotId, lackFollowers.getOrDefault(slotId, 0) + 1); + return this; + } + + public MigrateSlotGroup addFollower(int slotId, int num) { + lackFollowers.put(slotId, lackFollowers.getOrDefault(slotId, 0) + num); + return this; + } + + public List getLeadersByScore(ScoreStrategy scoreStrategy) { + List leaders = Lists.newArrayList(this.leaders); + leaders.sort( + new Comparator() { + @Override + public int compare(Integer slotId1, Integer slotId2) { + return scoreStrategy.score(slotId1) - scoreStrategy.score(slotId2); + } }); - return leaders; - } - - public List getFollowersByScore(ScoreStrategy scoreStrategy) { - List assignees = Lists.newArrayList(); - lackFollowers.forEach((slotId, nums)->assignees.add(new FollowerToAssign(slotId, nums))); - assignees.sort(new Comparator() { - @Override - public int compare(FollowerToAssign o1, FollowerToAssign o2) { - return scoreStrategy.score(o1) - scoreStrategy.score(o2); - } + return leaders; + } + + public List getFollowersByScore(ScoreStrategy scoreStrategy) { + List assignees = Lists.newArrayList(); + lackFollowers.forEach((slotId, nums) -> assignees.add(new FollowerToAssign(slotId, nums))); + assignees.sort( + new Comparator() { + @Override + public int compare(FollowerToAssign o1, FollowerToAssign o2) { + return scoreStrategy.score(o1) - scoreStrategy.score(o2); + } }); - return assignees; + return assignees; + } + + /** + * Gets get leaders. + * + * @return the get leaders + */ + public Set getLeaders() { + return Collections.unmodifiableSet(leaders); + } + + /** + * Gets get followers. + * + * @return the get followers + */ + public Map getLackFollowers() { + return Collections.unmodifiableMap(lackFollowers); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + MigrateSlotGroup that = (MigrateSlotGroup) o; + return Objects.equals(leaders, that.leaders) + && Objects.equals(lackFollowers, that.lackFollowers); + } + + @Override + public int hashCode() { + return Objects.hash(leaders, lackFollowers); + } + + @Override + public String toString() { + return "MigrateSlotGroup{" + "leaders=" + leaders + ", lackFollowers=" + lackFollowers + '}'; + } + + public static class FollowerToAssign { + private final int slotId; + private final int assigneeNums; + + public FollowerToAssign(int slotId, int assigneeNums) { + this.slotId = slotId; + this.assigneeNums = assigneeNums; } - /** - * Gets get leaders. - * - * @return the get leaders - */ - public Set getLeaders() { - return Collections.unmodifiableSet(leaders); + public int getSlotId() { + return slotId; } - /** - * Gets get followers. - * - * @return the get followers - */ - public Map getLackFollowers() { - return Collections.unmodifiableMap(lackFollowers); + public int getAssigneeNums() { + return assigneeNums; } @Override public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - MigrateSlotGroup that = (MigrateSlotGroup) o; - return Objects.equals(leaders, that.leaders) - && Objects.equals(lackFollowers, that.lackFollowers); + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + FollowerToAssign that = (FollowerToAssign) o; + return slotId == that.slotId && assigneeNums == that.assigneeNums; } @Override public int hashCode() { - return Objects.hash(leaders, lackFollowers); - } - - @Override - public String toString() { - return "MigrateSlotGroup{" + "leaders=" + leaders + ", lackFollowers=" + lackFollowers - + '}'; - } - - public static class FollowerToAssign { - private final int slotId; - private final int assigneeNums; - - public FollowerToAssign(int slotId, int assigneeNums) { - this.slotId = slotId; - this.assigneeNums = assigneeNums; - } - - public int getSlotId() { - return slotId; - } - - public int getAssigneeNums() { - return assigneeNums; - } - - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - FollowerToAssign that = (FollowerToAssign) o; - return slotId == that.slotId && assigneeNums == that.assigneeNums; - } - - @Override - public int hashCode() { - return Objects.hash(slotId, assigneeNums); - } + return Objects.hash(slotId, assigneeNums); } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/Builder.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/Builder.java index 6da8349a6..11339b7ed 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/Builder.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/Builder.java @@ -18,9 +18,8 @@ /** * @author chen.zhu - *

- * Jan 12, 2021 + *

Jan 12, 2021 */ public interface Builder { - T build(); + T build(); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/SlotBuilder.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/SlotBuilder.java index 02e006145..143e7a32d 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/SlotBuilder.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/SlotBuilder.java @@ -20,121 +20,132 @@ import com.alipay.sofa.registry.exception.SofaRegistryRuntimeException; import com.alipay.sofa.registry.util.DatumVersionUtil; import com.google.common.collect.Sets; -import org.apache.commons.lang.StringUtils; - import java.util.Collection; import java.util.Collections; import java.util.Set; +import org.apache.commons.lang.StringUtils; /** * @author chen.zhu - *

- * Jan 12, 2021 + *

Jan 12, 2021 */ public class SlotBuilder implements Builder { - private final int slotId; - - private final int followerNums; - - private String leader; - - private final Set followers = Sets.newHashSet(); - - private long epoch; - - public SlotBuilder(int slotId, int followerNums) { - this.slotId = slotId; - this.followerNums = followerNums; - } - - public SlotBuilder(int slotId, int followerNums, String leader, long epoch) { - this.slotId = slotId; - this.followerNums = followerNums; - this.leader = leader; - this.epoch = epoch; - } + private final int slotId; - public SlotBuilder setLeader(String leader) { - if (!StringUtils.equals(this.leader, leader)) { - this.leader = leader; - epoch = DatumVersionUtil.nextId(); - } - return this; - } + private final int followerNums; - public boolean addFollower(String follower) { - if (StringUtils.isBlank(follower)) { - throw new IllegalArgumentException("add empty follower"); - } - if (followers.contains(follower)) { - return true; - } - if (followers.size() >= followerNums) { - return false; - } - followers.add(follower); - return true; - } + private String leader; - public boolean addFollower(Collection followerCollection) { - for (String follower : followerCollection) { - if (!addFollower(follower)) { - return false; - } - } - return true; - } + private final Set followers = Sets.newHashSet(); - public boolean removeFollower(String follower) { - return followers.remove(follower); - } + private long epoch; - public int getFollowerSize() { - return followers.size(); - } + public SlotBuilder(int slotId, int followerNums) { + this.slotId = slotId; + this.followerNums = followerNums; + } - public boolean containsFollower(String follower) { - return followers.contains(follower); - } + public SlotBuilder(int slotId, int followerNums, String leader, long epoch) { + this.slotId = slotId; + this.followerNums = followerNums; + this.leader = leader; + this.epoch = epoch; + } - private boolean isReady() { - return leader != null; + public SlotBuilder setLeader(String leader) { + if (!StringUtils.equals(this.leader, leader)) { + this.leader = leader; + epoch = DatumVersionUtil.nextId(); } + return this; + } - public String getLeader() { - return leader; + public boolean addFollower(String follower) { + if (StringUtils.isBlank(follower)) { + throw new IllegalArgumentException("add empty follower"); } - - public int getSlotId() { - return slotId; + if (followers.contains(follower)) { + return true; } - - public Set getFollowers() { - return Collections.unmodifiableSet(Sets.newHashSet(followers)); + if (followers.size() >= followerNums) { + return false; } - - public long getEpoch() { - return epoch; + followers.add(follower); + return true; + } + + public boolean addFollower(Collection followerCollection) { + for (String follower : followerCollection) { + if (!addFollower(follower)) { + return false; + } } - - @Override - public Slot build() { - if (!isReady()) { - throw new SofaRegistryRuntimeException("slot builder is not ready for build: leader[" - + leader + "], followers[" - + StringUtils.join(followers, ",") + "]"); - } - if (epoch <= 0) { - this.epoch = DatumVersionUtil.nextId(); - } - return new Slot(slotId, leader, epoch, followers); + return true; + } + + public boolean removeFollower(String follower) { + return followers.remove(follower); + } + + public int getFollowerSize() { + return followers.size(); + } + + public boolean containsFollower(String follower) { + return followers.contains(follower); + } + + private boolean isReady() { + return leader != null; + } + + public String getLeader() { + return leader; + } + + public int getSlotId() { + return slotId; + } + + public Set getFollowers() { + return Collections.unmodifiableSet(Sets.newHashSet(followers)); + } + + public long getEpoch() { + return epoch; + } + + @Override + public Slot build() { + if (!isReady()) { + throw new SofaRegistryRuntimeException( + "slot builder is not ready for build: leader[" + + leader + + "], followers[" + + StringUtils.join(followers, ",") + + "]"); } - - @Override - public String toString() { - return "SlotBuilder{" + "slotId=" + slotId + ", followerNums=" + followerNums - + ", leader='" + leader + '\'' + ", followers=" + followers + ", epoch=" + epoch - + '}'; + if (epoch <= 0) { + this.epoch = DatumVersionUtil.nextId(); } + return new Slot(slotId, leader, epoch, followers); + } + + @Override + public String toString() { + return "SlotBuilder{" + + "slotId=" + + slotId + + ", followerNums=" + + followerNums + + ", leader='" + + leader + + '\'' + + ", followers=" + + followers + + ", epoch=" + + epoch + + '}'; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/SlotTableBuilder.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/SlotTableBuilder.java index e471f9438..31dcc2e28 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/SlotTableBuilder.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/builder/SlotTableBuilder.java @@ -27,248 +27,259 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang.StringUtils; - import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.StringUtils; /** * @author chen.zhu - *

- * Jan 12, 2021 + *

Jan 12, 2021 */ public class SlotTableBuilder implements Builder { - private static final Logger logger = LoggerFactory - .getLogger(SlotTableBuilder.class); - - private final Map buildingSlots = Maps.newHashMap(); - - private final Map reverseMap = Maps.newHashMap(); - - private final int slotNums; + private static final Logger logger = LoggerFactory.getLogger(SlotTableBuilder.class); - private final int followerNums; + private final Map buildingSlots = Maps.newHashMap(); - private long epoch; + private final Map reverseMap = Maps.newHashMap(); - private final SlotTable initSlotTable; + private final int slotNums; - public SlotTableBuilder(SlotTable initSlotTable, int slotNums, int slotReplicas) { - this.slotNums = slotNums; - this.followerNums = slotReplicas - 1; - this.initSlotTable = initSlotTable; - } + private final int followerNums; - public SlotBuilder getOrCreate(int slotId) { - buildingSlots.putIfAbsent(slotId, new SlotBuilder(slotId, followerNums)); - return buildingSlots.get(slotId); - } + private long epoch; - public void init(List dataServers) { - for (int slotId = 0; slotId < slotNums; slotId++) { - Slot slot = initSlotTable == null ? null : initSlotTable.getSlot(slotId); - if (slot == null) { - getOrCreate(slotId); - continue; - } - SlotBuilder slotBuilder = new SlotBuilder(slotId, followerNums, slot.getLeader(), - slot.getLeaderEpoch()); - if (!slotBuilder.addFollower(initSlotTable.getSlot(slotId).getFollowers())) { - throw new IllegalArgumentException(String.format("to many followers, %s", - slotBuilder)); - } - buildingSlots.put(slotId, slotBuilder); - } - initReverseMap(dataServers); - } + private final SlotTable initSlotTable; - private void initReverseMap(List dataServers) { - for (int slotId = 0; slotId < slotNums; slotId++) { - SlotBuilder slotBuilder = getOrCreate(slotId); - String leader = slotBuilder.getLeader(); - if (leader != null) { - DataNodeSlot dataNodeSlot = reverseMap.computeIfAbsent(leader, - k->new DataNodeSlot(leader)); - dataNodeSlot.addLeader(slotId); - } - Set followers = slotBuilder.getFollowers(); - for (String follower : followers) { - DataNodeSlot dataNodeSlot = reverseMap.computeIfAbsent(follower, - k->new DataNodeSlot(follower)); - dataNodeSlot.addFollower(slotId); - } - } - if (CollectionUtils.isEmpty(dataServers)) { - return; - } - dataServers.forEach(dataServer->reverseMap.putIfAbsent(dataServer, new DataNodeSlot(dataServer))); - } + public SlotTableBuilder(SlotTable initSlotTable, int slotNums, int slotReplicas) { + this.slotNums = slotNums; + this.followerNums = slotReplicas - 1; + this.initSlotTable = initSlotTable; + } - public String replaceLeader(int slotId, String nextLeader) { - SlotBuilder slotBuilder = getOrCreate(slotId); - String prevLeader = slotBuilder.getLeader(); - slotBuilder.setLeader(nextLeader).removeFollower(nextLeader); - DataNodeSlot nextLeaderDataNodeSlot = reverseMap.computeIfAbsent(nextLeader, - k->new DataNodeSlot(nextLeader)); - nextLeaderDataNodeSlot.addLeader(slotId); - nextLeaderDataNodeSlot.removeFollower(slotId); - if (!StringUtils.isEmpty(prevLeader)) { - reverseMap.get(prevLeader).removeLeader(slotId); - } - return prevLeader; - } + public SlotBuilder getOrCreate(int slotId) { + buildingSlots.putIfAbsent(slotId, new SlotBuilder(slotId, followerNums)); + return buildingSlots.get(slotId); + } - public SlotTableBuilder removeFollower(int slotId, String follower) { - SlotBuilder slotBuilder = getOrCreate(slotId); - if (slotBuilder.removeFollower(follower)) { - reverseMap.get(follower).removeFollower(slotId); - } - return this; + public void init(List dataServers) { + for (int slotId = 0; slotId < slotNums; slotId++) { + Slot slot = initSlotTable == null ? null : initSlotTable.getSlot(slotId); + if (slot == null) { + getOrCreate(slotId); + continue; + } + SlotBuilder slotBuilder = + new SlotBuilder(slotId, followerNums, slot.getLeader(), slot.getLeaderEpoch()); + if (!slotBuilder.addFollower(initSlotTable.getSlot(slotId).getFollowers())) { + throw new IllegalArgumentException(String.format("to many followers, %s", slotBuilder)); + } + buildingSlots.put(slotId, slotBuilder); } - - public SlotTableBuilder addFollower(int slotId, String follower) { - SlotBuilder slotBuilder = getOrCreate(slotId); - if (!slotBuilder.addFollower(follower)) { - throw new IllegalArgumentException(String.format("to many followers, %s", slotBuilder)); - } - DataNodeSlot dataNodeSlot = reverseMap.computeIfAbsent(follower, - k->new DataNodeSlot(follower)); + initReverseMap(dataServers); + } + + private void initReverseMap(List dataServers) { + for (int slotId = 0; slotId < slotNums; slotId++) { + SlotBuilder slotBuilder = getOrCreate(slotId); + String leader = slotBuilder.getLeader(); + if (leader != null) { + DataNodeSlot dataNodeSlot = + reverseMap.computeIfAbsent(leader, k -> new DataNodeSlot(leader)); + dataNodeSlot.addLeader(slotId); + } + Set followers = slotBuilder.getFollowers(); + for (String follower : followers) { + DataNodeSlot dataNodeSlot = + reverseMap.computeIfAbsent(follower, k -> new DataNodeSlot(follower)); dataNodeSlot.addFollower(slotId); - return this; - } - - public List getDataServersOwnsFollower(int followerSlot) { - SlotBuilder slotBuilder = getOrCreate(followerSlot); - return Lists.newArrayList(slotBuilder.getFollowers()); + } } - - public String getDataServersOwnsLeader(int leaderSlot) { - SlotBuilder slotBuilder = getOrCreate(leaderSlot); - return slotBuilder.getLeader(); - } - - public boolean hasNoAssignedSlots() { - if (buildingSlots.size() < slotNums) { - return true; - } - for (SlotBuilder slotBuilder : buildingSlots.values()) { - if (StringUtils.isEmpty(slotBuilder.getLeader())) { - return true; - } - if (slotBuilder.getFollowerSize() < followerNums) { - return true; - } - } - return false; + if (CollectionUtils.isEmpty(dataServers)) { + return; } - - public void removeDataServerSlots(String dataServer) { - for (SlotBuilder slotBuilder : buildingSlots.values()) { - if (slotBuilder.removeFollower(dataServer)) { - logger.info("[removeDataServerSlots] slot [{}] remove follower data-server[{}]", - slotBuilder.getSlotId(), dataServer); - } - if (dataServer.equals(slotBuilder.getLeader())) { - logger.info("[removeDataServerSlots] slot [{}] remove leader data-server[{}]", - slotBuilder.getSlotId(), dataServer); - slotBuilder.setLeader(null); - } - } - reverseMap.remove(dataServer); + dataServers.forEach( + dataServer -> reverseMap.putIfAbsent(dataServer, new DataNodeSlot(dataServer))); + } + + public String replaceLeader(int slotId, String nextLeader) { + SlotBuilder slotBuilder = getOrCreate(slotId); + String prevLeader = slotBuilder.getLeader(); + slotBuilder.setLeader(nextLeader).removeFollower(nextLeader); + DataNodeSlot nextLeaderDataNodeSlot = + reverseMap.computeIfAbsent(nextLeader, k -> new DataNodeSlot(nextLeader)); + nextLeaderDataNodeSlot.addLeader(slotId); + nextLeaderDataNodeSlot.removeFollower(slotId); + if (!StringUtils.isEmpty(prevLeader)) { + reverseMap.get(prevLeader).removeLeader(slotId); } + return prevLeader; + } - public MigrateSlotGroup getNoAssignedSlots() { - MigrateSlotGroup migrateSlotGroup = new MigrateSlotGroup(); - for (int slotId = 0; slotId < slotNums; slotId++) { - SlotBuilder slotBuilder = getOrCreate(slotId); - if (StringUtils.isEmpty(slotBuilder.getLeader())) { - migrateSlotGroup.addLeader(slotId); - } - int lackFollowerNums = followerNums - slotBuilder.getFollowers().size(); - if (lackFollowerNums > 0) { - migrateSlotGroup.addFollower(slotId, lackFollowerNums); - } - } - return migrateSlotGroup; + public SlotTableBuilder removeFollower(int slotId, String follower) { + SlotBuilder slotBuilder = getOrCreate(slotId); + if (slotBuilder.removeFollower(follower)) { + reverseMap.get(follower).removeFollower(slotId); } + return this; + } - public List getDataNodeSlotsLeaderBeyond(int num) { - return reverseMap.values() - .stream() - .filter(dataNodeSlot -> {return dataNodeSlot.getLeaders().size() > num;}) - .collect(Collectors.toList()); + public SlotTableBuilder addFollower(int slotId, String follower) { + SlotBuilder slotBuilder = getOrCreate(slotId); + if (!slotBuilder.addFollower(follower)) { + throw new IllegalArgumentException(String.format("to many followers, %s", slotBuilder)); } - - public List getDataNodeSlotsLeaderBelow(int num) { - return reverseMap.values() - .stream() - .filter(dataNodeSlot -> {return dataNodeSlot.getLeaders().size() < num;}) - .collect(Collectors.toList()); + DataNodeSlot dataNodeSlot = + reverseMap.computeIfAbsent(follower, k -> new DataNodeSlot(follower)); + dataNodeSlot.addFollower(slotId); + return this; + } + + public List getDataServersOwnsFollower(int followerSlot) { + SlotBuilder slotBuilder = getOrCreate(followerSlot); + return Lists.newArrayList(slotBuilder.getFollowers()); + } + + public String getDataServersOwnsLeader(int leaderSlot) { + SlotBuilder slotBuilder = getOrCreate(leaderSlot); + return slotBuilder.getLeader(); + } + + public boolean hasNoAssignedSlots() { + if (buildingSlots.size() < slotNums) { + return true; } - - public List getDataNodeSlotsFollowerBeyond(int num) { - return reverseMap.values() - .stream() - .filter(dataNodeSlot -> {return dataNodeSlot.getFollowers().size() > num;}) - .collect(Collectors.toList()); + for (SlotBuilder slotBuilder : buildingSlots.values()) { + if (StringUtils.isEmpty(slotBuilder.getLeader())) { + return true; + } + if (slotBuilder.getFollowerSize() < followerNums) { + return true; + } } - - public List getDataNodeSlotsFollowerBelow(int num) { - return reverseMap.values() - .stream() - .filter(dataNodeSlot -> {return dataNodeSlot.getFollowers().size() < num;}) - .collect(Collectors.toList()); + return false; + } + + public void removeDataServerSlots(String dataServer) { + for (SlotBuilder slotBuilder : buildingSlots.values()) { + if (slotBuilder.removeFollower(dataServer)) { + logger.info( + "[removeDataServerSlots] slot [{}] remove follower data-server[{}]", + slotBuilder.getSlotId(), + dataServer); + } + if (dataServer.equals(slotBuilder.getLeader())) { + logger.info( + "[removeDataServerSlots] slot [{}] remove leader data-server[{}]", + slotBuilder.getSlotId(), + dataServer); + slotBuilder.setLeader(null); + } } - - public void incrEpoch() { - this.epoch = DatumVersionUtil.nextId(); + reverseMap.remove(dataServer); + } + + public MigrateSlotGroup getNoAssignedSlots() { + MigrateSlotGroup migrateSlotGroup = new MigrateSlotGroup(); + for (int slotId = 0; slotId < slotNums; slotId++) { + SlotBuilder slotBuilder = getOrCreate(slotId); + if (StringUtils.isEmpty(slotBuilder.getLeader())) { + migrateSlotGroup.addLeader(slotId); + } + int lackFollowerNums = followerNums - slotBuilder.getFollowers().size(); + if (lackFollowerNums > 0) { + migrateSlotGroup.addFollower(slotId, lackFollowerNums); + } } - - @Override - public SlotTable build() { - Map stableSlots = Maps.newHashMap(); - buildingSlots.forEach((slotId, slotBuilder)->{ - stableSlots.put(slotId, slotBuilder.build()); - epoch= Math.max(epoch, stableSlots.get(slotId).getLeaderEpoch()); + return migrateSlotGroup; + } + + public List getDataNodeSlotsLeaderBeyond(int num) { + return reverseMap.values().stream() + .filter( + dataNodeSlot -> { + return dataNodeSlot.getLeaders().size() > num; + }) + .collect(Collectors.toList()); + } + + public List getDataNodeSlotsLeaderBelow(int num) { + return reverseMap.values().stream() + .filter( + dataNodeSlot -> { + return dataNodeSlot.getLeaders().size() < num; + }) + .collect(Collectors.toList()); + } + + public List getDataNodeSlotsFollowerBeyond(int num) { + return reverseMap.values().stream() + .filter( + dataNodeSlot -> { + return dataNodeSlot.getFollowers().size() > num; + }) + .collect(Collectors.toList()); + } + + public List getDataNodeSlotsFollowerBelow(int num) { + return reverseMap.values().stream() + .filter( + dataNodeSlot -> { + return dataNodeSlot.getFollowers().size() < num; + }) + .collect(Collectors.toList()); + } + + public void incrEpoch() { + this.epoch = DatumVersionUtil.nextId(); + } + + @Override + public SlotTable build() { + Map stableSlots = Maps.newHashMap(); + buildingSlots.forEach( + (slotId, slotBuilder) -> { + stableSlots.put(slotId, slotBuilder.build()); + epoch = Math.max(epoch, stableSlots.get(slotId).getLeaderEpoch()); }); - return new SlotTable(epoch, stableSlots.values()); - } - - public DataNodeSlot getDataNodeSlot(String dataServer) { - DataNodeSlot dataNodeSlot = getDataNodeSlotIfPresent(dataServer); - if (dataNodeSlot == null) { - throw new IllegalArgumentException("no DataNodeSlot for " + dataServer); - } - return dataNodeSlot; - } + return new SlotTable(epoch, stableSlots.values()); + } - public DataNodeSlot getDataNodeSlotIfPresent(String dataServer) { - return reverseMap.get(dataServer); + public DataNodeSlot getDataNodeSlot(String dataServer) { + DataNodeSlot dataNodeSlot = getDataNodeSlotIfPresent(dataServer); + if (dataNodeSlot == null) { + throw new IllegalArgumentException("no DataNodeSlot for " + dataServer); } - - @Override - public String toString() { - try { - return JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() - .writeValueAsString(this); - } catch (JsonProcessingException e) { - return ""; - } + return dataNodeSlot; + } + + public DataNodeSlot getDataNodeSlotIfPresent(String dataServer) { + return reverseMap.get(dataServer); + } + + @Override + public String toString() { + try { + return JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() + .writeValueAsString(this); + } catch (JsonProcessingException e) { + return ""; } + } - public SlotTable getInitSlotTable() { - return initSlotTable; - } + public SlotTable getInitSlotTable() { + return initSlotTable; + } - public int getSlotNums() { - return slotNums; - } + public int getSlotNums() { + return slotNums; + } - public int getSlotReplicas() { - return followerNums + 1; - } + public int getSlotReplicas() { + return followerNums + 1; + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/comparator/Comparators.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/comparator/Comparators.java index 584c1f525..4c732c5b6 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/comparator/Comparators.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/comparator/Comparators.java @@ -18,152 +18,152 @@ import com.alipay.sofa.registry.common.model.slot.DataNodeSlot; import com.alipay.sofa.registry.server.meta.slot.util.builder.SlotTableBuilder; - import java.util.Collection; import java.util.Collections; import java.util.Comparator; /** * @author chen.zhu - *

- * Jan 27, 2021 + *

Jan 27, 2021 */ public class Comparators { - public static DataServerFollowerSizeComparator mostFollowersFirst(SlotTableBuilder slotTableBuilder) { - return new DataServerFollowerSizeComparator(slotTableBuilder, SortType.DES); - } + public static DataServerFollowerSizeComparator mostFollowersFirst( + SlotTableBuilder slotTableBuilder) { + return new DataServerFollowerSizeComparator(slotTableBuilder, SortType.DES); + } - public static DataServerFollowerSizeComparator leastFollowersFirst(SlotTableBuilder slotTableBuilder) { - return new DataServerFollowerSizeComparator(slotTableBuilder, SortType.ASC); - } + public static DataServerFollowerSizeComparator leastFollowersFirst( + SlotTableBuilder slotTableBuilder) { + return new DataServerFollowerSizeComparator(slotTableBuilder, SortType.ASC); + } - public static DataServerLeaderSizeComparator mostLeadersFirst(SlotTableBuilder slotTableBuilder) { - return new DataServerLeaderSizeComparator(slotTableBuilder, SortType.DES); - } + public static DataServerLeaderSizeComparator mostLeadersFirst(SlotTableBuilder slotTableBuilder) { + return new DataServerLeaderSizeComparator(slotTableBuilder, SortType.DES); + } - public static DataServerLeaderSizeComparator leastLeadersFirst(SlotTableBuilder slotTableBuilder) { - return new DataServerLeaderSizeComparator(slotTableBuilder, SortType.ASC); - } + public static DataServerLeaderSizeComparator leastLeadersFirst( + SlotTableBuilder slotTableBuilder) { + return new DataServerLeaderSizeComparator(slotTableBuilder, SortType.ASC); + } - public static SlotLeaderRelateDataServerLeaderSizeComparator slotLeaderHasMostLeaderSlots(SlotTableBuilder slotTableBuilder) { - return new SlotLeaderRelateDataServerLeaderSizeComparator(slotTableBuilder, SortType.DES); - } + public static SlotLeaderRelateDataServerLeaderSizeComparator slotLeaderHasMostLeaderSlots( + SlotTableBuilder slotTableBuilder) { + return new SlotLeaderRelateDataServerLeaderSizeComparator(slotTableBuilder, SortType.DES); + } - public static abstract class AbstractSlotComparator implements Comparator { + public abstract static class AbstractSlotComparator implements Comparator { - protected SlotTableBuilder slotTableBuilder; + protected SlotTableBuilder slotTableBuilder; - protected SortType sortType; + protected SortType sortType; + + public AbstractSlotComparator(SlotTableBuilder slotTableBuilder, SortType sortType) { + this.slotTableBuilder = slotTableBuilder; + this.sortType = sortType; + } + } - public AbstractSlotComparator(SlotTableBuilder slotTableBuilder, SortType sortType) { - this.slotTableBuilder = slotTableBuilder; - this.sortType = sortType; - } + /** + * ---------------------------------- Data Server Comparators + * -------------------------------------------- + */ + public abstract static class AbstractDataServerComparator extends AbstractSlotComparator { + public AbstractDataServerComparator(SlotTableBuilder slotTableBuilder, SortType sortType) { + super(slotTableBuilder, sortType); } - /** - * ---------------------------------- Data Server Comparators -------------------------------------------- - * */ - public static abstract class AbstractDataServerComparator extends - AbstractSlotComparator { - - public AbstractDataServerComparator(SlotTableBuilder slotTableBuilder, SortType sortType) { - super(slotTableBuilder, sortType); - } - - @Override - public int compare(String dataServer1, String dataServer2) { - DataNodeSlot dataNodeSlot1 = slotTableBuilder.getDataNodeSlot(dataServer1); - DataNodeSlot dataNodeSlot2 = slotTableBuilder.getDataNodeSlot(dataServer2); - int score = getFirstClassMember(dataNodeSlot1).size() - - getFirstClassMember(dataNodeSlot2).size(); - if (score == 0) { - score = getEconomyMember(dataNodeSlot1).size() - - getEconomyMember(dataNodeSlot2).size(); - } - return sortType.getScore(score); - } - - protected Collection getFirstClassMember(DataNodeSlot dataNodeSlot) { - return Collections.emptyList(); - } - - protected Collection getEconomyMember(DataNodeSlot dataNodeSlot) { - return Collections.emptyList(); - }; + @Override + public int compare(String dataServer1, String dataServer2) { + DataNodeSlot dataNodeSlot1 = slotTableBuilder.getDataNodeSlot(dataServer1); + DataNodeSlot dataNodeSlot2 = slotTableBuilder.getDataNodeSlot(dataServer2); + int score = + getFirstClassMember(dataNodeSlot1).size() - getFirstClassMember(dataNodeSlot2).size(); + if (score == 0) { + score = getEconomyMember(dataNodeSlot1).size() - getEconomyMember(dataNodeSlot2).size(); + } + return sortType.getScore(score); } - public static class DataServerFollowerSizeComparator extends AbstractDataServerComparator { + protected Collection getFirstClassMember(DataNodeSlot dataNodeSlot) { + return Collections.emptyList(); + } - public DataServerFollowerSizeComparator(SlotTableBuilder slotTableBuilder, SortType sortType) { - super(slotTableBuilder, sortType); - } + protected Collection getEconomyMember(DataNodeSlot dataNodeSlot) { + return Collections.emptyList(); + }; + } - @Override - protected Collection getFirstClassMember(DataNodeSlot dataNodeSlot) { - return dataNodeSlot.getFollowers(); - } + public static class DataServerFollowerSizeComparator extends AbstractDataServerComparator { - @Override - protected Collection getEconomyMember(DataNodeSlot dataNodeSlot) { - return dataNodeSlot.getLeaders(); - } + public DataServerFollowerSizeComparator(SlotTableBuilder slotTableBuilder, SortType sortType) { + super(slotTableBuilder, sortType); } - public static class DataServerLeaderSizeComparator extends AbstractDataServerComparator { + @Override + protected Collection getFirstClassMember(DataNodeSlot dataNodeSlot) { + return dataNodeSlot.getFollowers(); + } - public DataServerLeaderSizeComparator(SlotTableBuilder slotTableBuilder, SortType sortType) { - super(slotTableBuilder, sortType); - } + @Override + protected Collection getEconomyMember(DataNodeSlot dataNodeSlot) { + return dataNodeSlot.getLeaders(); + } + } - @Override - protected Collection getFirstClassMember(DataNodeSlot dataNodeSlot) { - return dataNodeSlot.getLeaders(); - } + public static class DataServerLeaderSizeComparator extends AbstractDataServerComparator { - @Override - protected Collection getEconomyMember(DataNodeSlot dataNodeSlot) { - return dataNodeSlot.getFollowers(); - } + public DataServerLeaderSizeComparator(SlotTableBuilder slotTableBuilder, SortType sortType) { + super(slotTableBuilder, sortType); } - /** - * ---------------------------------- Slot Comparators -------------------------------------------- - * */ + @Override + protected Collection getFirstClassMember(DataNodeSlot dataNodeSlot) { + return dataNodeSlot.getLeaders(); + } - public static abstract class AbstractSlotNumberComparator extends - AbstractSlotComparator { + @Override + protected Collection getEconomyMember(DataNodeSlot dataNodeSlot) { + return dataNodeSlot.getFollowers(); + } + } - public AbstractSlotNumberComparator(SlotTableBuilder slotTableBuilder, SortType sortType) { - super(slotTableBuilder, sortType); - } + /** + * ---------------------------------- Slot Comparators + * -------------------------------------------- + */ + public abstract static class AbstractSlotNumberComparator + extends AbstractSlotComparator { - @Override - public int compare(Integer slotId1, Integer slotId2) { - String dataServer1 = slotTableBuilder.getOrCreate(slotId1).getLeader(); - String dataServer2 = slotTableBuilder.getOrCreate(slotId2).getLeader(); - return getDataServerComparator().compare(dataServer1, dataServer2); - } + public AbstractSlotNumberComparator(SlotTableBuilder slotTableBuilder, SortType sortType) { + super(slotTableBuilder, sortType); + } - protected abstract AbstractDataServerComparator getDataServerComparator(); + @Override + public int compare(Integer slotId1, Integer slotId2) { + String dataServer1 = slotTableBuilder.getOrCreate(slotId1).getLeader(); + String dataServer2 = slotTableBuilder.getOrCreate(slotId2).getLeader(); + return getDataServerComparator().compare(dataServer1, dataServer2); } - public static class SlotLeaderRelateDataServerLeaderSizeComparator extends - AbstractSlotNumberComparator { + protected abstract AbstractDataServerComparator getDataServerComparator(); + } - private final AbstractDataServerComparator dataServerComparator; + public static class SlotLeaderRelateDataServerLeaderSizeComparator + extends AbstractSlotNumberComparator { - public SlotLeaderRelateDataServerLeaderSizeComparator(SlotTableBuilder slotTableBuilder, - SortType sortType) { - super(slotTableBuilder, sortType); - dataServerComparator = new DataServerLeaderSizeComparator(slotTableBuilder, sortType); - } + private final AbstractDataServerComparator dataServerComparator; + + public SlotLeaderRelateDataServerLeaderSizeComparator( + SlotTableBuilder slotTableBuilder, SortType sortType) { + super(slotTableBuilder, sortType); + dataServerComparator = new DataServerLeaderSizeComparator(slotTableBuilder, sortType); + } - @Override - protected AbstractDataServerComparator getDataServerComparator() { - return dataServerComparator; - } + @Override + protected AbstractDataServerComparator getDataServerComparator() { + return dataServerComparator; } + } } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/comparator/SortType.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/comparator/SortType.java index 89d7bb751..2f9ef3242 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/comparator/SortType.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/comparator/SortType.java @@ -18,23 +18,21 @@ /** * @author chen.zhu - *

- * Jan 18, 2021 + *

Jan 18, 2021 */ public enum SortType { + ASC { + @Override + public int getScore(int score) { + return score; + } + }, + DES { + @Override + public int getScore(int score) { + return -score; + } + }; - ASC { - @Override - public int getScore(int score) { - return score; - } - }, - DES { - @Override - public int getScore(int score) { - return -score; - } - }; - - public abstract int getScore(int score); + public abstract int getScore(int score); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/selector/Selector.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/selector/Selector.java index 50b333bd6..aa8b5f26a 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/selector/Selector.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/selector/Selector.java @@ -20,10 +20,9 @@ /** * @author chen.zhu - *

- * Jan 15, 2021 + *

Jan 15, 2021 */ public interface Selector { - T select(Collection candidates); + T select(Collection candidates); } diff --git a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/selector/Selectors.java b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/selector/Selectors.java index 72e66bc66..71054b0b0 100644 --- a/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/selector/Selectors.java +++ b/server/server/meta/src/main/java/com/alipay/sofa/registry/server/meta/slot/util/selector/Selectors.java @@ -19,134 +19,129 @@ import com.alipay.sofa.registry.server.meta.slot.util.builder.SlotTableBuilder; import com.alipay.sofa.registry.server.meta.slot.util.comparator.Comparators; import com.google.common.collect.Lists; - import java.util.Collection; import java.util.List; import java.util.Set; /** * @author chen.zhu - *

- * Jan 27, 2021 + *

Jan 27, 2021 */ public class Selectors { - public static DefaultSlotLeaderSelector slotLeaderSelector(SlotTableBuilder slotTableBuilder, - int slotId) { - return new DefaultSlotLeaderSelector(slotTableBuilder, slotId); - } + public static DefaultSlotLeaderSelector slotLeaderSelector( + SlotTableBuilder slotTableBuilder, int slotId) { + return new DefaultSlotLeaderSelector(slotTableBuilder, slotId); + } - public static MostLeaderFirstSelector mostLeaderFirst(SlotTableBuilder slotTableBuilder) { - return new MostLeaderFirstSelector(slotTableBuilder); - } + public static MostLeaderFirstSelector mostLeaderFirst(SlotTableBuilder slotTableBuilder) { + return new MostLeaderFirstSelector(slotTableBuilder); + } - public static abstract class AbstractSlotTableBuilderAwareSelector implements Selector { + public abstract static class AbstractSlotTableBuilderAwareSelector implements Selector { - protected final SlotTableBuilder slotTableBuilder; + protected final SlotTableBuilder slotTableBuilder; - public AbstractSlotTableBuilderAwareSelector(SlotTableBuilder slotTableBuilder) { - this.slotTableBuilder = slotTableBuilder; - } + public AbstractSlotTableBuilderAwareSelector(SlotTableBuilder slotTableBuilder) { + this.slotTableBuilder = slotTableBuilder; } + } - public static abstract class AbstractDataServerSelector - extends - AbstractSlotTableBuilderAwareSelector { + public abstract static class AbstractDataServerSelector + extends AbstractSlotTableBuilderAwareSelector { - public AbstractDataServerSelector(SlotTableBuilder slotTableBuilder) { - super(slotTableBuilder); - } - - @Override - public String select(Collection candidates) { - List sortedCandidates = Lists.newArrayList(candidates); - sortedCandidates.sort(getDataServerComparator()); - return sortedCandidates.isEmpty() ? null : sortedCandidates.get(0); - } - - protected abstract Comparators.AbstractDataServerComparator getDataServerComparator(); + public AbstractDataServerSelector(SlotTableBuilder slotTableBuilder) { + super(slotTableBuilder); + } + @Override + public String select(Collection candidates) { + List sortedCandidates = Lists.newArrayList(candidates); + sortedCandidates.sort(getDataServerComparator()); + return sortedCandidates.isEmpty() ? null : sortedCandidates.get(0); } - public static class MostFollowerFirstSelector extends AbstractDataServerSelector { + protected abstract Comparators.AbstractDataServerComparator getDataServerComparator(); + } - private final Comparators.AbstractDataServerComparator comparator; + public static class MostFollowerFirstSelector extends AbstractDataServerSelector { - public MostFollowerFirstSelector(SlotTableBuilder slotTableBuilder) { - super(slotTableBuilder); - this.comparator = Comparators.mostFollowersFirst(slotTableBuilder); - } + private final Comparators.AbstractDataServerComparator comparator; - @Override - protected Comparators.AbstractDataServerComparator getDataServerComparator() { - return comparator; - } + public MostFollowerFirstSelector(SlotTableBuilder slotTableBuilder) { + super(slotTableBuilder); + this.comparator = Comparators.mostFollowersFirst(slotTableBuilder); } - public static class LeastFollowerFirstSelector extends AbstractDataServerSelector { + @Override + protected Comparators.AbstractDataServerComparator getDataServerComparator() { + return comparator; + } + } - private final Comparators.AbstractDataServerComparator comparator; + public static class LeastFollowerFirstSelector extends AbstractDataServerSelector { - public LeastFollowerFirstSelector(SlotTableBuilder slotTableBuilder) { - super(slotTableBuilder); - this.comparator = Comparators.leastFollowersFirst(slotTableBuilder); - } + private final Comparators.AbstractDataServerComparator comparator; - @Override - protected Comparators.AbstractDataServerComparator getDataServerComparator() { - return comparator; - } + public LeastFollowerFirstSelector(SlotTableBuilder slotTableBuilder) { + super(slotTableBuilder); + this.comparator = Comparators.leastFollowersFirst(slotTableBuilder); } - public static class LeastLeaderFirstSelector extends AbstractDataServerSelector { + @Override + protected Comparators.AbstractDataServerComparator getDataServerComparator() { + return comparator; + } + } - private final Comparators.AbstractDataServerComparator comparator; + public static class LeastLeaderFirstSelector extends AbstractDataServerSelector { - public LeastLeaderFirstSelector(SlotTableBuilder slotTableBuilder) { - super(slotTableBuilder); - this.comparator = Comparators.leastLeadersFirst(slotTableBuilder); - } + private final Comparators.AbstractDataServerComparator comparator; - @Override - protected Comparators.AbstractDataServerComparator getDataServerComparator() { - return comparator; - } + public LeastLeaderFirstSelector(SlotTableBuilder slotTableBuilder) { + super(slotTableBuilder); + this.comparator = Comparators.leastLeadersFirst(slotTableBuilder); } - public static class MostLeaderFirstSelector extends AbstractDataServerSelector { + @Override + protected Comparators.AbstractDataServerComparator getDataServerComparator() { + return comparator; + } + } - private final Comparators.AbstractDataServerComparator comparator; + public static class MostLeaderFirstSelector extends AbstractDataServerSelector { - public MostLeaderFirstSelector(SlotTableBuilder slotTableBuilder) { - super(slotTableBuilder); - comparator = Comparators.mostLeadersFirst(slotTableBuilder); - } + private final Comparators.AbstractDataServerComparator comparator; - @Override - protected Comparators.AbstractDataServerComparator getDataServerComparator() { - return comparator; - } + public MostLeaderFirstSelector(SlotTableBuilder slotTableBuilder) { + super(slotTableBuilder); + comparator = Comparators.mostLeadersFirst(slotTableBuilder); } - public static class DefaultSlotLeaderSelector implements Selector { + @Override + protected Comparators.AbstractDataServerComparator getDataServerComparator() { + return comparator; + } + } - private final SlotTableBuilder slotTableBuilder; + public static class DefaultSlotLeaderSelector implements Selector { - private final int slotId; + private final SlotTableBuilder slotTableBuilder; - public DefaultSlotLeaderSelector(SlotTableBuilder slotTableBuilder, int slotId) { - this.slotTableBuilder = slotTableBuilder; - this.slotId = slotId; - } + private final int slotId; - @Override - public String select(Collection candidates) { - Set currentFollowers = slotTableBuilder.getOrCreate(slotId).getFollowers(); - Collection followerCandidates = Lists.newArrayList(candidates); - followerCandidates.retainAll(currentFollowers); - followerCandidates = followerCandidates.isEmpty() ? candidates : followerCandidates; - return new LeastLeaderFirstSelector(slotTableBuilder).select(followerCandidates); - } + public DefaultSlotLeaderSelector(SlotTableBuilder slotTableBuilder, int slotId) { + this.slotTableBuilder = slotTableBuilder; + this.slotId = slotId; + } + @Override + public String select(Collection candidates) { + Set currentFollowers = slotTableBuilder.getOrCreate(slotId).getFollowers(); + Collection followerCandidates = Lists.newArrayList(candidates); + followerCandidates.retainAll(currentFollowers); + followerCandidates = followerCandidates.isEmpty() ? candidates : followerCandidates; + return new LeastLeaderFirstSelector(slotTableBuilder).select(followerCandidates); } + } } diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/AllTests.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/AllTests.java index a841e8fd9..cd2e95d80 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/AllTests.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/AllTests.java @@ -18,10 +18,8 @@ /** * @author chen.zhu - *

- * Nov 13, 2020 + *

Nov 13, 2020 */ - import com.alipay.sofa.registry.common.model.slot.Crc32CSlotFunctionTest; import com.alipay.sofa.registry.server.meta.cluster.node.NodeModifiedTest; import com.alipay.sofa.registry.server.meta.cluster.node.TestAbstractNodeEventTest; @@ -55,20 +53,35 @@ import org.junit.runners.Suite; @RunWith(Suite.class) -@Suite.SuiteClasses({ Crc32CSlotFunctionTest.class, DefaultCrossDcMetaServerTest.class, - CrossDcSlotAllocatorTest.class, DefaultCurrentDcMetaServerTest.class, - DefaultSessionServerManagerTest.class, DefaultDataServerManagerTest.class, - CrossDcMetaServerManagerTest.class, - LeaseTest.class, HeartbeatRequestHandlerTest.class, - DefaultMetaServerManagerTest.class, DefaultDataServerServiceTest.class, - LocalMetaServerTest.class, DefaultSessionServerServiceTest.class, - DefaultProvideDataNotifierTest.class, SimpleSlotManagerTest.class, - NodeModifiedTest.class, BalanceTaskTest.class, - TestAbstractNodeEventTest.class, DefaultSlotManagerTest.class, - DefaultSlotTableMonitorTest.class, DiskSlotTableRecorderTest.class, - SlotTableResourceTest.class, SlotMigrationIntegrationTest.class, - SlotTableBuilderTest.class, SlotBuilderTest.class, - NodeComparatorTest.class, MigrateSlotGroupTest.class, - ScheduledSlotArrangerTest.class, LeaderOnlyBalancerTest.class }) -public class AllTests { -} +@Suite.SuiteClasses({ + Crc32CSlotFunctionTest.class, + DefaultCrossDcMetaServerTest.class, + CrossDcSlotAllocatorTest.class, + DefaultCurrentDcMetaServerTest.class, + DefaultSessionServerManagerTest.class, + DefaultDataServerManagerTest.class, + CrossDcMetaServerManagerTest.class, + LeaseTest.class, + HeartbeatRequestHandlerTest.class, + DefaultMetaServerManagerTest.class, + DefaultDataServerServiceTest.class, + LocalMetaServerTest.class, + DefaultSessionServerServiceTest.class, + DefaultProvideDataNotifierTest.class, + SimpleSlotManagerTest.class, + NodeModifiedTest.class, + BalanceTaskTest.class, + TestAbstractNodeEventTest.class, + DefaultSlotManagerTest.class, + DefaultSlotTableMonitorTest.class, + DiskSlotTableRecorderTest.class, + SlotTableResourceTest.class, + SlotMigrationIntegrationTest.class, + SlotTableBuilderTest.class, + SlotBuilderTest.class, + NodeComparatorTest.class, + MigrateSlotGroupTest.class, + ScheduledSlotArrangerTest.class, + LeaderOnlyBalancerTest.class +}) +public class AllTests {} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/common/model/slot/BaseSlotFunctionTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/common/model/slot/BaseSlotFunctionTest.java index fb191acdc..5df073977 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/common/model/slot/BaseSlotFunctionTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/common/model/slot/BaseSlotFunctionTest.java @@ -19,20 +19,19 @@ import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; import com.alipay.sofa.registry.util.FileUtils; import com.alipay.sofa.registry.util.JsonUtils; - import java.io.File; import java.io.IOException; /** * @author chen.zhu - *

- * Jan 13, 2021 + *

Jan 13, 2021 */ public class BaseSlotFunctionTest extends AbstractMetaServerTest { - public String[] getDataInfoIds() throws IOException { - String fileContent = new String(FileUtils.readFileToByteArray(new File( - "src/test/resources/test/data_info_ids.json"))); - return JsonUtils.read(fileContent, String[].class); - } + public String[] getDataInfoIds() throws IOException { + String fileContent = + new String( + FileUtils.readFileToByteArray(new File("src/test/resources/test/data_info_ids.json"))); + return JsonUtils.read(fileContent, String[].class); + } } diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/common/model/slot/Crc32CSlotFunctionTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/common/model/slot/Crc32CSlotFunctionTest.java index 5586bf62a..aca9f012c 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/common/model/slot/Crc32CSlotFunctionTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/common/model/slot/Crc32CSlotFunctionTest.java @@ -19,68 +19,70 @@ import com.alipay.sofa.registry.common.model.slot.func.Crc32cSlotFunction; import com.alipay.sofa.registry.util.JsonUtils; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; - import java.io.IOException; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; public class Crc32CSlotFunctionTest extends BaseSlotFunctionTest { - private Crc32cSlotFunction slotFunction; + private Crc32cSlotFunction slotFunction; - @Before - public void beforeCRC32SlotFunctionTest() { - slotFunction = new Crc32cSlotFunction(); - } + @Before + public void beforeCRC32SlotFunctionTest() { + slotFunction = new Crc32cSlotFunction(); + } - @Test - public void testMaxSlots() { - Assert.assertEquals(SlotConfig.SLOT_NUM, slotFunction.maxSlots()); - } + @Test + public void testMaxSlots() { + Assert.assertEquals(SlotConfig.SLOT_NUM, slotFunction.maxSlots()); + } - @Test - public void testSlotOfMultiThreadSafe() throws InterruptedException { - int tasks = 100; - final String mark = randomString(); - int expected = slotFunction.slotOf(mark); - CyclicBarrier barrier = new CyclicBarrier(tasks); - CountDownLatch latch = new CountDownLatch(tasks); - for (int i = 0; i < tasks; i++) { - executors.execute(new Runnable() { - @Override - public void run() { - try { - barrier.await(); - } catch (Exception e) { - } - Assert.assertEquals(expected, slotFunction.slotOf(mark)); - latch.countDown(); - } - }); - } - latch.await(); + @Test + public void testSlotOfMultiThreadSafe() throws InterruptedException { + int tasks = 100; + final String mark = randomString(); + int expected = slotFunction.slotOf(mark); + CyclicBarrier barrier = new CyclicBarrier(tasks); + CountDownLatch latch = new CountDownLatch(tasks); + for (int i = 0; i < tasks; i++) { + executors.execute( + new Runnable() { + @Override + public void run() { + try { + barrier.await(); + } catch (Exception e) { + } + Assert.assertEquals(expected, slotFunction.slotOf(mark)); + latch.countDown(); + } + }); } + latch.await(); + } - @Test - public void testBalance() throws IOException { - String[] dataInfoIds = getDataInfoIds(); - int slotNums = 256; - Map counter = Maps.newHashMap(); - for (int i = 0; i < slotNums; i++) { - counter.put(i, 0); - } - slotFunction = new Crc32cSlotFunction(slotNums); - logger.info("[length] {}", dataInfoIds.length); - for (String dataInfoId : dataInfoIds) { - int slotId = slotFunction.slotOf(dataInfoId); - counter.put(slotId, counter.get(slotId) + 1); - } - logger.info("[result]\n{}", JsonUtils.getJacksonObjectMapper() - .writerWithDefaultPrettyPrinter().writeValueAsString(counter)); + @Test + public void testBalance() throws IOException { + String[] dataInfoIds = getDataInfoIds(); + int slotNums = 256; + Map counter = Maps.newHashMap(); + for (int i = 0; i < slotNums; i++) { + counter.put(i, 0); } - -} \ No newline at end of file + slotFunction = new Crc32cSlotFunction(slotNums); + logger.info("[length] {}", dataInfoIds.length); + for (String dataInfoId : dataInfoIds) { + int slotId = slotFunction.slotOf(dataInfoId); + counter.put(slotId, counter.get(slotId) + 1); + } + logger.info( + "[result]\n{}", + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() + .writeValueAsString(counter)); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractH2DbTestBase.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractH2DbTestBase.java index d1e3c19f7..e48bfb7ce 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractH2DbTestBase.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractH2DbTestBase.java @@ -19,11 +19,15 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.util.FileUtils; +import java.io.*; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; +import java.sql.SQLException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.util.Strings; import org.h2.tools.Server; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.springframework.beans.BeansException; @@ -31,164 +35,154 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.sql.DataSource; -import java.io.*; -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.Arrays; - /** * @author chen.zhu - *

- * Mar 15, 2021 + *

Mar 15, 2021 */ @ActiveProfiles("test") @SpringBootTest(classes = AbstractH2DbTestBase.JdbcTestConfig.class) @RunWith(SpringJUnit4ClassRunner.class) public class AbstractH2DbTestBase extends AbstractTest implements ApplicationContextAware { - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractH2DbTestBase.class); - public static final String TABLE_STRUCTURE = "sql/h2/create_table.sql"; - public static final String TABLE_DATA = "sql/h2/base_info.sql"; - - protected final String KEY_H2_PORT = "h2Port"; - private Server h2Server; + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractH2DbTestBase.class); + public static final String TABLE_STRUCTURE = "sql/h2/create_table.sql"; + public static final String TABLE_DATA = "sql/h2/base_info.sql"; + + protected final String KEY_H2_PORT = "h2Port"; + private Server h2Server; + + protected ApplicationContext applicationContext; + + @BeforeClass + public static void beforeAbstractH2DbTestBase() + throws SQLException, IOException, ClassNotFoundException { + createTables(); + } + + protected void startH2Server() throws SQLException { + + int h2Port = Integer.parseInt(System.getProperty(KEY_H2_PORT, "9123")); + h2Server = Server.createTcpServer("-tcpPort", String.valueOf(h2Port), "-tcpAllowOthers"); + h2Server.start(); + // new Console().runTool(); + } + + protected String prepareDatas() { + return ""; + } + + private static void createTables() throws ClassNotFoundException, SQLException, IOException { + String driver = "org.h2.Driver"; + Class.forName(driver); + String url = "jdbc:h2:mem:metadatadb;DB_CLOSE_DELAY=-1;MODE=MySQL;MV_STORE=FALSE"; + String username = "sa"; + String password = ""; + Connection connection = null; + try { + connection = DriverManager.getConnection(url, username, password); + executeSqlScript(connection, readFileAsString(TABLE_STRUCTURE)); + } finally { + if (connection != null) { + connection.close(); + } + } + } - protected ApplicationContext applicationContext; + public static String readFileAsString(String fileName) throws IOException { - @BeforeClass - public static void beforeAbstractH2DbTestBase() throws SQLException, IOException, ClassNotFoundException { - createTables(); + try (InputStream ins = getFileInputStream(fileName)) { + String fileContent = IOUtils.toString(ins); + return fileContent; } + } - protected void startH2Server() throws SQLException { + public static InputStream getFileInputStream(String fileName) throws FileNotFoundException { - int h2Port = Integer.parseInt(System.getProperty(KEY_H2_PORT, "9123")); - h2Server = Server.createTcpServer("-tcpPort", String.valueOf(h2Port), "-tcpAllowOthers"); - h2Server.start(); - // new Console().runTool(); - } + return getFileInputStream("./", fileName, FileUtils.class); + } - protected String prepareDatas() { - return ""; - } + public static InputStream getFileInputStream(String path, String fileName, Class clazz) + throws FileNotFoundException { - private static void createTables() throws ClassNotFoundException, SQLException, IOException { - String driver = "org.h2.Driver"; - Class.forName(driver); - String url = "jdbc:h2:mem:metadatadb;DB_CLOSE_DELAY=-1;MODE=MySQL;MV_STORE=FALSE"; - String username = "sa"; - String password = ""; - Connection connection = null; + File f = null; + if (path != null) { + f = new File(path + "/" + fileName); + if (f.exists()) { try { - connection = DriverManager.getConnection(url, username, password); - executeSqlScript(connection, readFileAsString(TABLE_STRUCTURE)); - } finally { - if (connection != null) { - connection.close(); - } + LOGGER.info("[getFileInputStream]{}", f.getAbsolutePath()); + return new FileInputStream(f); + } catch (IOException e) { + throw new IllegalArgumentException("file load fail:" + f, e); } + } } - public static String readFileAsString(String fileName) throws IOException{ - - try(InputStream ins = getFileInputStream(fileName)){ - String fileContent = IOUtils.toString(ins); - return fileContent; - } + // try file + f = new File(fileName); + if (f.exists()) { + try { + LOGGER.info("[getFileInputStream]{}", f.getAbsolutePath()); + return new FileInputStream(f); + } catch (IOException e) { + throw new IllegalArgumentException("file load fail:" + f, e); + } } - public static InputStream getFileInputStream(String fileName) throws FileNotFoundException { - - return getFileInputStream("./", fileName, FileUtils.class); + // try classpath + java.net.URL url = clazz.getResource(fileName); + if (url == null) { + url = clazz.getClassLoader().getResource(fileName); + } + if (url != null) { + try { + LOGGER.info("[load]{}", url); + return url.openStream(); + } catch (IOException e) { + throw new IllegalArgumentException("classpath load fail:" + url, e); + } } - public static InputStream getFileInputStream(String path, String fileName, Class clazz) throws FileNotFoundException{ - - File f = null; - if(path != null){ - f = new File(path+ "/" + fileName); - if(f.exists()){ - try { - LOGGER.info("[getFileInputStream]{}", f.getAbsolutePath()); - return new FileInputStream(f); - } catch (IOException e) { - throw new IllegalArgumentException("file load fail:" + f, e); - } - } - } - - //try file - f = new File(fileName); - if(f.exists()){ - try { - LOGGER.info("[getFileInputStream]{}", f.getAbsolutePath()); - return new FileInputStream(f); - } catch (IOException e) { - throw new IllegalArgumentException("file load fail:" + f, e); - } - } + throw new FileNotFoundException(path + "," + fileName); + } - //try classpath - java.net.URL url = clazz.getResource(fileName); - if(url == null){ - url = clazz.getClassLoader().getResource(fileName); - } - if(url != null){ - try { - LOGGER.info("[load]{}", url); - return url.openStream(); - } catch (IOException e) { - throw new IllegalArgumentException("classpath load fail:" + url, e); - } - } - - throw new FileNotFoundException(path + "," + fileName); + protected static void executeSqlScript(Connection conn, String prepareSql) throws SQLException { + if (StringUtils.isEmpty(prepareSql)) { + return; } - - protected static void executeSqlScript(Connection conn, String prepareSql) throws SQLException { - if (StringUtils.isEmpty(prepareSql)) { - return; - } - PreparedStatement stmt = null; - try { - conn.setAutoCommit(false); - if (!Strings.isEmpty(prepareSql)) { - for (String sql : prepareSql.split(";")) { - stmt = conn.prepareStatement(sql); - stmt.executeUpdate(); - } - } - conn.commit(); - - } catch (Exception ex) { - if (null != conn) { - conn.rollback(); - } - } finally { - if (null != stmt) { - stmt.close(); - } - if (null != conn) { - conn.setAutoCommit(true); - conn.close(); - } + PreparedStatement stmt = null; + try { + conn.setAutoCommit(false); + if (!Strings.isEmpty(prepareSql)) { + for (String sql : prepareSql.split(";")) { + stmt = conn.prepareStatement(sql); + stmt.executeUpdate(); } + } + conn.commit(); + + } catch (Exception ex) { + if (null != conn) { + conn.rollback(); + } + } finally { + if (null != stmt) { + stmt.close(); + } + if (null != conn) { + conn.setAutoCommit(true); + conn.close(); + } } + } - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - @SpringBootApplication - public static class JdbcTestConfig { + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } - } + @SpringBootApplication + public static class JdbcTestConfig {} } diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractMetaServerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractMetaServerTest.java index 883444409..dbe9f42e5 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractMetaServerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractMetaServerTest.java @@ -16,6 +16,9 @@ */ package com.alipay.sofa.registry.server.meta; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.Slot; @@ -33,19 +36,11 @@ import com.alipay.sofa.registry.util.MathUtils; import com.alipay.sofa.registry.util.ObjectFactory; import com.google.common.collect.Maps; -import org.assertj.core.util.Lists; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.rules.TestName; -import org.mockito.Mock; - import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.net.InetSocketAddress; import java.net.ServerSocket; -import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; @@ -57,521 +52,545 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BooleanSupplier; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.assertj.core.util.Lists; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.rules.TestName; /** * @author chen.zhu - *

- * Nov 18, 2020 + *

Nov 18, 2020 */ public class AbstractMetaServerTest extends AbstractTest { - protected MetaLeaderService metaLeaderService; - - @Rule - public TestName name = new TestName(); + protected MetaLeaderService metaLeaderService; - private BalancePolicy balancePolicy = new NaiveBalancePolicy(); + @Rule public TestName name = new TestName(); - @Before - public void beforeAbstractMetaServerTest() { - metaLeaderService = mock(MetaLeaderService.class); - } + private BalancePolicy balancePolicy = new NaiveBalancePolicy(); - public static void setFinalStatic(Field field, Object newValue) throws Exception { - field.setAccessible(true); + @Before + public void beforeAbstractMetaServerTest() { + metaLeaderService = mock(MetaLeaderService.class); + } - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + public static void setFinalStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); - field.set(null, newValue); - } + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); - protected static void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier, - int waitTimeMilli) throws TimeoutException, - InterruptedException { + field.set(null, newValue); + } - waitConditionUntilTimeOut(booleanSupplier, waitTimeMilli, 2); - } + protected static void waitConditionUntilTimeOut( + BooleanSupplier booleanSupplier, int waitTimeMilli) + throws TimeoutException, InterruptedException { - protected static void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier, - int waitTimeMilli, int intervalMilli) - throws TimeoutException, - InterruptedException { + waitConditionUntilTimeOut(booleanSupplier, waitTimeMilli, 2); + } - long maxTime = System.currentTimeMillis() + waitTimeMilli; + protected static void waitConditionUntilTimeOut( + BooleanSupplier booleanSupplier, int waitTimeMilli, int intervalMilli) + throws TimeoutException, InterruptedException { - while (true) { - boolean result = booleanSupplier.getAsBoolean(); - if (result) { - return; - } - if (System.currentTimeMillis() >= maxTime) { - throw new TimeoutException("timeout still false:" + waitTimeMilli); - } - Thread.sleep(intervalMilli); - } - } + long maxTime = System.currentTimeMillis() + waitTimeMilli; - protected URL randomURL() { - return randomURL("127.0.0.1"); + while (true) { + boolean result = booleanSupplier.getAsBoolean(); + if (result) { + return; + } + if (System.currentTimeMillis() >= maxTime) { + throw new TimeoutException("timeout still false:" + waitTimeMilli); + } + Thread.sleep(intervalMilli); } + } - protected URL randomURL(String ip) { - return new URL(ip, randomPort()); - } + protected URL randomURL() { + return randomURL("127.0.0.1"); + } - public static int randomPort() { - return randomPort(10000, 20000, null); - } + protected URL randomURL(String ip) { + return new URL(ip, randomPort()); + } - public static int randomPort(int min, int max, Set different) { + public static int randomPort() { + return randomPort(10000, 20000, null); + } - Random random = new Random(); + public static int randomPort(int min, int max, Set different) { - for (int i = min; i <= max; i++) { - int port = min + random.nextInt(max - min + 1); - if ((different == null || !different.contains(port)) && isUsable(port)) { - return port; - } - } + Random random = new Random(); - throw new IllegalStateException(String.format("random port not found:(%d, %d)", min, max)); + for (int i = min; i <= max; i++) { + int port = min + random.nextInt(max - min + 1); + if ((different == null || !different.contains(port)) && isUsable(port)) { + return port; + } } - public static int netmask = (1 << 8) - 1; + throw new IllegalStateException(String.format("random port not found:(%d, %d)", min, max)); + } - public static String randomIp() { - return String.format("%d.%d.%d.%d", (Math.abs(random.nextInt()) % netmask + 1), - (Math.abs(random.nextInt()) % netmask + 1), (Math.abs(random.nextInt()) % netmask + 1), - (Math.abs(random.nextInt()) % netmask + 1)); - } + public static int netmask = (1 << 8) - 1; - protected static boolean isUsable(int port) { + public static String randomIp() { + return String.format( + "%d.%d.%d.%d", + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1)); + } - try (ServerSocket s = new ServerSocket()) { - s.bind(new InetSocketAddress(port)); - return true; - } catch (IOException e) { - } - return false; - } + protected static boolean isUsable(int port) { - public static String getDc() { - return "DEFAULT_DC"; + try (ServerSocket s = new ServerSocket()) { + s.bind(new InetSocketAddress(port)); + return true; + } catch (IOException e) { } + return false; + } - public static String randomString() { + public static String getDc() { + return "DEFAULT_DC"; + } - return randomString(1 << 10); - } + public static String randomString() { - public static String randomString(int length) { + return randomString(1 << 10); + } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - sb.append((char) ('a' + (int) (26 * Math.random()))); - } + public static String randomString(int length) { - return sb.toString(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + sb.append((char) ('a' + (int) (26 * Math.random()))); + } + + return sb.toString(); + } + + public static Client getRpcClient( + ScheduledExecutorService scheduled, int responseDelayMilli, Object responseObj) { + return new MockRpcClient() + .setScheduled(scheduled) + .setResponseDelayMilli(responseDelayMilli) + .setResponseObj(responseObj); + } + + public static Client getRpcClient( + ScheduledExecutorService scheduled, int responseDelayMilli, Throwable th) { + return new MockRpcClient() + .setScheduled(scheduled) + .setResponseDelayMilli(responseDelayMilli) + .setPositive(false) + .setThrowable(th); + } + + public static Client getRpcClient(Object response, int responseDelayMilli) { + return new MockRpcClient().setResponseObj(response).setResponseDelayMilli(responseDelayMilli); + } + + public void makeMetaLeader() throws TimeoutException, InterruptedException { + when(metaLeaderService.amILeader()).thenReturn(true); + when(metaLeaderService.amIStableAsLeader()).thenReturn(true); + } + + public void makeMetaNonLeader() throws TimeoutException, InterruptedException { + when(metaLeaderService.amILeader()).thenReturn(false); + } + + public void printSlotTable(SlotTable slotTable) { + try { + logger.warn( + "{}", + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() + .writeValueAsString(slotTable)); + } catch (Exception ignore) { + } + } + + protected boolean isSlotTableBalanced(SlotTable slotTable, List dataNodes) { + Map leaderCounter = Maps.newHashMap(); + for (Slot slot : slotTable.getSlots()) { + counterIncr(leaderCounter, slot.getLeader()); + } + Map followerCounter = Maps.newHashMap(); + for (Slot slot : slotTable.getSlots()) { + for (String follower : slot.getFollowers()) { + counterIncr(followerCounter, follower); + } + } + AtomicInteger leaderTotal = new AtomicInteger(); + leaderCounter.values().forEach(count -> leaderTotal.addAndGet(count)); + int leaderAverage = MathUtils.divideCeil(leaderTotal.get(), dataNodes.size()); + int leaderHighWaterMark = balancePolicy.getHighWaterMarkSlotLeaderNums(leaderAverage); + + AtomicInteger followerTotal = new AtomicInteger(); + followerCounter.values().forEach(count -> followerTotal.addAndGet(count)); + int followerAverage = MathUtils.divideCeil(followerTotal.get(), dataNodes.size()); + int followerHighWaterMark = balancePolicy.getHighWaterMarkSlotFollowerNums(followerAverage); + + logger.info("[isSlotTableBalanced][leaderCounter] {}", leaderCounter); + logger.info("[isSlotTableBalanced][followerCounter] {}", followerCounter); + for (DataNode dataNode : dataNodes) { + if (leaderCounter.get(dataNode.getIp()) == null) { + return false; + } + if (leaderCounter.get(dataNode.getIp()) > leaderHighWaterMark) { + logger.info( + "[highLeader] {}, {}, {}", + dataNode.getIp(), + leaderCounter.get(dataNode.getIp()), + leaderHighWaterMark); + return false; + } + + if (followerCounter.get(dataNode.getIp()) > followerHighWaterMark) { + logger.info( + "[highFollower] {}, {}, {}", + dataNode.getIp(), + followerCounter.get(dataNode.getIp()), + followerHighWaterMark); + return false; + } } + return true; + } - public static Client getRpcClient(ScheduledExecutorService scheduled, int responseDelayMilli, - Object responseObj) { - return new MockRpcClient().setScheduled(scheduled) - .setResponseDelayMilli(responseDelayMilli).setResponseObj(responseObj); - } + protected void assertSlotTableNoDupLeaderFollower(SlotTable slotTable) { + slotTable + .getSlotMap() + .forEach( + (slotId, slot) -> { + Assert.assertFalse(slot.getFollowers().contains(slot.getLeader())); + }); + } - public static Client getRpcClient(ScheduledExecutorService scheduled, int responseDelayMilli, - Throwable th) { - return new MockRpcClient().setScheduled(scheduled) - .setResponseDelayMilli(responseDelayMilli).setPositive(false).setThrowable(th); - } + private void counterIncr(Map counter, String ip) { + Integer prev = counter.get(ip); + counter.put(ip, prev == null ? 1 : prev + 1); + } - public static Client getRpcClient(Object response, int responseDelayMilli) { - return new MockRpcClient().setResponseObj(response).setResponseDelayMilli( - responseDelayMilli); + protected boolean isSlotTableLeaderBalanced(SlotTable slotTable, List dataNodes) { + Map counter = Maps.newHashMap(); + for (Slot slot : slotTable.getSlots()) { + counterIncr(counter, slot.getLeader()); } - public void makeMetaLeader() throws TimeoutException, InterruptedException { - when(metaLeaderService.amILeader()).thenReturn(true); - when(metaLeaderService.amIStableAsLeader()).thenReturn(true); - } + int average = slotTable.getSlotMap().size() / dataNodes.size(); + int lowWaterMark = balancePolicy.getLowWaterMarkSlotLeaderNums(average); - public void makeMetaNonLeader() throws TimeoutException, InterruptedException { - when(metaLeaderService.amILeader()).thenReturn(false); + logger.info("[isSlotTableLeaderBalanced][counter] {}", counter); + for (DataNode dataNode : dataNodes) { + if (counter.get(dataNode.getIp()) == null) { + return false; + } + if (counter.get(dataNode.getIp()) < lowWaterMark) { + return false; + } + // if (counter.get(dataNode.getIp()) > highWaterMark) { + // return false; + // } } + return true; + } - public void printSlotTable(SlotTable slotTable) { - try { - logger.warn("{}", JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() - .writeValueAsString(slotTable)); - } catch (Exception ignore) { - } - } + public static class MockRpcClient implements Client { - protected boolean isSlotTableBalanced(SlotTable slotTable, List dataNodes) { - Map leaderCounter = Maps.newHashMap(); - for (Slot slot : slotTable.getSlots()) { - counterIncr(leaderCounter, slot.getLeader()); - } - Map followerCounter = Maps.newHashMap(); - for (Slot slot : slotTable.getSlots()) { - for (String follower : slot.getFollowers()) { - counterIncr(followerCounter, follower); - } - } - AtomicInteger leaderTotal = new AtomicInteger(); - leaderCounter.values().forEach(count -> leaderTotal.addAndGet(count)); - int leaderAverage = MathUtils.divideCeil(leaderTotal.get(), dataNodes.size()); - int leaderHighWaterMark = balancePolicy.getHighWaterMarkSlotLeaderNums(leaderAverage); - - AtomicInteger followerTotal = new AtomicInteger(); - followerCounter.values().forEach(count -> followerTotal.addAndGet(count)); - int followerAverage = MathUtils.divideCeil(followerTotal.get(), dataNodes.size()); - int followerHighWaterMark = balancePolicy.getHighWaterMarkSlotFollowerNums(followerAverage); - - logger.info("[isSlotTableBalanced][leaderCounter] {}", leaderCounter); - logger.info("[isSlotTableBalanced][followerCounter] {}", followerCounter); - for (DataNode dataNode : dataNodes) { - if (leaderCounter.get(dataNode.getIp()) == null) { - return false; - } - if (leaderCounter.get(dataNode.getIp()) > leaderHighWaterMark) { - logger.info("[highLeader] {}, {}, {}", dataNode.getIp(), leaderCounter.get(dataNode.getIp()), leaderHighWaterMark); - return false; - } + private ObjectFactory response; - if (followerCounter.get(dataNode.getIp()) > followerHighWaterMark) { - logger.info("[highFollower] {}, {}, {}", dataNode.getIp(), followerCounter.get(dataNode.getIp()), followerHighWaterMark); - return false; - } - } - return true; - } + private int responseDelayMilli; - protected void assertSlotTableNoDupLeaderFollower(SlotTable slotTable) { - slotTable.getSlotMap().forEach((slotId, slot) -> { - Assert.assertFalse(slot.getFollowers().contains(slot.getLeader())); - }); - } + private ScheduledExecutorService scheduled; - private void counterIncr(Map counter, String ip) { - Integer prev = counter.get(ip); - counter.put(ip, prev == null ? 1 : prev + 1); - } + private Channel channel; - protected boolean isSlotTableLeaderBalanced(SlotTable slotTable, List dataNodes) { - Map counter = Maps.newHashMap(); - for (Slot slot : slotTable.getSlots()) { - counterIncr(counter, slot.getLeader()); - } + private boolean isPositive = true; - int average = slotTable.getSlotMap().size() / dataNodes.size(); - int lowWaterMark = balancePolicy.getLowWaterMarkSlotLeaderNums(average); + private Throwable throwable; - logger.info("[isSlotTableLeaderBalanced][counter] {}", counter); - for (DataNode dataNode : dataNodes) { - if (counter.get(dataNode.getIp()) == null) { - return false; - } - if (counter.get(dataNode.getIp()) < lowWaterMark) { - return false; - } - // if (counter.get(dataNode.getIp()) > highWaterMark) { - // return false; - // } - } - return true; + @Override + public Channel getChannel(URL url) { + return null; } - public static class MockRpcClient implements Client { - - private ObjectFactory response; - - private int responseDelayMilli; - - private ScheduledExecutorService scheduled; - - private Channel channel; - - private boolean isPositive = true; - - private Throwable throwable; - - @Override - public Channel getChannel(URL url) { - return null; - } + @Override + public Channel connect(URL url) { + return null; + } - @Override - public Channel connect(URL url) { - return null; - } + @Override + public Object sendSync(URL url, Object message, int timeoutMillis) { + try { + Thread.sleep(responseDelayMilli); + throwIfNegative(); + } catch (Throwable e) { + throw new SofaRegistryRuntimeException(e); + } + return response.create(); + } - @Override - public Object sendSync(URL url, Object message, int timeoutMillis) { - try { - Thread.sleep(responseDelayMilli); - throwIfNegative(); - } catch (Throwable e) { - throw new SofaRegistryRuntimeException(e); - } - return response.create(); - } + @Override + public Object sendSync(Channel channel, Object message, int timeoutMillis) { + try { + Thread.sleep(responseDelayMilli); + throwIfNegative(); + } catch (Throwable e) { + throw new SofaRegistryRuntimeException(e); + } + return response.create(); + } - @Override - public Object sendSync(Channel channel, Object message, int timeoutMillis) { - try { - Thread.sleep(responseDelayMilli); - throwIfNegative(); - } catch (Throwable e) { - throw new SofaRegistryRuntimeException(e); - } - return response.create(); - } + @Override + public void sendCallback( + URL url, Object message, CallbackHandler callbackHandler, int timeoutMillis) { + if (isPositive) { + scheduled.schedule( + () -> callbackHandler.onCallback(channel, response.create()), + responseDelayMilli, + TimeUnit.MILLISECONDS); + } else { + scheduled.schedule( + () -> callbackHandler.onException(channel, throwable), + responseDelayMilli, + TimeUnit.MILLISECONDS); + } + } - @Override - public void sendCallback(URL url, Object message, CallbackHandler callbackHandler, int timeoutMillis) { - if (isPositive) { - scheduled.schedule(() -> - callbackHandler.onCallback(channel, - response.create()), - responseDelayMilli, - TimeUnit.MILLISECONDS); - } else { - scheduled.schedule(() -> callbackHandler.onException(channel, throwable), responseDelayMilli, TimeUnit.MILLISECONDS); - } - } + @Override + public InetSocketAddress getLocalAddress() { + return null; + } - @Override - public InetSocketAddress getLocalAddress() { - return null; - } + @Override + public void close() {} - @Override - public void close() { + @Override + public boolean isClosed() { + return false; + } + private void throwIfNegative() throws Throwable { + if (!isPositive) { + if (throwable != null) { + throw throwable; + } else { + throw new SofaRegistryRuntimeException("expected exception"); } + } + } - @Override - public boolean isClosed() { - return false; - } + public MockRpcClient setResponse(ObjectFactory response) { + this.response = response; + return this; + } - private void throwIfNegative() throws Throwable { - if (!isPositive) { - if (throwable != null) { - throw throwable; - } else { - throw new SofaRegistryRuntimeException("expected exception"); - } + public MockRpcClient setResponseObj(Object responseObj) { + this.response = + new ObjectFactory() { + @Override + public Object create() { + return responseObj; } - } - - public MockRpcClient setResponse(ObjectFactory response) { - this.response = response; - return this; - } - - public MockRpcClient setResponseObj(Object responseObj) { - this.response = new ObjectFactory() { - @Override - public Object create() { - return responseObj; - } - }; - return this; - } - - public MockRpcClient setResponseDelayMilli(int responseDelayMilli) { - this.responseDelayMilli = responseDelayMilli; - return this; - } - - public MockRpcClient setScheduled(ScheduledExecutorService scheduled) { - this.scheduled = scheduled; - return this; - } - - public MockRpcClient setChannel(Channel channel) { - this.channel = channel; - return this; - } - - public MockRpcClient setPositive(boolean positive) { - isPositive = positive; - return this; - } + }; + return this; + } + + public MockRpcClient setResponseDelayMilli(int responseDelayMilli) { + this.responseDelayMilli = responseDelayMilli; + return this; + } - public MockRpcClient setThrowable(Throwable throwable) { - this.throwable = throwable; - return this; - } + public MockRpcClient setScheduled(ScheduledExecutorService scheduled) { + this.scheduled = scheduled; + return this; } - protected List randomDataNodes(int num) { - List result = Lists.newArrayList(); - for(int i = 0; i < num; i++) { - result.add(new DataNode(randomURL(randomIp()), getDc())); - } - return result; + public MockRpcClient setChannel(Channel channel) { + this.channel = channel; + return this; } - protected SlotTable randomSlotTable() { - return new SlotTableGenerator(randomDataNodes(3)).createSlotTable(); + public MockRpcClient setPositive(boolean positive) { + isPositive = positive; + return this; } - protected SlotTable randomSlotTable(List dataNodes) { - return new SlotTableGenerator(dataNodes).createSlotTable(); + public MockRpcClient setThrowable(Throwable throwable) { + this.throwable = throwable; + return this; } + } - protected SlotTable randomUnBalancedSlotTable(List dataNodes) { - return new SlotTableGenerator(dataNodes).createLeaderUnBalancedSlotTable(); + protected List randomDataNodes(int num) { + List result = Lists.newArrayList(); + for (int i = 0; i < num; i++) { + result.add(new DataNode(randomURL(randomIp()), getDc())); } + return result; + } + + protected SlotTable randomSlotTable() { + return new SlotTableGenerator(randomDataNodes(3)).createSlotTable(); + } - protected boolean isMoreBalanced(SlotTable before, SlotTable current, List dataNodes) { - // Map beforeLeaderCount = SlotTableUtils.getSlotTableLeaderCount(before); - // Map currentLeaderCount = SlotTableUtils.getSlotTableLeaderCount(current); - // - // Map beforeSlotsCount = SlotTableUtils.getSlotTableSlotCount(before); - // Map currentSlotsCount = SlotTableUtils.getSlotTableSlotCount(current); + protected SlotTable randomSlotTable(List dataNodes) { + return new SlotTableGenerator(dataNodes).createSlotTable(); + } - int maxLeaderGapBefore = maxLeaderGap(before, dataNodes); - int maxLeaderGapCurrent = maxLeaderGap(current, dataNodes); - int maxSlotsGapBefore = maxSlotGap(before, dataNodes); - int maxSlotsGapCurrent = maxSlotGap(current, dataNodes); - logger.info("[before leader gap] {}", maxLeaderGapBefore); - logger.info("[current leader gap] {}", maxLeaderGapCurrent); - logger.info("[before slots gap] {}", maxSlotsGapBefore); - logger.info("[current slots gap] {}", maxSlotsGapCurrent); - return maxLeaderGapBefore > maxLeaderGapCurrent || maxSlotsGapBefore > maxSlotsGapCurrent; + protected SlotTable randomUnBalancedSlotTable(List dataNodes) { + return new SlotTableGenerator(dataNodes).createLeaderUnBalancedSlotTable(); + } + + protected boolean isMoreBalanced(SlotTable before, SlotTable current, List dataNodes) { + // Map beforeLeaderCount = + // SlotTableUtils.getSlotTableLeaderCount(before); + // Map currentLeaderCount = + // SlotTableUtils.getSlotTableLeaderCount(current); + // + // Map beforeSlotsCount = SlotTableUtils.getSlotTableSlotCount(before); + // Map currentSlotsCount = + // SlotTableUtils.getSlotTableSlotCount(current); + + int maxLeaderGapBefore = maxLeaderGap(before, dataNodes); + int maxLeaderGapCurrent = maxLeaderGap(current, dataNodes); + int maxSlotsGapBefore = maxSlotGap(before, dataNodes); + int maxSlotsGapCurrent = maxSlotGap(current, dataNodes); + logger.info("[before leader gap] {}", maxLeaderGapBefore); + logger.info("[current leader gap] {}", maxLeaderGapCurrent); + logger.info("[before slots gap] {}", maxSlotsGapBefore); + logger.info("[current slots gap] {}", maxSlotsGapCurrent); + return maxLeaderGapBefore > maxLeaderGapCurrent || maxSlotsGapBefore > maxSlotsGapCurrent; + } + + private int maxLeaderGap(SlotTable slotTable, List dataNodes) { + Map counter = new HashMap<>(dataNodes.size()); + dataNodes.forEach(dataNode -> counter.put(dataNode.getIp(), 0)); + for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { + int count = counter.get(entry.getValue().getLeader()); + counter.put(entry.getValue().getLeader(), count + 1); } + return maxGap(counter); + } - private int maxLeaderGap(SlotTable slotTable, List dataNodes) { - Map counter = new HashMap<>(dataNodes.size()); - dataNodes.forEach(dataNode -> counter.put(dataNode.getIp(), 0)); - for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { - int count = counter.get(entry.getValue().getLeader()); - counter.put(entry.getValue().getLeader(), count + 1); - } - return maxGap(counter); - } - - private int maxSlotGap(SlotTable slotTable, List dataNodes) { - Map counter = new HashMap<>(dataNodes.size()); - dataNodes.forEach(dataNode -> counter.put(dataNode.getIp(), 0)); - for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { - int count = counter.get(entry.getValue().getLeader()); - counter.put(entry.getValue().getLeader(), count + 1); - for (String dataServer : entry.getValue().getFollowers()) { - count = counter.get(dataServer); - counter.put(dataServer, count + 1); - } - } - return maxGap(counter); + private int maxSlotGap(SlotTable slotTable, List dataNodes) { + Map counter = new HashMap<>(dataNodes.size()); + dataNodes.forEach(dataNode -> counter.put(dataNode.getIp(), 0)); + for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { + int count = counter.get(entry.getValue().getLeader()); + counter.put(entry.getValue().getLeader(), count + 1); + for (String dataServer : entry.getValue().getFollowers()) { + count = counter.get(dataServer); + counter.put(dataServer, count + 1); + } } + return maxGap(counter); + } - private int maxGap(Map stats) { - int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; - for (int count : stats.values()) { - min = Math.min(count, min); - max = Math.max(count, max); - } - return max - min; + private int maxGap(Map stats) { + int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE; + for (int count : stats.values()) { + min = Math.min(count, min); + max = Math.max(count, max); } + return max - min; + } - public static class SlotTableGenerator { + public static class SlotTableGenerator { - private final List dataNodes; + private final List dataNodes; - public SlotTableGenerator(List dataNodes) { - this.dataNodes = dataNodes; - } + public SlotTableGenerator(List dataNodes) { + this.dataNodes = dataNodes; + } - public SlotTable createSlotTable() { - long epoch = DatumVersionUtil.nextId(); - Map slotMap = generateSlotMap(); - return new SlotTable(epoch, slotMap.values()); - } + public SlotTable createSlotTable() { + long epoch = DatumVersionUtil.nextId(); + Map slotMap = generateSlotMap(); + return new SlotTable(epoch, slotMap.values()); + } - public SlotTable createLeaderUnBalancedSlotTable() { - long epoch = DatumVersionUtil.nextId(); - Map slotMap = generateUnBalancedSlotMap(); - return new SlotTable(epoch, slotMap.values()); - } + public SlotTable createLeaderUnBalancedSlotTable() { + long epoch = DatumVersionUtil.nextId(); + Map slotMap = generateUnBalancedSlotMap(); + return new SlotTable(epoch, slotMap.values()); + } - private Map generateSlotMap() { - Map slotMap = Maps.newHashMap(); - for (int i = 0; i < SlotConfig.SLOT_NUM; i++) { - long epoch = DatumVersionUtil.nextId(); - String leader = getNextLeader().getIp(); - List followers = Lists.newArrayList(); - for (int j = 0; j < SlotConfig.SLOT_REPLICAS - 1; j++) { - followers.add(getNextFollower().getIp()); - } - Slot slot = new Slot(i, leader, epoch, followers); - slotMap.put(i, slot); - } - return slotMap; + private Map generateSlotMap() { + Map slotMap = Maps.newHashMap(); + for (int i = 0; i < SlotConfig.SLOT_NUM; i++) { + long epoch = DatumVersionUtil.nextId(); + String leader = getNextLeader().getIp(); + List followers = Lists.newArrayList(); + for (int j = 0; j < SlotConfig.SLOT_REPLICAS - 1; j++) { + followers.add(getNextFollower().getIp()); } + Slot slot = new Slot(i, leader, epoch, followers); + slotMap.put(i, slot); + } + return slotMap; + } - private Map generateUnBalancedSlotMap() { - Map slotMap = Maps.newHashMap(); - int leaderIndex = Math.abs(random.nextInt()) % dataNodes.size(); - String leader = dataNodes.get(leaderIndex).getIp(); - for (int i = 0; i < SlotConfig.SLOT_NUM; i++) { - long epoch = DatumVersionUtil.nextId(); - List followers = Lists.newArrayList(); - for (int j = 0; j < SlotConfig.SLOT_REPLICAS - 1; j++) { - DataNode follower = getNextFollower(); - while (follower.getIp().equalsIgnoreCase(leader) - || followers.contains(follower)) { - follower = getNextUnbalancedFollower(); - } - followers.add(follower.getIp()); - } - Slot slot = new Slot(i, leader, epoch, followers); - slotMap.put(i, slot); - } - return slotMap; + private Map generateUnBalancedSlotMap() { + Map slotMap = Maps.newHashMap(); + int leaderIndex = Math.abs(random.nextInt()) % dataNodes.size(); + String leader = dataNodes.get(leaderIndex).getIp(); + for (int i = 0; i < SlotConfig.SLOT_NUM; i++) { + long epoch = DatumVersionUtil.nextId(); + List followers = Lists.newArrayList(); + for (int j = 0; j < SlotConfig.SLOT_REPLICAS - 1; j++) { + DataNode follower = getNextFollower(); + while (follower.getIp().equalsIgnoreCase(leader) || followers.contains(follower)) { + follower = getNextUnbalancedFollower(); + } + followers.add(follower.getIp()); } + Slot slot = new Slot(i, leader, epoch, followers); + slotMap.put(i, slot); + } + return slotMap; + } - private AtomicInteger nextLeader = new AtomicInteger(); + private AtomicInteger nextLeader = new AtomicInteger(); - private AtomicInteger nextFollower = new AtomicInteger(1); + private AtomicInteger nextFollower = new AtomicInteger(1); - private DataNode getNextLeader() { - return dataNodes.get(nextLeader.getAndIncrement() % dataNodes.size()); - } + private DataNode getNextLeader() { + return dataNodes.get(nextLeader.getAndIncrement() % dataNodes.size()); + } - private DataNode getNextFollower() { - return dataNodes.get(nextFollower.getAndIncrement() % dataNodes.size()); - } + private DataNode getNextFollower() { + return dataNodes.get(nextFollower.getAndIncrement() % dataNodes.size()); + } - private DataNode getNextUnbalancedFollower() { - return dataNodes.get(nextFollower.getAndIncrement() % dataNodes.size()); - } + private DataNode getNextUnbalancedFollower() { + return dataNodes.get(nextFollower.getAndIncrement() % dataNodes.size()); + } - public SlotTableGenerator setNextLeader(int nextLeader) { - this.nextLeader.set(nextLeader); - return this; - } + public SlotTableGenerator setNextLeader(int nextLeader) { + this.nextLeader.set(nextLeader); + return this; + } - public SlotTableGenerator setNextFollower(int nextFollower) { - this.nextFollower.set(nextFollower); - return this; - } + public SlotTableGenerator setNextFollower(int nextFollower) { + this.nextFollower.set(nextFollower); + return this; } + } - public static class NodeComparator implements Comparator { + public static class NodeComparator implements Comparator { - @Override - public int compare(Node o1, Node o2) { - return o1.getNodeUrl().getIpAddress().compareTo(o2.getNodeUrl().getIpAddress()); - } + @Override + public int compare(Node o1, Node o2) { + return o1.getNodeUrl().getIpAddress().compareTo(o2.getNodeUrl().getIpAddress()); } + } } diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractTest.java index 635c0f304..b1d79d375 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AbstractTest.java @@ -22,12 +22,6 @@ import com.alipay.sofa.registry.observer.UnblockingObserver; import com.alipay.sofa.registry.util.NamedThreadFactory; import io.netty.util.ResourceLeakDetector; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.rules.TestName; - import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -47,246 +41,253 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BooleanSupplier; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.rules.TestName; /** * @author chen.zhu - *

- * Mar 15, 2021 + *

Mar 15, 2021 */ public class AbstractTest { - protected final Logger logger = LoggerFactory.getLogger(getClass()); + protected final Logger logger = LoggerFactory.getLogger(getClass()); - protected ExecutorService executors; + protected ExecutorService executors; - protected ScheduledExecutorService scheduled; + protected ScheduledExecutorService scheduled; - @Rule - public TestName name = new TestName(); + @Rule public TestName name = new TestName(); - public static final Random random = new Random(); + public static final Random random = new Random(); - @BeforeClass - public static void beforeAbstractTestClass() { - System.setProperty("spring.main.show_banner", "false"); - System.setProperty("spring.profiles.active", "test"); - } - - @Before - public void beforeAbstractTest() throws Exception { - - ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); - Thread.interrupted();//clear interrupt + @BeforeClass + public static void beforeAbstractTestClass() { + System.setProperty("spring.main.show_banner", "false"); + System.setProperty("spring.profiles.active", "test"); + } - executors = Executors.newCachedThreadPool(new NamedThreadFactory(name.getMethodName())); - scheduled = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), - new NamedThreadFactory("sched-" + name.getMethodName())); - if (logger.isInfoEnabled()) { - logger.info(remarkableMessage("[begin test][{}]"), name.getMethodName()); - } - } + @Before + public void beforeAbstractTest() throws Exception { - @After - public void afterAbstractTest() throws IOException, NoSuchMethodException, - InvocationTargetException, IllegalAccessException { - executors.shutdownNow(); - scheduled.shutdownNow(); + ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); + Thread.interrupted(); // clear interrupt - logger.info(remarkableMessage("[end test][{}]"), name.getMethodName()); + executors = Executors.newCachedThreadPool(new NamedThreadFactory(name.getMethodName())); + scheduled = + Executors.newScheduledThreadPool( + Runtime.getRuntime().availableProcessors(), + new NamedThreadFactory("sched-" + name.getMethodName())); + if (logger.isInfoEnabled()) { + logger.info(remarkableMessage("[begin test][{}]"), name.getMethodName()); } - - protected static void setEnv(Map newenv) throws Exception { - try { - Class processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); - Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); - theEnvironmentField.setAccessible(true); - Map env = (Map) theEnvironmentField.get(null); - env.putAll(newenv); - Field theCaseInsensitiveEnvironmentField = processEnvironmentClass - .getDeclaredField("theCaseInsensitiveEnvironment"); - theCaseInsensitiveEnvironmentField.setAccessible(true); - Map cienv = (Map) theCaseInsensitiveEnvironmentField - .get(null); - cienv.putAll(newenv); - } catch (NoSuchFieldException e) { - Class[] classes = Collections.class.getDeclaredClasses(); - Map env = System.getenv(); - for (Class cl : classes) { - if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { - Field field = cl.getDeclaredField("m"); - field.setAccessible(true); - Object obj = field.get(env); - Map map = (Map) obj; - map.clear(); - map.putAll(newenv); - } - } + } + + @After + public void afterAbstractTest() + throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { + executors.shutdownNow(); + scheduled.shutdownNow(); + + logger.info(remarkableMessage("[end test][{}]"), name.getMethodName()); + } + + protected static void setEnv(Map newenv) throws Exception { + try { + Class processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); + Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); + theEnvironmentField.setAccessible(true); + Map env = (Map) theEnvironmentField.get(null); + env.putAll(newenv); + Field theCaseInsensitiveEnvironmentField = + processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment"); + theCaseInsensitiveEnvironmentField.setAccessible(true); + Map cienv = + (Map) theCaseInsensitiveEnvironmentField.get(null); + cienv.putAll(newenv); + } catch (NoSuchFieldException e) { + Class[] classes = Collections.class.getDeclaredClasses(); + Map env = System.getenv(); + for (Class cl : classes) { + if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { + Field field = cl.getDeclaredField("m"); + field.setAccessible(true); + Object obj = field.get(env); + Map map = (Map) obj; + map.clear(); + map.putAll(newenv); } + } } + } - public static void setFinalStatic(Field field, Object newValue) throws Exception { - field.setAccessible(true); + public static void setFinalStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); - field.set(null, newValue); - } + field.set(null, newValue); + } - protected String remarkableMessage(String msg) { - return String.format("--------------------------%s--------------------------\r\n", msg); - } + protected String remarkableMessage(String msg) { + return String.format("--------------------------%s--------------------------\r\n", msg); + } - protected void waitForAnyKeyToExit() throws IOException { - logger.info("type any key to exit.................."); - waitForAnyKey(); - } + protected void waitForAnyKeyToExit() throws IOException { + logger.info("type any key to exit.................."); + waitForAnyKey(); + } - protected void waitForAnyKey() throws IOException { - System.in.read(); - } + protected void waitForAnyKey() throws IOException { + System.in.read(); + } - protected void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier) - throws TimeoutException, - InterruptedException { + protected void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier) + throws TimeoutException, InterruptedException { - waitConditionUntilTimeOut(booleanSupplier, 5000, 2); - } + waitConditionUntilTimeOut(booleanSupplier, 5000, 2); + } - protected static void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier, - int waitTimeMilli) throws TimeoutException, - InterruptedException { + protected static void waitConditionUntilTimeOut( + BooleanSupplier booleanSupplier, int waitTimeMilli) + throws TimeoutException, InterruptedException { - waitConditionUntilTimeOut(booleanSupplier, waitTimeMilli, 2); - } + waitConditionUntilTimeOut(booleanSupplier, waitTimeMilli, 2); + } - protected static void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier, - int waitTimeMilli, int intervalMilli) - throws TimeoutException, - InterruptedException { - - long maxTime = System.currentTimeMillis() + waitTimeMilli; - - while (true) { - boolean result = booleanSupplier.getAsBoolean(); - if (result) { - return; - } - if (System.currentTimeMillis() >= maxTime) { - throw new TimeoutException("timeout still false:" + waitTimeMilli); - } - Thread.sleep(intervalMilli); - } - } + protected static void waitConditionUntilTimeOut( + BooleanSupplier booleanSupplier, int waitTimeMilli, int intervalMilli) + throws TimeoutException, InterruptedException { + + long maxTime = System.currentTimeMillis() + waitTimeMilli; - public static int randomPort() { - return randomPort(10000, 20000, null); + while (true) { + boolean result = booleanSupplier.getAsBoolean(); + if (result) { + return; + } + if (System.currentTimeMillis() >= maxTime) { + throw new TimeoutException("timeout still false:" + waitTimeMilli); + } + Thread.sleep(intervalMilli); } + } - public static int randomPort(int min, int max, Set different) { + public static int randomPort() { + return randomPort(10000, 20000, null); + } - Random random = new Random(); + public static int randomPort(int min, int max, Set different) { - for (int i = min; i <= max; i++) { - int port = min + random.nextInt(max - min + 1); - if ((different == null || !different.contains(port)) && isUsable(port)) { - return port; - } - } + Random random = new Random(); - throw new IllegalStateException(String.format("random port not found:(%d, %d)", min, max)); + for (int i = min; i <= max; i++) { + int port = min + random.nextInt(max - min + 1); + if ((different == null || !different.contains(port)) && isUsable(port)) { + return port; + } } - public static int netmask = (1 << 8) - 1; + throw new IllegalStateException(String.format("random port not found:(%d, %d)", min, max)); + } - public static String randomIp() { - return String.format("%d.%d.%d.%d", (Math.abs(random.nextInt()) % netmask + 1), - (Math.abs(random.nextInt()) % netmask + 1), (Math.abs(random.nextInt()) % netmask + 1), - (Math.abs(random.nextInt()) % netmask + 1)); - } + public static int netmask = (1 << 8) - 1; - protected static boolean isUsable(int port) { + public static String randomIp() { + return String.format( + "%d.%d.%d.%d", + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1)); + } - try (ServerSocket s = new ServerSocket()) { - s.bind(new InetSocketAddress(port)); - return true; - } catch (IOException e) { - } - return false; - } + protected static boolean isUsable(int port) { - public static String getDc() { - return "DEFAULT_DC"; + try (ServerSocket s = new ServerSocket()) { + s.bind(new InetSocketAddress(port)); + return true; + } catch (IOException e) { } + return false; + } - public static String randomString() { + public static String getDc() { + return "DEFAULT_DC"; + } - return randomString(1 << 10); - } + public static String randomString() { - public static String randomString(int length) { + return randomString(1 << 10); + } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - sb.append((char) ('a' + (int) (26 * Math.random()))); - } + public static String randomString(int length) { - return sb.toString(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + sb.append((char) ('a' + (int) (26 * Math.random()))); } - public static class NotifyObserversCounter implements UnblockingObserver { + return sb.toString(); + } - private final AtomicInteger counter = new AtomicInteger(0); + public static class NotifyObserversCounter implements UnblockingObserver { - @Override - public void update(Observable source, Object message) { - counter.getAndIncrement(); - } + private final AtomicInteger counter = new AtomicInteger(0); - public int getCounter() { - return counter.get(); - } + @Override + public void update(Observable source, Object message) { + counter.getAndIncrement(); } - public static class ConcurrentExecutor implements Executor { + public int getCounter() { + return counter.get(); + } + } - private final int tasks; + public static class ConcurrentExecutor implements Executor { - private final CyclicBarrier barrier; + private final int tasks; - private final CountDownLatch latch; + private final CyclicBarrier barrier; - private final ExecutorService executors; + private final CountDownLatch latch; - public ConcurrentExecutor(int tasks, ExecutorService executors) { - this.tasks = tasks; - this.barrier = new CyclicBarrier(tasks); - this.latch = new CountDownLatch(tasks); - this.executors = executors; - } + private final ExecutorService executors; - @Override - public void execute(final Runnable command) { - for (int i = 0; i < tasks; i++) { - executors.execute(new Runnable() { - @Override - public void run() { - try { - barrier.await(); - command.run(); - } catch (Exception ignore) { - } - - latch.countDown(); - } - }); - } - try { - latch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } + public ConcurrentExecutor(int tasks, ExecutorService executors) { + this.tasks = tasks; + this.barrier = new CyclicBarrier(tasks); + this.latch = new CountDownLatch(tasks); + this.executors = executors; + } + + @Override + public void execute(final Runnable command) { + for (int i = 0; i < tasks; i++) { + executors.execute( + new Runnable() { + @Override + public void run() { + try { + barrier.await(); + command.run(); + } catch (Exception ignore) { + } + + latch.countDown(); + } + }); + } + try { + latch.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } } + } } diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AppTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AppTest.java index 6e2e48a27..eaa9790bd 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AppTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/AppTest.java @@ -16,30 +16,29 @@ */ package com.alipay.sofa.registry.server.meta; +import java.io.IOException; +import java.sql.SQLException; import org.junit.After; import org.junit.Test; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; -import java.io.IOException; -import java.sql.SQLException; - @SpringBootApplication @EnableScheduling public class AppTest extends AbstractMetaServerTest { - @Test - public void startMetaServer() throws IOException, SQLException { - // start(); - } + @Test + public void startMetaServer() throws IOException, SQLException { + // start(); + } - private void start() throws IOException, SQLException { - SpringApplication.run(AppTest.class); - } + private void start() throws IOException, SQLException { + SpringApplication.run(AppTest.class); + } - @After - public void afterAppTest() throws IOException { - // waitForAnyKeyToExit(); - } -} \ No newline at end of file + @After + public void afterAppTest() throws IOException { + // waitForAnyKeyToExit(); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeModifiedTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeModifiedTest.java index a6c152e2d..1415239bf 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeModifiedTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/cluster/node/NodeModifiedTest.java @@ -25,38 +25,35 @@ /** * @author zhuchen * @date Dec 15, 2020, 8:02:29 PM - * - * nothing here, simply increase unit test coverage + *

nothing here, simply increase unit test coverage */ public class NodeModifiedTest extends AbstractMetaServerTest { - @Test - public void testGetOldNode() { - NodeModified event = new NodeModified<>( - new SimpleNode(randomIp()), - new SimpleNode(randomIp())); - Assert.assertNotNull(event.getNewNode()); - Assert.assertNotNull(event.getOldNode()); - Assert.assertNotEquals(event.getOldNode(), event.getNewNode()); - } - - public static class SimpleNode implements Node { + @Test + public void testGetOldNode() { + NodeModified event = + new NodeModified<>(new SimpleNode(randomIp()), new SimpleNode(randomIp())); + Assert.assertNotNull(event.getNewNode()); + Assert.assertNotNull(event.getOldNode()); + Assert.assertNotEquals(event.getOldNode(), event.getNewNode()); + } - private String ip; + public static class SimpleNode implements Node { - public SimpleNode(String ip) { - this.ip = ip; - } + private String ip; - @Override - public NodeType getNodeType() { - return NodeType.DATA; - } + public SimpleNode(String ip) { + this.ip = ip; + } - @Override - public URL getNodeUrl() { - return new URL(ip); - } + @Override + public NodeType getNodeType() { + return NodeType.DATA; } -} \ No newline at end of file + @Override + public URL getNodeUrl() { + return new URL(ip); + } + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/cluster/node/TestAbstractNodeEventTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/cluster/node/TestAbstractNodeEventTest.java index a7df6ebc2..10a9d5250 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/cluster/node/TestAbstractNodeEventTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/cluster/node/TestAbstractNodeEventTest.java @@ -23,15 +23,13 @@ public class TestAbstractNodeEventTest { - private Logger logger = LoggerFactory.getLogger(TestAbstractNodeEventTest.class); + private Logger logger = LoggerFactory.getLogger(TestAbstractNodeEventTest.class); - @Test - public void testGetNode() { - NodeModifiedTest.SimpleNode simpleNode = new NodeModifiedTest.SimpleNode( - "127.0.0.1"); - AbstractNodeEvent event = new AbstractNodeEvent(simpleNode) { - }; - Assert.assertEquals(simpleNode, event.getNode()); - logger.info("[testGetNode] {}", event); - } -} \ No newline at end of file + @Test + public void testGetNode() { + NodeModifiedTest.SimpleNode simpleNode = new NodeModifiedTest.SimpleNode("127.0.0.1"); + AbstractNodeEvent event = new AbstractNodeEvent(simpleNode) {}; + Assert.assertEquals(simpleNode, event.getNode()); + logger.info("[testGetNode] {}", event); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/LeaseTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/LeaseTest.java index bbbc371b9..433b77b18 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/LeaseTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/LeaseTest.java @@ -19,68 +19,67 @@ import com.alipay.sofa.registry.common.model.metaserver.Lease; import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; +import java.util.concurrent.TimeUnit; import org.junit.Assert; import org.junit.Test; -import java.util.concurrent.TimeUnit; - public class LeaseTest extends AbstractMetaServerTest { - private Lease lease; + private Lease lease; - @Test - public void testIsExpired() throws InterruptedException { - lease = new Lease<>(new Object(), 1, TimeUnit.MILLISECONDS); - Thread.sleep(2); - Assert.assertTrue(lease.isExpired()); - lease.renew(1); - Assert.assertFalse(lease.isExpired()); - } + @Test + public void testIsExpired() throws InterruptedException { + lease = new Lease<>(new Object(), 1, TimeUnit.MILLISECONDS); + Thread.sleep(2); + Assert.assertTrue(lease.isExpired()); + lease.renew(1); + Assert.assertFalse(lease.isExpired()); + } - @Test - public void testGetBeginTimestamp() throws InterruptedException { - lease = new Lease<>(new Object(), 1); - long begin = lease.getBeginTimestamp(); - lease.renew(); - Thread.sleep(5); - lease.renew(); - Assert.assertEquals(begin, lease.getBeginTimestamp()); - } + @Test + public void testGetBeginTimestamp() throws InterruptedException { + lease = new Lease<>(new Object(), 1); + long begin = lease.getBeginTimestamp(); + lease.renew(); + Thread.sleep(5); + lease.renew(); + Assert.assertEquals(begin, lease.getBeginTimestamp()); + } - @Test - public void testGetLastUpdateTimestamp() throws InterruptedException { - lease = new Lease<>(new Object(), 1); - long firstUpdate = lease.getLastUpdateTimestamp(); - lease.renew(); - Thread.sleep(5); - lease.renew(); - Assert.assertNotEquals(firstUpdate, lease.getLastUpdateTimestamp()); - } + @Test + public void testGetLastUpdateTimestamp() throws InterruptedException { + lease = new Lease<>(new Object(), 1); + long firstUpdate = lease.getLastUpdateTimestamp(); + lease.renew(); + Thread.sleep(5); + lease.renew(); + Assert.assertNotEquals(firstUpdate, lease.getLastUpdateTimestamp()); + } - @Test - public void testSetRenewal() { - Object first = new Object(); - lease = new Lease<>(first, 1); - lease.renew(); - Object second = new Object(); - lease.setRenewal(second); - Assert.assertNotEquals(first, lease.getRenewal()); - } + @Test + public void testSetRenewal() { + Object first = new Object(); + lease = new Lease<>(first, 1); + lease.renew(); + Object second = new Object(); + lease.setRenewal(second); + Assert.assertNotEquals(first, lease.getRenewal()); + } - @Test - public void testEquals() throws InterruptedException { - DataNode sample = new DataNode(randomURL(randomIp()), getDc()); - Lease lease1 = new Lease<>(new Object(), 1, TimeUnit.MILLISECONDS); - Lease lease2 = new Lease<>(sample, 1, TimeUnit.MILLISECONDS); - Thread.sleep(5); - Lease lease3 = new Lease<>(new DataNode(sample.getNodeUrl(), getDc()), 1, - TimeUnit.MILLISECONDS); - Lease lease4 = lease2; - lease4.setRenewal(lease3.getRenewal()); + @Test + public void testEquals() throws InterruptedException { + DataNode sample = new DataNode(randomURL(randomIp()), getDc()); + Lease lease1 = new Lease<>(new Object(), 1, TimeUnit.MILLISECONDS); + Lease lease2 = new Lease<>(sample, 1, TimeUnit.MILLISECONDS); + Thread.sleep(5); + Lease lease3 = + new Lease<>(new DataNode(sample.getNodeUrl(), getDc()), 1, TimeUnit.MILLISECONDS); + Lease lease4 = lease2; + lease4.setRenewal(lease3.getRenewal()); - Assert.assertNotEquals(lease1, lease2); - Assert.assertNotEquals(lease2, lease3); - Assert.assertEquals(lease2, lease4); - Assert.assertNotEquals(lease2.hashCode(), lease3.hashCode()); - } -} \ No newline at end of file + Assert.assertNotEquals(lease1, lease2); + Assert.assertNotEquals(lease2, lease3); + Assert.assertEquals(lease2, lease4); + Assert.assertNotEquals(lease2.hashCode(), lease3.hashCode()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/data/DefaultDataServerManagerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/data/DefaultDataServerManagerTest.java index 64a319e2f..10b5d722e 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/data/DefaultDataServerManagerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/data/DefaultDataServerManagerTest.java @@ -16,9 +16,12 @@ */ package com.alipay.sofa.registry.server.meta.lease.data; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; import com.alipay.sofa.registry.server.meta.bootstrap.config.MetaServerConfig; +import java.util.concurrent.TimeoutException; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -26,78 +29,77 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.when; - public class DefaultDataServerManagerTest extends AbstractMetaServerTest { - private DefaultDataServerManager dataServerManager; + private DefaultDataServerManager dataServerManager; - @Mock - private MetaServerConfig metaServerConfig; + @Mock private MetaServerConfig metaServerConfig; - @Before - public void beforeDefaultdataServerManagerTest() throws Exception { - MockitoAnnotations.initMocks(this); - dataServerManager = new DefaultDataServerManager(metaServerConfig) { + @Before + public void beforeDefaultdataServerManagerTest() throws Exception { + MockitoAnnotations.initMocks(this); + dataServerManager = + new DefaultDataServerManager(metaServerConfig) { - @Override - protected boolean amILeader() { - return true; - } + @Override + protected boolean amILeader() { + return true; + } }; - dataServerManager.setMetaServerConfig(metaServerConfig); - when(metaServerConfig.getExpireCheckIntervalMilli()).thenReturn(60); - dataServerManager.postConstruct(); - } + dataServerManager.setMetaServerConfig(metaServerConfig); + when(metaServerConfig.getExpireCheckIntervalMilli()).thenReturn(60); + dataServerManager.postConstruct(); + } - @After - public void afterDefaultdataServerManagerTest() throws Exception { - dataServerManager.preDestory(); - } + @After + public void afterDefaultdataServerManagerTest() throws Exception { + dataServerManager.preDestory(); + } - @Test - public void testGetEpoch() { -// dataServerManager.setRaftDataLeaseManager((LeaseManager) Proxy.newProxyInstance( -// Thread.currentThread().getContextClassLoader(), new Class[] { LeaseManager.class }, -// new InvocationHandler() { -// @Override -// public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { -// return method.invoke(dataServerManager.getLocalLeaseManager(), args); -// } -// })); - Assert.assertEquals(0, dataServerManager.getEpoch()); - dataServerManager.renew(new DataNode(randomURL(randomIp()), getDc()), 1000); - dataServerManager.renew(new DataNode(randomURL(randomIp()), getDc()), 1000); - Assert.assertNotEquals(0, dataServerManager.getEpoch()); - } + @Test + public void testGetEpoch() { + // dataServerManager.setRaftDataLeaseManager((LeaseManager) + // Proxy.newProxyInstance( + // Thread.currentThread().getContextClassLoader(), new Class[] { LeaseManager.class + // }, + // new InvocationHandler() { + // @Override + // public Object invoke(Object proxy, Method method, Object[] args) throws + // Throwable { + // return method.invoke(dataServerManager.getLocalLeaseManager(), args); + // } + // })); + Assert.assertEquals(0, dataServerManager.getEpoch()); + dataServerManager.renew(new DataNode(randomURL(randomIp()), getDc()), 1000); + dataServerManager.renew(new DataNode(randomURL(randomIp()), getDc()), 1000); + Assert.assertNotEquals(0, dataServerManager.getEpoch()); + } - @Test - public void testIsLeaderGetClusterMembers() throws TimeoutException, InterruptedException { - DataNode node = new DataNode(randomURL(randomIp()), getDc()); -// dataServerManager.getLocalLeaseManager().renew(node, 1000); -// makeRaftLeader(); -// dataServerManager.renew(node, 1000); -// Assert.assertEquals(1, dataServerManager.getClusterMembers().size()); -// verify(dataServerManager.getLocalLeaseManager(), atLeast(1)).getClusterMembers(); - } + @Test + public void testIsLeaderGetClusterMembers() throws TimeoutException, InterruptedException { + DataNode node = new DataNode(randomURL(randomIp()), getDc()); + // dataServerManager.getLocalLeaseManager().renew(node, 1000); + // makeRaftLeader(); + // dataServerManager.renew(node, 1000); + // Assert.assertEquals(1, dataServerManager.getClusterMembers().size()); + // verify(dataServerManager.getLocalLeaseManager(), atLeast(1)).getClusterMembers(); + } - @Test - public void testEvitTime() { - Assert.assertEquals(60, dataServerManager.getEvictBetweenMilli()); - } + @Test + public void testEvitTime() { + Assert.assertEquals(60, dataServerManager.getEvictBetweenMilli()); + } - @Test - public void testDataServerManagerRefreshEpochOnlyOnceWhenNewRegistered() - throws TimeoutException, - InterruptedException { - makeMetaLeader(); - DataNode node = new DataNode(randomURL(randomIp()), getDc()); -// DataLeaseManager leaseManager = spy(new DataLeaseManager()); -// dataServerManager.setDataLeaseManager(leaseManager).setRaftDataLeaseManager(leaseManager); -// dataServerManager.renew(node, 1000); -// Assert.assertEquals(1, dataServerManager.getClusterMembers().size()); -// verify(leaseManager, times(1)).refreshEpoch(anyLong()); - } -} \ No newline at end of file + @Test + public void testDataServerManagerRefreshEpochOnlyOnceWhenNewRegistered() + throws TimeoutException, InterruptedException { + makeMetaLeader(); + DataNode node = new DataNode(randomURL(randomIp()), getDc()); + // DataLeaseManager leaseManager = spy(new DataLeaseManager()); + // + // dataServerManager.setDataLeaseManager(leaseManager).setRaftDataLeaseManager(leaseManager); + // dataServerManager.renew(node, 1000); + // Assert.assertEquals(1, dataServerManager.getClusterMembers().size()); + // verify(leaseManager, times(1)).refreshEpoch(anyLong()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/impl/CrossDcMetaServerManagerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/impl/CrossDcMetaServerManagerTest.java index f0449db14..cd57de3e8 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/impl/CrossDcMetaServerManagerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/impl/CrossDcMetaServerManagerTest.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.lease.impl; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.exception.InitializeException; import com.alipay.sofa.registry.lifecycle.impl.LifecycleHelper; import com.alipay.sofa.registry.remoting.bolt.exchange.BoltExchange; @@ -24,6 +26,9 @@ import com.alipay.sofa.registry.server.meta.bootstrap.config.NodeConfig; import com.alipay.sofa.registry.server.meta.metaserver.CrossDcMetaServer; import com.google.common.collect.ImmutableMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.TimeoutException; import org.assertj.core.util.Lists; import org.assertj.core.util.Sets; import org.junit.After; @@ -33,110 +38,119 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.when; - public class CrossDcMetaServerManagerTest extends AbstractMetaServerTest { - private DefaultCrossDcMetaServerManager crossDcMetaServerManager; + private DefaultCrossDcMetaServerManager crossDcMetaServerManager; - @Mock - private NodeConfig nodeConfig; + @Mock private NodeConfig nodeConfig; - @Mock - private MetaServerConfig metaServerConfig; + @Mock private MetaServerConfig metaServerConfig; - @Mock - private BoltExchange boltExchange; + @Mock private BoltExchange boltExchange; - @Before - public void beforeCrossDcMetaServerManagerTest() { - MockitoAnnotations.initMocks(this); - crossDcMetaServerManager = new DefaultCrossDcMetaServerManager() - .setMetaServerConfig(metaServerConfig).setBoltExchange(boltExchange) - .setExecutors(executors).setNodeConfig(nodeConfig).setScheduled(scheduled); - when(metaServerConfig.getCrossDcMetaSyncIntervalMilli()).thenReturn(10000); - } + @Before + public void beforeCrossDcMetaServerManagerTest() { + MockitoAnnotations.initMocks(this); + crossDcMetaServerManager = + new DefaultCrossDcMetaServerManager() + .setMetaServerConfig(metaServerConfig) + .setBoltExchange(boltExchange) + .setExecutors(executors) + .setNodeConfig(nodeConfig) + .setScheduled(scheduled); + when(metaServerConfig.getCrossDcMetaSyncIntervalMilli()).thenReturn(10000); + } - @After - public void afterCrossDcMetaServerManagerTest() throws Exception { - crossDcMetaServerManager.preDestory(); - } + @After + public void afterCrossDcMetaServerManagerTest() throws Exception { + crossDcMetaServerManager.preDestory(); + } - @Test - public void testGetOrCreate() throws InterruptedException { - int tasks = 100; - when(nodeConfig.getDataCenterMetaServers(getDc())).thenReturn( - Sets.newLinkedHashSet(randomIp(), randomIp(), randomIp())); - CountDownLatch latch = new CountDownLatch(tasks); - CyclicBarrier barrier = new CyclicBarrier(tasks); - for (int i = 0; i < tasks; i++) { - executors.execute(new Runnable() { - @Override - public void run() { - try { - barrier.await(); - } catch (Exception ignore) { - } - crossDcMetaServerManager.getOrCreate(getDc()); - latch.countDown(); - } - }); - } - latch.await(); - Assert.assertEquals(1, crossDcMetaServerManager.getCrossDcMetaServers().size()); - Assert.assertTrue(crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState() - .canStart()); - Assert.assertTrue(crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState() - .isInitialized()); + @Test + public void testGetOrCreate() throws InterruptedException { + int tasks = 100; + when(nodeConfig.getDataCenterMetaServers(getDc())) + .thenReturn(Sets.newLinkedHashSet(randomIp(), randomIp(), randomIp())); + CountDownLatch latch = new CountDownLatch(tasks); + CyclicBarrier barrier = new CyclicBarrier(tasks); + for (int i = 0; i < tasks; i++) { + executors.execute( + new Runnable() { + @Override + public void run() { + try { + barrier.await(); + } catch (Exception ignore) { + } + crossDcMetaServerManager.getOrCreate(getDc()); + latch.countDown(); + } + }); } + latch.await(); + Assert.assertEquals(1, crossDcMetaServerManager.getCrossDcMetaServers().size()); + Assert.assertTrue(crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().canStart()); + Assert.assertTrue( + crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().isInitialized()); + } - @Test - public void testRemove() { - } + @Test + public void testRemove() {} - @Test - public void testIsLeader() throws Exception { - when(nodeConfig.getDataCenterMetaServers(getDc())).thenReturn(Sets.newLinkedHashSet(randomIp(), randomIp(), randomIp())); - when(nodeConfig.getMetaNodeIP()).thenReturn(ImmutableMap.of( - getDc(), Lists.newArrayList(randomIp(), randomIp(), randomIp()), - "dc2", Lists.newArrayList(randomIp(), randomIp(), randomIp()), - "dc3", Lists.newArrayList(randomIp(), randomIp(), randomIp()) - )); - crossDcMetaServerManager.postConstruct(); - crossDcMetaServerManager.becomeLeader(); - waitConditionUntilTimeOut(()->crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().isStarted(), 1000); - //wait for concurrent modification - Thread.sleep(10); - Assert.assertTrue(crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().isStarted()); - for(CrossDcMetaServer metaServer : crossDcMetaServerManager.getCrossDcMetaServers().values()) { - Assert.assertTrue(metaServer.getLifecycleState().isStarted()); - } + @Test + public void testIsLeader() throws Exception { + when(nodeConfig.getDataCenterMetaServers(getDc())) + .thenReturn(Sets.newLinkedHashSet(randomIp(), randomIp(), randomIp())); + when(nodeConfig.getMetaNodeIP()) + .thenReturn( + ImmutableMap.of( + getDc(), + Lists.newArrayList(randomIp(), randomIp(), randomIp()), + "dc2", + Lists.newArrayList(randomIp(), randomIp(), randomIp()), + "dc3", + Lists.newArrayList(randomIp(), randomIp(), randomIp()))); + crossDcMetaServerManager.postConstruct(); + crossDcMetaServerManager.becomeLeader(); + waitConditionUntilTimeOut( + () -> crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().isStarted(), 1000); + // wait for concurrent modification + Thread.sleep(10); + Assert.assertTrue( + crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().isStarted()); + for (CrossDcMetaServer metaServer : crossDcMetaServerManager.getCrossDcMetaServers().values()) { + Assert.assertTrue(metaServer.getLifecycleState().isStarted()); } + } - @Test - public void testNotLeader() throws InitializeException, TimeoutException, InterruptedException { - when(nodeConfig.getDataCenterMetaServers(getDc())).thenReturn(Sets.newLinkedHashSet(randomIp(), randomIp(), randomIp())); - when(nodeConfig.getMetaNodeIP()).thenReturn(ImmutableMap.of( - getDc(), Lists.newArrayList(randomIp(), randomIp(), randomIp()), - "dc2", Lists.newArrayList(randomIp(), randomIp(), randomIp()), - "dc3", Lists.newArrayList(randomIp(), randomIp(), randomIp()) - )); - LifecycleHelper.initializeIfPossible(crossDcMetaServerManager); - crossDcMetaServerManager.becomeLeader(); - waitConditionUntilTimeOut(()->crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().isStarted(), 1000); - //wait for concurrent modification - Thread.sleep(10); - Assert.assertTrue(crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().isStarted()); - crossDcMetaServerManager.loseLeader(); - waitConditionUntilTimeOut(()->crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().isStopped(), 1000); - //wait for concurrent modification - Thread.sleep(10); - for(CrossDcMetaServer metaServer : crossDcMetaServerManager.getCrossDcMetaServers().values()) { - Assert.assertTrue(metaServer.getLifecycleState().isStopped()); - } + @Test + public void testNotLeader() throws InitializeException, TimeoutException, InterruptedException { + when(nodeConfig.getDataCenterMetaServers(getDc())) + .thenReturn(Sets.newLinkedHashSet(randomIp(), randomIp(), randomIp())); + when(nodeConfig.getMetaNodeIP()) + .thenReturn( + ImmutableMap.of( + getDc(), + Lists.newArrayList(randomIp(), randomIp(), randomIp()), + "dc2", + Lists.newArrayList(randomIp(), randomIp(), randomIp()), + "dc3", + Lists.newArrayList(randomIp(), randomIp(), randomIp()))); + LifecycleHelper.initializeIfPossible(crossDcMetaServerManager); + crossDcMetaServerManager.becomeLeader(); + waitConditionUntilTimeOut( + () -> crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().isStarted(), 1000); + // wait for concurrent modification + Thread.sleep(10); + Assert.assertTrue( + crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().isStarted()); + crossDcMetaServerManager.loseLeader(); + waitConditionUntilTimeOut( + () -> crossDcMetaServerManager.getOrCreate(getDc()).getLifecycleState().isStopped(), 1000); + // wait for concurrent modification + Thread.sleep(10); + for (CrossDcMetaServer metaServer : crossDcMetaServerManager.getCrossDcMetaServers().values()) { + Assert.assertTrue(metaServer.getLifecycleState().isStopped()); } -} \ No newline at end of file + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/impl/TestAbstractRaftEnabledLeaseManager.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/impl/TestAbstractRaftEnabledLeaseManager.java index ca8520ea7..d9b10ee4a 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/impl/TestAbstractRaftEnabledLeaseManager.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/impl/TestAbstractRaftEnabledLeaseManager.java @@ -20,243 +20,243 @@ public class TestAbstractRaftEnabledLeaseManager extends AbstractMetaServerTest { - private String snapshotFile = "TEST-SERVICE-ID"; + private String snapshotFile = "TEST-SERVICE-ID"; - // private final AbstractCachablePersistenceLeaseManager - // localLeaseManager = spy(new AbstractCachablePersistenceLeaseManager<>( - // snapshotFile)); - // - // private final AtomicReference> raftLeaseManager = - // new AtomicReference<>(); - // - // private final AtomicInteger evitTimeMilli = new AtomicInteger( - // 1000 * 60); - // - // private final AtomicBoolean leaderNotify = new AtomicBoolean( - // true); - // - // private AbstractRaftEnabledLeaseManager manager = new - // AbstractRaftEnabledLeaseManager() { - // @Override - // protected long getIntervalMilli() { - // return evitTimeMilli - // .get(); - // } - // - // @Override - // protected AbstractCachablePersistenceLeaseManager - // getLocalLeaseManager() { - // return localLeaseManager; - // } - // - // @Override - // protected LeaseManager getRaftLeaseManager() { - // return raftLeaseManager - // .get(); - // } - // - // @Override - // protected long getEvictBetweenMilli() { - // return evitTimeMilli - // .get(); - // } - // - // @Override - // protected boolean isRaftLeader() { - // return leaderNotify - // .get(); - // } - // }; - // - // private RaftExchanger raftExchanger; - // - // @Before - // public void beforeTestAbstractRaftEnabledLeaseManager() throws - // InitializeException, - // StartException { - // raftExchanger = mock(RaftExchanger.class); - // raftLeaseManager.set((LeaseManager) - // Proxy.newProxyInstance(Thread.currentThread() - // .getContextClassLoader(), new Class[] { LeaseManager.class }, new - // InvocationHandler() { - // @Override - // public Object invoke(Object proxy, Method method, Object[] args) throws - // Throwable { - // return method.invoke(localLeaseManager, args); - // } - // })); - // manager.setScheduled(scheduled).setExecutors(executors); - // LifecycleHelper.initializeIfPossible(manager); - // LifecycleHelper.startIfPossible(manager); - // } - // - // @After - // public void afterTestAbstractRaftEnabledLeaseManager() throws - // StopException, DisposeException { - // LifecycleHelper.stopIfPossible(manager); - // LifecycleHelper.disposeIfPossible(manager); - // } - // - // @Test - // public void testRunRaftProxy() throws Exception { - // leaderNotify.set(false); - // int size = manager.getClusterMembers().size(); - // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); - // manager.renew(node, 10); - // waitConditionUntilTimeOut(()->manager.getLease(node) != null, 1000); - // Assert.assertEquals(node, manager.getLease(node).getRenewal()); - // Assert.assertFalse(manager.getLease(node).isExpired()); - // Assert.assertTrue(manager.getClusterMembers().size() > size); - // manager.cancel(manager.getLease(node).prepareCancel()); - // waitConditionUntilTimeOut(()->manager.getClusterMembers().size() == size, - // 1000); - // Assert.assertEquals(size, manager.getClusterMembers().size()); - // } - // - // @Test - // public void testRaftBatchInsert() throws Exception { - // leaderNotify.set(false); - // int tasks = 100; - // CyclicBarrier barrier = new CyclicBarrier(tasks / 10); - // CountDownLatch latch = new CountDownLatch(tasks); - // for (int i = 0; i < tasks; i++) { - // executors.execute(new Runnable() { - // @Override - // public void run() { - // try { - // barrier.await(); - // } catch (Exception ignore) { - // } - // manager.renew(new MetaNode(randomURL(randomIp()), getDc()), 10); - // latch.countDown(); - // } - // }); - // } - // logger.info("[count] {}", latch.getCount()); - // TimeUnit.MILLISECONDS.sleep(1000); - // logger.info("[count] {}", latch.getCount()); - // latch.await(3, TimeUnit.SECONDS); - // Assert.assertEquals(tasks, manager.getClusterMembers().size()); - // } - // - // @Test - // public void testRegister() { - // manager.renew(new MetaNode(randomURL(randomIp()), getDc()), 10); - // Assert.assertEquals(1, manager.getClusterMembers().size()); - // Lease lease = - // manager.getLease(manager.getClusterMembers().get(0)); - // Assert.assertFalse(lease.isExpired()); - // } - // - // @Test(expected = UnsupportedOperationException.class) - // public void testDirectRegister() { - // manager.register(new Lease(new MetaNode(randomURL(), getDc()), - // 1)); - // } - // - // @Test - // public void testGetEpoch() throws TimeoutException, InterruptedException - // { - // raftLeaseManager.set(spy(new - // AbstractCachablePersistenceLeaseManager<>(snapshotFile))); - // leaderNotify.set(true); - // manager.getEpoch(); - // verify(raftLeaseManager.get(), never()).getEpoch(); - // - // leaderNotify.set(false); - // manager.getEpoch(); - // verify(raftLeaseManager.get(), times(1)).getEpoch(); - // } - // - // @Test - // public void testCancel() { - // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); - // manager.renew(node, 10); - // Assert.assertEquals(1, manager.getClusterMembers().size()); - // manager.cancel(manager.getLease(node).prepareCancel()); - // Assert.assertEquals(0, manager.getClusterMembers().size()); - // } - // - // @Test - // public void testRenew() throws InterruptedException { - // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); - // manager.renew(node, 1); - // Assert.assertEquals(1, manager.getClusterMembers().size()); - // Lease lease = manager.getLease(node); - // long prevLastUpdateTime = lease.getLastUpdateTimestamp(); - // long prevBeginTime = lease.getBeginTimestamp(); - // // let time pass, so last update time could be diff - // Thread.sleep(5); - // manager.renew(node, 10); - // lease = manager.getLease(node); - // Assert.assertEquals(prevBeginTime, lease.getBeginTimestamp()); - // Assert.assertNotEquals(prevLastUpdateTime, - // lease.getLastUpdateTimestamp()); - // } - // - // @Test - // public void testEvict() throws InterruptedException { - // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); - // manager.renew(node, 1); - // Assert.assertEquals(1, manager.getClusterMembers().size()); - // TimeUnit.SECONDS.sleep(1); - // TimeUnit.MILLISECONDS.sleep(100); - // manager.evict(); - // Assert.assertEquals(0, manager.getClusterMembers().size()); - // } - // - // @Test - // public void testEvictTooQuick() throws InterruptedException { - // manager = spy(manager); - // evitTimeMilli.set(3000); - // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); - // manager.renew(node, 1); - // Assert.assertEquals(1, manager.getClusterMembers().size()); - // manager.evict(); - // manager.evict(); - // manager.evict(); - // verify(localLeaseManager, times(1)).getExpiredLeases(); - // } - // - // @Test - // public void testEvitTooQuickThreadSafe() throws InterruptedException { - // manager = spy(manager); - // evitTimeMilli.set(1000); - // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); - // manager.renew(node, 1); - // Assert.assertEquals(1, manager.getClusterMembers().size()); - // int tasks = 100; - // CyclicBarrier barrier = new CyclicBarrier(tasks); - // CountDownLatch latch = new CountDownLatch(tasks); - // for (int i = 0; i < tasks; i++) { - // executors.execute(new Runnable() { - // @Override - // public void run() { - // try { - // barrier.await(); - // } catch (Exception ignore) { - // } - // manager.evict(); - // latch.countDown(); - // } - // }); - // } - // latch.await(); - // verify(localLeaseManager, times(1)).getExpiredLeases(); - // } - // - // @Test - // public void testEvictConcurrentModificateWithRenew() { - // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); - // manager.renew(node, 10); - // verify(localLeaseManager, times(1)).getLease(node); - // - // Assert.assertEquals(1, manager.getClusterMembers().size()); - // when(localLeaseManager.getExpiredLeases()).thenReturn( - // Lists.newArrayList(new Lease(node, 1000))); - // manager.evict(); - // verify(localLeaseManager, times(2)).getLease(node); - // Assert.assertEquals(1, manager.getClusterMembers().size()); - // } + // private final AbstractCachablePersistenceLeaseManager + // localLeaseManager = spy(new AbstractCachablePersistenceLeaseManager<>( + // snapshotFile)); + // + // private final AtomicReference> raftLeaseManager = + // new AtomicReference<>(); + // + // private final AtomicInteger evitTimeMilli = new AtomicInteger( + // 1000 * 60); + // + // private final AtomicBoolean leaderNotify = new AtomicBoolean( + // true); + // + // private AbstractRaftEnabledLeaseManager manager = new + // AbstractRaftEnabledLeaseManager() { + // @Override + // protected long getIntervalMilli() { + // return evitTimeMilli + // .get(); + // } + // + // @Override + // protected AbstractCachablePersistenceLeaseManager + // getLocalLeaseManager() { + // return localLeaseManager; + // } + // + // @Override + // protected LeaseManager getRaftLeaseManager() { + // return raftLeaseManager + // .get(); + // } + // + // @Override + // protected long getEvictBetweenMilli() { + // return evitTimeMilli + // .get(); + // } + // + // @Override + // protected boolean isRaftLeader() { + // return leaderNotify + // .get(); + // } + // }; + // + // private RaftExchanger raftExchanger; + // + // @Before + // public void beforeTestAbstractRaftEnabledLeaseManager() throws + // InitializeException, + // StartException { + // raftExchanger = mock(RaftExchanger.class); + // raftLeaseManager.set((LeaseManager) + // Proxy.newProxyInstance(Thread.currentThread() + // .getContextClassLoader(), new Class[] { LeaseManager.class }, new + // InvocationHandler() { + // @Override + // public Object invoke(Object proxy, Method method, Object[] args) throws + // Throwable { + // return method.invoke(localLeaseManager, args); + // } + // })); + // manager.setScheduled(scheduled).setExecutors(executors); + // LifecycleHelper.initializeIfPossible(manager); + // LifecycleHelper.startIfPossible(manager); + // } + // + // @After + // public void afterTestAbstractRaftEnabledLeaseManager() throws + // StopException, DisposeException { + // LifecycleHelper.stopIfPossible(manager); + // LifecycleHelper.disposeIfPossible(manager); + // } + // + // @Test + // public void testRunRaftProxy() throws Exception { + // leaderNotify.set(false); + // int size = manager.getClusterMembers().size(); + // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); + // manager.renew(node, 10); + // waitConditionUntilTimeOut(()->manager.getLease(node) != null, 1000); + // Assert.assertEquals(node, manager.getLease(node).getRenewal()); + // Assert.assertFalse(manager.getLease(node).isExpired()); + // Assert.assertTrue(manager.getClusterMembers().size() > size); + // manager.cancel(manager.getLease(node).prepareCancel()); + // waitConditionUntilTimeOut(()->manager.getClusterMembers().size() == size, + // 1000); + // Assert.assertEquals(size, manager.getClusterMembers().size()); + // } + // + // @Test + // public void testRaftBatchInsert() throws Exception { + // leaderNotify.set(false); + // int tasks = 100; + // CyclicBarrier barrier = new CyclicBarrier(tasks / 10); + // CountDownLatch latch = new CountDownLatch(tasks); + // for (int i = 0; i < tasks; i++) { + // executors.execute(new Runnable() { + // @Override + // public void run() { + // try { + // barrier.await(); + // } catch (Exception ignore) { + // } + // manager.renew(new MetaNode(randomURL(randomIp()), getDc()), 10); + // latch.countDown(); + // } + // }); + // } + // logger.info("[count] {}", latch.getCount()); + // TimeUnit.MILLISECONDS.sleep(1000); + // logger.info("[count] {}", latch.getCount()); + // latch.await(3, TimeUnit.SECONDS); + // Assert.assertEquals(tasks, manager.getClusterMembers().size()); + // } + // + // @Test + // public void testRegister() { + // manager.renew(new MetaNode(randomURL(randomIp()), getDc()), 10); + // Assert.assertEquals(1, manager.getClusterMembers().size()); + // Lease lease = + // manager.getLease(manager.getClusterMembers().get(0)); + // Assert.assertFalse(lease.isExpired()); + // } + // + // @Test(expected = UnsupportedOperationException.class) + // public void testDirectRegister() { + // manager.register(new Lease(new MetaNode(randomURL(), getDc()), + // 1)); + // } + // + // @Test + // public void testGetEpoch() throws TimeoutException, InterruptedException + // { + // raftLeaseManager.set(spy(new + // AbstractCachablePersistenceLeaseManager<>(snapshotFile))); + // leaderNotify.set(true); + // manager.getEpoch(); + // verify(raftLeaseManager.get(), never()).getEpoch(); + // + // leaderNotify.set(false); + // manager.getEpoch(); + // verify(raftLeaseManager.get(), times(1)).getEpoch(); + // } + // + // @Test + // public void testCancel() { + // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); + // manager.renew(node, 10); + // Assert.assertEquals(1, manager.getClusterMembers().size()); + // manager.cancel(manager.getLease(node).prepareCancel()); + // Assert.assertEquals(0, manager.getClusterMembers().size()); + // } + // + // @Test + // public void testRenew() throws InterruptedException { + // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); + // manager.renew(node, 1); + // Assert.assertEquals(1, manager.getClusterMembers().size()); + // Lease lease = manager.getLease(node); + // long prevLastUpdateTime = lease.getLastUpdateTimestamp(); + // long prevBeginTime = lease.getBeginTimestamp(); + // // let time pass, so last update time could be diff + // Thread.sleep(5); + // manager.renew(node, 10); + // lease = manager.getLease(node); + // Assert.assertEquals(prevBeginTime, lease.getBeginTimestamp()); + // Assert.assertNotEquals(prevLastUpdateTime, + // lease.getLastUpdateTimestamp()); + // } + // + // @Test + // public void testEvict() throws InterruptedException { + // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); + // manager.renew(node, 1); + // Assert.assertEquals(1, manager.getClusterMembers().size()); + // TimeUnit.SECONDS.sleep(1); + // TimeUnit.MILLISECONDS.sleep(100); + // manager.evict(); + // Assert.assertEquals(0, manager.getClusterMembers().size()); + // } + // + // @Test + // public void testEvictTooQuick() throws InterruptedException { + // manager = spy(manager); + // evitTimeMilli.set(3000); + // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); + // manager.renew(node, 1); + // Assert.assertEquals(1, manager.getClusterMembers().size()); + // manager.evict(); + // manager.evict(); + // manager.evict(); + // verify(localLeaseManager, times(1)).getExpiredLeases(); + // } + // + // @Test + // public void testEvitTooQuickThreadSafe() throws InterruptedException { + // manager = spy(manager); + // evitTimeMilli.set(1000); + // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); + // manager.renew(node, 1); + // Assert.assertEquals(1, manager.getClusterMembers().size()); + // int tasks = 100; + // CyclicBarrier barrier = new CyclicBarrier(tasks); + // CountDownLatch latch = new CountDownLatch(tasks); + // for (int i = 0; i < tasks; i++) { + // executors.execute(new Runnable() { + // @Override + // public void run() { + // try { + // barrier.await(); + // } catch (Exception ignore) { + // } + // manager.evict(); + // latch.countDown(); + // } + // }); + // } + // latch.await(); + // verify(localLeaseManager, times(1)).getExpiredLeases(); + // } + // + // @Test + // public void testEvictConcurrentModificateWithRenew() { + // MetaNode node = new MetaNode(randomURL(randomIp()), getDc()); + // manager.renew(node, 10); + // verify(localLeaseManager, times(1)).getLease(node); + // + // Assert.assertEquals(1, manager.getClusterMembers().size()); + // when(localLeaseManager.getExpiredLeases()).thenReturn( + // Lists.newArrayList(new Lease(node, 1000))); + // manager.evict(); + // verify(localLeaseManager, times(2)).getLease(node); + // Assert.assertEquals(1, manager.getClusterMembers().size()); + // } -} \ No newline at end of file +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/session/DefaultSessionServerManagerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/session/DefaultSessionServerManagerTest.java index 7b31e7995..69e479f38 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/session/DefaultSessionServerManagerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/lease/session/DefaultSessionServerManagerTest.java @@ -16,10 +16,13 @@ */ package com.alipay.sofa.registry.server.meta.lease.session; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.common.model.ProcessId; import com.alipay.sofa.registry.common.model.metaserver.nodes.SessionNode; import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; import com.alipay.sofa.registry.server.meta.bootstrap.config.MetaServerConfig; +import java.util.concurrent.TimeoutException; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -27,95 +30,88 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.when; - public class DefaultSessionServerManagerTest extends AbstractMetaServerTest { - private DefaultSessionServerManager sessionManager; + private DefaultSessionServerManager sessionManager; - @Mock - private MetaServerConfig metaServerConfig; + @Mock private MetaServerConfig metaServerConfig; - @Before - public void beforeDefaultSessionManagerTest() throws Exception { - MockitoAnnotations.initMocks(this); - sessionManager = new DefaultSessionServerManager() { - @Override - protected boolean amILeader() { - return true; - } + @Before + public void beforeDefaultSessionManagerTest() throws Exception { + MockitoAnnotations.initMocks(this); + sessionManager = + new DefaultSessionServerManager() { + @Override + protected boolean amILeader() { + return true; + } }; -// SessionLeaseManager sessionLeaseManager = new SessionLeaseManager(); - sessionManager.setMetaServerConfig(metaServerConfig) -// .setSessionLeaseManager(sessionLeaseManager) -// .setRaftSessionLeaseManager(sessionLeaseManager) - ; - when(metaServerConfig.getExpireCheckIntervalMilli()).thenReturn(60); - sessionManager.postConstruct(); - } - - @After - public void afterDefaultSessionManagerTest() throws Exception { - sessionManager.preDestory(); - } - - @Test - public void testGetEpoch() throws TimeoutException, InterruptedException { - Assert.assertEquals(0, sessionManager.getEpoch()); - sessionManager.renew(new SessionNode(randomURL(randomIp()), getDc()), 1000); - waitConditionUntilTimeOut(()->sessionManager.getEpoch() > 0, 100); - Assert.assertNotEquals(0, sessionManager.getEpoch()); - } - - @Test - public void testGetClusterMembers() { - Assert.assertTrue(sessionManager.getSessionServerMetaInfo().getClusterMembers().isEmpty()); - } - - @Test - public void testRenew() throws TimeoutException, InterruptedException { -// SessionLeaseManager leaseManager = spy(new SessionLeaseManager()); -// sessionManager.setRaftSessionLeaseManager(leaseManager) -// .setSessionLeaseManager(leaseManager); - SessionNode sessionNode = new SessionNode(randomURL(randomIp()), getDc()); - long timestamp = System.currentTimeMillis(); - sessionNode - .setProcessId(new ProcessId(sessionNode.getIp(), timestamp, 1, random.nextInt())); - NotifyObserversCounter counter = new NotifyObserversCounter(); - sessionManager.addObserver(counter); - - makeMetaLeader(); - - sessionManager.renew(sessionNode, 1); -// verify(leaseManager, times(1)).register(any()); - Assert.assertEquals(1, counter.getCounter()); - - sessionManager.renew(sessionNode, 1); -// verify(leaseManager, times(1)).register(any()); - Assert.assertEquals(1, counter.getCounter()); - - SessionNode sessionNode2 = new SessionNode(sessionNode.getNodeUrl(), getDc()); - sessionNode2 - .setProcessId(new ProcessId(sessionNode.getIp(), timestamp, 2, random.nextInt())); - Assert.assertFalse(sessionManager.renew(sessionNode2, 1)); -// verify(leaseManager, times(2)).register(any()); -// verify(leaseManager, times(1)).renew(any(), anyInt()); - Assert.assertEquals(2, counter.getCounter()); - } - - @Test - public void testDataServerManagerRefreshEpochOnlyOnceWhenNewRegistered() - throws TimeoutException, - InterruptedException { - makeMetaLeader(); - SessionNode node = new SessionNode(randomURL(randomIp()), getDc()); -// SessionLeaseManager leaseManager = spy(new SessionLeaseManager()); -// sessionManager.setSessionLeaseManager(leaseManager) -// .setRaftSessionLeaseManager(leaseManager); - sessionManager.renew(node, 1000); - Assert.assertEquals(1, sessionManager.getSessionServerMetaInfo().getClusterMembers().size()); -// verify(leaseManager, times(1)).refreshEpoch(anyLong()); - } -} \ No newline at end of file + // SessionLeaseManager sessionLeaseManager = new SessionLeaseManager(); + sessionManager.setMetaServerConfig(metaServerConfig) + // .setSessionLeaseManager(sessionLeaseManager) + // .setRaftSessionLeaseManager(sessionLeaseManager) + ; + when(metaServerConfig.getExpireCheckIntervalMilli()).thenReturn(60); + sessionManager.postConstruct(); + } + + @After + public void afterDefaultSessionManagerTest() throws Exception { + sessionManager.preDestory(); + } + + @Test + public void testGetEpoch() throws TimeoutException, InterruptedException { + Assert.assertEquals(0, sessionManager.getEpoch()); + sessionManager.renew(new SessionNode(randomURL(randomIp()), getDc()), 1000); + waitConditionUntilTimeOut(() -> sessionManager.getEpoch() > 0, 100); + Assert.assertNotEquals(0, sessionManager.getEpoch()); + } + + @Test + public void testGetClusterMembers() { + Assert.assertTrue(sessionManager.getSessionServerMetaInfo().getClusterMembers().isEmpty()); + } + + @Test + public void testRenew() throws TimeoutException, InterruptedException { + // SessionLeaseManager leaseManager = spy(new SessionLeaseManager()); + // sessionManager.setRaftSessionLeaseManager(leaseManager) + // .setSessionLeaseManager(leaseManager); + SessionNode sessionNode = new SessionNode(randomURL(randomIp()), getDc()); + long timestamp = System.currentTimeMillis(); + sessionNode.setProcessId(new ProcessId(sessionNode.getIp(), timestamp, 1, random.nextInt())); + NotifyObserversCounter counter = new NotifyObserversCounter(); + sessionManager.addObserver(counter); + + makeMetaLeader(); + + sessionManager.renew(sessionNode, 1); + // verify(leaseManager, times(1)).register(any()); + Assert.assertEquals(1, counter.getCounter()); + + sessionManager.renew(sessionNode, 1); + // verify(leaseManager, times(1)).register(any()); + Assert.assertEquals(1, counter.getCounter()); + + SessionNode sessionNode2 = new SessionNode(sessionNode.getNodeUrl(), getDc()); + sessionNode2.setProcessId(new ProcessId(sessionNode.getIp(), timestamp, 2, random.nextInt())); + Assert.assertFalse(sessionManager.renew(sessionNode2, 1)); + // verify(leaseManager, times(2)).register(any()); + // verify(leaseManager, times(1)).renew(any(), anyInt()); + Assert.assertEquals(2, counter.getCounter()); + } + + @Test + public void testDataServerManagerRefreshEpochOnlyOnceWhenNewRegistered() + throws TimeoutException, InterruptedException { + makeMetaLeader(); + SessionNode node = new SessionNode(randomURL(randomIp()), getDc()); + // SessionLeaseManager leaseManager = spy(new SessionLeaseManager()); + // sessionManager.setSessionLeaseManager(leaseManager) + // .setRaftSessionLeaseManager(leaseManager); + sessionManager.renew(node, 1000); + Assert.assertEquals(1, sessionManager.getSessionServerMetaInfo().getClusterMembers().size()); + // verify(leaseManager, times(1)).refreshEpoch(anyLong()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCrossDcMetaServerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCrossDcMetaServerTest.java index 5add8c68e..36e13c6f0 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCrossDcMetaServerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCrossDcMetaServerTest.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.metaserver.impl; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.metaserver.DataCenterNodes; import com.alipay.sofa.registry.common.model.metaserver.nodes.MetaNode; @@ -27,6 +29,8 @@ import com.alipay.sofa.registry.server.meta.bootstrap.config.MetaServerConfig; import com.alipay.sofa.registry.server.meta.slot.SlotAllocator; import com.google.common.collect.ImmutableMap; +import java.util.*; +import java.util.concurrent.TimeoutException; import org.assertj.core.util.Lists; import org.junit.After; import org.junit.Assert; @@ -35,205 +39,225 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.*; -import java.util.concurrent.TimeoutException; +public class DefaultCrossDcMetaServerTest extends AbstractMetaServerTest { -import static org.mockito.Mockito.*; + private DefaultCrossDcMetaServer server; -public class DefaultCrossDcMetaServerTest extends AbstractMetaServerTest { + @Mock private Exchange exchange; + + @Mock private MetaServerConfig metaServerConfig; + + @Mock private MetaLeaderService metaLeaderService; + + @Before + public void beforeDefaultCrossDcMetaServerTest() { + MockitoAnnotations.initMocks(this); + when(metaServerConfig.getCrossDcMetaSyncIntervalMilli()).thenReturn(60 * 1000); + Collection collection = Lists.newArrayList("10.0.0.1", "10.0.0.2"); + server = + spy( + new DefaultCrossDcMetaServer( + getDc(), + collection, + scheduled, + exchange, + this.metaLeaderService, + metaServerConfig)); + } + + @After + public void afterDefaultCrossDcMetaServerTest() throws Exception { + LifecycleHelper.startIfPossible(server); + LifecycleHelper.disposeIfPossible(server); + } + + @Test + public void testDoInitialize() throws Exception { + LifecycleHelper.initializeIfPossible(server); + Assert.assertTrue(server.getLifecycleState().canStart()); + } + + @Test + public void testDoStart() throws Exception { + LifecycleHelper.initializeIfPossible(server); + LifecycleHelper.startIfPossible(server); + Assert.assertTrue(server.getLifecycleState().canStop()); + } - private DefaultCrossDcMetaServer server; - - @Mock - private Exchange exchange; - - @Mock - private MetaServerConfig metaServerConfig; - - @Mock - private MetaLeaderService metaLeaderService; - - @Before - public void beforeDefaultCrossDcMetaServerTest() { - MockitoAnnotations.initMocks(this); - when(metaServerConfig.getCrossDcMetaSyncIntervalMilli()).thenReturn(60 * 1000); - Collection collection = Lists.newArrayList("10.0.0.1", "10.0.0.2"); - server = spy(new DefaultCrossDcMetaServer(getDc(), collection, scheduled, exchange, - this.metaLeaderService, metaServerConfig)); - } - - @After - public void afterDefaultCrossDcMetaServerTest() throws Exception { - LifecycleHelper.startIfPossible(server); - LifecycleHelper.disposeIfPossible(server); - } - - @Test - public void testDoInitialize() throws Exception { - LifecycleHelper.initializeIfPossible(server); - Assert.assertTrue(server.getLifecycleState().canStart()); - } - - @Test - public void testDoStart() throws Exception { - LifecycleHelper.initializeIfPossible(server); - LifecycleHelper.startIfPossible(server); - Assert.assertTrue(server.getLifecycleState().canStop()); - } - - @Test - public void testDoStop() throws Exception { - LifecycleHelper.initializeIfPossible(server); - LifecycleHelper.startIfPossible(server); - LifecycleHelper.stopIfPossible(server); - Assert.assertTrue(server.getLifecycleState().canStart()); - } - - @Test - public void testDoDispose() throws Exception { - LifecycleHelper.disposeIfPossible(server); - Assert.assertTrue(server.getLifecycleState().canInitialize()); - } - - @Test - public void testTestGetDc() { - Assert.assertEquals(getDc(), server.getDc()); - } - - @Test(expected = IllegalStateException.class) - public void testGetSlotTable() { - server.getSlotTable(); - } - - @Test - public void testRefreshSlotTableWithResult() throws Exception { - LifecycleHelper.initializeIfPossible(server); - LifecycleHelper.startIfPossible(server); - Assert.assertEquals(2, server.getClusterMembers().size()); - DataCenterNodes message = new DataCenterNodes(Node.NodeType.META, System.currentTimeMillis(), getDc()); - Map nodes = ImmutableMap.of("10.0.0.1",new MetaNode(randomURL("10.0.0.1"), getDc()), - "10.0.0.2",new MetaNode(randomURL("10.0.0.2"), getDc()), - "10.0.0.3",new MetaNode(randomURL("10.0.0.3"), getDc())); - message.setNodes(nodes); - when(exchange.getClient(Exchange.META_SERVER_TYPE)).thenReturn(getRpcClient(scheduled, 1, message)); - server.doRefresh(0); - waitConditionUntilTimeOut(()->server.getClusterMembers().size() > 2, 1000); - List expected = Lists.newArrayList(message.getNodes().values()); - expected.sort(new NodeComparator()); - List actual = server.getClusterMembers(); - actual.sort(new NodeComparator()); - Assert.assertEquals(expected, actual); - } - - @Test - public void testDoRefreshWithFirstTimeout() throws Exception { - LifecycleHelper.initializeIfPossible(server); - LifecycleHelper.startIfPossible(server); - Assert.assertEquals(2, server.getClusterMembers().size()); - DataCenterNodes message = new DataCenterNodes(Node.NodeType.META, System.currentTimeMillis(), getDc()); - Map nodes = ImmutableMap.of("10.0.0.1",new MetaNode(randomURL("10.0.0.1"), getDc()), - "10.0.0.2",new MetaNode(randomURL("10.0.0.2"), getDc()), - "10.0.0.3",new MetaNode(randomURL("10.0.0.3"), getDc())); - message.setNodes(nodes); - when(exchange.getClient(Exchange.META_SERVER_TYPE)) - .thenReturn(getRpcClient(scheduled, 3, new TimeoutException("expected timeout"))) - .thenReturn(getRpcClient(scheduled, 1, message)); - server.doRefresh(0); - waitConditionUntilTimeOut(()->server.getClusterMeta().getClusterMembers().size() > 2, 1000); - List expected = Lists.newArrayList(message.getNodes().values()); - expected.sort(new NodeComparator()); - List actual = server.getClusterMembers(); - actual.sort(new NodeComparator()); - Assert.assertEquals(expected, actual); - } - - @Test - public void testDoRefreshWithOverRetryTimes() throws Exception { - LifecycleHelper.initializeIfPossible(server); - LifecycleHelper.startIfPossible(server); - Assert.assertEquals(2, server.getClusterMembers().size()); - - when(exchange.getClient(Exchange.META_SERVER_TYPE)).thenReturn( - getRpcClient(scheduled, 1, new TimeoutException())); - server.doRefresh(0); - Thread.sleep(100); - verify(server, atLeast(3)).doRefresh(anyInt()); - } - - //run manually - // @Test - // @Ignore - public void testRaftMechanismWorks() throws Exception { - - server = new DefaultCrossDcMetaServer(getDc(), Lists.newArrayList(NetUtil.getLocalAddress().getHostAddress()), - scheduled, exchange, this.metaLeaderService, metaServerConfig); - DataCenterNodes message = new DataCenterNodes(Node.NodeType.META, System.currentTimeMillis(), getDc()); - Map nodes = ImmutableMap.of( - "10.0.0.1", new MetaNode(randomURL("10.0.0.1"), getDc()), - "10.0.0.2", new MetaNode(randomURL("10.0.0.2"), getDc()), - "10.0.0.3", new MetaNode(randomURL("10.0.0.3"), getDc()), - "10.0.0.4", new MetaNode(randomURL("10.0.0.4"), getDc()), - "10.0.0.5", new MetaNode(randomURL("10.0.0.5"), getDc()) - ); - message.setNodes(nodes); - when(exchange.getClient(Exchange.META_SERVER_TYPE)) -// .thenReturn(getRpcClient(scheduled, 3, new TimeoutException())) - .thenReturn(getRpcClient(scheduled, 1, message)); - LifecycleHelper.initializeIfPossible(server); - LifecycleHelper.startIfPossible(server); - - server.doRefresh(0); - waitConditionUntilTimeOut(()->server.getClusterMembers().size() > 4, 30000); - List expected = Lists.newArrayList(message.getNodes().values()); - Collections.sort(expected, new Comparator() { - @Override - public int compare(MetaNode o1, MetaNode o2) { - return o1.getIp().compareTo(o2.getIp()); - } + @Test + public void testDoStop() throws Exception { + LifecycleHelper.initializeIfPossible(server); + LifecycleHelper.startIfPossible(server); + LifecycleHelper.stopIfPossible(server); + Assert.assertTrue(server.getLifecycleState().canStart()); + } + + @Test + public void testDoDispose() throws Exception { + LifecycleHelper.disposeIfPossible(server); + Assert.assertTrue(server.getLifecycleState().canInitialize()); + } + + @Test + public void testTestGetDc() { + Assert.assertEquals(getDc(), server.getDc()); + } + + @Test(expected = IllegalStateException.class) + public void testGetSlotTable() { + server.getSlotTable(); + } + + @Test + public void testRefreshSlotTableWithResult() throws Exception { + LifecycleHelper.initializeIfPossible(server); + LifecycleHelper.startIfPossible(server); + Assert.assertEquals(2, server.getClusterMembers().size()); + DataCenterNodes message = + new DataCenterNodes(Node.NodeType.META, System.currentTimeMillis(), getDc()); + Map nodes = + ImmutableMap.of( + "10.0.0.1", + new MetaNode(randomURL("10.0.0.1"), getDc()), + "10.0.0.2", + new MetaNode(randomURL("10.0.0.2"), getDc()), + "10.0.0.3", + new MetaNode(randomURL("10.0.0.3"), getDc())); + message.setNodes(nodes); + when(exchange.getClient(Exchange.META_SERVER_TYPE)) + .thenReturn(getRpcClient(scheduled, 1, message)); + server.doRefresh(0); + waitConditionUntilTimeOut(() -> server.getClusterMembers().size() > 2, 1000); + List expected = Lists.newArrayList(message.getNodes().values()); + expected.sort(new NodeComparator()); + List actual = server.getClusterMembers(); + actual.sort(new NodeComparator()); + Assert.assertEquals(expected, actual); + } + + @Test + public void testDoRefreshWithFirstTimeout() throws Exception { + LifecycleHelper.initializeIfPossible(server); + LifecycleHelper.startIfPossible(server); + Assert.assertEquals(2, server.getClusterMembers().size()); + DataCenterNodes message = + new DataCenterNodes(Node.NodeType.META, System.currentTimeMillis(), getDc()); + Map nodes = + ImmutableMap.of( + "10.0.0.1", + new MetaNode(randomURL("10.0.0.1"), getDc()), + "10.0.0.2", + new MetaNode(randomURL("10.0.0.2"), getDc()), + "10.0.0.3", + new MetaNode(randomURL("10.0.0.3"), getDc())); + message.setNodes(nodes); + when(exchange.getClient(Exchange.META_SERVER_TYPE)) + .thenReturn(getRpcClient(scheduled, 3, new TimeoutException("expected timeout"))) + .thenReturn(getRpcClient(scheduled, 1, message)); + server.doRefresh(0); + waitConditionUntilTimeOut(() -> server.getClusterMeta().getClusterMembers().size() > 2, 1000); + List expected = Lists.newArrayList(message.getNodes().values()); + expected.sort(new NodeComparator()); + List actual = server.getClusterMembers(); + actual.sort(new NodeComparator()); + Assert.assertEquals(expected, actual); + } + + @Test + public void testDoRefreshWithOverRetryTimes() throws Exception { + LifecycleHelper.initializeIfPossible(server); + LifecycleHelper.startIfPossible(server); + Assert.assertEquals(2, server.getClusterMembers().size()); + + when(exchange.getClient(Exchange.META_SERVER_TYPE)) + .thenReturn(getRpcClient(scheduled, 1, new TimeoutException())); + server.doRefresh(0); + Thread.sleep(100); + verify(server, atLeast(3)).doRefresh(anyInt()); + } + + // run manually + // @Test + // @Ignore + public void testRaftMechanismWorks() throws Exception { + + server = + new DefaultCrossDcMetaServer( + getDc(), + Lists.newArrayList(NetUtil.getLocalAddress().getHostAddress()), + scheduled, + exchange, + this.metaLeaderService, + metaServerConfig); + DataCenterNodes message = + new DataCenterNodes(Node.NodeType.META, System.currentTimeMillis(), getDc()); + Map nodes = + ImmutableMap.of( + "10.0.0.1", new MetaNode(randomURL("10.0.0.1"), getDc()), + "10.0.0.2", new MetaNode(randomURL("10.0.0.2"), getDc()), + "10.0.0.3", new MetaNode(randomURL("10.0.0.3"), getDc()), + "10.0.0.4", new MetaNode(randomURL("10.0.0.4"), getDc()), + "10.0.0.5", new MetaNode(randomURL("10.0.0.5"), getDc())); + message.setNodes(nodes); + when(exchange.getClient(Exchange.META_SERVER_TYPE)) + // .thenReturn(getRpcClient(scheduled, 3, new TimeoutException())) + .thenReturn(getRpcClient(scheduled, 1, message)); + LifecycleHelper.initializeIfPossible(server); + LifecycleHelper.startIfPossible(server); + + server.doRefresh(0); + waitConditionUntilTimeOut(() -> server.getClusterMembers().size() > 4, 30000); + List expected = Lists.newArrayList(message.getNodes().values()); + Collections.sort( + expected, + new Comparator() { + @Override + public int compare(MetaNode o1, MetaNode o2) { + return o1.getIp().compareTo(o2.getIp()); + } }); - List real = server.getClusterMembers(); - Collections.sort(real, new Comparator() { - @Override - public int compare(MetaNode o1, MetaNode o2) { - return o1.getIp().compareTo(o2.getIp()); - } + List real = server.getClusterMembers(); + Collections.sort( + real, + new Comparator() { + @Override + public int compare(MetaNode o1, MetaNode o2) { + return o1.getIp().compareTo(o2.getIp()); + } }); - Assert.assertEquals(expected.size(), real.size()); - // wait for rpc safe quit - Thread.sleep(100); - } - - @Test - public void testRefresh() { - server.refresh(); - verify(server, never()).doRefresh(anyInt()); - } - - @Test - public void testGetRefreshCount() throws Exception { - LifecycleHelper.initializeIfPossible(server); - LifecycleHelper.startIfPossible(server); - when(exchange.getClient(Exchange.META_SERVER_TYPE)).thenReturn( - getRpcClient(scheduled, 1, new TimeoutException())); - server.refresh(); - server.refresh(); - server.refresh(); - Assert.assertEquals(3, server.getRefreshCount()); - } - - @Test - public void testGetLastRefreshTime() { - } - - @Test - public void testGetSlotTable2() throws Exception { - LifecycleHelper.initializeIfPossible(server); - LifecycleHelper.startIfPossible(server); - SlotAllocator allocator = mock(SlotAllocator.class); - server.setAllocator(allocator); - server.getSlotTable(); - verify(allocator, atLeast(1)).getSlotTable(); - } - - -} \ No newline at end of file + Assert.assertEquals(expected.size(), real.size()); + // wait for rpc safe quit + Thread.sleep(100); + } + + @Test + public void testRefresh() { + server.refresh(); + verify(server, never()).doRefresh(anyInt()); + } + + @Test + public void testGetRefreshCount() throws Exception { + LifecycleHelper.initializeIfPossible(server); + LifecycleHelper.startIfPossible(server); + when(exchange.getClient(Exchange.META_SERVER_TYPE)) + .thenReturn(getRpcClient(scheduled, 1, new TimeoutException())); + server.refresh(); + server.refresh(); + server.refresh(); + Assert.assertEquals(3, server.getRefreshCount()); + } + + @Test + public void testGetLastRefreshTime() {} + + @Test + public void testGetSlotTable2() throws Exception { + LifecycleHelper.initializeIfPossible(server); + LifecycleHelper.startIfPossible(server); + SlotAllocator allocator = mock(SlotAllocator.class); + server.setAllocator(allocator); + server.getSlotTable(); + verify(allocator, atLeast(1)).getSlotTable(); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCurrentDcMetaServerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCurrentDcMetaServerTest.java index fe415f5a0..923af7dc6 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCurrentDcMetaServerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultCurrentDcMetaServerTest.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.metaserver.impl; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.metaserver.cluster.VersionedList; import com.alipay.sofa.registry.common.model.metaserver.nodes.MetaNode; import com.alipay.sofa.registry.common.model.metaserver.nodes.SessionNode; @@ -29,6 +31,8 @@ import com.alipay.sofa.registry.server.meta.slot.SlotManager; import com.alipay.sofa.registry.util.DatumVersionUtil; import com.google.common.collect.ImmutableMap; +import java.util.List; +import java.util.concurrent.TimeoutException; import org.assertj.core.util.Lists; import org.junit.After; import org.junit.Assert; @@ -37,140 +41,146 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.List; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.*; - public class DefaultCurrentDcMetaServerTest extends AbstractMetaServerTest { - private DefaultCurrentDcMetaServer metaServer; + private DefaultCurrentDcMetaServer metaServer; - @Mock - private SessionServerManager sessionServerManager; + @Mock private SessionServerManager sessionServerManager; - @Mock - private DataServerManager dataServerManager; + @Mock private DataServerManager dataServerManager; - @Mock - private SlotManager slotManager; + @Mock private SlotManager slotManager; - @Mock - private NodeConfig nodeConfig; + @Mock private NodeConfig nodeConfig; - @Before - public void beforeDefaultCurrentDcMetaServerTest() throws Exception { - MockitoAnnotations.initMocks(this); - metaServer = new DefaultCurrentDcMetaServer().setDataServerManager(dataServerManager) - .setSessionManager(sessionServerManager).setNodeConfig(nodeConfig).setSlotManager(slotManager); - when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); - when(nodeConfig.getMetaNodeIP()).thenReturn( + @Before + public void beforeDefaultCurrentDcMetaServerTest() throws Exception { + MockitoAnnotations.initMocks(this); + metaServer = + new DefaultCurrentDcMetaServer() + .setDataServerManager(dataServerManager) + .setSessionManager(sessionServerManager) + .setNodeConfig(nodeConfig) + .setSlotManager(slotManager); + when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); + when(nodeConfig.getMetaNodeIP()) + .thenReturn( ImmutableMap.of(getDc(), Lists.newArrayList(randomIp(), randomIp(), randomIp()))); - metaServer.postConstruct(); - } - - @After - public void afterDefaultCurrentDcMetaServerTest() throws Exception { - metaServer.preDestory(); - } - - @Test - public void testGetSessionServers() { - when(sessionServerManager.getSessionServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), - Lists.newArrayList(new SessionNode(randomURL(), getDc()), new SessionNode(randomURL(), - getDc())))); - Assert.assertEquals(2, metaServer.getSessionServerManager().getSessionServerMetaInfo().getClusterMembers().size()); - verify(sessionServerManager, times(1)).getSessionServerMetaInfo(); - } - - @Test - public void testUpdateClusterMembers() throws Exception { - - List prevClusterNodes = metaServer.getClusterMembers(); - long prevEpoch = metaServer.getEpoch(); - metaServer.updateClusterMembers(new VersionedList<>(DatumVersionUtil.nextId(), - Lists.newArrayList(new MetaNode(randomURL(randomIp()), - getDc()), new MetaNode(randomURL(randomIp()), getDc()), new MetaNode( - randomURL(randomIp()), getDc()), new MetaNode(randomURL(randomIp()), getDc()), - new MetaNode(randomURL(randomIp()), getDc()), new MetaNode(randomURL(randomIp()), - getDc())))); - long currentEpoch = metaServer.getEpoch(); - // wait for raft communication - Thread.sleep(100); - List currentClusterNodes = metaServer.getClusterMembers(); - - LifecycleHelper.stopIfPossible(metaServer); - LifecycleHelper.disposeIfPossible(metaServer); - - Assert.assertTrue(currentEpoch > prevEpoch); - Assert.assertNotEquals(currentClusterNodes.size(), prevClusterNodes.size()); - } - - @Test - public void testGetClusterMembers() throws TimeoutException, InterruptedException { - makeMetaLeader(); - metaServer.getClusterMembers(); - - makeMetaNonLeader(); - metaServer.getClusterMembers(); - } - - @Test - public void testGetSlotTable() throws TimeoutException, InterruptedException { - when(slotManager.getSlotTable()).thenReturn( - new SlotTable(DatumVersionUtil.nextId(), Lists.newArrayList(new Slot(1, randomIp(), 2, - Lists.newArrayList(randomIp()))))); - - makeMetaLeader(); - SlotTable slotTable = metaServer.getSlotTable(); - verify(slotManager, times(1)).getSlotTable(); - Assert.assertEquals(1, slotTable.getSlotIds().size()); - - makeMetaNonLeader(); - slotTable = metaServer.getSlotTable(); - verify(slotManager, times(2)).getSlotTable(); - Assert.assertEquals(1, slotTable.getSlotIds().size()); - } - - @Test - public void testCancel() throws InterruptedException, TimeoutException { - MetaNode metaNode = new MetaNode(randomURL(), getDc()); - metaServer.renew(metaNode); - - makeMetaLeader(); - metaServer.cancel(metaNode); - metaServer.renew(metaNode); - - makeMetaNonLeader(); - metaServer.cancel(metaNode); - } - - @Test - public void testGetEpoch() throws TimeoutException, InterruptedException { - metaServer.renew(new MetaNode(randomURL(), getDc())); - makeMetaLeader(); - Assert.assertTrue(metaServer.getEpoch() <= DatumVersionUtil.nextId()); - - makeMetaNonLeader(); - metaServer.getEpoch(); - } - - @Test - public void testRenew() { - NotifyObserversCounter notifyCounter = new NotifyObserversCounter(); - metaServer.addObserver(notifyCounter); - MetaNode metaNode = new MetaNode(randomURL(), getDc()); - - metaServer.renew(metaNode); - metaServer.renew(metaNode); - - Assert.assertEquals(2, notifyCounter.getCounter()); - } - - @Test - public void testGetDataManager() { - DataServerManager manager = metaServer.getDataServerManager(); - Assert.assertEquals(dataServerManager, manager); - } - -} \ No newline at end of file + metaServer.postConstruct(); + } + + @After + public void afterDefaultCurrentDcMetaServerTest() throws Exception { + metaServer.preDestory(); + } + + @Test + public void testGetSessionServers() { + when(sessionServerManager.getSessionServerMetaInfo()) + .thenReturn( + new VersionedList<>( + DatumVersionUtil.nextId(), + Lists.newArrayList( + new SessionNode(randomURL(), getDc()), new SessionNode(randomURL(), getDc())))); + Assert.assertEquals( + 2, + metaServer.getSessionServerManager().getSessionServerMetaInfo().getClusterMembers().size()); + verify(sessionServerManager, times(1)).getSessionServerMetaInfo(); + } + + @Test + public void testUpdateClusterMembers() throws Exception { + + List prevClusterNodes = metaServer.getClusterMembers(); + long prevEpoch = metaServer.getEpoch(); + metaServer.updateClusterMembers( + new VersionedList<>( + DatumVersionUtil.nextId(), + Lists.newArrayList( + new MetaNode(randomURL(randomIp()), getDc()), + new MetaNode(randomURL(randomIp()), getDc()), + new MetaNode(randomURL(randomIp()), getDc()), + new MetaNode(randomURL(randomIp()), getDc()), + new MetaNode(randomURL(randomIp()), getDc()), + new MetaNode(randomURL(randomIp()), getDc())))); + long currentEpoch = metaServer.getEpoch(); + // wait for raft communication + Thread.sleep(100); + List currentClusterNodes = metaServer.getClusterMembers(); + + LifecycleHelper.stopIfPossible(metaServer); + LifecycleHelper.disposeIfPossible(metaServer); + + Assert.assertTrue(currentEpoch > prevEpoch); + Assert.assertNotEquals(currentClusterNodes.size(), prevClusterNodes.size()); + } + + @Test + public void testGetClusterMembers() throws TimeoutException, InterruptedException { + makeMetaLeader(); + metaServer.getClusterMembers(); + + makeMetaNonLeader(); + metaServer.getClusterMembers(); + } + + @Test + public void testGetSlotTable() throws TimeoutException, InterruptedException { + when(slotManager.getSlotTable()) + .thenReturn( + new SlotTable( + DatumVersionUtil.nextId(), + Lists.newArrayList(new Slot(1, randomIp(), 2, Lists.newArrayList(randomIp()))))); + + makeMetaLeader(); + SlotTable slotTable = metaServer.getSlotTable(); + verify(slotManager, times(1)).getSlotTable(); + Assert.assertEquals(1, slotTable.getSlotIds().size()); + + makeMetaNonLeader(); + slotTable = metaServer.getSlotTable(); + verify(slotManager, times(2)).getSlotTable(); + Assert.assertEquals(1, slotTable.getSlotIds().size()); + } + + @Test + public void testCancel() throws InterruptedException, TimeoutException { + MetaNode metaNode = new MetaNode(randomURL(), getDc()); + metaServer.renew(metaNode); + + makeMetaLeader(); + metaServer.cancel(metaNode); + metaServer.renew(metaNode); + + makeMetaNonLeader(); + metaServer.cancel(metaNode); + } + + @Test + public void testGetEpoch() throws TimeoutException, InterruptedException { + metaServer.renew(new MetaNode(randomURL(), getDc())); + makeMetaLeader(); + Assert.assertTrue(metaServer.getEpoch() <= DatumVersionUtil.nextId()); + + makeMetaNonLeader(); + metaServer.getEpoch(); + } + + @Test + public void testRenew() { + NotifyObserversCounter notifyCounter = new NotifyObserversCounter(); + metaServer.addObserver(notifyCounter); + MetaNode metaNode = new MetaNode(randomURL(), getDc()); + + metaServer.renew(metaNode); + metaServer.renew(metaNode); + + Assert.assertEquals(2, notifyCounter.getCounter()); + } + + @Test + public void testGetDataManager() { + DataServerManager manager = metaServer.getDataServerManager(); + Assert.assertEquals(dataServerManager, manager); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaServerManagerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaServerManagerTest.java index eeac82a6b..7c3762456 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaServerManagerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/DefaultMetaServerManagerTest.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.metaserver.impl; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.metaserver.cluster.VersionedList; import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; @@ -31,56 +33,54 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import static org.mockito.Mockito.*; - public class DefaultMetaServerManagerTest extends AbstractMetaServerTest { - @Mock - private DefaultCrossDcMetaServerManager crossDcMetaServerManager; + @Mock private DefaultCrossDcMetaServerManager crossDcMetaServerManager; - @Mock - private CurrentDcMetaServer currentDcMetaServer; + @Mock private CurrentDcMetaServer currentDcMetaServer; - @Mock - private SessionServerManager sessionServerManager; + @Mock private SessionServerManager sessionServerManager; - @Mock - private DataServerManager dataServerManager; + @Mock private DataServerManager dataServerManager; - @Mock - private NodeConfig nodeConfig; + @Mock private NodeConfig nodeConfig; - private DefaultMetaServerManager manager; + private DefaultMetaServerManager manager; - @Before - public void beforeDefaultMetaServerManagerTest() { - MockitoAnnotations.initMocks(this); - manager = new DefaultMetaServerManager(); - manager.setCrossDcMetaServerManager(crossDcMetaServerManager) - .setCurrentDcMetaServer(currentDcMetaServer).setSessionManager(sessionServerManager) - .setDataServerManager(dataServerManager).setNodeConfig(nodeConfig); - } + @Before + public void beforeDefaultMetaServerManagerTest() { + MockitoAnnotations.initMocks(this); + manager = new DefaultMetaServerManager(); + manager + .setCrossDcMetaServerManager(crossDcMetaServerManager) + .setCurrentDcMetaServer(currentDcMetaServer) + .setSessionManager(sessionServerManager) + .setDataServerManager(dataServerManager) + .setNodeConfig(nodeConfig); + } - @Test - public void testGetSummary() { - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), Lists.newArrayList())); - manager.getSummary(Node.NodeType.DATA); - verify(dataServerManager, times(1)).getDataServerMetaInfo(); - verify(sessionServerManager, never()).getSessionServerMetaInfo(); - } + @Test + public void testGetSummary() { + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), Lists.newArrayList())); + manager.getSummary(Node.NodeType.DATA); + verify(dataServerManager, times(1)).getDataServerMetaInfo(); + verify(sessionServerManager, never()).getSessionServerMetaInfo(); + } - @Test - public void testGetSummary2() { - when(sessionServerManager.getSessionServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), Lists.newArrayList())); - manager.getSummary(Node.NodeType.SESSION); - // verify(sessionManager, times(1)).getClusterMembers(); - verify(dataServerManager, never()).getDataServerMetaInfo(); - } + @Test + public void testGetSummary2() { + when(sessionServerManager.getSessionServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), Lists.newArrayList())); + manager.getSummary(Node.NodeType.SESSION); + // verify(sessionManager, times(1)).getClusterMembers(); + verify(dataServerManager, never()).getDataServerMetaInfo(); + } - @Test - public void testGetSummary3() { - manager.getSummary(Node.NodeType.META); - verify(currentDcMetaServer, times(1)).getClusterMembers(); - verify(sessionServerManager, never()).getSessionServerMetaInfo(); - } -} \ No newline at end of file + @Test + public void testGetSummary3() { + manager.getSummary(Node.NodeType.META); + verify(currentDcMetaServer, times(1)).getClusterMembers(); + verify(sessionServerManager, never()).getSessionServerMetaInfo(); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/LocalMetaServerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/LocalMetaServerTest.java index 3f2889090..448ab6a85 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/LocalMetaServerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/metaserver/impl/LocalMetaServerTest.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.metaserver.impl; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.metaserver.cluster.VersionedList; import com.alipay.sofa.registry.common.model.metaserver.nodes.MetaNode; import com.alipay.sofa.registry.common.model.slot.SlotTable; @@ -26,6 +28,12 @@ import com.alipay.sofa.registry.server.meta.slot.SlotManager; import com.alipay.sofa.registry.server.meta.slot.manager.SimpleSlotManager; import com.alipay.sofa.registry.util.DatumVersionUtil; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import org.assertj.core.util.Lists; import org.junit.After; import org.junit.Assert; @@ -34,154 +42,146 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.IOException; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.*; - public class LocalMetaServerTest extends AbstractMetaServerTest { - private LocalMetaServer metaServer ; - - private SlotManager slotManager; - - @Mock - private DataServerManager dataServerManager; - - @Mock - private SessionServerManager sessionServerManager; - - @Before - public void beforeDefaultLocalMetaServerTest() throws Exception { - MockitoAnnotations.initMocks(this); - slotManager = spy(new SimpleSlotManager()); - metaServer = spy(new LocalMetaServer(slotManager, dataServerManager, sessionServerManager)); - LifecycleHelper.initializeIfPossible(metaServer); - LifecycleHelper.startIfPossible(metaServer); - } - - @After - public void afterDefaultLocalMetaServerTest() throws Exception { - LifecycleHelper.stopIfPossible(metaServer); - LifecycleHelper.disposeIfPossible(metaServer); - } - - @Test - public void testGetSlotTable() { - when(slotManager.getSlotTable()).thenReturn(new SlotTable(0L, Collections.emptyList())); - metaServer.getSlotTable(); - verify(slotManager, times(1)).getSlotTable(); - } - - @Test - public void testGetClusterMembers() throws TimeoutException, InterruptedException { - List metaNodeList = Lists.newArrayList(new MetaNode(randomURL(randomIp()), getDc()), - new MetaNode(randomURL(randomIp()), getDc()), new MetaNode(randomURL(randomIp()), getDc())); - metaServer.updateClusterMembers(new VersionedList<>(DatumVersionUtil.nextId(), metaNodeList)); - waitConditionUntilTimeOut(()->!metaServer.getClusterMembers().isEmpty(), 100); - metaNodeList.sort(new NodeComparator()); - List actual = metaServer.getClusterMembers(); - actual.sort(new NodeComparator()); - Assert.assertEquals(metaNodeList, actual); + private LocalMetaServer metaServer; + + private SlotManager slotManager; + + @Mock private DataServerManager dataServerManager; + + @Mock private SessionServerManager sessionServerManager; + + @Before + public void beforeDefaultLocalMetaServerTest() throws Exception { + MockitoAnnotations.initMocks(this); + slotManager = spy(new SimpleSlotManager()); + metaServer = spy(new LocalMetaServer(slotManager, dataServerManager, sessionServerManager)); + LifecycleHelper.initializeIfPossible(metaServer); + LifecycleHelper.startIfPossible(metaServer); + } + + @After + public void afterDefaultLocalMetaServerTest() throws Exception { + LifecycleHelper.stopIfPossible(metaServer); + LifecycleHelper.disposeIfPossible(metaServer); + } + + @Test + public void testGetSlotTable() { + when(slotManager.getSlotTable()).thenReturn(new SlotTable(0L, Collections.emptyList())); + metaServer.getSlotTable(); + verify(slotManager, times(1)).getSlotTable(); + } + + @Test + public void testGetClusterMembers() throws TimeoutException, InterruptedException { + List metaNodeList = + Lists.newArrayList( + new MetaNode(randomURL(randomIp()), getDc()), + new MetaNode(randomURL(randomIp()), getDc()), + new MetaNode(randomURL(randomIp()), getDc())); + metaServer.updateClusterMembers(new VersionedList<>(DatumVersionUtil.nextId(), metaNodeList)); + waitConditionUntilTimeOut(() -> !metaServer.getClusterMembers().isEmpty(), 100); + metaNodeList.sort(new NodeComparator()); + List actual = metaServer.getClusterMembers(); + actual.sort(new NodeComparator()); + Assert.assertEquals(metaNodeList, actual); + } + + @Test + public void testUpdateClusterMembers() throws InterruptedException { + int tasks = 1000; + CyclicBarrier barrier = new CyclicBarrier(tasks); + CountDownLatch latch = new CountDownLatch(tasks); + for (int i = 0; i < tasks; i++) { + executors.execute( + new Runnable() { + @Override + public void run() { + try { + barrier.await(); + } catch (Exception ignore) { + } + + metaServer.updateClusterMembers( + new VersionedList<>( + DatumVersionUtil.nextId(), + Lists.newArrayList( + new MetaNode(randomURL(), getDc()), + new MetaNode(randomURL(), getDc()), + new MetaNode(randomURL(), getDc())))); + latch.countDown(); + } + }); } - - @Test - public void testUpdateClusterMembers() throws InterruptedException { - int tasks = 1000; - CyclicBarrier barrier = new CyclicBarrier(tasks); - CountDownLatch latch = new CountDownLatch(tasks); - for (int i = 0; i < tasks; i++) { - executors.execute(new Runnable() { - @Override - public void run() { - try { - barrier.await(); - } catch (Exception ignore) { - } - - metaServer.updateClusterMembers(new VersionedList<>( - DatumVersionUtil.nextId(),Lists.newArrayList(new MetaNode(randomURL(), - getDc()), new MetaNode(randomURL(), getDc()), new MetaNode(randomURL(), - getDc())))); - latch.countDown(); - } - }); - - } - latch.await(2, TimeUnit.SECONDS); - verify(metaServer, times(tasks)).updateClusterMembers(any()); - + latch.await(2, TimeUnit.SECONDS); + verify(metaServer, times(tasks)).updateClusterMembers(any()); + } + + @Test + public void testRenew() throws InterruptedException { + int tasks = 1000; + CyclicBarrier barrier = new CyclicBarrier(tasks); + CountDownLatch latch = new CountDownLatch(tasks); + for (int i = 0; i < tasks; i++) { + executors.execute( + new Runnable() { + @Override + public void run() { + try { + barrier.await(); + } catch (Exception ignore) { + } + metaServer.renew(new MetaNode(randomURL(), getDc())); + latch.countDown(); + } + }); } - - @Test - public void testRenew() throws InterruptedException { - int tasks = 1000; - CyclicBarrier barrier = new CyclicBarrier(tasks); - CountDownLatch latch = new CountDownLatch(tasks); - for (int i = 0; i < tasks; i++) { - executors.execute(new Runnable() { - @Override - public void run() { - try { - barrier.await(); - } catch (Exception ignore) { - } - metaServer.renew(new MetaNode(randomURL(), getDc())); - latch.countDown(); - } - }); - - } - latch.await(2, TimeUnit.SECONDS); - verify(metaServer, times(tasks)).renew(any()); + latch.await(2, TimeUnit.SECONDS); + verify(metaServer, times(tasks)).renew(any()); + } + + @Test + public void testCancel() throws InterruptedException { + int tasks = 1000; + CyclicBarrier barrier = new CyclicBarrier(tasks); + CountDownLatch latch = new CountDownLatch(tasks); + for (int i = 0; i < tasks; i++) { + executors.execute( + new Runnable() { + @Override + public void run() { + try { + barrier.await(); + } catch (Exception ignore) { + } + metaServer.renew(new MetaNode(randomURL(), getDc())); + latch.countDown(); + } + }); } - - @Test - public void testCancel() throws InterruptedException { - int tasks = 1000; - CyclicBarrier barrier = new CyclicBarrier(tasks); - CountDownLatch latch = new CountDownLatch(tasks); - for (int i = 0; i < tasks; i++) { - executors.execute(new Runnable() { - @Override - public void run() { - try { - barrier.await(); - } catch (Exception ignore) { - } - metaServer.renew(new MetaNode(randomURL(), getDc())); - latch.countDown(); - } - }); - - } - latch.await(2, TimeUnit.SECONDS); - verify(metaServer, times(tasks)).renew(any()); - - CyclicBarrier barrier2 = new CyclicBarrier(tasks); - CountDownLatch latch2 = new CountDownLatch(tasks); - for (int i = 0; i < tasks; i++) { - executors.execute(new Runnable() { - @Override - public void run() { - try { - barrier2.await(); - } catch (Exception ignore) { - } - metaServer.cancel(new MetaNode(randomURL(), getDc())); - latch2.countDown(); - } - }); - - } - latch2.await(2, TimeUnit.SECONDS); - Thread.sleep(50); - verify(metaServer, times(tasks)).cancel(any()); + latch.await(2, TimeUnit.SECONDS); + verify(metaServer, times(tasks)).renew(any()); + + CyclicBarrier barrier2 = new CyclicBarrier(tasks); + CountDownLatch latch2 = new CountDownLatch(tasks); + for (int i = 0; i < tasks; i++) { + executors.execute( + new Runnable() { + @Override + public void run() { + try { + barrier2.await(); + } catch (Exception ignore) { + } + metaServer.cancel(new MetaNode(randomURL(), getDc())); + latch2.countDown(); + } + }); } - -} \ No newline at end of file + latch2.await(2, TimeUnit.SECONDS); + Thread.sleep(50); + verify(metaServer, times(tasks)).cancel(any()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/DefaultSlotTableMonitorTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/DefaultSlotTableMonitorTest.java index dd3cf88eb..1759d62d9 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/DefaultSlotTableMonitorTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/DefaultSlotTableMonitorTest.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.monitor; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.metaserver.inter.heartbeat.HeartbeatRequest; import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.*; @@ -23,162 +25,248 @@ import com.alipay.sofa.registry.server.meta.bootstrap.config.NodeConfig; import com.alipay.sofa.registry.server.meta.monitor.impl.DefaultSlotTableMonitor; import com.alipay.sofa.registry.server.meta.slot.manager.SimpleSlotManager; +import java.util.List; import org.assertj.core.util.Lists; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.List; - -import static org.mockito.Mockito.*; - public class DefaultSlotTableMonitorTest extends AbstractMetaServerTest { - private DefaultSlotTableMonitor monitor = new DefaultSlotTableMonitor(); + private DefaultSlotTableMonitor monitor = new DefaultSlotTableMonitor(); - private SimpleSlotManager slotManager; + private SimpleSlotManager slotManager; - private List dataNodes; + private List dataNodes; - @Before - public void beforeDefaultSlotTableMonitorTest() throws Exception { - NodeConfig nodeConfig = mock(NodeConfig.class); - when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); - slotManager = new SimpleSlotManager(); - dataNodes = Lists.newArrayList(new DataNode(randomURL(randomIp()), getDc()), new DataNode( - randomURL(randomIp()), getDc()), new DataNode(randomURL(randomIp()), getDc())); - slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); - slotManager = spy(slotManager); - monitor.setSlotManager(slotManager); - monitor.postConstruct(); - } + @Before + public void beforeDefaultSlotTableMonitorTest() throws Exception { + NodeConfig nodeConfig = mock(NodeConfig.class); + when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); + slotManager = new SimpleSlotManager(); + dataNodes = + Lists.newArrayList( + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc())); + slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); + slotManager = spy(slotManager); + monitor.setSlotManager(slotManager); + monitor.postConstruct(); + } - @After - public void afterDefaultSlotTableMonitorTest() throws Exception { - monitor.preDestroy(); - } + @After + public void afterDefaultSlotTableMonitorTest() throws Exception { + monitor.preDestroy(); + } - @Test - public void testRecordSlotTable() { - monitor.recordSlotTable(); - verify(slotManager, atLeast(1)).getSlotTable(); - } + @Test + public void testRecordSlotTable() { + monitor.recordSlotTable(); + verify(slotManager, atLeast(1)).getSlotTable(); + } - @Test - public void testUpdate() { - slotManager.refresh(randomSlotTable()); - verify(slotManager, atLeast(1)).getSlotTable(); + @Test + public void testUpdate() { + slotManager.refresh(randomSlotTable()); + verify(slotManager, atLeast(1)).getSlotTable(); + } + + @Test + public void testIsSlotTableStable() { + monitor.update(slotManager, slotManager.getSlotTable()); + Assert.assertFalse(monitor.isStableTableStable()); + SlotTable slotTable = slotManager.getSlotTable(); + for (DataNode dataNode : dataNodes) { + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + BaseSlotStatus.LeaderStatus.HEALTHY)); + }); + dataNodeSlot + .getFollowers() + .forEach( + slotId -> { + slotStatuses.add( + new FollowerSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + System.currentTimeMillis(), + System.currentTimeMillis())); + }); + monitor.onHeartbeat( + new HeartbeatRequest( + dataNode, + slotManager.getSlotTable().getEpoch(), + getDc(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), + slotStatuses)); } + Assert.assertTrue(monitor.isStableTableStable()); - @Test - public void testIsSlotTableStable() { - monitor.update(slotManager, slotManager.getSlotTable()); - Assert.assertFalse(monitor.isStableTableStable()); - SlotTable slotTable = slotManager.getSlotTable(); - for(DataNode dataNode : dataNodes) { - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), BaseSlotStatus.LeaderStatus.HEALTHY)); - }); - dataNodeSlot.getFollowers().forEach(slotId -> { - slotStatuses.add(new FollowerSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), System.currentTimeMillis(), System.currentTimeMillis())); - }); - monitor.onHeartbeat(new HeartbeatRequest(dataNode, slotManager.getSlotTable().getEpoch(), getDc(), - System.currentTimeMillis(), - new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), - slotStatuses)); - } - Assert.assertTrue(monitor.isStableTableStable()); - - final boolean[] unstable = {false}; - for(DataNode dataNode : dataNodes) { - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { + final boolean[] unstable = {false}; + for (DataNode dataNode : dataNodes) { + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { if (!unstable[0]) { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), BaseSlotStatus.LeaderStatus.UNHEALTHY)); - unstable[0] = true; + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + BaseSlotStatus.LeaderStatus.UNHEALTHY)); + unstable[0] = true; } else { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), BaseSlotStatus.LeaderStatus.HEALTHY)); + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + BaseSlotStatus.LeaderStatus.HEALTHY)); } - }); - dataNodeSlot.getFollowers().forEach(slotId -> { - slotStatuses.add(new FollowerSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), System.currentTimeMillis(), System.currentTimeMillis())); - }); - monitor.onHeartbeat(new HeartbeatRequest(dataNode, slotManager.getSlotTable().getEpoch(), getDc(), - System.currentTimeMillis(), - new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), - slotStatuses)); - } - Assert.assertFalse(monitor.isStableTableStable()); + }); + dataNodeSlot + .getFollowers() + .forEach( + slotId -> { + slotStatuses.add( + new FollowerSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + System.currentTimeMillis(), + System.currentTimeMillis())); + }); + monitor.onHeartbeat( + new HeartbeatRequest( + dataNode, + slotManager.getSlotTable().getEpoch(), + getDc(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), + slotStatuses)); } + Assert.assertFalse(monitor.isStableTableStable()); + } - @Test - public void testOnHeartbeatWithPrevEpoch() { - monitor.update(slotManager, slotManager.getSlotTable()); - Assert.assertFalse(monitor.isStableTableStable()); - SlotTable slotTable = slotManager.getSlotTable(); - for(DataNode dataNode : dataNodes) { - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), BaseSlotStatus.LeaderStatus.HEALTHY)); - }); - monitor.onHeartbeat(new HeartbeatRequest(dataNode, slotTable.getEpoch() - 1, getDc(), - System.currentTimeMillis(), - new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), - slotStatuses)); - } - Assert.assertFalse(monitor.isStableTableStable()); + @Test + public void testOnHeartbeatWithPrevEpoch() { + monitor.update(slotManager, slotManager.getSlotTable()); + Assert.assertFalse(monitor.isStableTableStable()); + SlotTable slotTable = slotManager.getSlotTable(); + for (DataNode dataNode : dataNodes) { + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + BaseSlotStatus.LeaderStatus.HEALTHY)); + }); + monitor.onHeartbeat( + new HeartbeatRequest( + dataNode, + slotTable.getEpoch() - 1, + getDc(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), + slotStatuses)); } + Assert.assertFalse(monitor.isStableTableStable()); + } - @Test - public void testUpdateSlotTableThenIsStableShouldBeFalse() { - monitor.update(slotManager, slotManager.getSlotTable()); - Assert.assertFalse(monitor.isStableTableStable()); - SlotTable slotTable = slotManager.getSlotTable(); - for (DataNode dataNode : dataNodes) { - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), BaseSlotStatus.LeaderStatus.HEALTHY)); - }); - dataNodeSlot.getFollowers().forEach(slotId -> { - slotStatuses.add(new FollowerSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), System.currentTimeMillis(), System.currentTimeMillis())); - }); - monitor.onHeartbeat(new HeartbeatRequest(dataNode, slotManager.getSlotTable().getEpoch(), getDc(), - System.currentTimeMillis(), - new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), - slotStatuses)); - } - Assert.assertTrue(monitor.isStableTableStable()); - - slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); - monitor.update(slotManager, slotManager.getSlotTable()); - Assert.assertFalse(monitor.isStableTableStable()); + @Test + public void testUpdateSlotTableThenIsStableShouldBeFalse() { + monitor.update(slotManager, slotManager.getSlotTable()); + Assert.assertFalse(monitor.isStableTableStable()); + SlotTable slotTable = slotManager.getSlotTable(); + for (DataNode dataNode : dataNodes) { + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + BaseSlotStatus.LeaderStatus.HEALTHY)); + }); + dataNodeSlot + .getFollowers() + .forEach( + slotId -> { + slotStatuses.add( + new FollowerSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + System.currentTimeMillis(), + System.currentTimeMillis())); + }); + monitor.onHeartbeat( + new HeartbeatRequest( + dataNode, + slotManager.getSlotTable().getEpoch(), + getDc(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), + slotStatuses)); } + Assert.assertTrue(monitor.isStableTableStable()); - @Test - public void testReportDataServerLag() { - String ip = randomIp(); - monitor.onHeartbeat(new HeartbeatRequest(new DataNode(randomURL(ip), getDc()), - -1L, getDc(), System.currentTimeMillis(), new SlotConfig.SlotBasicInfo( - SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), Lists - .newArrayList())); - monitor.onHeartbeat(new HeartbeatRequest(new DataNode(randomURL(ip), getDc()), - -1L, getDc(), System.currentTimeMillis(), new SlotConfig.SlotBasicInfo( - SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), Lists - .newArrayList())); - Assert.assertTrue(Metrics.DataSlot.getDataServerSlotLagTimes(ip) > 1); - } -} \ No newline at end of file + slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); + monitor.update(slotManager, slotManager.getSlotTable()); + Assert.assertFalse(monitor.isStableTableStable()); + } + + @Test + public void testReportDataServerLag() { + String ip = randomIp(); + monitor.onHeartbeat( + new HeartbeatRequest( + new DataNode(randomURL(ip), getDc()), + -1L, + getDc(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), + Lists.newArrayList())); + monitor.onHeartbeat( + new HeartbeatRequest( + new DataNode(randomURL(ip), getDc()), + -1L, + getDc(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC), + Lists.newArrayList())); + Assert.assertTrue(Metrics.DataSlot.getDataServerSlotLagTimes(ip) > 1); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotStatsTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotStatsTest.java index 80b9a644d..f1ac2c2eb 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotStatsTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotStatsTest.java @@ -31,47 +31,54 @@ */ public class DefaultSlotStatsTest { - private DefaultSlotStats slotStats; + private DefaultSlotStats slotStats; - private Slot slot; + private Slot slot; - @Before - public void beforeDefaultSlotStatsTest() { - slot = new Slot(1, "10.0.0.1", System.currentTimeMillis(), Lists.newArrayList("10.0.0.2", - "10.0.0.3")); - slotStats = new DefaultSlotStats(slot); - } + @Before + public void beforeDefaultSlotStatsTest() { + slot = + new Slot( + 1, "10.0.0.1", System.currentTimeMillis(), Lists.newArrayList("10.0.0.2", "10.0.0.3")); + slotStats = new DefaultSlotStats(slot); + } - @Test - public void testGetSlot() { - Assert.assertEquals(slot, slotStats.getSlot()); - } + @Test + public void testGetSlot() { + Assert.assertEquals(slot, slotStats.getSlot()); + } - @Test - public void testIsLeaderStable() { - Assert.assertFalse(slotStats.isLeaderStable()); - slotStats.updateLeaderState(new LeaderSlotStatus(1, System.currentTimeMillis(), "10.0.0.1", - BaseSlotStatus.LeaderStatus.HEALTHY)); - Assert.assertTrue(slotStats.isLeaderStable()); - } + @Test + public void testIsLeaderStable() { + Assert.assertFalse(slotStats.isLeaderStable()); + slotStats.updateLeaderState( + new LeaderSlotStatus( + 1, System.currentTimeMillis(), "10.0.0.1", BaseSlotStatus.LeaderStatus.HEALTHY)); + Assert.assertTrue(slotStats.isLeaderStable()); + } - @Test - public void testIsFollowerStable() { - Assert.assertFalse(slotStats.isFollowerStable(null)); - Assert.assertFalse(slotStats.isFollowerStable("")); - Assert.assertFalse(slotStats.isFollowerStable("10.0.0.2")); - slotStats.updateFollowerState(new FollowerSlotStatus(1, System.currentTimeMillis(), - "10.0.0.2", -1, -1)); - Assert.assertFalse(slotStats.isFollowerStable("10.0.0.2")); - slotStats.updateFollowerState(new FollowerSlotStatus(1, System.currentTimeMillis(), - "10.0.0.2", System.currentTimeMillis(), System.currentTimeMillis() - 3000)); - Assert.assertTrue(slotStats.isFollowerStable("10.0.0.2")); - } + @Test + public void testIsFollowerStable() { + Assert.assertFalse(slotStats.isFollowerStable(null)); + Assert.assertFalse(slotStats.isFollowerStable("")); + Assert.assertFalse(slotStats.isFollowerStable("10.0.0.2")); + slotStats.updateFollowerState( + new FollowerSlotStatus(1, System.currentTimeMillis(), "10.0.0.2", -1, -1)); + Assert.assertFalse(slotStats.isFollowerStable("10.0.0.2")); + slotStats.updateFollowerState( + new FollowerSlotStatus( + 1, + System.currentTimeMillis(), + "10.0.0.2", + System.currentTimeMillis(), + System.currentTimeMillis() - 3000)); + Assert.assertTrue(slotStats.isFollowerStable("10.0.0.2")); + } - @Test - public void testUpdateFollowerState() { - slotStats.updateFollowerState(new FollowerSlotStatus(1, System.currentTimeMillis(), - "10.0.0.2", -1, -1)); - Assert.assertFalse(slotStats.isFollowerStable("10.0.0.2")); - } -} \ No newline at end of file + @Test + public void testUpdateFollowerState() { + slotStats.updateFollowerState( + new FollowerSlotStatus(1, System.currentTimeMillis(), "10.0.0.2", -1, -1)); + Assert.assertFalse(slotStats.isFollowerStable("10.0.0.2")); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableStatsTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableStatsTest.java index cc34a4311..ddb797ef2 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableStatsTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/monitor/impl/DefaultSlotTableStatsTest.java @@ -16,6 +16,10 @@ */ package com.alipay.sofa.registry.server.meta.monitor.impl; +import static com.alipay.sofa.registry.server.meta.monitor.impl.DefaultSlotStats.MAX_SYNC_GAP; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.*; import com.alipay.sofa.registry.exception.InitializeException; @@ -24,247 +28,317 @@ import com.alipay.sofa.registry.server.meta.monitor.SlotStats; import com.alipay.sofa.registry.server.meta.slot.manager.SimpleSlotManager; import com.alipay.sofa.registry.server.shared.util.NodeUtils; -import com.alipay.sofa.registry.util.DatumVersionUtil; +import java.util.List; +import java.util.Map; +import java.util.Set; import org.assertj.core.util.Lists; import org.assertj.core.util.Sets; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static com.alipay.sofa.registry.server.meta.monitor.impl.DefaultSlotStats.MAX_SYNC_GAP; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class DefaultSlotTableStatsTest extends AbstractMetaServerTest { - private SimpleSlotManager slotManager; + private SimpleSlotManager slotManager; - private List dataNodes; + private List dataNodes; - private DefaultSlotTableStats slotTableStats; + private DefaultSlotTableStats slotTableStats; - private NodeConfig nodeConfig; + private NodeConfig nodeConfig; - @Before - public void beforeDefaultSlotTableMonitorTest() throws Exception { - nodeConfig = mock(NodeConfig.class); - when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); - slotManager = new SimpleSlotManager(); - slotTableStats = new DefaultSlotTableStats(slotManager); - dataNodes = Lists.newArrayList(new DataNode(randomURL(randomIp()), getDc()), new DataNode( - randomURL(randomIp()), getDc()), new DataNode(randomURL(randomIp()), getDc())); - slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); - slotTableStats.initialize(); + @Before + public void beforeDefaultSlotTableMonitorTest() throws Exception { + nodeConfig = mock(NodeConfig.class); + when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); + slotManager = new SimpleSlotManager(); + slotTableStats = new DefaultSlotTableStats(slotManager); + dataNodes = + Lists.newArrayList( + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc())); + slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); + slotTableStats.initialize(); + } + + @Test + public void testIsSlotTableStable() { + Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + SlotTable slotTable = slotManager.getSlotTable(); + for (DataNode dataNode : dataNodes) { + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + BaseSlotStatus.LeaderStatus.HEALTHY)); + }); + slotTableStats.checkSlotStatuses(dataNode, slotStatuses); } + Assert.assertTrue(slotTableStats.isSlotLeadersStable()); + } - @Test - public void testIsSlotTableStable() { - Assert.assertFalse(slotTableStats.isSlotLeadersStable()); - SlotTable slotTable = slotManager.getSlotTable(); - for(DataNode dataNode : dataNodes) { - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), BaseSlotStatus.LeaderStatus.HEALTHY)); - }); - slotTableStats.checkSlotStatuses(dataNode, slotStatuses); - } - Assert.assertTrue(slotTableStats.isSlotLeadersStable()); + @Test + public void testCheckSlotStatuses() { + Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + SlotTable slotTable = slotManager.getSlotTable(); + for (DataNode dataNode : dataNodes) { + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch() - 1, + dataNode.getIp(), + BaseSlotStatus.LeaderStatus.HEALTHY)); + }); + slotTableStats.checkSlotStatuses(dataNode, slotStatuses); } + Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + } - @Test - public void testCheckSlotStatuses() { - Assert.assertFalse(slotTableStats.isSlotLeadersStable()); - SlotTable slotTable = slotManager.getSlotTable(); - for(DataNode dataNode : dataNodes) { - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch() - 1, - dataNode.getIp(), BaseSlotStatus.LeaderStatus.HEALTHY)); - }); - slotTableStats.checkSlotStatuses(dataNode, slotStatuses); - } - Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + @Test + public void testUpdateSlotTable() { + Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + SlotTable slotTable = slotManager.getSlotTable(); + for (DataNode dataNode : dataNodes) { + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + BaseSlotStatus.LeaderStatus.HEALTHY)); + }); + slotTableStats.checkSlotStatuses(dataNode, slotStatuses); } + Assert.assertTrue(slotTableStats.isSlotLeadersStable()); - @Test - public void testUpdateSlotTable() { - Assert.assertFalse(slotTableStats.isSlotLeadersStable()); - SlotTable slotTable = slotManager.getSlotTable(); - for(DataNode dataNode : dataNodes) { - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), BaseSlotStatus.LeaderStatus.HEALTHY)); - }); - slotTableStats.checkSlotStatuses(dataNode, slotStatuses); - } - Assert.assertTrue(slotTableStats.isSlotLeadersStable()); + slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); + slotTableStats.updateSlotTable(slotManager.getSlotTable()); + Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + } - slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); - slotTableStats.updateSlotTable(slotManager.getSlotTable()); - Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + @Test + public void testDataReportHeartbeatWhenInit() throws InitializeException { + slotManager = new SimpleSlotManager(); + slotTableStats = new DefaultSlotTableStats(slotManager); + slotTableStats.initialize(); + List slotStatuses = Lists.newArrayList(); + for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { + slotStatuses.add( + new LeaderSlotStatus(slotId, 0, randomIp(), BaseSlotStatus.LeaderStatus.UNHEALTHY)); } + slotTableStats.checkSlotStatuses(new DataNode(randomURL(randomIp()), getDc()), slotStatuses); + } - @Test - public void testDataReportHeartbeatWhenInit() throws InitializeException { - slotManager = new SimpleSlotManager(); - slotTableStats = new DefaultSlotTableStats(slotManager); - slotTableStats.initialize(); - List slotStatuses = Lists.newArrayList(); - for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { - slotStatuses.add(new LeaderSlotStatus(slotId, 0, randomIp(), - BaseSlotStatus.LeaderStatus.UNHEALTHY)); - } - slotTableStats - .checkSlotStatuses(new DataNode(randomURL(randomIp()), getDc()), slotStatuses); + @Test + public void testFollowerStatus() { + Assert.assertFalse(slotTableStats.isSlotFollowersStable()); + DataNode dataNode = new DataNode(randomURL(randomIp()), getDc()); + List slotStatuses = Lists.newArrayList(); + for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { + slotStatuses.add( + new FollowerSlotStatus( + slotId, + slotManager.getSlotTable().getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + System.currentTimeMillis(), + -1)); } + slotTableStats.checkSlotStatuses(dataNode, slotStatuses); + Assert.assertFalse(slotTableStats.isSlotFollowersStable()); - @Test - public void testFollowerStatus() { - Assert.assertFalse(slotTableStats.isSlotFollowersStable()); - DataNode dataNode = new DataNode(randomURL(randomIp()), getDc()); - List slotStatuses = Lists.newArrayList(); - for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { - slotStatuses - .add(new FollowerSlotStatus(slotId, slotManager.getSlotTable().getSlot(slotId) - .getLeaderEpoch(), dataNode.getIp(), System.currentTimeMillis(), -1)); - } - slotTableStats.checkSlotStatuses(dataNode, slotStatuses); - Assert.assertFalse(slotTableStats.isSlotFollowersStable()); + slotStatuses = Lists.newArrayList(); + for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { + slotStatuses.add( + new FollowerSlotStatus( + slotId, + slotManager.getSlotTable().getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + System.currentTimeMillis(), + System.currentTimeMillis() - MAX_SYNC_GAP)); + } + slotTableStats.checkSlotStatuses(dataNode, slotStatuses); + Assert.assertFalse(slotTableStats.isSlotFollowersStable()); - slotStatuses = Lists.newArrayList(); - for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { - slotStatuses.add(new FollowerSlotStatus(slotId, slotManager.getSlotTable() - .getSlot(slotId).getLeaderEpoch(), dataNode.getIp(), System.currentTimeMillis(), - System.currentTimeMillis() - MAX_SYNC_GAP)); - } - slotTableStats.checkSlotStatuses(dataNode, slotStatuses); - Assert.assertFalse(slotTableStats.isSlotFollowersStable()); + logger.info(remarkableMessage("[splitter]")); + for (DataNode node : dataNodes) { + slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotManager.getDataNodeManagedSlot(node.getIp(), false); + for (int slotId : dataNodeSlot.getFollowers()) { + slotStatuses.add( + new FollowerSlotStatus( + slotId, + slotManager.getSlotTable().getSlot(slotId).getLeaderEpoch(), + node.getIp(), + System.currentTimeMillis(), + System.currentTimeMillis() - 1000)); + } + slotTableStats.checkSlotStatuses(node, slotStatuses); + } + Assert.assertTrue(slotTableStats.isSlotFollowersStable()); + } - logger.info(remarkableMessage("[splitter]")); - for (DataNode node : dataNodes) { - slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotManager.getDataNodeManagedSlot(node.getIp(), false); - for (int slotId : dataNodeSlot.getFollowers()) { - slotStatuses.add(new FollowerSlotStatus(slotId, slotManager.getSlotTable() - .getSlot(slotId).getLeaderEpoch(), node.getIp(), System.currentTimeMillis(), - System.currentTimeMillis() - 1000)); - } - slotTableStats.checkSlotStatuses(node, slotStatuses); - } - Assert.assertTrue(slotTableStats.isSlotFollowersStable()); + @Test + public void testUpdateSlotTableWhenFollowerChangeOnly() { + Assert.assertFalse(slotTableStats.isSlotFollowersStable()); + List slotStatuses = Lists.newArrayList(); + for (DataNode node : dataNodes) { + slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotManager.getDataNodeManagedSlot(node.getIp(), false); + for (int slotId : dataNodeSlot.getFollowers()) { + slotStatuses.add( + new FollowerSlotStatus( + slotId, + slotManager.getSlotTable().getSlot(slotId).getLeaderEpoch(), + node.getIp(), + System.currentTimeMillis(), + System.currentTimeMillis() - 1000)); + } + slotTableStats.checkSlotStatuses(node, slotStatuses); } + Assert.assertTrue(slotTableStats.isSlotFollowersStable()); - @Test - public void testUpdateSlotTableWhenFollowerChangeOnly() { - Assert.assertFalse(slotTableStats.isSlotFollowersStable()); - List slotStatuses = Lists.newArrayList(); - for (DataNode node : dataNodes) { - slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotManager.getDataNodeManagedSlot(node.getIp(), false); - for (int slotId : dataNodeSlot.getFollowers()) { - slotStatuses.add(new FollowerSlotStatus(slotId, slotManager.getSlotTable() - .getSlot(slotId).getLeaderEpoch(), node.getIp(), System.currentTimeMillis(), - System.currentTimeMillis() - 1000)); - } - slotTableStats.checkSlotStatuses(node, slotStatuses); - } - Assert.assertTrue(slotTableStats.isSlotFollowersStable()); + SlotTable prev = slotManager.getSlotTable(); + Map slotMap = prev.getSlotMap(); + Slot prevSlot = slotMap.get(1); + Set followers = Sets.newHashSet(prevSlot.getFollowers()); + List newFollowers = NodeUtils.transferNodeToIpList(dataNodes); + newFollowers.removeAll(followers); + slotMap.put(1, new Slot(1, prevSlot.getLeader(), prevSlot.getLeaderEpoch(), newFollowers)); + SlotTable slotTable = new SlotTable(prev.getEpoch() + 1, slotMap.values()); + slotManager.refresh(slotTable); - SlotTable prev = slotManager.getSlotTable(); - Map slotMap = prev.getSlotMap(); - Slot prevSlot = slotMap.get(1); - Set followers = Sets.newHashSet(prevSlot.getFollowers()); - List newFollowers = NodeUtils.transferNodeToIpList(dataNodes); - newFollowers.removeAll(followers); - slotMap.put(1, new Slot(1, prevSlot.getLeader(), prevSlot.getLeaderEpoch(), newFollowers)); - SlotTable slotTable = new SlotTable(prev.getEpoch() + 1, slotMap.values()); - slotManager.refresh(slotTable); + SlotStats prevSlotStats = slotTableStats.getSlotStats(1); + slotTableStats.updateSlotTable(slotTable); + Assert.assertFalse(slotTableStats.isSlotFollowersStable()); + SlotStats curSlotStats = slotTableStats.getSlotStats(1); + Assert.assertNotEquals(prevSlotStats, curSlotStats); + } - SlotStats prevSlotStats = slotTableStats.getSlotStats(1); - slotTableStats.updateSlotTable(slotTable); - Assert.assertFalse(slotTableStats.isSlotFollowersStable()); - SlotStats curSlotStats = slotTableStats.getSlotStats(1); - Assert.assertNotEquals(prevSlotStats, curSlotStats); + @Test + public void testStableResultNotImpactByStableData() { + Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + SlotTable slotTable = slotManager.getSlotTable(); + for (DataNode dataNode : dataNodes) { + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + BaseSlotStatus.LeaderStatus.HEALTHY)); + }); + slotTableStats.checkSlotStatuses(dataNode, slotStatuses); } - - @Test - public void testStableResultNotImpactByStableData() { - Assert.assertFalse(slotTableStats.isSlotLeadersStable()); - SlotTable slotTable = slotManager.getSlotTable(); - for(DataNode dataNode : dataNodes) { - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), BaseSlotStatus.LeaderStatus.HEALTHY)); + Assert.assertTrue(slotTableStats.isSlotLeadersStable()); + // now, we add some stable data, that data-server is reporting slots it does not contains + DataNode dataNode1 = dataNodes.get(0); + DataNode dataNode2 = dataNodes.get(1); + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode1.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode2.getIp(), + BaseSlotStatus.LeaderStatus.UNHEALTHY)); }); - slotTableStats.checkSlotStatuses(dataNode, slotStatuses); - } - Assert.assertTrue(slotTableStats.isSlotLeadersStable()); - // now, we add some stable data, that data-server is reporting slots it does not contains - DataNode dataNode1 = dataNodes.get(0); - DataNode dataNode2 = dataNodes.get(1); - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode1.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode2.getIp(), BaseSlotStatus.LeaderStatus.UNHEALTHY)); - }); - slotTableStats.checkSlotStatuses(dataNode2, slotStatuses); - Assert.assertTrue(slotTableStats.isSlotLeadersStable()); - } + slotTableStats.checkSlotStatuses(dataNode2, slotStatuses); + Assert.assertTrue(slotTableStats.isSlotLeadersStable()); + } - @Test - public void testSlotTableUpdateFollowerStableData() { - Assert.assertFalse(slotTableStats.isSlotLeadersStable()); - SlotTable slotTable = slotManager.getSlotTable(); - for(DataNode dataNode : dataNodes) { - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), BaseSlotStatus.LeaderStatus.HEALTHY)); - }); - slotTableStats.checkSlotStatuses(dataNode, slotStatuses); - } - Assert.assertTrue(slotTableStats.isSlotLeadersStable()); - // now, we add some stable data, that data-server is reporting slots it does not contains - DataNode dataNode1 = dataNodes.get(0); - DataNode dataNode2 = dataNodes.get(1); - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode1.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { - slotStatuses.add(new FollowerSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode2.getIp(), System.currentTimeMillis(), -1L)); - }); - slotTableStats.checkSlotStatuses(dataNode2, slotStatuses); - Assert.assertTrue(slotTableStats.isSlotLeadersStable()); + @Test + public void testSlotTableUpdateFollowerStableData() { + Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + SlotTable slotTable = slotManager.getSlotTable(); + for (DataNode dataNode : dataNodes) { + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + BaseSlotStatus.LeaderStatus.HEALTHY)); + }); + slotTableStats.checkSlotStatuses(dataNode, slotStatuses); } - - @Test - public void testSlotNotEquals() { - Assert.assertFalse(slotTableStats.isSlotLeadersStable()); - SlotTable slotTable = slotManager.getSlotTable(); - for(DataNode dataNode : dataNodes) { - List slotStatuses = Lists.newArrayList(); - DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); - dataNodeSlot.getLeaders().forEach(slotId -> { - slotStatuses.add(new LeaderSlotStatus(slotId, slotTable.getSlot(slotId).getLeaderEpoch(), - dataNode.getIp(), BaseSlotStatus.LeaderStatus.HEALTHY)); + Assert.assertTrue(slotTableStats.isSlotLeadersStable()); + // now, we add some stable data, that data-server is reporting slots it does not contains + DataNode dataNode1 = dataNodes.get(0); + DataNode dataNode2 = dataNodes.get(1); + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode1.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { + slotStatuses.add( + new FollowerSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode2.getIp(), + System.currentTimeMillis(), + -1L)); }); - slotTableStats.checkSlotStatuses(dataNode, slotStatuses); - } - Assert.assertTrue(slotTableStats.isSlotLeadersStable()); - slotManager.refresh(new SlotTableGenerator(dataNodes).setNextLeader(1).setNextFollower(2).createSlotTable()); - Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + slotTableStats.checkSlotStatuses(dataNode2, slotStatuses); + Assert.assertTrue(slotTableStats.isSlotLeadersStable()); + } + + @Test + public void testSlotNotEquals() { + Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + SlotTable slotTable = slotManager.getSlotTable(); + for (DataNode dataNode : dataNodes) { + List slotStatuses = Lists.newArrayList(); + DataNodeSlot dataNodeSlot = slotTable.transfer(dataNode.getIp(), false).get(0); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> { + slotStatuses.add( + new LeaderSlotStatus( + slotId, + slotTable.getSlot(slotId).getLeaderEpoch(), + dataNode.getIp(), + BaseSlotStatus.LeaderStatus.HEALTHY)); + }); + slotTableStats.checkSlotStatuses(dataNode, slotStatuses); } -} \ No newline at end of file + Assert.assertTrue(slotTableStats.isSlotLeadersStable()); + slotManager.refresh( + new SlotTableGenerator(dataNodes).setNextLeader(1).setNextFollower(2).createSlotTable()); + Assert.assertFalse(slotTableStats.isSlotLeadersStable()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/provide/data/DefaultProvideDataNotifierTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/provide/data/DefaultProvideDataNotifierTest.java index 2fc00067d..b6424057e 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/provide/data/DefaultProvideDataNotifierTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/provide/data/DefaultProvideDataNotifierTest.java @@ -16,6 +16,9 @@ */ package com.alipay.sofa.registry.server.meta.provide.data; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.metaserver.DataOperator; import com.alipay.sofa.registry.common.model.metaserver.ProvideDataChangeEvent; @@ -27,43 +30,49 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - public class DefaultProvideDataNotifierTest { - private DefaultProvideDataNotifier notifier = new DefaultProvideDataNotifier(); - - @Mock - private DefaultDataServerService defaultDataServerService; + private DefaultProvideDataNotifier notifier = new DefaultProvideDataNotifier(); - @Mock - private DefaultSessionServerService defaultSessionServerService; + @Mock private DefaultDataServerService defaultDataServerService; - @Before - public void beforeDefaultProvideDataNotifierTest() { - MockitoAnnotations.initMocks(this); - notifier.setDataServerProvideDataNotifier(defaultDataServerService) - .setSessionServerProvideDataNotifier(defaultSessionServerService); - } + @Mock private DefaultSessionServerService defaultSessionServerService; - @Test - public void testNotifyProvideDataChange() { - notifier.notifyProvideDataChange(new ProvideDataChangeEvent("message", System - .currentTimeMillis(), DataOperator.ADD, Sets.newHashSet(Node.NodeType.DATA))); - verify(defaultDataServerService, times(1)).notifyProvideDataChange(any()); - verify(defaultSessionServerService, never()).notifyProvideDataChange(any()); + @Before + public void beforeDefaultProvideDataNotifierTest() { + MockitoAnnotations.initMocks(this); + notifier + .setDataServerProvideDataNotifier(defaultDataServerService) + .setSessionServerProvideDataNotifier(defaultSessionServerService); + } - notifier.notifyProvideDataChange(new ProvideDataChangeEvent("message", System - .currentTimeMillis(), DataOperator.ADD, Sets.newHashSet(Node.NodeType.SESSION))); - verify(defaultDataServerService, times(1)).notifyProvideDataChange(any()); - verify(defaultSessionServerService, times(1)).notifyProvideDataChange(any()); + @Test + public void testNotifyProvideDataChange() { + notifier.notifyProvideDataChange( + new ProvideDataChangeEvent( + "message", + System.currentTimeMillis(), + DataOperator.ADD, + Sets.newHashSet(Node.NodeType.DATA))); + verify(defaultDataServerService, times(1)).notifyProvideDataChange(any()); + verify(defaultSessionServerService, never()).notifyProvideDataChange(any()); - notifier.notifyProvideDataChange(new ProvideDataChangeEvent("message", System - .currentTimeMillis(), DataOperator.ADD, Sets.newHashSet(Node.NodeType.SESSION, - Node.NodeType.DATA))); - verify(defaultDataServerService, times(2)).notifyProvideDataChange(any()); - verify(defaultSessionServerService, times(2)).notifyProvideDataChange(any()); + notifier.notifyProvideDataChange( + new ProvideDataChangeEvent( + "message", + System.currentTimeMillis(), + DataOperator.ADD, + Sets.newHashSet(Node.NodeType.SESSION))); + verify(defaultDataServerService, times(1)).notifyProvideDataChange(any()); + verify(defaultSessionServerService, times(1)).notifyProvideDataChange(any()); - } -} \ No newline at end of file + notifier.notifyProvideDataChange( + new ProvideDataChangeEvent( + "message", + System.currentTimeMillis(), + DataOperator.ADD, + Sets.newHashSet(Node.NodeType.SESSION, Node.NodeType.DATA))); + verify(defaultDataServerService, times(2)).notifyProvideDataChange(any()); + verify(defaultSessionServerService, times(2)).notifyProvideDataChange(any()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/data/DefaultDataServerServiceTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/data/DefaultDataServerServiceTest.java index ad20bc2f5..7d0032b73 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/data/DefaultDataServerServiceTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/data/DefaultDataServerServiceTest.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.remoting.data; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.constants.ValueConstants; import com.alipay.sofa.registry.common.model.metaserver.DataOperator; @@ -33,6 +35,8 @@ import com.alipay.sofa.registry.server.meta.remoting.connection.DataConnectionHandler; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; import com.alipay.sofa.registry.util.DatumVersionUtil; +import java.net.InetSocketAddress; +import java.util.concurrent.TimeoutException; import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Test; @@ -41,155 +45,199 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import java.net.InetSocketAddress; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.*; - public class DefaultDataServerServiceTest extends AbstractMetaServerTest { - private DefaultDataServerService notifier = new DefaultDataServerService(); + private DefaultDataServerService notifier = new DefaultDataServerService(); - @Mock - private DataServerManager dataServerManager; + @Mock private DataServerManager dataServerManager; - @Mock - private DataNodeExchanger dataNodeExchanger; + @Mock private DataNodeExchanger dataNodeExchanger; - @Mock - private DataConnectionHandler dataConnectionHandler; + @Mock private DataConnectionHandler dataConnectionHandler; - @Before - public void beforeDataServerProvideDataNotifierTest() { - MockitoAnnotations.initMocks(this); - notifier.setDataConnectionHandler(dataConnectionHandler) - .setDataNodeExchanger(dataNodeExchanger).setDataServerManager(dataServerManager); - } + @Before + public void beforeDataServerProvideDataNotifierTest() { + MockitoAnnotations.initMocks(this); + notifier + .setDataConnectionHandler(dataConnectionHandler) + .setDataNodeExchanger(dataNodeExchanger) + .setDataServerManager(dataServerManager); + } - @Test - public void testNotify() throws RequestException { - notifier.notifyProvideDataChange(new ProvideDataChangeEvent( + @Test + public void testNotify() throws RequestException { + notifier.notifyProvideDataChange( + new ProvideDataChangeEvent( ValueConstants.BLACK_LIST_DATA_ID, System.currentTimeMillis(), DataOperator.ADD)); - verify(dataServerManager, never()).getDataServerMetaInfo(); - verify(dataNodeExchanger, never()).request(any(Request.class)); - } - - @Test - public void testNotifyWithNoDataNodes() throws RequestException { - when(dataConnectionHandler.getConnections(anyString())).thenReturn( - Lists.newArrayList(new InetSocketAddress(randomIp(), - Math.abs(random.nextInt(65535)) % 65535), + verify(dataServerManager, never()).getDataServerMetaInfo(); + verify(dataNodeExchanger, never()).request(any(Request.class)); + } + + @Test + public void testNotifyWithNoDataNodes() throws RequestException { + when(dataConnectionHandler.getConnections(anyString())) + .thenReturn( + Lists.newArrayList( + new InetSocketAddress(randomIp(), Math.abs(random.nextInt(65535)) % 65535), new InetSocketAddress(randomIp(), Math.abs(random.nextInt(65535)) % 65535))); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), Lists.newArrayList())); - notifier.notifyProvideDataChange(new ProvideDataChangeEvent( + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), Lists.newArrayList())); + notifier.notifyProvideDataChange( + new ProvideDataChangeEvent( ValueConstants.BLACK_LIST_DATA_ID, System.currentTimeMillis(), DataOperator.ADD)); - verify(dataServerManager, times(1)).getDataServerMetaInfo(); - verify(dataNodeExchanger, never()).request(any(Request.class)); - } - - @Test - public void testNotifyNoMatchingDataNodesWithConnect() throws RequestException { - when(dataConnectionHandler.getConnections(anyString())) - .thenReturn(Lists.newArrayList(new InetSocketAddress(randomIp(), Math.abs(random.nextInt(65535)) % 65535), - new InetSocketAddress(randomIp(), Math.abs(random.nextInt(65535)) % 65535 ) )); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), randomDataNodes(3))); - when(dataNodeExchanger.request(any(Request.class))).thenReturn(()->{return null;}); - notifier.notifyProvideDataChange(new ProvideDataChangeEvent(ValueConstants.BLACK_LIST_DATA_ID, - System.currentTimeMillis(), DataOperator.ADD)); - verify(dataNodeExchanger, never()).request(any(Request.class)); - } - - @Test - public void testNotifyNormal() throws RequestException, InterruptedException { - String ip1 = randomIp(), ip2 = randomIp(); - when(dataConnectionHandler.getConnections(anyString())) - .thenReturn(Lists.newArrayList(new InetSocketAddress(ip1, Math.abs(random.nextInt(65535)) % 65535), - new InetSocketAddress(ip2, Math.abs(random.nextInt(65535)) % 65535 ), - new InetSocketAddress(randomIp(), 1024))); - when(dataServerManager.getDataServerMetaInfo()) - .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), Lists.newArrayList(new DataNode(randomURL(ip1), getDc()), - new DataNode(randomURL(ip2), getDc()), - new DataNode(randomURL(randomIp()), getDc())))); - when(dataNodeExchanger.request(any(Request.class))).thenReturn(()->{return null;}); - notifier.notifyProvideDataChange(new ProvideDataChangeEvent(ValueConstants.BLACK_LIST_DATA_ID, - System.currentTimeMillis(), DataOperator.ADD)); - Thread.sleep(50); - verify(dataNodeExchanger, times(2)).request(any(Request.class)); - } - - @Test(expected = SofaRegistryRuntimeException.class) - public void testExpectedException() { - notifier.setDataConnectionHandler(new AbstractServerHandler() { - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.DATA; - } - - @Override - public Object doHandle(Channel channel, Object request) { - return null; - } - - @Override - public Class interest() { - return null; - } + verify(dataServerManager, times(1)).getDataServerMetaInfo(); + verify(dataNodeExchanger, never()).request(any(Request.class)); + } + + @Test + public void testNotifyNoMatchingDataNodesWithConnect() throws RequestException { + when(dataConnectionHandler.getConnections(anyString())) + .thenReturn( + Lists.newArrayList( + new InetSocketAddress(randomIp(), Math.abs(random.nextInt(65535)) % 65535), + new InetSocketAddress(randomIp(), Math.abs(random.nextInt(65535)) % 65535))); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), randomDataNodes(3))); + when(dataNodeExchanger.request(any(Request.class))) + .thenReturn( + () -> { + return null; + }); + notifier.notifyProvideDataChange( + new ProvideDataChangeEvent( + ValueConstants.BLACK_LIST_DATA_ID, System.currentTimeMillis(), DataOperator.ADD)); + verify(dataNodeExchanger, never()).request(any(Request.class)); + } + + @Test + public void testNotifyNormal() throws RequestException, InterruptedException { + String ip1 = randomIp(), ip2 = randomIp(); + when(dataConnectionHandler.getConnections(anyString())) + .thenReturn( + Lists.newArrayList( + new InetSocketAddress(ip1, Math.abs(random.nextInt(65535)) % 65535), + new InetSocketAddress(ip2, Math.abs(random.nextInt(65535)) % 65535), + new InetSocketAddress(randomIp(), 1024))); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn( + new VersionedList<>( + DatumVersionUtil.nextId(), + Lists.newArrayList( + new DataNode(randomURL(ip1), getDc()), + new DataNode(randomURL(ip2), getDc()), + new DataNode(randomURL(randomIp()), getDc())))); + when(dataNodeExchanger.request(any(Request.class))) + .thenReturn( + () -> { + return null; + }); + notifier.notifyProvideDataChange( + new ProvideDataChangeEvent( + ValueConstants.BLACK_LIST_DATA_ID, System.currentTimeMillis(), DataOperator.ADD)); + Thread.sleep(50); + verify(dataNodeExchanger, times(2)).request(any(Request.class)); + } + + @Test(expected = SofaRegistryRuntimeException.class) + public void testExpectedException() { + notifier.setDataConnectionHandler( + new AbstractServerHandler() { + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.DATA; + } + + @Override + public Object doHandle(Channel channel, Object request) { + return null; + } + + @Override + public Class interest() { + return null; + } }); - notifier.getNodeConnectManager(); - } - - @Test - public void testBoltRequest() throws RequestException, InterruptedException { - String ip1 = randomIp(), ip2 = randomIp(); - Client rpcClient = spy(getRpcClient(scheduled, 10, new TimeoutException("expected"))); - when(dataNodeExchanger.request(any(Request.class))).then(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { + notifier.getNodeConnectManager(); + } + + @Test + public void testBoltRequest() throws RequestException, InterruptedException { + String ip1 = randomIp(), ip2 = randomIp(); + Client rpcClient = spy(getRpcClient(scheduled, 10, new TimeoutException("expected"))); + when(dataNodeExchanger.request(any(Request.class))) + .then( + new Answer() { + @Override + public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Request request = invocationOnMock.getArgumentAt(0, Request.class); - rpcClient.sendCallback(request.getRequestUrl(), request.getRequestBody(), - request.getCallBackHandler(), 100); + rpcClient.sendCallback( + request.getRequestUrl(), + request.getRequestBody(), + request.getCallBackHandler(), + 100); return null; - } - }); - notifier.setDataNodeExchanger(dataNodeExchanger); - when(dataConnectionHandler.getConnections(anyString())).thenReturn( - Lists.newArrayList(new InetSocketAddress(ip1, Math.abs(random.nextInt(65535)) % 65535), + } + }); + notifier.setDataNodeExchanger(dataNodeExchanger); + when(dataConnectionHandler.getConnections(anyString())) + .thenReturn( + Lists.newArrayList( + new InetSocketAddress(ip1, Math.abs(random.nextInt(65535)) % 65535), new InetSocketAddress(ip2, Math.abs(random.nextInt(65535)) % 65535), new InetSocketAddress(randomIp(), 1024))); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), - Lists.newArrayList(new DataNode(randomURL(ip1), getDc()), new DataNode(randomURL(ip2), - getDc()), new DataNode(randomURL(randomIp()), getDc())))); - notifier.notifyProvideDataChange(new ProvideDataChangeEvent( + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn( + new VersionedList<>( + DatumVersionUtil.nextId(), + Lists.newArrayList( + new DataNode(randomURL(ip1), getDc()), + new DataNode(randomURL(ip2), getDc()), + new DataNode(randomURL(randomIp()), getDc())))); + notifier.notifyProvideDataChange( + new ProvideDataChangeEvent( ValueConstants.BLACK_LIST_DATA_ID, System.currentTimeMillis(), DataOperator.ADD)); - Thread.sleep(100); - verify(rpcClient, atLeast(1)).sendCallback(any(), any(), any(), anyInt()); - } - - @Test - public void testBoltResponsePositive() throws InterruptedException, RequestException { - String ip1 = randomIp(), ip2 = randomIp(); - when(dataConnectionHandler.getConnections(anyString())).thenReturn( - Lists.newArrayList(new InetSocketAddress(ip1, Math.abs(random.nextInt(65535)) % 65535), + Thread.sleep(100); + verify(rpcClient, atLeast(1)).sendCallback(any(), any(), any(), anyInt()); + } + + @Test + public void testBoltResponsePositive() throws InterruptedException, RequestException { + String ip1 = randomIp(), ip2 = randomIp(); + when(dataConnectionHandler.getConnections(anyString())) + .thenReturn( + Lists.newArrayList( + new InetSocketAddress(ip1, Math.abs(random.nextInt(65535)) % 65535), new InetSocketAddress(ip2, Math.abs(random.nextInt(65535)) % 65535), new InetSocketAddress(randomIp(), 1024))); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), - Lists.newArrayList(new DataNode(randomURL(ip1), getDc()), new DataNode(randomURL(ip2), - getDc()), new DataNode(randomURL(randomIp()), getDc())))); - Client client2 = spy(getRpcClient(scheduled, 10, "Response")); - DataNodeExchanger otherNodeExchanger = mock(DataNodeExchanger.class); - when(otherNodeExchanger.request(any(Request.class))).then(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn( + new VersionedList<>( + DatumVersionUtil.nextId(), + Lists.newArrayList( + new DataNode(randomURL(ip1), getDc()), + new DataNode(randomURL(ip2), getDc()), + new DataNode(randomURL(randomIp()), getDc())))); + Client client2 = spy(getRpcClient(scheduled, 10, "Response")); + DataNodeExchanger otherNodeExchanger = mock(DataNodeExchanger.class); + when(otherNodeExchanger.request(any(Request.class))) + .then( + new Answer() { + @Override + public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Request request = invocationOnMock.getArgumentAt(0, Request.class); logger.warn("[testBoltResponsePositive]"); - client2.sendCallback(request.getRequestUrl(), request.getRequestBody(), - request.getCallBackHandler(), 10000); + client2.sendCallback( + request.getRequestUrl(), + request.getRequestBody(), + request.getCallBackHandler(), + 10000); return null; - } - }); - notifier.setDataNodeExchanger(otherNodeExchanger); - notifier.notifyProvideDataChange(new ProvideDataChangeEvent( + } + }); + notifier.setDataNodeExchanger(otherNodeExchanger); + notifier.notifyProvideDataChange( + new ProvideDataChangeEvent( ValueConstants.BLACK_LIST_DATA_ID, System.currentTimeMillis(), DataOperator.ADD)); - Thread.sleep(200); - } -} \ No newline at end of file + Thread.sleep(200); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/handler/HeartbeatRequestHandlerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/handler/HeartbeatRequestHandlerTest.java index 0b1d968a6..859502f8e 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/handler/HeartbeatRequestHandlerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/handler/HeartbeatRequestHandlerTest.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.remoting.handler; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.GenericResponse; import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.metaserver.inter.heartbeat.HeartbeatRequest; @@ -29,101 +31,115 @@ import com.alipay.sofa.registry.server.meta.lease.session.SessionServerManager; import com.alipay.sofa.registry.server.meta.metaserver.impl.DefaultCurrentDcMetaServer; import com.alipay.sofa.registry.server.meta.slot.manager.DefaultSlotManager; +import java.util.concurrent.TimeoutException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.*; - public class HeartbeatRequestHandlerTest extends AbstractMetaServerTest { - private HeartbeatRequestHandler handler = new HeartbeatRequestHandler(); - - @Mock - private Channel channel; - - @Mock - private DefaultCurrentDcMetaServer currentDcMetaServer; - - @Mock - private SessionServerManager sessionServerManager; - - @Mock - private DataServerManager dataServerManager; - - @Mock - private MetaLeaderService metaLeaderService; - - private DefaultSlotManager slotManager; - - @Before - public void beforeHeartbeatRequestHandlerTest() { - MockitoAnnotations.initMocks(this); - NodeConfig nodeConfig = mock(NodeConfig.class); - handler.setNodeConfig(nodeConfig); - when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); - slotManager = new DefaultSlotManager(metaLeaderService); - handler.setDefaultSlotManager(slotManager) - .setCurrentDcMetaServer(currentDcMetaServer) - .setMetaLeaderElector(metaLeaderService); - when(currentDcMetaServer.getDataServerManager()).thenReturn(dataServerManager); - when(currentDcMetaServer.getSessionServerManager()).thenReturn(sessionServerManager); - when(currentDcMetaServer.getSlotTable()).thenReturn(slotManager.getSlotTable()); - } - - @Test - public void testDoHandle() throws TimeoutException, InterruptedException { - makeMetaLeader(); - slotManager.refresh(randomSlotTable(randomDataNodes(3))); - HeartbeatRequest heartbeat = new HeartbeatRequest<>(new DataNode( - randomURL(randomIp()), getDc()), 0, getDc(), System.currentTimeMillis(), - new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, - SlotConfig.FUNC)); - Assert.assertTrue(((GenericResponse) handler.doHandle(channel, heartbeat)).isSuccess()); - } - - @Test - public void testDoHandleWithErrDC() throws TimeoutException, InterruptedException { - makeMetaLeader(); - slotManager.refresh(randomSlotTable(randomDataNodes(3))); - HeartbeatRequest heartbeat = new HeartbeatRequest<>(new DataNode( - randomURL(randomIp()), getDc()), 0, "ERROR_DC", System.currentTimeMillis(), - new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, - SlotConfig.FUNC)); - handler.doHandle(channel, heartbeat); - verify(channel, times(1)).close(); - } - - @Test - public void testDoHandleWithErrSlotConfig() throws TimeoutException, InterruptedException { - makeMetaLeader(); - slotManager.refresh(randomSlotTable(randomDataNodes(3))); - HeartbeatRequest heartbeat = new HeartbeatRequest<>(new DataNode( - randomURL(randomIp()), getDc()), 0, getDc(), System.currentTimeMillis(), - new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM - 1, SlotConfig.SLOT_REPLICAS, - SlotConfig.FUNC)); - handler.doHandle(channel, heartbeat); - verify(channel, times(1)).close(); - - heartbeat = new HeartbeatRequest<>(new DataNode(randomURL(randomIp()), getDc()), 0, - getDc(), System.currentTimeMillis(), new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM, - SlotConfig.SLOT_REPLICAS - 1, SlotConfig.FUNC)); - handler.doHandle(channel, heartbeat); - verify(channel, times(2)).close(); - - heartbeat = new HeartbeatRequest<>(new DataNode(randomURL(randomIp()), getDc()), 0, - getDc(), System.currentTimeMillis(), new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM, - SlotConfig.SLOT_REPLICAS, "unknown")); - handler.doHandle(channel, heartbeat); - verify(channel, times(3)).close(); - } - - @Test - public void testInterest() { - Assert.assertEquals(HeartbeatRequest.class, handler.interest()); - } -} \ No newline at end of file + private HeartbeatRequestHandler handler = new HeartbeatRequestHandler(); + + @Mock private Channel channel; + + @Mock private DefaultCurrentDcMetaServer currentDcMetaServer; + + @Mock private SessionServerManager sessionServerManager; + + @Mock private DataServerManager dataServerManager; + + @Mock private MetaLeaderService metaLeaderService; + + private DefaultSlotManager slotManager; + + @Before + public void beforeHeartbeatRequestHandlerTest() { + MockitoAnnotations.initMocks(this); + NodeConfig nodeConfig = mock(NodeConfig.class); + handler.setNodeConfig(nodeConfig); + when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); + slotManager = new DefaultSlotManager(metaLeaderService); + handler + .setDefaultSlotManager(slotManager) + .setCurrentDcMetaServer(currentDcMetaServer) + .setMetaLeaderElector(metaLeaderService); + when(currentDcMetaServer.getDataServerManager()).thenReturn(dataServerManager); + when(currentDcMetaServer.getSessionServerManager()).thenReturn(sessionServerManager); + when(currentDcMetaServer.getSlotTable()).thenReturn(slotManager.getSlotTable()); + } + + @Test + public void testDoHandle() throws TimeoutException, InterruptedException { + makeMetaLeader(); + slotManager.refresh(randomSlotTable(randomDataNodes(3))); + HeartbeatRequest heartbeat = + new HeartbeatRequest<>( + new DataNode(randomURL(randomIp()), getDc()), + 0, + getDc(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC)); + Assert.assertTrue(((GenericResponse) handler.doHandle(channel, heartbeat)).isSuccess()); + } + + @Test + public void testDoHandleWithErrDC() throws TimeoutException, InterruptedException { + makeMetaLeader(); + slotManager.refresh(randomSlotTable(randomDataNodes(3))); + HeartbeatRequest heartbeat = + new HeartbeatRequest<>( + new DataNode(randomURL(randomIp()), getDc()), + 0, + "ERROR_DC", + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC)); + handler.doHandle(channel, heartbeat); + verify(channel, times(1)).close(); + } + + @Test + public void testDoHandleWithErrSlotConfig() throws TimeoutException, InterruptedException { + makeMetaLeader(); + slotManager.refresh(randomSlotTable(randomDataNodes(3))); + HeartbeatRequest heartbeat = + new HeartbeatRequest<>( + new DataNode(randomURL(randomIp()), getDc()), + 0, + getDc(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM - 1, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC)); + handler.doHandle(channel, heartbeat); + verify(channel, times(1)).close(); + + heartbeat = + new HeartbeatRequest<>( + new DataNode(randomURL(randomIp()), getDc()), + 0, + getDc(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS - 1, SlotConfig.FUNC)); + handler.doHandle(channel, heartbeat); + verify(channel, times(2)).close(); + + heartbeat = + new HeartbeatRequest<>( + new DataNode(randomURL(randomIp()), getDc()), + 0, + getDc(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, "unknown")); + handler.doHandle(channel, heartbeat); + verify(channel, times(3)).close(); + } + + @Test + public void testInterest() { + Assert.assertEquals(HeartbeatRequest.class, handler.interest()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/session/DefaultSessionServerServiceTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/session/DefaultSessionServerServiceTest.java index 58fc85d63..700b70f6e 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/session/DefaultSessionServerServiceTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/remoting/session/DefaultSessionServerServiceTest.java @@ -16,6 +16,9 @@ */ package com.alipay.sofa.registry.server.meta.remoting.session; +import static org.mockito.Matchers.*; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.constants.ValueConstants; import com.alipay.sofa.registry.common.model.metaserver.DataOperator; import com.alipay.sofa.registry.common.model.metaserver.ProvideDataChangeEvent; @@ -29,6 +32,8 @@ import com.alipay.sofa.registry.server.meta.remoting.SessionNodeExchanger; import com.alipay.sofa.registry.server.meta.remoting.connection.SessionConnectionHandler; import com.alipay.sofa.registry.util.DatumVersionUtil; +import java.net.InetSocketAddress; +import java.util.concurrent.TimeoutException; import org.assertj.core.util.Lists; import org.junit.Before; import org.junit.Test; @@ -37,85 +42,103 @@ import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; -import java.net.InetSocketAddress; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Matchers.*; -import static org.mockito.Mockito.*; - public class DefaultSessionServerServiceTest extends AbstractMetaServerTest { - private DefaultSessionServerService notifier = new DefaultSessionServerService(); + private DefaultSessionServerService notifier = new DefaultSessionServerService(); - @Mock - private SessionNodeExchanger sessionNodeExchanger; + @Mock private SessionNodeExchanger sessionNodeExchanger; - @Mock - private SessionConnectionHandler sessionConnectionHandler; + @Mock private SessionConnectionHandler sessionConnectionHandler; - @Mock - private SessionServerManager sessionServerManager; + @Mock private SessionServerManager sessionServerManager; - @Before - public void beforeSessionServerProvideDataNotifierTest() { - MockitoAnnotations.initMocks(this); - notifier.setSessionConnectionHandler(sessionConnectionHandler) - .setSessionNodeExchanger(sessionNodeExchanger) - .setSessionServerManager(sessionServerManager); - } + @Before + public void beforeSessionServerProvideDataNotifierTest() { + MockitoAnnotations.initMocks(this); + notifier + .setSessionConnectionHandler(sessionConnectionHandler) + .setSessionNodeExchanger(sessionNodeExchanger) + .setSessionServerManager(sessionServerManager); + } - @Test - public void testBoltRequest() throws RequestException, InterruptedException { - String ip1 = randomIp(), ip2 = randomIp(); - Client rpcClient = spy(getRpcClient(scheduled, 10, new TimeoutException("expected"))); - when(sessionNodeExchanger.request(any(Request.class))).then(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { + @Test + public void testBoltRequest() throws RequestException, InterruptedException { + String ip1 = randomIp(), ip2 = randomIp(); + Client rpcClient = spy(getRpcClient(scheduled, 10, new TimeoutException("expected"))); + when(sessionNodeExchanger.request(any(Request.class))) + .then( + new Answer() { + @Override + public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Request request = invocationOnMock.getArgumentAt(0, Request.class); - rpcClient.sendCallback(request.getRequestUrl(), request.getRequestBody(), - request.getCallBackHandler(), 100); + rpcClient.sendCallback( + request.getRequestUrl(), + request.getRequestBody(), + request.getCallBackHandler(), + 100); return null; - } - }); - notifier.setSessionNodeExchanger(sessionNodeExchanger); - when(sessionConnectionHandler.getConnections(anyString())).thenReturn( - Lists.newArrayList(new InetSocketAddress(ip1, Math.abs(random.nextInt(65535)) % 65535), + } + }); + notifier.setSessionNodeExchanger(sessionNodeExchanger); + when(sessionConnectionHandler.getConnections(anyString())) + .thenReturn( + Lists.newArrayList( + new InetSocketAddress(ip1, Math.abs(random.nextInt(65535)) % 65535), new InetSocketAddress(ip2, Math.abs(random.nextInt(65535)) % 65535), new InetSocketAddress(randomIp(), 1024))); - when(sessionServerManager.getSessionServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), - Lists.newArrayList(new SessionNode(randomURL(ip1), getDc()), new SessionNode( - randomURL(ip2), getDc()), new SessionNode(randomURL(randomIp()), getDc())))); - notifier.notifyProvideDataChange(new ProvideDataChangeEvent( + when(sessionServerManager.getSessionServerMetaInfo()) + .thenReturn( + new VersionedList<>( + DatumVersionUtil.nextId(), + Lists.newArrayList( + new SessionNode(randomURL(ip1), getDc()), + new SessionNode(randomURL(ip2), getDc()), + new SessionNode(randomURL(randomIp()), getDc())))); + notifier.notifyProvideDataChange( + new ProvideDataChangeEvent( ValueConstants.BLACK_LIST_DATA_ID, System.currentTimeMillis(), DataOperator.ADD)); - Thread.sleep(50); - verify(rpcClient, atLeast(1)).sendCallback(any(), any(), any(), anyInt()); - } + Thread.sleep(50); + verify(rpcClient, atLeast(1)).sendCallback(any(), any(), any(), anyInt()); + } - @Test - public void testBoltResponsePositive() throws InterruptedException, RequestException { - String ip1 = randomIp(), ip2 = randomIp(); - when(sessionConnectionHandler.getConnections(anyString())).thenReturn( - Lists.newArrayList(new InetSocketAddress(ip1, Math.abs(random.nextInt(65535)) % 65535), + @Test + public void testBoltResponsePositive() throws InterruptedException, RequestException { + String ip1 = randomIp(), ip2 = randomIp(); + when(sessionConnectionHandler.getConnections(anyString())) + .thenReturn( + Lists.newArrayList( + new InetSocketAddress(ip1, Math.abs(random.nextInt(65535)) % 65535), new InetSocketAddress(ip2, Math.abs(random.nextInt(65535)) % 65535), new InetSocketAddress(randomIp(), 1024))); - when(sessionServerManager.getSessionServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), - Lists.newArrayList(new SessionNode(randomURL(ip1), getDc()), new SessionNode( - randomURL(ip2), getDc()), new SessionNode(randomURL(randomIp()), getDc())))); - Client client2 = spy(getRpcClient(scheduled, 10, "Response")); - SessionNodeExchanger otherNodeExchanger = mock(SessionNodeExchanger.class); - when(otherNodeExchanger.request(any(Request.class))).then(new Answer() { - @Override - public Object answer(InvocationOnMock invocationOnMock) throws Throwable { + when(sessionServerManager.getSessionServerMetaInfo()) + .thenReturn( + new VersionedList<>( + DatumVersionUtil.nextId(), + Lists.newArrayList( + new SessionNode(randomURL(ip1), getDc()), + new SessionNode(randomURL(ip2), getDc()), + new SessionNode(randomURL(randomIp()), getDc())))); + Client client2 = spy(getRpcClient(scheduled, 10, "Response")); + SessionNodeExchanger otherNodeExchanger = mock(SessionNodeExchanger.class); + when(otherNodeExchanger.request(any(Request.class))) + .then( + new Answer() { + @Override + public Object answer(InvocationOnMock invocationOnMock) throws Throwable { Request request = invocationOnMock.getArgumentAt(0, Request.class); logger.warn("[testBoltResponsePositive]"); - client2.sendCallback(request.getRequestUrl(), request.getRequestBody(), - request.getCallBackHandler(), 10000); + client2.sendCallback( + request.getRequestUrl(), + request.getRequestBody(), + request.getCallBackHandler(), + 10000); return null; - } - }); - notifier.setSessionNodeExchanger(otherNodeExchanger); - notifier.notifyProvideDataChange(new ProvideDataChangeEvent( + } + }); + notifier.setSessionNodeExchanger(otherNodeExchanger); + notifier.notifyProvideDataChange( + new ProvideDataChangeEvent( ValueConstants.BLACK_LIST_DATA_ID, System.currentTimeMillis(), DataOperator.ADD)); - Thread.sleep(200); - } -} \ No newline at end of file + Thread.sleep(200); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/resource/SlotTableResourceTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/resource/SlotTableResourceTest.java index d2f53dc80..4af8df6e5 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/resource/SlotTableResourceTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/resource/SlotTableResourceTest.java @@ -16,13 +16,14 @@ */ package com.alipay.sofa.registry.server.meta.resource; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.GenericResponse; import com.alipay.sofa.registry.common.model.metaserver.cluster.VersionedList; import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.SlotTable; import com.alipay.sofa.registry.exception.SofaRegistryRuntimeException; import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; -import com.alipay.sofa.registry.server.meta.AbstractTest; import com.alipay.sofa.registry.server.meta.bootstrap.config.NodeConfig; import com.alipay.sofa.registry.server.meta.lease.data.DefaultDataServerManager; import com.alipay.sofa.registry.server.meta.monitor.SlotTableMonitor; @@ -30,81 +31,83 @@ import com.alipay.sofa.registry.server.meta.slot.arrange.ScheduledSlotArranger; import com.alipay.sofa.registry.server.meta.slot.manager.SimpleSlotManager; import com.alipay.sofa.registry.util.DatumVersionUtil; +import java.util.List; +import java.util.concurrent.TimeoutException; import org.assertj.core.util.Lists; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.List; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.*; - /** * @author zhuchen * @date Mar 2, 2021, 11:48:41 AM */ public class SlotTableResourceTest extends AbstractMetaServerTest { - private SlotManager slotManager; - - private DefaultDataServerManager dataServerManager; - - private SlotTableResource resource; - - private ScheduledSlotArranger slotArranger; - - private SlotTableMonitor slotTableMonitor; - - @Before - public void beforeSlotTableResourceTest() { - NodeConfig nodeConfig = mock(NodeConfig.class); - when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); - slotManager = new SimpleSlotManager(); - dataServerManager = mock(DefaultDataServerManager.class); - slotTableMonitor = mock(SlotTableMonitor.class); - slotArranger = spy(new ScheduledSlotArranger(dataServerManager, slotManager, slotTableMonitor, metaLeaderService)); - resource = new SlotTableResource(slotManager, dataServerManager, - slotArranger, metaLeaderService); - } - - @Test - public void testForceRefreshSlotTable() throws TimeoutException, InterruptedException { - makeMetaLeader(); - List dataNodes = Lists.newArrayList(new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), new DataNode(randomURL(randomIp()), - getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - SlotTable slotTable = new SlotTableGenerator(dataNodes).createLeaderUnBalancedSlotTable(); - slotManager.refresh(slotTable); - - when(slotArranger.tryLock()).thenReturn(true); - GenericResponse current = resource.forceRefreshSlotTable(); - printSlotTable(current.getData()); - Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), dataNodes)); - } - - @Test - public void testStartReconcile() throws Exception { - slotArranger.postConstruct(); - slotArranger.suspend(); - resource.startSlotTableReconcile(); - Assert.assertEquals("running", resource.getReconcileStatus().getMessage()); - } - - @Test - public void testStopReconcile() throws Exception { - slotArranger.postConstruct(); - resource.stopSlotTableReconcile(); - Assert.assertEquals("stopped", resource.getReconcileStatus().getMessage()); - } - - @Test - public void testGetDataStats() { - when(dataServerManager.getDataServersStats()).thenThrow( - new SofaRegistryRuntimeException("expected exception")); - GenericResponse response = resource.getDataSlotStatuses(); - Assert.assertEquals("expected exception", response.getMessage()); - } - -} \ No newline at end of file + private SlotManager slotManager; + + private DefaultDataServerManager dataServerManager; + + private SlotTableResource resource; + + private ScheduledSlotArranger slotArranger; + + private SlotTableMonitor slotTableMonitor; + + @Before + public void beforeSlotTableResourceTest() { + NodeConfig nodeConfig = mock(NodeConfig.class); + when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); + slotManager = new SimpleSlotManager(); + dataServerManager = mock(DefaultDataServerManager.class); + slotTableMonitor = mock(SlotTableMonitor.class); + slotArranger = + spy( + new ScheduledSlotArranger( + dataServerManager, slotManager, slotTableMonitor, metaLeaderService)); + resource = + new SlotTableResource(slotManager, dataServerManager, slotArranger, metaLeaderService); + } + + @Test + public void testForceRefreshSlotTable() throws TimeoutException, InterruptedException { + makeMetaLeader(); + List dataNodes = + Lists.newArrayList( + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + SlotTable slotTable = new SlotTableGenerator(dataNodes).createLeaderUnBalancedSlotTable(); + slotManager.refresh(slotTable); + + when(slotArranger.tryLock()).thenReturn(true); + GenericResponse current = resource.forceRefreshSlotTable(); + printSlotTable(current.getData()); + Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), dataNodes)); + } + + @Test + public void testStartReconcile() throws Exception { + slotArranger.postConstruct(); + slotArranger.suspend(); + resource.startSlotTableReconcile(); + Assert.assertEquals("running", resource.getReconcileStatus().getMessage()); + } + + @Test + public void testStopReconcile() throws Exception { + slotArranger.postConstruct(); + resource.stopSlotTableReconcile(); + Assert.assertEquals("stopped", resource.getReconcileStatus().getMessage()); + } + + @Test + public void testGetDataStats() { + when(dataServerManager.getDataServersStats()) + .thenThrow(new SofaRegistryRuntimeException("expected exception")); + GenericResponse response = resource.getDataSlotStatuses(); + Assert.assertEquals("expected exception", response.getMessage()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareFilterTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareFilterTest.java index 0202b70a3..aa1b6b242 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareFilterTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/resource/filter/LeaderAwareFilterTest.java @@ -16,44 +16,36 @@ */ package com.alipay.sofa.registry.server.meta.resource.filter; +import static org.junit.Assert.*; + import com.alipay.sofa.registry.common.model.store.URL; -import com.alipay.sofa.registry.core.model.Result; import com.alipay.sofa.registry.remoting.Channel; import com.alipay.sofa.registry.remoting.jersey.JerseyClient; import com.alipay.sofa.registry.server.meta.AbstractH2DbTestBase; import com.alipay.sofa.registry.server.meta.bootstrap.config.MetaServerConfig; import com.alipay.sofa.registry.server.shared.env.ServerEnv; import com.alipay.sofa.registry.store.api.elector.LeaderElector; +import java.util.concurrent.TimeoutException; +import javax.ws.rs.core.Response; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import javax.ws.rs.core.Response; -import java.util.concurrent.TimeoutException; - -import static org.junit.Assert.*; - public class LeaderAwareFilterTest extends AbstractH2DbTestBase { - @Autowired - private LeaderElector leaderElector; + @Autowired private LeaderElector leaderElector; - @Autowired - private MetaServerConfig metaServerConfig; + @Autowired private MetaServerConfig metaServerConfig; - private Channel channel; + private Channel channel; - @Test - public void testFilterWorks() throws TimeoutException, InterruptedException { - leaderElector.change2Observer(); - channel = JerseyClient.getInstance().connect(new URL(ServerEnv.IP, metaServerConfig.getHttpServerPort())); - waitConditionUntilTimeOut(()->!leaderElector.amILeader(), 2000); - Response response = channel - .getWebTarget() - .path("stopPushDataSwitch/open") - .request() - .get(); - logger.info("[response] {}", response); - } -} \ No newline at end of file + @Test + public void testFilterWorks() throws TimeoutException, InterruptedException { + leaderElector.change2Observer(); + channel = + JerseyClient.getInstance() + .connect(new URL(ServerEnv.IP, metaServerConfig.getHttpServerPort())); + waitConditionUntilTimeOut(() -> !leaderElector.amILeader(), 2000); + Response response = channel.getWebTarget().path("stopPushDataSwitch/open").request().get(); + logger.info("[response] {}", response); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/arrange/CrossDcSlotAllocatorTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/arrange/CrossDcSlotAllocatorTest.java index b25f6d8d3..e79d484e6 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/arrange/CrossDcSlotAllocatorTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/arrange/CrossDcSlotAllocatorTest.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.slot.arrange; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.metaserver.nodes.MetaNode; import com.alipay.sofa.registry.common.model.slot.Slot; import com.alipay.sofa.registry.common.model.slot.SlotTable; @@ -28,6 +30,7 @@ import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; import com.alipay.sofa.registry.server.meta.MetaLeaderService; import com.alipay.sofa.registry.server.meta.metaserver.CrossDcMetaServer; +import java.util.concurrent.TimeoutException; import org.assertj.core.util.Lists; import org.junit.After; import org.junit.Assert; @@ -36,122 +39,133 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.*; - public class CrossDcSlotAllocatorTest extends AbstractMetaServerTest { - private CrossDcSlotAllocator allocator; - - @Mock - private CrossDcMetaServer crossDcMetaServer; - - @Mock - private Exchange exchange; - - @Mock - private MetaLeaderService leaderElector; - - @Before - public void beforeCrossDcSlotAllocatorTest() throws Exception { - MockitoAnnotations.initMocks(this); - when(crossDcMetaServer.getClusterMembers()).thenReturn( - Lists.newArrayList(new MetaNode(randomURL(), getDc()))); - when(crossDcMetaServer.getClusterMembers()).thenReturn( - Lists.newArrayList(new MetaNode(randomURL(), getDc()))); - allocator = spy(new CrossDcSlotAllocator(getDc(), scheduled, exchange, crossDcMetaServer, - leaderElector)); - } - - @After - public void afterCrossDcSlotAllocatorTest() throws Exception { - LifecycleHelper.stopIfPossible(allocator); - LifecycleHelper.disposeIfPossible(allocator); - } - - @Test - public void testGetSlotTable() throws TimeoutException, InterruptedException, InitializeException, StartException { - LifecycleHelper.initializeIfPossible(allocator); - LifecycleHelper.startIfPossible(allocator); - Assert.assertNull(allocator.getSlotTable()); - - when(exchange.getClient(Exchange.META_SERVER_TYPE)).thenReturn(getRpcClient(scheduled, 1, - new SlotTable(System.currentTimeMillis(), Lists.newArrayList( - new Slot(1, "10.0.0.1", System.currentTimeMillis(), Lists.newArrayList("10.0.0.2")) - )))); - allocator.refreshSlotTable(0); - waitConditionUntilTimeOut(()->allocator.getSlotTable() != null, 1000); - - Assert.assertNotNull(allocator.getSlotTable()); - Assert.assertEquals("10.0.0.1", allocator.getSlotTable().getSlot(1).getLeader()); - } - - @Test - public void testTestGetDc() { - Assert.assertEquals(getDc(), allocator.getDc()); - } - - @Test - public void testRefreshSlotTableFirstFailure() throws TimeoutException, InterruptedException, StartException, InitializeException { - LifecycleHelper.initializeIfPossible(allocator); - LifecycleHelper.startIfPossible(allocator); - Assert.assertNull(allocator.getSlotTable()); - - when(exchange.getClient(Exchange.META_SERVER_TYPE)) - .thenReturn(getRpcClient(scheduled, 3, new TimeoutException("expected timeout"))) - .thenReturn(getRpcClient(scheduled, 1, - new SlotTable(System.currentTimeMillis(), Lists.newArrayList( - new Slot(1, "10.0.0.1", System.currentTimeMillis(), Lists.newArrayList("10.0.0.2")) - )))); - allocator.refreshSlotTable(0); - waitConditionUntilTimeOut(()->allocator.getSlotTable() != null, 1000); - - Assert.assertNotNull(allocator.getSlotTable()); - Assert.assertEquals("10.0.0.1", allocator.getSlotTable().getSlot(1).getLeader()); - } - - @Test - public void testRefreshSlotTableRetryOverTimes() throws TimeoutException, InterruptedException, - StartException, InitializeException { - LifecycleHelper.initializeIfPossible(allocator); - LifecycleHelper.startIfPossible(allocator); - - Assert.assertNull(allocator.getSlotTable()); - - when(exchange.getClient(Exchange.META_SERVER_TYPE)).thenReturn( - getRpcClient(scheduled, 3, new TimeoutException("expected timeout"))); - - allocator.refreshSlotTable(0); - Thread.sleep(100); - - Assert.assertNull(allocator.getSlotTable()); - verify(allocator, atLeast(2)).refreshSlotTable(anyInt()); - } - - @Test - public void testDoInitialize() throws InitializeException { - LifecycleHelper.initializeIfPossible(allocator); - Assert.assertEquals(LifecycleState.LifecyclePhase.INITIALIZED, allocator - .getLifecycleState().getPhase()); - } - - @Test - public void testDoStart() throws InitializeException, StopException, StartException { - LifecycleHelper.initializeIfPossible(allocator); - LifecycleHelper.startIfPossible(allocator); - Assert.assertEquals(LifecycleState.LifecyclePhase.STARTED, allocator.getLifecycleState() - .getPhase()); - verify(allocator, never()).refreshSlotTable(anyInt()); - verify(allocator, times(1)).doStart(); - } - - @Test - public void testDoStop() { - - } - - @Test - public void testDoDispose() { - } -} \ No newline at end of file + private CrossDcSlotAllocator allocator; + + @Mock private CrossDcMetaServer crossDcMetaServer; + + @Mock private Exchange exchange; + + @Mock private MetaLeaderService leaderElector; + + @Before + public void beforeCrossDcSlotAllocatorTest() throws Exception { + MockitoAnnotations.initMocks(this); + when(crossDcMetaServer.getClusterMembers()) + .thenReturn(Lists.newArrayList(new MetaNode(randomURL(), getDc()))); + when(crossDcMetaServer.getClusterMembers()) + .thenReturn(Lists.newArrayList(new MetaNode(randomURL(), getDc()))); + allocator = + spy( + new CrossDcSlotAllocator( + getDc(), scheduled, exchange, crossDcMetaServer, leaderElector)); + } + + @After + public void afterCrossDcSlotAllocatorTest() throws Exception { + LifecycleHelper.stopIfPossible(allocator); + LifecycleHelper.disposeIfPossible(allocator); + } + + @Test + public void testGetSlotTable() + throws TimeoutException, InterruptedException, InitializeException, StartException { + LifecycleHelper.initializeIfPossible(allocator); + LifecycleHelper.startIfPossible(allocator); + Assert.assertNull(allocator.getSlotTable()); + + when(exchange.getClient(Exchange.META_SERVER_TYPE)) + .thenReturn( + getRpcClient( + scheduled, + 1, + new SlotTable( + System.currentTimeMillis(), + Lists.newArrayList( + new Slot( + 1, + "10.0.0.1", + System.currentTimeMillis(), + Lists.newArrayList("10.0.0.2")))))); + allocator.refreshSlotTable(0); + waitConditionUntilTimeOut(() -> allocator.getSlotTable() != null, 1000); + + Assert.assertNotNull(allocator.getSlotTable()); + Assert.assertEquals("10.0.0.1", allocator.getSlotTable().getSlot(1).getLeader()); + } + + @Test + public void testTestGetDc() { + Assert.assertEquals(getDc(), allocator.getDc()); + } + + @Test + public void testRefreshSlotTableFirstFailure() + throws TimeoutException, InterruptedException, StartException, InitializeException { + LifecycleHelper.initializeIfPossible(allocator); + LifecycleHelper.startIfPossible(allocator); + Assert.assertNull(allocator.getSlotTable()); + + when(exchange.getClient(Exchange.META_SERVER_TYPE)) + .thenReturn(getRpcClient(scheduled, 3, new TimeoutException("expected timeout"))) + .thenReturn( + getRpcClient( + scheduled, + 1, + new SlotTable( + System.currentTimeMillis(), + Lists.newArrayList( + new Slot( + 1, + "10.0.0.1", + System.currentTimeMillis(), + Lists.newArrayList("10.0.0.2")))))); + allocator.refreshSlotTable(0); + waitConditionUntilTimeOut(() -> allocator.getSlotTable() != null, 1000); + + Assert.assertNotNull(allocator.getSlotTable()); + Assert.assertEquals("10.0.0.1", allocator.getSlotTable().getSlot(1).getLeader()); + } + + @Test + public void testRefreshSlotTableRetryOverTimes() + throws TimeoutException, InterruptedException, StartException, InitializeException { + LifecycleHelper.initializeIfPossible(allocator); + LifecycleHelper.startIfPossible(allocator); + + Assert.assertNull(allocator.getSlotTable()); + + when(exchange.getClient(Exchange.META_SERVER_TYPE)) + .thenReturn(getRpcClient(scheduled, 3, new TimeoutException("expected timeout"))); + + allocator.refreshSlotTable(0); + Thread.sleep(100); + + Assert.assertNull(allocator.getSlotTable()); + verify(allocator, atLeast(2)).refreshSlotTable(anyInt()); + } + + @Test + public void testDoInitialize() throws InitializeException { + LifecycleHelper.initializeIfPossible(allocator); + Assert.assertEquals( + LifecycleState.LifecyclePhase.INITIALIZED, allocator.getLifecycleState().getPhase()); + } + + @Test + public void testDoStart() throws InitializeException, StopException, StartException { + LifecycleHelper.initializeIfPossible(allocator); + LifecycleHelper.startIfPossible(allocator); + Assert.assertEquals( + LifecycleState.LifecyclePhase.STARTED, allocator.getLifecycleState().getPhase()); + verify(allocator, never()).refreshSlotTable(anyInt()); + verify(allocator, times(1)).doStart(); + } + + @Test + public void testDoStop() {} + + @Test + public void testDoDispose() {} +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/arrange/ScheduledSlotArrangerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/arrange/ScheduledSlotArrangerTest.java index a48864400..a1fb6d2b2 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/arrange/ScheduledSlotArrangerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/arrange/ScheduledSlotArrangerTest.java @@ -16,92 +16,89 @@ */ package com.alipay.sofa.registry.server.meta.slot.arrange; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; import com.alipay.sofa.registry.server.meta.lease.data.DefaultDataServerManager; import com.alipay.sofa.registry.server.meta.monitor.SlotTableMonitor; import com.alipay.sofa.registry.server.meta.resource.SlotTableResource; import com.alipay.sofa.registry.server.meta.slot.SlotManager; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.atomic.AtomicInteger; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; - public class ScheduledSlotArrangerTest extends AbstractMetaServerTest { - private ScheduledSlotArranger slotArranger; - - private SlotTableResource slotTableResource; - - @Mock - private DefaultDataServerManager dataServerManager; - - @Mock - private SlotManager slotManager; - - @Mock - private SlotTableMonitor slotTableMonitor; - - - @Before - public void beforeScheduledSlotArrangerTest() { - MockitoAnnotations.initMocks(this); - when(metaLeaderService.amILeader()).thenReturn(true); - when(metaLeaderService.amIStableAsLeader()).thenReturn(true); - slotArranger = spy(new ScheduledSlotArranger(dataServerManager, - slotManager, slotTableMonitor, metaLeaderService)); - } - - @Test - public void testTryLock() throws InterruptedException { - Assert.assertTrue(slotArranger.tryLock()); - slotArranger.unlock(); - Assert.assertTrue(slotArranger.tryLock()); - slotArranger.unlock(); - AtomicInteger counter = new AtomicInteger(); - int tasks = 100; - CyclicBarrier barrier = new CyclicBarrier(tasks); - CountDownLatch latch = new CountDownLatch(tasks); - for (int i = 0; i < tasks; i++) { - executors.execute(new Runnable() { - @Override - public void run() { - try { - barrier.await(); - if (slotArranger.tryLock()) { - counter.incrementAndGet(); - } - } catch (Throwable th) { - - } finally { - latch.countDown(); - } + private ScheduledSlotArranger slotArranger; + + private SlotTableResource slotTableResource; + + @Mock private DefaultDataServerManager dataServerManager; + + @Mock private SlotManager slotManager; + + @Mock private SlotTableMonitor slotTableMonitor; + + @Before + public void beforeScheduledSlotArrangerTest() { + MockitoAnnotations.initMocks(this); + when(metaLeaderService.amILeader()).thenReturn(true); + when(metaLeaderService.amIStableAsLeader()).thenReturn(true); + slotArranger = + spy( + new ScheduledSlotArranger( + dataServerManager, slotManager, slotTableMonitor, metaLeaderService)); + } + + @Test + public void testTryLock() throws InterruptedException { + Assert.assertTrue(slotArranger.tryLock()); + slotArranger.unlock(); + Assert.assertTrue(slotArranger.tryLock()); + slotArranger.unlock(); + AtomicInteger counter = new AtomicInteger(); + int tasks = 100; + CyclicBarrier barrier = new CyclicBarrier(tasks); + CountDownLatch latch = new CountDownLatch(tasks); + for (int i = 0; i < tasks; i++) { + executors.execute( + new Runnable() { + @Override + public void run() { + try { + barrier.await(); + if (slotArranger.tryLock()) { + counter.incrementAndGet(); } - }); - } - latch.await(); - Assert.assertEquals(1, counter.get()); - } + } catch (Throwable th) { - @Test - public void testStopStartReconcile() throws Exception { - slotTableResource = new SlotTableResource(slotManager, dataServerManager, slotArranger, metaLeaderService); - slotArranger.postConstruct(); - Assert.assertEquals("running", slotTableResource.getReconcileStatus().getMessage()); - - slotTableResource.stopSlotTableReconcile(); - Assert.assertEquals("stopped", slotTableResource.getReconcileStatus().getMessage()); - - slotTableResource.startSlotTableReconcile(); - Assert.assertEquals("running", slotTableResource.getReconcileStatus().getMessage()); + } finally { + latch.countDown(); + } + } + }); } - - -} \ No newline at end of file + latch.await(); + Assert.assertEquals(1, counter.get()); + } + + @Test + public void testStopStartReconcile() throws Exception { + slotTableResource = + new SlotTableResource(slotManager, dataServerManager, slotArranger, metaLeaderService); + slotArranger.postConstruct(); + Assert.assertEquals("running", slotTableResource.getReconcileStatus().getMessage()); + + slotTableResource.stopSlotTableReconcile(); + Assert.assertEquals("stopped", slotTableResource.getReconcileStatus().getMessage()); + + slotTableResource.startSlotTableReconcile(); + Assert.assertEquals("running", slotTableResource.getReconcileStatus().getMessage()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/balance/DefaultSlotBalancerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/balance/DefaultSlotBalancerTest.java index cff89d0ce..42073001a 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/balance/DefaultSlotBalancerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/balance/DefaultSlotBalancerTest.java @@ -16,6 +16,9 @@ */ package com.alipay.sofa.registry.server.meta.slot.balance; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.common.model.metaserver.cluster.VersionedList; import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.SlotTable; @@ -28,74 +31,77 @@ import com.alipay.sofa.registry.server.meta.slot.util.builder.SlotTableBuilder; import com.alipay.sofa.registry.server.shared.util.NodeUtils; import com.alipay.sofa.registry.util.DatumVersionUtil; +import java.util.List; import org.assertj.core.util.Lists; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.List; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class DefaultSlotBalancerTest extends AbstractMetaServerTest { - private DefaultSlotBalancer slotBalancer; + private DefaultSlotBalancer slotBalancer; - private SimpleSlotManager slotManager; + private SimpleSlotManager slotManager; - private DataServerManager dataServerManager; + private DataServerManager dataServerManager; - private SlotTableMonitor slotTableMonitor; + private SlotTableMonitor slotTableMonitor; - @Before - public void beforeDefaultSlotBalancerTest() { - NodeConfig nodeConfig = mock(NodeConfig.class); - when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); - slotManager = new SimpleSlotManager(); - dataServerManager = mock(DataServerManager.class); - slotTableMonitor = mock(SlotTableMonitor.class); - } + @Before + public void beforeDefaultSlotBalancerTest() { + NodeConfig nodeConfig = mock(NodeConfig.class); + when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); + slotManager = new SimpleSlotManager(); + dataServerManager = mock(DataServerManager.class); + slotTableMonitor = mock(SlotTableMonitor.class); + } - @Test - public void testBalance() { - List dataNodes = Lists.newArrayList(new DataNode(randomURL("10.0.0.1"), getDc()), - new DataNode(randomURL("10.0.0.2"), getDc()), new DataNode(randomURL("10.0.0.3"), - getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(),dataNodes)); + @Test + public void testBalance() { + List dataNodes = + Lists.newArrayList( + new DataNode(randomURL("10.0.0.1"), getDc()), + new DataNode(randomURL("10.0.0.2"), getDc()), + new DataNode(randomURL("10.0.0.3"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - SlotTable slotTable = randomSlotTable(Lists.newArrayList(new DataNode( - randomURL("10.0.0.1"), getDc()), new DataNode(randomURL("10.0.0.2"), getDc()))); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + SlotTable slotTable = + randomSlotTable( + Lists.newArrayList( + new DataNode(randomURL("10.0.0.1"), getDc()), + new DataNode(randomURL("10.0.0.2"), getDc()))); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - SlotBuilder sb = slotTableBuilder.getOrCreate(0); - replaceFollower(sb, "10.0.0.3"); - sb = slotTableBuilder.getOrCreate(1); - replaceFollower(sb, "10.0.0.3"); - sb = slotTableBuilder.getOrCreate(2); - replaceFollower(sb, "10.0.0.3"); + SlotBuilder sb = slotTableBuilder.getOrCreate(0); + replaceFollower(sb, "10.0.0.3"); + sb = slotTableBuilder.getOrCreate(1); + replaceFollower(sb, "10.0.0.3"); + sb = slotTableBuilder.getOrCreate(2); + replaceFollower(sb, "10.0.0.3"); - slotManager.refresh(slotTableBuilder.build()); - slotBalancer = new DefaultSlotBalancer(slotTableBuilder, Lists.newArrayList("10.0.0.1", - "10.0.0.2", "10.0.0.3")); - for (int i = 0; i < 10; i++) { - SlotTable slotTable1 = slotBalancer.balance(); - if (i == 0) { - Assert.assertNotNull(slotTable1); - } - if (slotTable1 == null) { - break; - } - logger.info("balance {}: {}", i, slotTable1); - assertSlotTableNoDupLeaderFollower(slotTable1); - } + slotManager.refresh(slotTableBuilder.build()); + slotBalancer = + new DefaultSlotBalancer( + slotTableBuilder, Lists.newArrayList("10.0.0.1", "10.0.0.2", "10.0.0.3")); + for (int i = 0; i < 10; i++) { + SlotTable slotTable1 = slotBalancer.balance(); + if (i == 0) { + Assert.assertNotNull(slotTable1); + } + if (slotTable1 == null) { + break; + } + logger.info("balance {}: {}", i, slotTable1); + assertSlotTableNoDupLeaderFollower(slotTable1); } + } - private static void replaceFollower(SlotBuilder sb, String follower) { - for (String f : sb.getFollowers()) { - sb.removeFollower(f); - } - sb.addFollower(follower); + private static void replaceFollower(SlotBuilder sb, String follower) { + for (String f : sb.getFollowers()) { + sb.removeFollower(f); } + sb.addFollower(follower); + } } diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/balance/LeaderOnlyBalancerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/balance/LeaderOnlyBalancerTest.java index b6816aa9f..079bead43 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/balance/LeaderOnlyBalancerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/balance/LeaderOnlyBalancerTest.java @@ -16,6 +16,9 @@ */ package com.alipay.sofa.registry.server.meta.slot.balance; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.SlotTable; import com.alipay.sofa.registry.common.model.store.URL; @@ -24,99 +27,106 @@ import com.alipay.sofa.registry.server.meta.slot.manager.SimpleSlotManager; import com.alipay.sofa.registry.server.meta.slot.util.builder.SlotTableBuilder; import com.alipay.sofa.registry.server.shared.util.NodeUtils; +import java.util.List; import org.assertj.core.util.Lists; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import java.util.List; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - public class LeaderOnlyBalancerTest extends AbstractMetaServerTest { - private SimpleSlotManager slotManager; + private SimpleSlotManager slotManager; - private List currentDataServers; + private List currentDataServers; - private SlotTableBuilder slotTableBuilder; + private SlotTableBuilder slotTableBuilder; - private LeaderOnlyBalancer balancer; + private LeaderOnlyBalancer balancer; - @BeforeClass - public static void beforeLeaderOnlyBalancerTestClass() { - System.setProperty("data.slot.num", "16"); - System.setProperty("data.slot.replicas", "1"); - System.setProperty("slot.leader.max.move", "2"); - } + @BeforeClass + public static void beforeLeaderOnlyBalancerTestClass() { + System.setProperty("data.slot.num", "16"); + System.setProperty("data.slot.replicas", "1"); + System.setProperty("slot.leader.max.move", "2"); + } - @Before - public void beforeLeaderOnlyBalancerTest() { - NodeConfig nodeConfig = mock(NodeConfig.class); - when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); + @Before + public void beforeLeaderOnlyBalancerTest() { + NodeConfig nodeConfig = mock(NodeConfig.class); + when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); - currentDataServers = Lists.newArrayList("10.0.0.1", "10.0.0.2", "10.0.0.3"); - slotManager = new SimpleSlotManager(); - slotTableBuilder = new SlotTableBuilder(slotManager.getSlotTable(), 16, 1); - balancer = new LeaderOnlyBalancer(slotTableBuilder, currentDataServers); - } + currentDataServers = Lists.newArrayList("10.0.0.1", "10.0.0.2", "10.0.0.3"); + slotManager = new SimpleSlotManager(); + slotTableBuilder = new SlotTableBuilder(slotManager.getSlotTable(), 16, 1); + balancer = new LeaderOnlyBalancer(slotTableBuilder, currentDataServers); + } - @Test - public void testBalance() { - String singleNode = currentDataServers.get(0); - for (int slotId = 0; slotId < 16; slotId++) { - slotTableBuilder.replaceLeader(slotId, singleNode); - } - slotTableBuilder.init(currentDataServers); - SlotTable prev = slotTableBuilder.build(); - SlotTable slotTable = balancer.balance(); - Assert.assertEquals(1, slotTable.transfer(currentDataServers.get(1), false).get(0) - .totalSlotNum()); - Assert.assertEquals(1, slotTable.transfer(currentDataServers.get(2), false).get(0) - .totalSlotNum()); - - Assert.assertTrue(isMoreBalanced(prev, slotTable, Lists.newArrayList(new DataNode(new URL( - "10.0.0.1"), getDc()), new DataNode(new URL("10.0.0.2"), getDc()), new DataNode( - new URL("10.0.0.3"), getDc())))); - - slotTable = balancer.balance(); - Assert.assertEquals(2, slotTable.transfer(currentDataServers.get(1), false).get(0) - .totalSlotNum()); - Assert.assertEquals(2, slotTable.transfer(currentDataServers.get(2), false).get(0) - .totalSlotNum()); - - Assert.assertTrue(isMoreBalanced(prev, slotTable, Lists.newArrayList(new DataNode(new URL( - "10.0.0.1"), getDc()), new DataNode(new URL("10.0.0.2"), getDc()), new DataNode( - new URL("10.0.0.3"), getDc())))); + @Test + public void testBalance() { + String singleNode = currentDataServers.get(0); + for (int slotId = 0; slotId < 16; slotId++) { + slotTableBuilder.replaceLeader(slotId, singleNode); } - - @Test - public void testNoDataNodesNeedBalance() { - List dataNodes = randomDataNodes(3); - SlotTable slotTable = randomSlotTable(dataNodes); - currentDataServers = NodeUtils.transferNodeToIpList(dataNodes); - slotTableBuilder.init(currentDataServers); - slotManager.refresh(slotTable); - balancer = new LeaderOnlyBalancer(slotTableBuilder, currentDataServers); - Assert.assertNull(balancer.balance()); - } - - @Test - public void testFindDataServersNeedLeaderSlots() { - String singleNode = currentDataServers.get(0); - for (int slotId = 0; slotId < 16; slotId++) { - slotTableBuilder.replaceLeader(slotId, singleNode); - } - slotTableBuilder.init(currentDataServers); - // TODO - // Assert.assertFalse(balancer.findDataServersNeedLeaderSlots( - // SlotConfig.SLOT_NUM / currentDataServers.size()).isEmpty()); - // Set expected = Sets.newHashSet("10.0.0.2", "10.0.0.3"); - // Set actual = balancer.findDataServersNeedLeaderSlots(SlotConfig.SLOT_NUM - // / currentDataServers.size()); - // - // Assert.assertEquals(expected, actual); + slotTableBuilder.init(currentDataServers); + SlotTable prev = slotTableBuilder.build(); + SlotTable slotTable = balancer.balance(); + Assert.assertEquals( + 1, slotTable.transfer(currentDataServers.get(1), false).get(0).totalSlotNum()); + Assert.assertEquals( + 1, slotTable.transfer(currentDataServers.get(2), false).get(0).totalSlotNum()); + + Assert.assertTrue( + isMoreBalanced( + prev, + slotTable, + Lists.newArrayList( + new DataNode(new URL("10.0.0.1"), getDc()), + new DataNode(new URL("10.0.0.2"), getDc()), + new DataNode(new URL("10.0.0.3"), getDc())))); + + slotTable = balancer.balance(); + Assert.assertEquals( + 2, slotTable.transfer(currentDataServers.get(1), false).get(0).totalSlotNum()); + Assert.assertEquals( + 2, slotTable.transfer(currentDataServers.get(2), false).get(0).totalSlotNum()); + + Assert.assertTrue( + isMoreBalanced( + prev, + slotTable, + Lists.newArrayList( + new DataNode(new URL("10.0.0.1"), getDc()), + new DataNode(new URL("10.0.0.2"), getDc()), + new DataNode(new URL("10.0.0.3"), getDc())))); + } + + @Test + public void testNoDataNodesNeedBalance() { + List dataNodes = randomDataNodes(3); + SlotTable slotTable = randomSlotTable(dataNodes); + currentDataServers = NodeUtils.transferNodeToIpList(dataNodes); + slotTableBuilder.init(currentDataServers); + slotManager.refresh(slotTable); + balancer = new LeaderOnlyBalancer(slotTableBuilder, currentDataServers); + Assert.assertNull(balancer.balance()); + } + + @Test + public void testFindDataServersNeedLeaderSlots() { + String singleNode = currentDataServers.get(0); + for (int slotId = 0; slotId < 16; slotId++) { + slotTableBuilder.replaceLeader(slotId, singleNode); } -} \ No newline at end of file + slotTableBuilder.init(currentDataServers); + // TODO + // Assert.assertFalse(balancer.findDataServersNeedLeaderSlots( + // SlotConfig.SLOT_NUM / currentDataServers.size()).isEmpty()); + // Set expected = Sets.newHashSet("10.0.0.2", "10.0.0.3"); + // Set actual = balancer.findDataServersNeedLeaderSlots(SlotConfig.SLOT_NUM + // / + // currentDataServers.size()); + // + // Assert.assertEquals(expected, actual); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/CheckerAction.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/CheckerAction.java index 64cf7ff4d..4cc90d638 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/CheckerAction.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/CheckerAction.java @@ -22,7 +22,6 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.server.shared.slot.SlotTableUtils; import com.alipay.sofa.registry.util.MathUtils; - import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; @@ -30,92 +29,102 @@ import java.util.OptionalDouble; /** - * * @author xiaojian.xj * @version $Id: CheckerAction.java, v 0.1 2021年02月03日 10:25 xiaojian.xj Exp $ */ - public interface CheckerAction { - boolean doCheck(SlotTable slotTable); - - default Tuple max(Map count) { - Optional> max = count.entrySet().stream().max((Comparator.comparing(Entry::getValue))); - return new Tuple<>(max.get().getKey(), max.get().getValue()); - } - - default Tuple min(Map count) { - Optional> max = count.entrySet().stream().min((Comparator.comparing(Entry::getValue))); - return new Tuple<>(max.get().getKey(), max.get().getValue()); - } - - default double average(Map count) { - OptionalDouble average = count.entrySet().stream().mapToInt(entry -> entry.getValue()).average(); - return average.getAsDouble(); - } - - default int sum(Map count) { - return (int)count.entrySet().stream().mapToInt(entry -> entry.getValue()).sum(); - } + boolean doCheck(SlotTable slotTable); + + default Tuple max(Map count) { + Optional> max = + count.entrySet().stream().max((Comparator.comparing(Entry::getValue))); + return new Tuple<>(max.get().getKey(), max.get().getValue()); + } + + default Tuple min(Map count) { + Optional> max = + count.entrySet().stream().min((Comparator.comparing(Entry::getValue))); + return new Tuple<>(max.get().getKey(), max.get().getValue()); + } + + default double average(Map count) { + OptionalDouble average = + count.entrySet().stream().mapToInt(entry -> entry.getValue()).average(); + return average.getAsDouble(); + } + + default int sum(Map count) { + return (int) count.entrySet().stream().mapToInt(entry -> entry.getValue()).sum(); + } } class SlotLeaderChecker implements CheckerAction { - private final Logger logger = LoggerFactory.getLogger(getClass()); - - @Override - public boolean doCheck(SlotTable slotTable) { - - Map leaderCount = SlotTableUtils.getSlotTableLeaderCount(slotTable); - logger.info("[slot leader checker] leaderCount: " + leaderCount); - Tuple max = max(leaderCount); - Tuple min = min(leaderCount); - int average = MathUtils.divideCeil(sum(leaderCount), leaderCount.size()); - logger.info("[slot leader checker] max-ip: {}, max-count:{}, min-ip: {}, min-count:{}, average: {}", - max.getFirst(), max.getSecond(), min.getFirst(), min.getSecond(), (int) average); - - return max.getSecond() < min.getSecond() * 2; - } + private final Logger logger = LoggerFactory.getLogger(getClass()); + + @Override + public boolean doCheck(SlotTable slotTable) { + + Map leaderCount = SlotTableUtils.getSlotTableLeaderCount(slotTable); + logger.info("[slot leader checker] leaderCount: " + leaderCount); + Tuple max = max(leaderCount); + Tuple min = min(leaderCount); + int average = MathUtils.divideCeil(sum(leaderCount), leaderCount.size()); + logger.info( + "[slot leader checker] max-ip: {}, max-count:{}, min-ip: {}, min-count:{}, average: {}", + max.getFirst(), + max.getSecond(), + min.getFirst(), + min.getSecond(), + (int) average); + + return max.getSecond() < min.getSecond() * 2; + } } class SlotChecker implements CheckerAction { - private final Logger logger = LoggerFactory.getLogger(getClass()); - - @Override - public boolean doCheck(SlotTable slotTable) { - Map slotCount = SlotTableUtils.getSlotTableSlotCount(slotTable); - logger.info("[slot checker] slotCount: " + slotCount); - - Tuple max = max(slotCount); - Tuple min = min(slotCount); - double average = average(slotCount); - logger.info("[slot checker] max-ip: {}, max-count:{}, min-ip: {}, min-count:{}, average: {}", - max.getFirst(), max.getSecond(), min.getFirst(), min.getSecond(), (int) average); - - return max.getSecond() < min.getSecond() * 2; - } + private final Logger logger = LoggerFactory.getLogger(getClass()); + + @Override + public boolean doCheck(SlotTable slotTable) { + Map slotCount = SlotTableUtils.getSlotTableSlotCount(slotTable); + logger.info("[slot checker] slotCount: " + slotCount); + + Tuple max = max(slotCount); + Tuple min = min(slotCount); + double average = average(slotCount); + logger.info( + "[slot checker] max-ip: {}, max-count:{}, min-ip: {}, min-count:{}, average: {}", + max.getFirst(), + max.getSecond(), + min.getFirst(), + min.getSecond(), + (int) average); + + return max.getSecond() < min.getSecond() * 2; + } } enum CheckEnum { + SLOT_LEADER_CHECKER(new SlotLeaderChecker()), - SLOT_LEADER_CHECKER(new SlotLeaderChecker()), - - SLOT_CHECKER(new SlotChecker()), - ; + SLOT_CHECKER(new SlotChecker()), + ; - private CheckerAction checkerAction; + private CheckerAction checkerAction; - CheckEnum(CheckerAction checkerAction) { - this.checkerAction = checkerAction; - } + CheckEnum(CheckerAction checkerAction) { + this.checkerAction = checkerAction; + } - /** - * Getter method for property checkerAction. - * - * @return property value of checkerAction - */ - public CheckerAction getCheckerAction() { - return checkerAction; - } -} \ No newline at end of file + /** + * Getter method for property checkerAction. + * + * @return property value of checkerAction + */ + public CheckerAction getCheckerAction() { + return checkerAction; + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/InjectionAction.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/InjectionAction.java index de4ceb880..236ea6e47 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/InjectionAction.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/InjectionAction.java @@ -18,91 +18,90 @@ import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.server.meta.slot.util.ListUtil; -import org.springframework.util.CollectionUtils; - import java.util.List; import java.util.Random; +import org.springframework.util.CollectionUtils; public interface InjectionAction { - Random random = new Random(); + Random random = new Random(); - void doInject(List total, List running); + void doInject(List total, List running); } enum InjectionEnum { - FIRST(0, new FirstInjectionAction()), START(70, new StartInjectionAction()), STOP( - 30, - new StopInjectionAction()), FINAL( - 0, - new FinalInjectionAction()), ; + FIRST(0, new FirstInjectionAction()), + START(70, new StartInjectionAction()), + STOP(30, new StopInjectionAction()), + FINAL(0, new FinalInjectionAction()), + ; - private int percent; + private int percent; - private InjectionAction injectionAction; + private InjectionAction injectionAction; - public static final Random random = new Random(); + public static final Random random = new Random(); - InjectionEnum(int percent, InjectionAction injectionAction) { - this.percent = percent; - this.injectionAction = injectionAction; - } - - public static InjectionEnum pickInject() { - int percent = random.nextInt(100); - if (percent < STOP.percent) { - return STOP; - } else { - return START; - } - } + InjectionEnum(int percent, InjectionAction injectionAction) { + this.percent = percent; + this.injectionAction = injectionAction; + } - /** - * Getter method for property injectionAction. - * - * @return property value of injectionAction - */ - public InjectionAction getInjectionAction() { - return injectionAction; + public static InjectionEnum pickInject() { + int percent = random.nextInt(100); + if (percent < STOP.percent) { + return STOP; + } else { + return START; } + } + + /** + * Getter method for property injectionAction. + * + * @return property value of injectionAction + */ + public InjectionAction getInjectionAction() { + return injectionAction; + } } class FirstInjectionAction implements InjectionAction { - @Override - public void doInject(List total, List running) { - running.addAll(ListUtil.randomPick(total, 1)); - } + @Override + public void doInject(List total, List running) { + running.addAll(ListUtil.randomPick(total, 1)); + } } class StartInjectionAction implements InjectionAction { - @Override - public void doInject(List total, List running) { - List reduce = ListUtil.reduce(total, running); - - if (CollectionUtils.isEmpty(reduce)) { - return; - } + @Override + public void doInject(List total, List running) { + List reduce = ListUtil.reduce(total, running); - int count = Math.min(total.size() / 3, random.nextInt(reduce.size()) + 1); - running.addAll(ListUtil.randomPick(reduce, count)); + if (CollectionUtils.isEmpty(reduce)) { + return; } + + int count = Math.min(total.size() / 3, random.nextInt(reduce.size()) + 1); + running.addAll(ListUtil.randomPick(reduce, count)); + } } class StopInjectionAction implements InjectionAction { - @Override - public void doInject(List total, List running) { - running.removeAll(ListUtil.randomPick(running, random.nextInt(running.size()) / 3 + 1)); - } + @Override + public void doInject(List total, List running) { + running.removeAll(ListUtil.randomPick(running, random.nextInt(running.size()) / 3 + 1)); + } } class FinalInjectionAction implements InjectionAction { - @Override - public void doInject(List total, List running) { - List reduce = ListUtil.reduce(total, running); - running.addAll(reduce); - } -} \ No newline at end of file + @Override + public void doInject(List total, List running) { + List reduce = ListUtil.reduce(total, running); + running.addAll(reduce); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/SlotChaosTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/SlotChaosTest.java index 42231fb74..5a58c2b4e 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/SlotChaosTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/chaos/SlotChaosTest.java @@ -16,11 +16,13 @@ */ package com.alipay.sofa.registry.server.meta.slot.chaos; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.common.model.metaserver.cluster.VersionedList; import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.SlotTable; import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; -import com.alipay.sofa.registry.server.meta.MetaLeaderService; import com.alipay.sofa.registry.server.meta.bootstrap.config.NodeConfig; import com.alipay.sofa.registry.server.meta.lease.data.DefaultDataServerManager; import com.alipay.sofa.registry.server.meta.monitor.SlotTableMonitor; @@ -28,20 +30,16 @@ import com.alipay.sofa.registry.server.meta.slot.arrange.ScheduledSlotArranger; import com.alipay.sofa.registry.server.meta.slot.manager.SimpleSlotManager; import com.alipay.sofa.registry.util.DatumVersionUtil; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.mockito.Mock; -import org.mockito.MockitoAnnotations; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; /** * @author xiaojian.xj @@ -49,114 +47,120 @@ */ public class SlotChaosTest extends AbstractMetaServerTest { - private DataServerInjection dataServerInjection; + private DataServerInjection dataServerInjection; - private SlotManager slotManager; + private SlotManager slotManager; - @Mock - private DefaultDataServerManager dataServerManager; + @Mock private DefaultDataServerManager dataServerManager; - private ScheduledSlotArranger scheduledSlotArranger; + private ScheduledSlotArranger scheduledSlotArranger; - @Mock - private SlotTableMonitor slotTableMonitor; + @Mock private SlotTableMonitor slotTableMonitor; - private int dataNodeNum = 20; + private int dataNodeNum = 20; - private int chaosRandom; + private int chaosRandom; - @BeforeClass - public static void beforeSlotMigrateChaosTestClass() throws Exception { - Map env = new HashMap<>(); + @BeforeClass + public static void beforeSlotMigrateChaosTestClass() throws Exception { + Map env = new HashMap<>(); - env.put("data.slot.num", "512"); - env.put("data.slot.replicas", "2"); - env.put("slot.leader.max.move", "2"); - setEnv(env); - } + env.put("data.slot.num", "512"); + env.put("data.slot.replicas", "2"); + env.put("slot.leader.max.move", "2"); + setEnv(env); + } - @Before - public void beforeSlotMigrateChaosTest() throws Exception { - MockitoAnnotations.initMocks(this); - makeMetaLeader(); + @Before + public void beforeSlotMigrateChaosTest() throws Exception { + MockitoAnnotations.initMocks(this); + makeMetaLeader(); - logger.info("[slot-chaos data-node] size: " + dataNodeNum); - dataServerInjection = new DataServerInjection(dataNodeNum); + logger.info("[slot-chaos data-node] size: " + dataNodeNum); + dataServerInjection = new DataServerInjection(dataNodeNum); - NodeConfig nodeConfig = mock(NodeConfig.class); - when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); - slotManager = new SimpleSlotManager(); + NodeConfig nodeConfig = mock(NodeConfig.class); + when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); + slotManager = new SimpleSlotManager(); - scheduledSlotArranger = new ScheduledSlotArranger(dataServerManager, - slotManager, slotTableMonitor, metaLeaderService); + scheduledSlotArranger = + new ScheduledSlotArranger( + dataServerManager, slotManager, slotTableMonitor, metaLeaderService); - when(slotTableMonitor.isStableTableStable()).thenReturn(true); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(VersionedList.EMPTY); - scheduledSlotArranger.postConstruct(); - } + when(slotTableMonitor.isStableTableStable()).thenReturn(true); + when(dataServerManager.getDataServerMetaInfo()).thenReturn(VersionedList.EMPTY); + scheduledSlotArranger.postConstruct(); + } + + @Test + public void testChaos() throws TimeoutException, InterruptedException { + logger.info("[slot-chaos slot] size: " + slotManager.getSlotNums()); + + do { + chaosRandom = random.nextInt(100); + } while (chaosRandom < 30); - @Test - public void testChaos() throws TimeoutException, InterruptedException { - logger.info("[slot-chaos slot] size: " + slotManager.getSlotNums()); - - do { - chaosRandom = random.nextInt(100); - } while (chaosRandom < 30); - - makeMetaLeader(); - logger.info("[slot-chaos slot] chaosRandom: " + chaosRandom); - - List running; - for (int i = 1; i <= chaosRandom; i++) { - // random up and down - running = dataServerInjection.inject(i); - when(dataServerManager.getDataServerMetaInfo()) - .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), running)); - scheduledSlotArranger.arrangeAsync(); - Thread.sleep(2000); - } - for (int i = 0; i < 500; i++) { - scheduledSlotArranger.arrangeAsync(); - Thread.sleep(20); - } - SlotTable finalSlotTable = slotManager.getSlotTable(); - for (CheckEnum checker : CheckEnum.values()) { - checker.getCheckerAction().doCheck(finalSlotTable); - } + makeMetaLeader(); + logger.info("[slot-chaos slot] chaosRandom: " + chaosRandom); + + List running; + for (int i = 1; i <= chaosRandom; i++) { + // random up and down + running = dataServerInjection.inject(i); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), running)); + scheduledSlotArranger.arrangeAsync(); + Thread.sleep(2000); + } + for (int i = 0; i < 500; i++) { + scheduledSlotArranger.arrangeAsync(); + Thread.sleep(20); } + SlotTable finalSlotTable = slotManager.getSlotTable(); + for (CheckEnum checker : CheckEnum.values()) { + checker.getCheckerAction().doCheck(finalSlotTable); + } + } + + public class DataServerInjection { + private int dataNodeNum; - public class DataServerInjection { - private int dataNodeNum; - - private List dataNodes; - - private List runningDataNodes = new ArrayList<>(); - - public DataServerInjection(int dataNodeNum) { - this.dataNodeNum = dataNodeNum; - this.dataNodes = randomDataNodes(dataNodeNum); - logger.info("[slot-chaos data-node] dataNodes: " + dataNodes); - } - - public List inject(int chaos) { - InjectionEnum injectType; - if (chaos == 1 || runningDataNodes.size() == 0) { - injectType = InjectionEnum.FIRST; - } else if (chaos == chaosRandom) { - injectType = InjectionEnum.FINAL; - } else if (runningDataNodes.size() == dataNodeNum) { - injectType = InjectionEnum.STOP; - } else { - injectType = InjectionEnum.pickInject(); - } - - logger.info("[slot-chaos inject before] chaos: {}, type: {}, size: {}, nodes: {}", - chaos, injectType, runningDataNodes.size(), runningDataNodes); - injectType.getInjectionAction().doInject(dataNodes, runningDataNodes); - logger.info("[slot-chaos inject after] chaos: {}, type: {}, size: {}, nodes: {}", - chaos, injectType, runningDataNodes.size(), runningDataNodes); - return runningDataNodes; - } + private List dataNodes; + + private List runningDataNodes = new ArrayList<>(); + + public DataServerInjection(int dataNodeNum) { + this.dataNodeNum = dataNodeNum; + this.dataNodes = randomDataNodes(dataNodeNum); + logger.info("[slot-chaos data-node] dataNodes: " + dataNodes); + } + public List inject(int chaos) { + InjectionEnum injectType; + if (chaos == 1 || runningDataNodes.size() == 0) { + injectType = InjectionEnum.FIRST; + } else if (chaos == chaosRandom) { + injectType = InjectionEnum.FINAL; + } else if (runningDataNodes.size() == dataNodeNum) { + injectType = InjectionEnum.STOP; + } else { + injectType = InjectionEnum.pickInject(); + } + + logger.info( + "[slot-chaos inject before] chaos: {}, type: {}, size: {}, nodes: {}", + chaos, + injectType, + runningDataNodes.size(), + runningDataNodes); + injectType.getInjectionAction().doInject(dataNodes, runningDataNodes); + logger.info( + "[slot-chaos inject after] chaos: {}, type: {}, size: {}, nodes: {}", + chaos, + injectType, + runningDataNodes.size(), + runningDataNodes); + return runningDataNodes; } -} \ No newline at end of file + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/manager/DefaultSlotManagerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/manager/DefaultSlotManagerTest.java index 05a9b31ff..b52b2830e 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/manager/DefaultSlotManagerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/manager/DefaultSlotManagerTest.java @@ -16,6 +16,9 @@ */ package com.alipay.sofa.registry.server.meta.slot.manager; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.exception.SofaRegistryRuntimeException; import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; import com.alipay.sofa.registry.server.meta.remoting.notifier.Notifier; @@ -24,44 +27,41 @@ import org.junit.Test; import org.mockito.MockitoAnnotations; -import static org.mockito.Matchers.any; -import static org.mockito.Mockito.*; - public class DefaultSlotManagerTest extends AbstractMetaServerTest { + private DefaultSlotManager slotManager; - private DefaultSlotManager slotManager; - - @Before - public void beforeDefaultSlotManagerTest() throws Exception { - MockitoAnnotations.initMocks(this); - when(metaLeaderService.amIStableAsLeader()).thenReturn(true); - when(metaLeaderService.amILeader()).thenReturn(true); - slotManager = new DefaultSlotManager(metaLeaderService); - slotManager.postConstruct(); - } + @Before + public void beforeDefaultSlotManagerTest() throws Exception { + MockitoAnnotations.initMocks(this); + when(metaLeaderService.amIStableAsLeader()).thenReturn(true); + when(metaLeaderService.amILeader()).thenReturn(true); + slotManager = new DefaultSlotManager(metaLeaderService); + slotManager.postConstruct(); + } - @Test - public void testSlotChangeNotification() throws InterruptedException { - Notifier notifier = mock(Notifier.class); - slotManager.setNotifiers(Lists.newArrayList(notifier)); - slotManager.refresh(randomSlotTable()); - Thread.sleep(100); - verify(notifier, atLeast(1)).notifySlotTableChange(any()); - } + @Test + public void testSlotChangeNotification() throws InterruptedException { + Notifier notifier = mock(Notifier.class); + slotManager.setNotifiers(Lists.newArrayList(notifier)); + slotManager.refresh(randomSlotTable()); + Thread.sleep(100); + verify(notifier, atLeast(1)).notifySlotTableChange(any()); + } - @Test - public void testSlotChangeNotifyOneFailWontAffectOthers() throws InterruptedException { - Notifier notifier1 = mock(Notifier.class); - Notifier notifier2 = mock(Notifier.class); - Notifier notifier3 = mock(Notifier.class); - doThrow(new SofaRegistryRuntimeException("expected")).when(notifier2) - .notifySlotTableChange(any()); - slotManager.setNotifiers(Lists.newArrayList(notifier1, notifier2, notifier3)); + @Test + public void testSlotChangeNotifyOneFailWontAffectOthers() throws InterruptedException { + Notifier notifier1 = mock(Notifier.class); + Notifier notifier2 = mock(Notifier.class); + Notifier notifier3 = mock(Notifier.class); + doThrow(new SofaRegistryRuntimeException("expected")) + .when(notifier2) + .notifySlotTableChange(any()); + slotManager.setNotifiers(Lists.newArrayList(notifier1, notifier2, notifier3)); - slotManager.refresh(randomSlotTable()); - Thread.sleep(100); - verify(notifier1, atLeast(1)).notifySlotTableChange(any()); - verify(notifier3, atLeast(1)).notifySlotTableChange(any()); - } -} \ No newline at end of file + slotManager.refresh(randomSlotTable()); + Thread.sleep(100); + verify(notifier1, atLeast(1)).notifySlotTableChange(any()); + verify(notifier3, atLeast(1)).notifySlotTableChange(any()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/manager/SimpleSlotManagerTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/manager/SimpleSlotManagerTest.java index b54fb009c..d5f9dd7f1 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/manager/SimpleSlotManagerTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/manager/SimpleSlotManagerTest.java @@ -16,12 +16,19 @@ */ package com.alipay.sofa.registry.server.meta.slot.manager; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.DataNodeSlot; import com.alipay.sofa.registry.common.model.slot.SlotConfig; import com.alipay.sofa.registry.common.model.slot.SlotTable; import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; import com.alipay.sofa.registry.server.meta.bootstrap.config.NodeConfig; +import java.util.List; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.CyclicBarrier; +import java.util.concurrent.atomic.AtomicReference; import org.assertj.core.util.Lists; import org.junit.Assert; import org.junit.Before; @@ -29,122 +36,143 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.CyclicBarrier; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.*; - public class SimpleSlotManagerTest extends AbstractMetaServerTest { - private SimpleSlotManager slotManager; - - @Mock - private NodeConfig nodeConfig; - - @Before - public void beforeLocalSlotManagerTest() throws Exception { - MockitoAnnotations.initMocks(this); - when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); - slotManager = new SimpleSlotManager(); - } - - @Test - public void testRefresh() { - slotManager = spy(slotManager); - List dataNodes = Lists.newArrayList(new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), new DataNode(randomURL(randomIp()), - getDc()), new DataNode(randomURL(randomIp()), getDc()), new DataNode( - randomURL(randomIp()), getDc())); - slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); - verify(slotManager, times(1)).refresh(any()); - Assert.assertFalse(slotManager.getDataNodeManagedSlot(dataNodes.get(0).getIp(), false).getLeaders() + private SimpleSlotManager slotManager; + + @Mock private NodeConfig nodeConfig; + + @Before + public void beforeLocalSlotManagerTest() throws Exception { + MockitoAnnotations.initMocks(this); + when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); + slotManager = new SimpleSlotManager(); + } + + @Test + public void testRefresh() { + slotManager = spy(slotManager); + List dataNodes = + Lists.newArrayList( + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc())); + slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); + verify(slotManager, times(1)).refresh(any()); + Assert.assertFalse( + slotManager.getDataNodeManagedSlot(dataNodes.get(0).getIp(), false).getLeaders().isEmpty()); + Assert.assertTrue( + slotManager + .getDataNodeManagedSlot(dataNodes.get(0).getIp(), true) + .getFollowers() .isEmpty()); - Assert.assertTrue(slotManager.getDataNodeManagedSlot(dataNodes.get(0).getIp(), true).getFollowers() - .isEmpty()); - } - - @Test - public void testRefreshWithLowerEpoch() { - List dataNodes = Lists.newArrayList(new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), new DataNode(randomURL(randomIp()), - getDc()), new DataNode(randomURL(randomIp()), getDc()), new DataNode( - randomURL(randomIp()), getDc())); - SlotTable slotTable = new SlotTableGenerator(dataNodes).createSlotTable(); - slotManager = spy(slotManager); - slotManager.refresh(slotTable); - SlotTable lowerEpochTable = new SlotTable(10, slotTable.getSlotMap().values()); - slotManager.refresh(lowerEpochTable); -// verify(slotManager, times(1)).setSlotTableCacheWrapper(any()); - } - - @Test - public void testConcurrentModification() throws InterruptedException { - CyclicBarrier barrier = new CyclicBarrier(2); - CountDownLatch latch = new CountDownLatch(2); - List dataNodes = Lists.newArrayList(new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc())); - - executors.execute(()->{ - try { - barrier.await(); - slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); - } catch (Exception e) {} - latch.countDown(); + } + + @Test + public void testRefreshWithLowerEpoch() { + List dataNodes = + Lists.newArrayList( + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc())); + SlotTable slotTable = new SlotTableGenerator(dataNodes).createSlotTable(); + slotManager = spy(slotManager); + slotManager.refresh(slotTable); + SlotTable lowerEpochTable = new SlotTable(10, slotTable.getSlotMap().values()); + slotManager.refresh(lowerEpochTable); + // verify(slotManager, times(1)).setSlotTableCacheWrapper(any()); + } + + @Test + public void testConcurrentModification() throws InterruptedException { + CyclicBarrier barrier = new CyclicBarrier(2); + CountDownLatch latch = new CountDownLatch(2); + List dataNodes = + Lists.newArrayList( + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc())); + + executors.execute( + () -> { + try { + barrier.await(); + slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); + } catch (Exception e) { + } + latch.countDown(); }); - AtomicReference ref = new AtomicReference<>(); - executors.execute(()->{ - try { - barrier.await(); - } catch (Exception e) { - - } - ref.set(slotManager.getSlotTable()); - latch.countDown(); + AtomicReference ref = new AtomicReference<>(); + executors.execute( + () -> { + try { + barrier.await(); + } catch (Exception e) { + + } + ref.set(slotManager.getSlotTable()); + latch.countDown(); }); - latch.await(); - Assert.assertNotNull(ref.get()); - } - - @Test - public void testGetDataNodeManagedSlot() { - List dataNodes = Lists.newArrayList(new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc())); - slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); - DataNodeSlot dataNodeSlot = slotManager.getDataNodeManagedSlot(dataNodes.get(0).getIp(), false); - assertEquals(dataNodes.get(0).getIp(), dataNodeSlot.getDataNode()); - dataNodeSlot.getLeaders().forEach(slotId-> - Assert.assertEquals(slotManager.getSlotTable().getSlot(slotId).getLeader(), - dataNodeSlot.getDataNode())); - dataNodeSlot.getFollowers().forEach(slotId-> - Assert.assertTrue(slotManager.getSlotTable().getSlot(slotId).getFollowers().contains( - dataNodeSlot.getDataNode()))); - logger.info("[leaders] {}", dataNodeSlot.getLeaders()); - logger.info("[followers] {}", dataNodeSlot.getFollowers()); - slotManager.getSlotTable().getSlotMap().forEach((slotId, slot)->{ - if(slot.getLeader().equalsIgnoreCase(dataNodeSlot.getDataNode())) { + latch.await(); + Assert.assertNotNull(ref.get()); + } + + @Test + public void testGetDataNodeManagedSlot() { + List dataNodes = + Lists.newArrayList( + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc())); + slotManager.refresh(new SlotTableGenerator(dataNodes).createSlotTable()); + DataNodeSlot dataNodeSlot = slotManager.getDataNodeManagedSlot(dataNodes.get(0).getIp(), false); + assertEquals(dataNodes.get(0).getIp(), dataNodeSlot.getDataNode()); + dataNodeSlot + .getLeaders() + .forEach( + slotId -> + Assert.assertEquals( + slotManager.getSlotTable().getSlot(slotId).getLeader(), + dataNodeSlot.getDataNode())); + dataNodeSlot + .getFollowers() + .forEach( + slotId -> + Assert.assertTrue( + slotManager + .getSlotTable() + .getSlot(slotId) + .getFollowers() + .contains(dataNodeSlot.getDataNode()))); + logger.info("[leaders] {}", dataNodeSlot.getLeaders()); + logger.info("[followers] {}", dataNodeSlot.getFollowers()); + slotManager + .getSlotTable() + .getSlotMap() + .forEach( + (slotId, slot) -> { + if (slot.getLeader().equalsIgnoreCase(dataNodeSlot.getDataNode())) { logger.info("[slot] {}", slotId); Assert.assertTrue(dataNodeSlot.getLeaders().contains(slotId)); - } - }); - } - - @Test - public void testGetSlotNums() { - Assert.assertEquals(SlotConfig.SLOT_NUM, slotManager.getSlotNums()); - } - - @Test - public void testGetSlotReplicaNums() { - Assert.assertEquals(SlotConfig.SLOT_REPLICAS, slotManager.getSlotReplicaNums()); - } - -} \ No newline at end of file + } + }); + } + + @Test + public void testGetSlotNums() { + Assert.assertEquals(SlotConfig.SLOT_NUM, slotManager.getSlotNums()); + } + + @Test + public void testGetSlotReplicaNums() { + Assert.assertEquals(SlotConfig.SLOT_REPLICAS, slotManager.getSlotReplicaNums()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/tasks/BalanceTaskTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/tasks/BalanceTaskTest.java index 9ef9999d2..f30558b59 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/tasks/BalanceTaskTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/tasks/BalanceTaskTest.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.slot.tasks; +import static org.mockito.Mockito.*; + import com.alipay.sofa.registry.common.model.metaserver.cluster.VersionedList; import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.SlotConfig; @@ -27,6 +29,8 @@ import com.alipay.sofa.registry.server.meta.slot.SlotManager; import com.alipay.sofa.registry.server.meta.slot.manager.SimpleSlotManager; import com.alipay.sofa.registry.util.DatumVersionUtil; +import java.util.List; +import java.util.concurrent.TimeoutException; import org.assertj.core.util.Lists; import org.junit.Assert; import org.junit.Before; @@ -34,81 +38,84 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.util.List; -import java.util.concurrent.TimeoutException; - -import static org.mockito.Mockito.*; - public class BalanceTaskTest extends AbstractMetaServerTest { - private BalanceTask task; + private BalanceTask task; - private SlotManager slotManager; + private SlotManager slotManager; - @Mock - private DataServerManager dataServerManager; + @Mock private DataServerManager dataServerManager; - @Before - public void beforeInitReshardingTaskTest() throws Exception { - MockitoAnnotations.initMocks(this); - List dataNodes = Lists.newArrayList(new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), new DataNode(randomURL(randomIp()), - getDc()), new DataNode(randomURL(randomIp()), getDc())); - when(dataServerManager.getDataServerMetaInfo()) - .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(),dataNodes)); - NodeConfig nodeConfig = mock(NodeConfig.class); - when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); - slotManager = new SimpleSlotManager(); - } + @Before + public void beforeInitReshardingTaskTest() throws Exception { + MockitoAnnotations.initMocks(this); + List dataNodes = + Lists.newArrayList( + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + NodeConfig nodeConfig = mock(NodeConfig.class); + when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); + slotManager = new SimpleSlotManager(); + } - @Test - public void testRun() throws TimeoutException, InterruptedException { - Assert.assertEquals(SlotTable.INIT, slotManager.getSlotTable()); - task = new BalanceTask(slotManager, dataServerManager); - task.run(); - Assert.assertNotEquals(SlotTable.INIT, slotManager.getSlotTable()); - printSlotTable(slotManager.getSlotTable()); - } + @Test + public void testRun() throws TimeoutException, InterruptedException { + Assert.assertEquals(SlotTable.INIT, slotManager.getSlotTable()); + task = new BalanceTask(slotManager, dataServerManager); + task.run(); + Assert.assertNotEquals(SlotTable.INIT, slotManager.getSlotTable()); + printSlotTable(slotManager.getSlotTable()); + } - @Test - public void testNoDupLeaderAndFollower() throws Exception { - List dataNodes = Lists.newArrayList( - new DataNode(new URL("100.88.142.32"), getDc()), - new DataNode(new URL("100.88.142.36"), getDc()), - new DataNode(new URL("100.88.142.19"), getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(),dataNodes)); - task = new BalanceTask(slotManager, dataServerManager); - task.run(); - SlotTable slotTable = slotManager.getSlotTable(); - slotTable.getSlotMap().forEach((slotId, slot) -> { - Assert.assertFalse(slot.getFollowers().contains(slot.getLeader())); - }); - } + @Test + public void testNoDupLeaderAndFollower() throws Exception { + List dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), + new DataNode(new URL("100.88.142.36"), getDc()), + new DataNode(new URL("100.88.142.19"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + task = new BalanceTask(slotManager, dataServerManager); + task.run(); + SlotTable slotTable = slotManager.getSlotTable(); + slotTable + .getSlotMap() + .forEach( + (slotId, slot) -> { + Assert.assertFalse(slot.getFollowers().contains(slot.getLeader())); + }); + } - @Test - public void nonExecutionDueToEmptyDataSet() { - when(dataServerManager.getDataServerMetaInfo()) - .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), Lists.newArrayList())); - slotManager = spy(slotManager); - task = new BalanceTask(slotManager, dataServerManager); - task.run(); - verify(slotManager, never()).refresh(any(SlotTable.class)); - } + @Test + public void nonExecutionDueToEmptyDataSet() { + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), Lists.newArrayList())); + slotManager = spy(slotManager); + task = new BalanceTask(slotManager, dataServerManager); + task.run(); + verify(slotManager, never()).refresh(any(SlotTable.class)); + } - @Test - public void testSlotEpochCorrect() { - List dataNodes = randomDataNodes(3); - SlotTable prev = randomSlotTable(dataNodes); - slotManager.refresh(prev); + @Test + public void testSlotEpochCorrect() { + List dataNodes = randomDataNodes(3); + SlotTable prev = randomSlotTable(dataNodes); + slotManager.refresh(prev); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(),dataNodes)); - task = new BalanceTask(slotManager, dataServerManager); - task.run(); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + task = new BalanceTask(slotManager, dataServerManager); + task.run(); - SlotTable current = slotManager.getSlotTable(); - for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { - Assert.assertTrue(prev.getSlot(slotId).getLeaderEpoch() < current.getSlot(slotId) - .getLeaderEpoch()); - } + SlotTable current = slotManager.getSlotTable(); + for (int slotId = 0; slotId < SlotConfig.SLOT_NUM; slotId++) { + Assert.assertTrue( + prev.getSlot(slotId).getLeaderEpoch() < current.getSlot(slotId).getLeaderEpoch()); } -} \ No newline at end of file + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/tasks/SlotMigrationIntegrationTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/tasks/SlotMigrationIntegrationTest.java index 8513fc358..f2389261a 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/tasks/SlotMigrationIntegrationTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/tasks/SlotMigrationIntegrationTest.java @@ -16,6 +16,9 @@ */ package com.alipay.sofa.registry.server.meta.slot.tasks; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + import com.alipay.sofa.registry.common.model.metaserver.cluster.VersionedList; import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.Slot; @@ -38,6 +41,9 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.Maps; +import java.io.File; +import java.util.List; +import java.util.Map; import org.assertj.core.util.Lists; import org.junit.Assert; import org.junit.Before; @@ -46,324 +52,414 @@ import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import java.io.File; -import java.util.List; -import java.util.Map; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - /** * @author chen.zhu - *

- * Jan 14, 2021 + *

Jan 14, 2021 */ public class SlotMigrationIntegrationTest extends AbstractMetaServerTest { - private SlotManager slotManager; - - @Mock - private DefaultDataServerManager dataServerManager; - - @Mock - private SlotTableMonitor slotTableMonitor; - - @Mock - private MetaLeaderService leaderElector; - - @BeforeClass - public static void beforeSlotMigrationIntegrationTestClass() { - System.setProperty("slot.frozen.milli", "1"); - } - - @Before - public void beforeSlotMigrationIntegrationTest() throws Exception { - MockitoAnnotations.initMocks(this); - List dataNodes = Lists.newArrayList(new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), new DataNode(randomURL(randomIp()), - getDc()), new DataNode(randomURL(randomIp()), getDc())); - when(dataServerManager.getDataServerMetaInfo()) - .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(),dataNodes)); - NodeConfig nodeConfig = mock(NodeConfig.class); - when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); - when(leaderElector.amIStableAsLeader()).thenReturn(true); - when(leaderElector.amILeader()).thenReturn(true); - slotManager = new DefaultSlotManager(leaderElector); - when(slotTableMonitor.isStableTableStable()).thenReturn(true); - } - - @Test - public void testDataServerAddedOneByOne() throws Exception { - System.setProperty("slot.leader.max.move", SlotConfig.SLOT_NUM + ""); - ScheduledSlotArranger assigner = new ScheduledSlotArranger(dataServerManager, - slotManager, slotTableMonitor, leaderElector); - assigner.getLifecycleState().setPhase(LifecycleState.LifecyclePhase.STARTED); - List dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), - getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - makeMetaLeader(); - assigner.arrangeSync(); - - dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), getDc()), + private SlotManager slotManager; + + @Mock private DefaultDataServerManager dataServerManager; + + @Mock private SlotTableMonitor slotTableMonitor; + + @Mock private MetaLeaderService leaderElector; + + @BeforeClass + public static void beforeSlotMigrationIntegrationTestClass() { + System.setProperty("slot.frozen.milli", "1"); + } + + @Before + public void beforeSlotMigrationIntegrationTest() throws Exception { + MockitoAnnotations.initMocks(this); + List dataNodes = + Lists.newArrayList( + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + NodeConfig nodeConfig = mock(NodeConfig.class); + when(nodeConfig.getLocalDataCenter()).thenReturn(getDc()); + when(leaderElector.amIStableAsLeader()).thenReturn(true); + when(leaderElector.amILeader()).thenReturn(true); + slotManager = new DefaultSlotManager(leaderElector); + when(slotTableMonitor.isStableTableStable()).thenReturn(true); + } + + @Test + public void testDataServerAddedOneByOne() throws Exception { + System.setProperty("slot.leader.max.move", SlotConfig.SLOT_NUM + ""); + ScheduledSlotArranger assigner = + new ScheduledSlotArranger(dataServerManager, slotManager, slotTableMonitor, leaderElector); + assigner.getLifecycleState().setPhase(LifecycleState.LifecyclePhase.STARTED); + List dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + makeMetaLeader(); + assigner.arrangeSync(); + + dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), new DataNode(new URL("100.88.142.36"), getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - loopArrange(assigner); - Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + loopArrange(assigner); + Assert.assertTrue( + isSlotTableBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - Thread.sleep(2); - loopArrange(assigner); - Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), + Thread.sleep(2); + loopArrange(assigner); + Assert.assertTrue( + isSlotTableBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - Assert.assertTrue(isSlotTableLeaderBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableLeaderBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - - Thread.sleep(2); - dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), getDc()), - new DataNode(new URL("100.88.142.36"), getDc()), new DataNode(new URL("100.88.142.19"), - getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - loopArrange(assigner); - logger.info(JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + + Thread.sleep(2); + dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), + new DataNode(new URL("100.88.142.36"), getDc()), + new DataNode(new URL("100.88.142.19"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + loopArrange(assigner); + logger.info( + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() .writeValueAsString(slotManager.getSlotTable())); - Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - - Thread.sleep(2); - dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), getDc()), - new DataNode(new URL("100.88.142.36"), getDc()), new DataNode(new URL("100.88.142.19"), - getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - loopArrange(assigner); - logger.info(JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + + Thread.sleep(2); + dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), + new DataNode(new URL("100.88.142.36"), getDc()), + new DataNode(new URL("100.88.142.19"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + loopArrange(assigner); + logger.info( + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() .writeValueAsString(slotManager.getSlotTable())); - Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - Assert.assertTrue(isSlotTableLeaderBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableLeaderBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - } - - @Test - public void testDataServerAddedAndDeleted() throws Exception { - System.setProperty("slot.leader.max.move", SlotConfig.SLOT_NUM + ""); - ScheduledSlotArranger assigner = new ScheduledSlotArranger(dataServerManager, - slotManager, slotTableMonitor, leaderElector); - assigner.getLifecycleState().setPhase(LifecycleState.LifecyclePhase.STARTED); - - List dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), - getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - makeMetaLeader(); - assigner.arrangeSync(); - logger.info(JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + } + + @Test + public void testDataServerAddedAndDeleted() throws Exception { + System.setProperty("slot.leader.max.move", SlotConfig.SLOT_NUM + ""); + ScheduledSlotArranger assigner = + new ScheduledSlotArranger(dataServerManager, slotManager, slotTableMonitor, leaderElector); + assigner.getLifecycleState().setPhase(LifecycleState.LifecyclePhase.STARTED); + + List dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + makeMetaLeader(); + assigner.arrangeSync(); + logger.info( + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() .writeValueAsString(slotManager.getSlotTable())); - dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), getDc()), + dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), new DataNode(new URL("100.88.142.36"), getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - assigner.arrangeSync(); - logger.info(JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + assigner.arrangeSync(); + logger.info( + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() .writeValueAsString(slotManager.getSlotTable())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - loopArrange(assigner); + loopArrange(assigner); - logger.info(JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() + logger.info( + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() .writeValueAsString(slotManager.getSlotTable())); - Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - Assert.assertTrue(isSlotTableLeaderBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableLeaderBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - - Thread.sleep(2); - dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), getDc()), - new DataNode(new URL("100.88.142.36"), getDc()), new DataNode(new URL("100.88.142.19"), - getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - loopArrange(assigner); - logger.info(JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + + Thread.sleep(2); + dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), + new DataNode(new URL("100.88.142.36"), getDc()), + new DataNode(new URL("100.88.142.19"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + loopArrange(assigner); + logger.info( + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() .writeValueAsString(slotManager.getSlotTable())); - Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - - Thread.sleep(2); - dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), getDc()), - new DataNode(new URL("100.88.142.36"), getDc()), new DataNode(new URL("100.88.142.19"), - getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - loopArrange(assigner); - logger.info(JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + + Thread.sleep(2); + dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), + new DataNode(new URL("100.88.142.36"), getDc()), + new DataNode(new URL("100.88.142.19"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + loopArrange(assigner); + logger.info( + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() .writeValueAsString(slotManager.getSlotTable())); - Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - Assert.assertTrue(isSlotTableLeaderBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableLeaderBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - Thread.sleep(2); - dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), getDc()), + Thread.sleep(2); + dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), new DataNode(new URL("100.88.142.36"), getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - loopArrange(assigner); - logger.info(JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + loopArrange(assigner); + logger.info( + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() .writeValueAsString(slotManager.getSlotTable())); - Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - Assert.assertTrue(isSlotTableLeaderBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableLeaderBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - - Thread.sleep(2); - dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), getDc()), - new DataNode(new URL("100.88.142.36"), getDc()), new DataNode(new URL("100.88.142.19"), - getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - loopArrange(assigner); - logger.info(JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + + Thread.sleep(2); + dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), + new DataNode(new URL("100.88.142.36"), getDc()), + new DataNode(new URL("100.88.142.19"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + loopArrange(assigner); + logger.info( + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() .writeValueAsString(slotManager.getSlotTable())); - Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - - Thread.sleep(2); - dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), getDc()), - new DataNode(new URL("100.88.142.36"), getDc()), new DataNode(new URL("100.88.142.19"), - getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - loopArrange(assigner); - logger.info(JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + + Thread.sleep(2); + dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), + new DataNode(new URL("100.88.142.36"), getDc()), + new DataNode(new URL("100.88.142.19"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + loopArrange(assigner); + logger.info( + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() .writeValueAsString(slotManager.getSlotTable())); - Assert.assertTrue(isSlotTableBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - Assert.assertTrue(isSlotTableLeaderBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableLeaderBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - } - - @Test - public void testDataLeaderBalance() throws Exception { - ScheduledSlotArranger assigner = new ScheduledSlotArranger(dataServerManager, - slotManager, slotTableMonitor, leaderElector); - assigner.getLifecycleState().setPhase(LifecycleState.LifecyclePhase.STARTED); - - byte[] bytes = FileUtils.readFileToByteArray(new File( - "src/test/resources/test/slot-table.json")); - SlotTable prevSlotTable = JsonUtils.getJacksonObjectMapper() - .readValue(bytes, InnerSlotTable.class).toSlotTable(); - slotManager.refresh(prevSlotTable); - List dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), - getDc()), new DataNode(new URL("100.88.142.36"), getDc()), new DataNode(new URL( - "100.88.142.19"), getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - makeMetaLeader(); - - loopArrange(assigner); - - logger.info(JsonUtils.getJacksonObjectMapper().writerWithDefaultPrettyPrinter() + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + } + + @Test + public void testDataLeaderBalance() throws Exception { + ScheduledSlotArranger assigner = + new ScheduledSlotArranger(dataServerManager, slotManager, slotTableMonitor, leaderElector); + assigner.getLifecycleState().setPhase(LifecycleState.LifecyclePhase.STARTED); + + byte[] bytes = + FileUtils.readFileToByteArray(new File("src/test/resources/test/slot-table.json")); + SlotTable prevSlotTable = + JsonUtils.getJacksonObjectMapper().readValue(bytes, InnerSlotTable.class).toSlotTable(); + slotManager.refresh(prevSlotTable); + List dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), + new DataNode(new URL("100.88.142.36"), getDc()), + new DataNode(new URL("100.88.142.19"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + makeMetaLeader(); + + loopArrange(assigner); + + logger.info( + JsonUtils.getJacksonObjectMapper() + .writerWithDefaultPrettyPrinter() .writeValueAsString(slotManager.getSlotTable())); - Assert.assertTrue(isSlotTableLeaderBalanced(slotManager.getSlotTable(), + Assert.assertTrue( + isSlotTableLeaderBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); - } - - @Test - public void testDataLeaderBalance2() throws Exception { - ScheduledSlotArranger assigner = new ScheduledSlotArranger(dataServerManager, - slotManager, slotTableMonitor, leaderElector); - assigner.getLifecycleState().setPhase(LifecycleState.LifecyclePhase.STARTED); - byte[] bytes = FileUtils.readFileToByteArray(new File( - "src/test/resources/test/slot-table-2.json")); - SlotTable prevSlotTable = JsonUtils.getJacksonObjectMapper() - .readValue(bytes, InnerSlotTable.class).toSlotTable(); - slotManager.refresh(prevSlotTable); - List dataNodes = Lists.newArrayList(new DataNode(new URL("100.83.52.136"), - getDc()), new DataNode(new URL("100.88.50.178"), getDc()), new DataNode(new URL( - "11.166.229.74"), getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - makeMetaLeader(); - - loopArrange(assigner); - - Assert.assertTrue(isSlotTableLeaderBalanced(slotManager.getSlotTable(), + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + } + + @Test + public void testDataLeaderBalance2() throws Exception { + ScheduledSlotArranger assigner = + new ScheduledSlotArranger(dataServerManager, slotManager, slotTableMonitor, leaderElector); + assigner.getLifecycleState().setPhase(LifecycleState.LifecyclePhase.STARTED); + byte[] bytes = + FileUtils.readFileToByteArray(new File("src/test/resources/test/slot-table-2.json")); + SlotTable prevSlotTable = + JsonUtils.getJacksonObjectMapper().readValue(bytes, InnerSlotTable.class).toSlotTable(); + slotManager.refresh(prevSlotTable); + List dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.83.52.136"), getDc()), + new DataNode(new URL("100.88.50.178"), getDc()), + new DataNode(new URL("11.166.229.74"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + makeMetaLeader(); + + loopArrange(assigner); + + Assert.assertTrue( + isSlotTableLeaderBalanced( + slotManager.getSlotTable(), dataServerManager.getDataServerMetaInfo().getClusterMembers())); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + } + + @Test + public void testNoInfinityLoop() throws Exception { + ScheduledSlotArranger assigner = + new ScheduledSlotArranger(dataServerManager, slotManager, slotTableMonitor, leaderElector); + assigner.getLifecycleState().setPhase(LifecycleState.LifecyclePhase.STARTED); + + byte[] bytes = + FileUtils.readFileToByteArray(new File("src/test/resources/test/slot-table.json")); + SlotTable prevSlotTable = + JsonUtils.getJacksonObjectMapper().readValue(bytes, InnerSlotTable.class).toSlotTable(); + slotManager.refresh(prevSlotTable); + List dataNodes = + Lists.newArrayList( + new DataNode(new URL("100.88.142.32"), getDc()), + new DataNode(new URL("100.88.142.36"), getDc()), + new DataNode(new URL("100.88.142.19"), getDc())); + when(dataServerManager.getDataServerMetaInfo()) + .thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); + makeMetaLeader(); + + loopArrange(assigner); + assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + } + + public static class InnerSlotTable { + private long epoch; + private List slots; + private List dataServers; + + @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) + public InnerSlotTable( + @JsonProperty("id") long epoch, + @JsonProperty("slots") List slots, + @JsonProperty("dataServers") List dataServers) { + this.epoch = epoch; + this.slots = slots; + this.dataServers = dataServers; } - @Test - public void testNoInfinityLoop() throws Exception { - ScheduledSlotArranger assigner = new ScheduledSlotArranger(dataServerManager, - slotManager, slotTableMonitor, leaderElector); - assigner.getLifecycleState().setPhase(LifecycleState.LifecyclePhase.STARTED); - - byte[] bytes = FileUtils.readFileToByteArray(new File( - "src/test/resources/test/slot-table.json")); - SlotTable prevSlotTable = JsonUtils.getJacksonObjectMapper() - .readValue(bytes, InnerSlotTable.class).toSlotTable(); - slotManager.refresh(prevSlotTable); - List dataNodes = Lists.newArrayList(new DataNode(new URL("100.88.142.32"), - getDc()), new DataNode(new URL("100.88.142.36"), getDc()), new DataNode(new URL( - "100.88.142.19"), getDc())); - when(dataServerManager.getDataServerMetaInfo()).thenReturn(new VersionedList<>(DatumVersionUtil.nextId(), dataNodes)); - makeMetaLeader(); - - loopArrange(assigner); - assertSlotTableNoDupLeaderFollower(slotManager.getSlotTable()); + public long getEpoch() { + return epoch; } - public static class InnerSlotTable { - private long epoch; - private List slots; - private List dataServers; - - @JsonCreator(mode = JsonCreator.Mode.PROPERTIES) - public InnerSlotTable(@JsonProperty("id") long epoch, - @JsonProperty("slots") List slots, - @JsonProperty("dataServers") List dataServers) { - this.epoch = epoch; - this.slots = slots; - this.dataServers = dataServers; - } - - public long getEpoch() { - return epoch; - } - - public List getSlots() { - return slots; - } - - public List getDataServers() { - return dataServers; - } - - public SlotTable toSlotTable() { - Map slotMap = Maps.newHashMap(); - slots.forEach(slot -> slotMap.put(slot.getId(), slot)); - return new SlotTable(epoch, slotMap.values()); - } + public List getSlots() { + return slots; } - private SlotTableBuilder createSlotTableBuilder(List currentDataNodeIps) { - SlotTable slotTable = slotManager.getSlotTable(); - com.alipay.sofa.registry.server.shared.comparator.NodeComparator comparator = new com.alipay.sofa.registry.server.shared.comparator.NodeComparator(slotTable.getDataServers(), currentDataNodeIps); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, - slotManager.getSlotNums(), slotManager.getSlotReplicaNums()); - - slotTableBuilder.init(currentDataNodeIps); - - comparator.getRemoved().forEach(slotTableBuilder::removeDataServerSlots); - return slotTableBuilder; + public List getDataServers() { + return dataServers; } - private void loopArrange(ScheduledSlotArranger arranger) { - for (int i = 0; i < 100; i++) { - arranger.arrangeSync(); - } + public SlotTable toSlotTable() { + Map slotMap = Maps.newHashMap(); + slots.forEach(slot -> slotMap.put(slot.getId(), slot)); + return new SlotTable(epoch, slotMap.values()); + } + } + + private SlotTableBuilder createSlotTableBuilder(List currentDataNodeIps) { + SlotTable slotTable = slotManager.getSlotTable(); + com.alipay.sofa.registry.server.shared.comparator.NodeComparator comparator = + new com.alipay.sofa.registry.server.shared.comparator.NodeComparator( + slotTable.getDataServers(), currentDataNodeIps); + SlotTableBuilder slotTableBuilder = + new SlotTableBuilder( + slotTable, slotManager.getSlotNums(), slotManager.getSlotReplicaNums()); + + slotTableBuilder.init(currentDataNodeIps); + + comparator.getRemoved().forEach(slotTableBuilder::removeDataServerSlots); + return slotTableBuilder; + } + + private void loopArrange(ScheduledSlotArranger arranger) { + for (int i = 0; i < 100; i++) { + arranger.arrangeSync(); } + } } diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/ListUtil.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/ListUtil.java index 3916b018a..29fe8c006 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/ListUtil.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/ListUtil.java @@ -16,44 +16,44 @@ */ package com.alipay.sofa.registry.server.meta.slot.util; -import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; +import static java.util.stream.Collectors.toList; +import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import java.util.Collections; import java.util.List; -import static java.util.stream.Collectors.toList; - /** - * * @author xiaojian.xj * @version $Id: ListUtil.java, v 0.1 2021年02月02日 21:02 xiaojian.xj Exp $ */ public class ListUtil { - /** - * 取差集 - * @param list1 - * @param list2 - * @return - */ - public static List reduce(List list1, List list2) { - List reduce = list1.stream().filter(item -> !list2.contains(item)).collect(toList()); - - return reduce; + /** + * 取差集 + * + * @param list1 + * @param list2 + * @return + */ + public static List reduce(List list1, List list2) { + List reduce = list1.stream().filter(item -> !list2.contains(item)).collect(toList()); + + return reduce; + } + + /** + * random pick + * + * @param list + * @param count + * @return + */ + public static List randomPick(List list, int count) { + if (list.size() <= count) { + return list; } - /** - * random pick - * @param list - * @param count - * @return - */ - public static List randomPick(List list, int count) { - if (list.size() <= count) { - return list; - } - - Collections.shuffle(list); - return list.subList(0, count); - } -} \ No newline at end of file + Collections.shuffle(list); + return list.subList(0, count); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/MigrateSlotGroupTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/MigrateSlotGroupTest.java index 03833cfc8..6d037b93e 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/MigrateSlotGroupTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/MigrateSlotGroupTest.java @@ -22,63 +22,67 @@ import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Sets; +import java.util.List; import org.junit.Assert; import org.junit.Test; -import java.util.List; - public class MigrateSlotGroupTest extends AbstractMetaServerTest { - private MigrateSlotGroup migrateSlotGroup = new MigrateSlotGroup(); + private MigrateSlotGroup migrateSlotGroup = new MigrateSlotGroup(); - @Test - public void testAddLeader() { - migrateSlotGroup.addLeader(1); - migrateSlotGroup.addLeader(2); - Assert.assertEquals(Sets.newHashSet(1, 2), migrateSlotGroup.getLeaders()); - } + @Test + public void testAddLeader() { + migrateSlotGroup.addLeader(1); + migrateSlotGroup.addLeader(2); + Assert.assertEquals(Sets.newHashSet(1, 2), migrateSlotGroup.getLeaders()); + } - @Test - public void testAddFollower() { - migrateSlotGroup.addFollower(1); - migrateSlotGroup.addFollower(2); - Assert.assertEquals(ImmutableMap.of(1, 1, 2, 1), migrateSlotGroup.getLackFollowers()); - } + @Test + public void testAddFollower() { + migrateSlotGroup.addFollower(1); + migrateSlotGroup.addFollower(2); + Assert.assertEquals(ImmutableMap.of(1, 1, 2, 1), migrateSlotGroup.getLackFollowers()); + } - @Test - public void testTestAddFollower() { - migrateSlotGroup.addFollower(1, 2); - migrateSlotGroup.addFollower(2, 3); - Assert.assertEquals(ImmutableMap.of(1, 2, 2, 3), migrateSlotGroup.getLackFollowers()); - logger.info("[migrate slot group] {}", migrateSlotGroup.toString()); - } + @Test + public void testTestAddFollower() { + migrateSlotGroup.addFollower(1, 2); + migrateSlotGroup.addFollower(2, 3); + Assert.assertEquals(ImmutableMap.of(1, 2, 2, 3), migrateSlotGroup.getLackFollowers()); + logger.info("[migrate slot group] {}", migrateSlotGroup.toString()); + } - @Test - public void testGetLeadersByScore() { - migrateSlotGroup.addLeader(1).addLeader(2).addLeader(3).addLeader(4).addLeader(5); - List result = migrateSlotGroup.getLeadersByScore(new ScoreStrategy() { - @Override - public int score(Integer slotId) { + @Test + public void testGetLeadersByScore() { + migrateSlotGroup.addLeader(1).addLeader(2).addLeader(3).addLeader(4).addLeader(5); + List result = + migrateSlotGroup.getLeadersByScore( + new ScoreStrategy() { + @Override + public int score(Integer slotId) { return SortType.DES.getScore(slotId); - } - }); - Assert.assertEquals(Lists.newArrayList(5, 4, 3, 2, 1), result); - } + } + }); + Assert.assertEquals(Lists.newArrayList(5, 4, 3, 2, 1), result); + } - @Test - public void testGetFollowersByScore() { - migrateSlotGroup.addFollower(1, 2).addFollower(2, 3).addFollower(3, 4).addFollower(4, 5); - List result = migrateSlotGroup - .getFollowersByScore(new ScoreStrategy() { - @Override - public int score(MigrateSlotGroup.FollowerToAssign followerToAssign) { - return SortType.ASC.getScore(followerToAssign.getAssigneeNums()); - } + @Test + public void testGetFollowersByScore() { + migrateSlotGroup.addFollower(1, 2).addFollower(2, 3).addFollower(3, 4).addFollower(4, 5); + List result = + migrateSlotGroup.getFollowersByScore( + new ScoreStrategy() { + @Override + public int score(MigrateSlotGroup.FollowerToAssign followerToAssign) { + return SortType.ASC.getScore(followerToAssign.getAssigneeNums()); + } }); - Assert.assertEquals(Lists.newArrayList(new MigrateSlotGroup.FollowerToAssign(1, 2), + Assert.assertEquals( + Lists.newArrayList( + new MigrateSlotGroup.FollowerToAssign(1, 2), new MigrateSlotGroup.FollowerToAssign(2, 3), new MigrateSlotGroup.FollowerToAssign(3, 4), - new MigrateSlotGroup.FollowerToAssign(4, 5)), result); - } - -} \ No newline at end of file + new MigrateSlotGroup.FollowerToAssign(4, 5)), + result); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/NodeComparatorTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/NodeComparatorTest.java index 672fe08f4..877646455 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/NodeComparatorTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/NodeComparatorTest.java @@ -18,25 +18,25 @@ import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; import com.alipay.sofa.registry.server.shared.util.NodeUtils; +import java.util.HashSet; +import java.util.List; import org.assertj.core.util.Lists; import org.junit.Assert; import org.junit.Test; -import java.util.HashSet; -import java.util.List; - public class NodeComparatorTest extends AbstractMetaServerTest { - @Test - public void testCompare() { - List prev = NodeUtils.transferNodeToIpList(randomDataNodes(6)); - List current = Lists.newArrayList(prev); - List added = NodeUtils.transferNodeToIpList(randomDataNodes(2)); - current.addAll(added); - List removed = prev.subList(0, 3); - current.removeAll(removed); - com.alipay.sofa.registry.server.shared.comparator.NodeComparator comparator = new com.alipay.sofa.registry.server.shared.comparator.NodeComparator(prev, current); - Assert.assertEquals(new HashSet<>(added), comparator.getAdded()); - Assert.assertEquals(new HashSet<>(removed), comparator.getRemoved()); - } -} \ No newline at end of file + @Test + public void testCompare() { + List prev = NodeUtils.transferNodeToIpList(randomDataNodes(6)); + List current = Lists.newArrayList(prev); + List added = NodeUtils.transferNodeToIpList(randomDataNodes(2)); + current.addAll(added); + List removed = prev.subList(0, 3); + current.removeAll(removed); + com.alipay.sofa.registry.server.shared.comparator.NodeComparator comparator = + new com.alipay.sofa.registry.server.shared.comparator.NodeComparator(prev, current); + Assert.assertEquals(new HashSet<>(added), comparator.getAdded()); + Assert.assertEquals(new HashSet<>(removed), comparator.getRemoved()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/SlotBuilderTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/SlotBuilderTest.java index 908f35928..10b43cfe4 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/SlotBuilderTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/SlotBuilderTest.java @@ -26,81 +26,79 @@ /** * @author chen.zhu - *

- * Jan 15, 2021 + *

Jan 15, 2021 */ public class SlotBuilderTest extends AbstractMetaServerTest { - private SlotBuilder slotBuilder; + private SlotBuilder slotBuilder; - @Before - public void beforeSlotBuilderTest() { - slotBuilder = new SlotBuilder(1, 1); - } + @Before + public void beforeSlotBuilderTest() { + slotBuilder = new SlotBuilder(1, 1); + } - @Test - public void testSetLeader() { - slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); - slotBuilder.setLeader("10.0.0.2"); - Assert.assertEquals("10.0.0.2", slotBuilder.getLeader()); - Assert.assertEquals(1, slotBuilder.getSlotId()); - } + @Test + public void testSetLeader() { + slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); + slotBuilder.setLeader("10.0.0.2"); + Assert.assertEquals("10.0.0.2", slotBuilder.getLeader()); + Assert.assertEquals(1, slotBuilder.getSlotId()); + } - @Test - public void testForceSetLeader() { - slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); - long epoch = slotBuilder.getEpoch(); - slotBuilder.setLeader("10.0.0.2"); - Assert.assertEquals("10.0.0.2", slotBuilder.getLeader()); - Assert.assertNotEquals(epoch, slotBuilder.getEpoch()); - Assert.assertEquals(1, slotBuilder.getSlotId()); - } + @Test + public void testForceSetLeader() { + slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); + long epoch = slotBuilder.getEpoch(); + slotBuilder.setLeader("10.0.0.2"); + Assert.assertEquals("10.0.0.2", slotBuilder.getLeader()); + Assert.assertNotEquals(epoch, slotBuilder.getEpoch()); + Assert.assertEquals(1, slotBuilder.getSlotId()); + } - @Test - public void testAddFollower() { - slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); - long epoch = slotBuilder.getEpoch(); - slotBuilder.addFollower("10.0.0.2"); - Assert.assertEquals(epoch, slotBuilder.getEpoch()); - Assert.assertTrue(slotBuilder.getFollowers().contains("10.0.0.2")); - try { - slotBuilder.addFollower("10.0.0.3"); - } catch (Exception e) { - e.printStackTrace(); - } - Assert.assertEquals(epoch, slotBuilder.getEpoch()); - Assert.assertFalse(slotBuilder.getFollowers().contains("10.0.0.3")); + @Test + public void testAddFollower() { + slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); + long epoch = slotBuilder.getEpoch(); + slotBuilder.addFollower("10.0.0.2"); + Assert.assertEquals(epoch, slotBuilder.getEpoch()); + Assert.assertTrue(slotBuilder.getFollowers().contains("10.0.0.2")); + try { + slotBuilder.addFollower("10.0.0.3"); + } catch (Exception e) { + e.printStackTrace(); } + Assert.assertEquals(epoch, slotBuilder.getEpoch()); + Assert.assertFalse(slotBuilder.getFollowers().contains("10.0.0.3")); + } - @Test - public void testRemoveFollower() { - slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); - long epoch = slotBuilder.getEpoch(); - slotBuilder.addFollower("10.0.0.2"); - Assert.assertEquals(epoch, slotBuilder.getEpoch()); - Assert.assertTrue(slotBuilder.getFollowers().contains("10.0.0.2")); + @Test + public void testRemoveFollower() { + slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); + long epoch = slotBuilder.getEpoch(); + slotBuilder.addFollower("10.0.0.2"); + Assert.assertEquals(epoch, slotBuilder.getEpoch()); + Assert.assertTrue(slotBuilder.getFollowers().contains("10.0.0.2")); - slotBuilder.removeFollower("10.0.0.2"); - slotBuilder.addFollower("10.0.0.3"); - Assert.assertEquals(epoch, slotBuilder.getEpoch()); - Assert.assertTrue(slotBuilder.getFollowers().contains("10.0.0.3")); - } + slotBuilder.removeFollower("10.0.0.2"); + slotBuilder.addFollower("10.0.0.3"); + Assert.assertEquals(epoch, slotBuilder.getEpoch()); + Assert.assertTrue(slotBuilder.getFollowers().contains("10.0.0.3")); + } - @Test(expected = SofaRegistryRuntimeException.class) - public void testBuild() { - slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); - slotBuilder.setLeader(null); - slotBuilder.build(); - } - - @Test - public void testBuildNormal() { - slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); - slotBuilder.setLeader("20.0.0.2"); - Slot slot = slotBuilder.build(); - Assert.assertEquals("20.0.0.2", slot.getLeader()); - logger.info("[slot-builder] {}", slotBuilder.toString()); - logger.info("[slot] {}", slot.toString()); - } + @Test(expected = SofaRegistryRuntimeException.class) + public void testBuild() { + slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); + slotBuilder.setLeader(null); + slotBuilder.build(); + } -} \ No newline at end of file + @Test + public void testBuildNormal() { + slotBuilder = new SlotBuilder(1, 1, "10.0.0.1", 100); + slotBuilder.setLeader("20.0.0.2"); + Slot slot = slotBuilder.build(); + Assert.assertEquals("20.0.0.2", slot.getLeader()); + logger.info("[slot-builder] {}", slotBuilder.toString()); + logger.info("[slot] {}", slot.toString()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/SlotTableBuilderTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/SlotTableBuilderTest.java index d7cc162fa..c7724406e 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/SlotTableBuilderTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/meta/slot/util/SlotTableBuilderTest.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.meta.slot.util; +import static org.junit.Assert.assertSame; + import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.DataNodeSlot; import com.alipay.sofa.registry.common.model.slot.SlotTable; @@ -24,293 +26,289 @@ import com.alipay.sofa.registry.server.meta.slot.util.builder.SlotTableBuilder; import com.alipay.sofa.registry.server.shared.util.NodeUtils; import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; - import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; - -import static org.junit.Assert.assertSame; +import org.junit.Assert; +import org.junit.Test; /** * @author chen.zhu - *

- * Jan 15, 2021 + *

Jan 15, 2021 */ public class SlotTableBuilderTest extends AbstractMetaServerTest { - @Test - public void testGetOrCreate() throws InterruptedException { - int slotId = random.nextInt(16); - int tasks = 10; - CyclicBarrier barrier = new CyclicBarrier(tasks); - CountDownLatch latch = new CountDownLatch(tasks); - List result = new ArrayList<>(tasks); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(null, 16, 2); - for (int i = 0; i < tasks; i++) { - final int index = i; - executors.execute(new Runnable() { - @Override - public void run() { - try { - barrier.await(); - result.add(index, slotTableBuilder.getOrCreate(slotId)); - } catch (Exception ignore) { - - } finally { - latch.countDown(); - } - } - }); - } - latch.await(); - SlotBuilder sample = slotTableBuilder.getOrCreate(slotId); - for (SlotBuilder sb : result) { - assertSame(sb, sample); - } - } - - @Test - public void testInit() { - List dataNodes = randomDataNodes(6); - SlotTable slotTable = randomSlotTable(dataNodes); - DataNode alternative = new DataNode(randomURL(randomIp()), getDc()); - dataNodes.add(alternative); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - Assert.assertNotNull(slotTableBuilder.getDataNodeSlot(alternative.getIp())); - - for (int slotId = 0; slotId < slotTable.getSlots().size(); slotId++) { - Assert.assertEquals(slotTableBuilder.getOrCreate(slotId).getLeader(), slotTable - .getSlot(slotId).getLeader()); - Assert.assertEquals(slotTableBuilder.getOrCreate(slotId).getEpoch(), - slotTable.getSlot(slotId).getLeaderEpoch()); - Assert.assertEquals(slotTableBuilder.getOrCreate(slotId).getFollowers(), slotTable - .getSlot(slotId).getFollowers()); - } - - for (DataNode dataNode : dataNodes) { - List samples = slotTable.transfer(dataNode.getIp(), false); - if (!samples.isEmpty()) { - Assert.assertEquals(samples.get(0), - slotTableBuilder.getDataNodeSlot(dataNode.getIp())); + @Test + public void testGetOrCreate() throws InterruptedException { + int slotId = random.nextInt(16); + int tasks = 10; + CyclicBarrier barrier = new CyclicBarrier(tasks); + CountDownLatch latch = new CountDownLatch(tasks); + List result = new ArrayList<>(tasks); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(null, 16, 2); + for (int i = 0; i < tasks; i++) { + final int index = i; + executors.execute( + new Runnable() { + @Override + public void run() { + try { + barrier.await(); + result.add(index, slotTableBuilder.getOrCreate(slotId)); + } catch (Exception ignore) { + + } finally { + latch.countDown(); + } } - } + }); } - - @Test - public void testSetLeader() { - List dataNodes = randomDataNodes(3); - SlotTable slotTable = randomSlotTable(dataNodes); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - int slotId = random.nextInt(16); - SlotBuilder sb = slotTableBuilder.getOrCreate(slotId); - String prevLeader = sb.getLeader(); - long prevEpoch = sb.getEpoch(); - String nextLeader = null; - int index = 0; - do { - nextLeader = dataNodes.get(index++).getIp(); - } while (nextLeader.equals(prevLeader)); - logger.info("[prev leader] {}", prevLeader); - logger.info("[next leader] {}", nextLeader); - slotTableBuilder.replaceLeader(slotId, nextLeader); - Assert.assertNotEquals(sb.getLeader(), prevLeader); - logger.info("[followers] {}", sb.getFollowers()); - Assert.assertTrue(sb.getEpoch() > prevEpoch); - - Assert.assertTrue(slotTableBuilder.getDataNodeSlot(nextLeader).getLeaders() - .contains(slotId)); + latch.await(); + SlotBuilder sample = slotTableBuilder.getOrCreate(slotId); + for (SlotBuilder sb : result) { + assertSame(sb, sample); } - - @Test - public void testRemoveFollower() { - List dataNodes = randomDataNodes(6); - SlotTable slotTable = randomSlotTable(dataNodes); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - int slotId = random.nextInt(16); - String follower = slotTable.getSlot(slotId).getFollowers().iterator().next(); - slotTableBuilder.removeFollower(slotId, follower); - Assert.assertFalse(slotTableBuilder.getOrCreate(slotId).getFollowers().contains(follower)); - Assert.assertFalse(slotTableBuilder.getDataNodeSlot(follower).getFollowers() - .contains(slotId)); + } + + @Test + public void testInit() { + List dataNodes = randomDataNodes(6); + SlotTable slotTable = randomSlotTable(dataNodes); + DataNode alternative = new DataNode(randomURL(randomIp()), getDc()); + dataNodes.add(alternative); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + Assert.assertNotNull(slotTableBuilder.getDataNodeSlot(alternative.getIp())); + + for (int slotId = 0; slotId < slotTable.getSlots().size(); slotId++) { + Assert.assertEquals( + slotTableBuilder.getOrCreate(slotId).getLeader(), slotTable.getSlot(slotId).getLeader()); + Assert.assertEquals( + slotTableBuilder.getOrCreate(slotId).getEpoch(), + slotTable.getSlot(slotId).getLeaderEpoch()); + Assert.assertEquals( + slotTableBuilder.getOrCreate(slotId).getFollowers(), + slotTable.getSlot(slotId).getFollowers()); } - @Test - public void testAddFollower() { - List dataNodes = randomDataNodes(6); - SlotTable slotTable = randomSlotTable(dataNodes); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - int slotId = random.nextInt(16); - SlotBuilder sb = slotTableBuilder.getOrCreate(slotId); - String prevFollower = sb.getFollowers().iterator().next(); - - long prevEpoch = sb.getEpoch(); - String nextFollower = prevFollower; - int index = 0; - do { - nextFollower = dataNodes.get(index++).getIp(); - } while (nextFollower.equals(prevFollower) || nextFollower.equals(sb.getLeader())); - - try { - slotTableBuilder.addFollower(slotId, nextFollower); - Assert.assertTrue("could not reach", false); - } catch (IllegalArgumentException e) { - Assert.assertTrue(e.getMessage().contains("to many")); - } - Assert.assertFalse(slotTableBuilder.getOrCreate(slotId).getFollowers() - .contains(nextFollower)); - Assert.assertFalse(slotTableBuilder.getDataNodeSlot(nextFollower).getFollowers() - .contains(slotId)); - - sb.removeFollower(prevFollower); - slotTableBuilder.addFollower(slotId, nextFollower); - Assert.assertTrue(slotTableBuilder.getOrCreate(slotId).getFollowers() - .contains(nextFollower)); - Assert.assertTrue(slotTableBuilder.getDataNodeSlot(nextFollower).getFollowers() - .contains(slotId)); + for (DataNode dataNode : dataNodes) { + List samples = slotTable.transfer(dataNode.getIp(), false); + if (!samples.isEmpty()) { + Assert.assertEquals(samples.get(0), slotTableBuilder.getDataNodeSlot(dataNode.getIp())); + } } - - @Test - public void testHasNoAssignedSlots() { - List dataNodes = randomDataNodes(6); - SlotTable slotTable = randomSlotTable(dataNodes); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - Assert.assertFalse(slotTableBuilder.hasNoAssignedSlots()); - - slotTableBuilder = new SlotTableBuilder(null, 16, 2); - Assert.assertTrue(slotTableBuilder.hasNoAssignedSlots()); - - dataNodes.add(new DataNode(randomURL(randomIp()), getDc())); - slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - Assert.assertFalse(slotTableBuilder.hasNoAssignedSlots()); + } + + @Test + public void testSetLeader() { + List dataNodes = randomDataNodes(3); + SlotTable slotTable = randomSlotTable(dataNodes); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + int slotId = random.nextInt(16); + SlotBuilder sb = slotTableBuilder.getOrCreate(slotId); + String prevLeader = sb.getLeader(); + long prevEpoch = sb.getEpoch(); + String nextLeader = null; + int index = 0; + do { + nextLeader = dataNodes.get(index++).getIp(); + } while (nextLeader.equals(prevLeader)); + logger.info("[prev leader] {}", prevLeader); + logger.info("[next leader] {}", nextLeader); + slotTableBuilder.replaceLeader(slotId, nextLeader); + Assert.assertNotEquals(sb.getLeader(), prevLeader); + logger.info("[followers] {}", sb.getFollowers()); + Assert.assertTrue(sb.getEpoch() > prevEpoch); + + Assert.assertTrue(slotTableBuilder.getDataNodeSlot(nextLeader).getLeaders().contains(slotId)); + } + + @Test + public void testRemoveFollower() { + List dataNodes = randomDataNodes(6); + SlotTable slotTable = randomSlotTable(dataNodes); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + int slotId = random.nextInt(16); + String follower = slotTable.getSlot(slotId).getFollowers().iterator().next(); + slotTableBuilder.removeFollower(slotId, follower); + Assert.assertFalse(slotTableBuilder.getOrCreate(slotId).getFollowers().contains(follower)); + Assert.assertFalse(slotTableBuilder.getDataNodeSlot(follower).getFollowers().contains(slotId)); + } + + @Test + public void testAddFollower() { + List dataNodes = randomDataNodes(6); + SlotTable slotTable = randomSlotTable(dataNodes); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + int slotId = random.nextInt(16); + SlotBuilder sb = slotTableBuilder.getOrCreate(slotId); + String prevFollower = sb.getFollowers().iterator().next(); + + long prevEpoch = sb.getEpoch(); + String nextFollower = prevFollower; + int index = 0; + do { + nextFollower = dataNodes.get(index++).getIp(); + } while (nextFollower.equals(prevFollower) || nextFollower.equals(sb.getLeader())); + + try { + slotTableBuilder.addFollower(slotId, nextFollower); + Assert.assertTrue("could not reach", false); + } catch (IllegalArgumentException e) { + Assert.assertTrue(e.getMessage().contains("to many")); } - - @Test - public void testRemoveDataServerSlots() { - List dataNodes = randomDataNodes(6); - SlotTable slotTable = randomSlotTable(dataNodes); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - Assert.assertFalse(slotTableBuilder.hasNoAssignedSlots()); - - slotTableBuilder.removeDataServerSlots(dataNodes.get(0).getIp()); - Assert.assertTrue(slotTableBuilder.hasNoAssignedSlots()); - - Assert.assertNull(slotTableBuilder.getDataNodeSlotIfPresent(dataNodes.get(0).getIp())); - + Assert.assertFalse(slotTableBuilder.getOrCreate(slotId).getFollowers().contains(nextFollower)); + Assert.assertFalse( + slotTableBuilder.getDataNodeSlot(nextFollower).getFollowers().contains(slotId)); + + sb.removeFollower(prevFollower); + slotTableBuilder.addFollower(slotId, nextFollower); + Assert.assertTrue(slotTableBuilder.getOrCreate(slotId).getFollowers().contains(nextFollower)); + Assert.assertTrue( + slotTableBuilder.getDataNodeSlot(nextFollower).getFollowers().contains(slotId)); + } + + @Test + public void testHasNoAssignedSlots() { + List dataNodes = randomDataNodes(6); + SlotTable slotTable = randomSlotTable(dataNodes); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + Assert.assertFalse(slotTableBuilder.hasNoAssignedSlots()); + + slotTableBuilder = new SlotTableBuilder(null, 16, 2); + Assert.assertTrue(slotTableBuilder.hasNoAssignedSlots()); + + dataNodes.add(new DataNode(randomURL(randomIp()), getDc())); + slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + Assert.assertFalse(slotTableBuilder.hasNoAssignedSlots()); + } + + @Test + public void testRemoveDataServerSlots() { + List dataNodes = randomDataNodes(6); + SlotTable slotTable = randomSlotTable(dataNodes); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + Assert.assertFalse(slotTableBuilder.hasNoAssignedSlots()); + + slotTableBuilder.removeDataServerSlots(dataNodes.get(0).getIp()); + Assert.assertTrue(slotTableBuilder.hasNoAssignedSlots()); + + Assert.assertNull(slotTableBuilder.getDataNodeSlotIfPresent(dataNodes.get(0).getIp())); + } + + @Test + public void testGetNoAssignedSlots() { + List dataNodes = randomDataNodes(6); + SlotTable slotTable = randomSlotTable(dataNodes); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + Assert.assertFalse(slotTableBuilder.hasNoAssignedSlots()); + DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(dataNodes.get(0).getIp()); + MigrateSlotGroup expected = new MigrateSlotGroup(); + dataNodeSlot.getLeaders().forEach(expected::addLeader); + dataNodeSlot.getFollowers().forEach(expected::addFollower); + + slotTableBuilder.removeDataServerSlots(dataNodes.get(0).getIp()); + Assert.assertTrue(slotTableBuilder.hasNoAssignedSlots()); + + MigrateSlotGroup actual = slotTableBuilder.getNoAssignedSlots(); + Assert.assertEquals(expected, actual); + } + + @Test + public void testGetDataNodeSlotsLeaderBeyond() { + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(null, 6, 2); + List dataNodes = randomDataNodes(3); + String leader = dataNodes.get(0).getIp(); + for (int i = 0; i < 6; i++) { + slotTableBuilder.getOrCreate(i); + slotTableBuilder.replaceLeader(i, leader); } - - @Test - public void testGetNoAssignedSlots() { - List dataNodes = randomDataNodes(6); - SlotTable slotTable = randomSlotTable(dataNodes); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 16, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - Assert.assertFalse(slotTableBuilder.hasNoAssignedSlots()); - DataNodeSlot dataNodeSlot = slotTableBuilder.getDataNodeSlot(dataNodes.get(0).getIp()); - MigrateSlotGroup expected = new MigrateSlotGroup(); - dataNodeSlot.getLeaders().forEach(expected::addLeader); - dataNodeSlot.getFollowers().forEach(expected::addFollower); - - slotTableBuilder.removeDataServerSlots(dataNodes.get(0).getIp()); - Assert.assertTrue(slotTableBuilder.hasNoAssignedSlots()); - - MigrateSlotGroup actual = slotTableBuilder.getNoAssignedSlots(); - Assert.assertEquals(expected, actual); + Assert.assertEquals( + Lists.newArrayList(slotTableBuilder.getDataNodeSlot(leader)), + slotTableBuilder.getDataNodeSlotsLeaderBeyond(6 / 3)); + } + + @Test + public void testGetDataNodeSlotsLeaderBelow() { + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(null, 6, 2); + List dataNodes = randomDataNodes(3); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + String leader = dataNodes.get(0).getIp(); + for (int i = 0; i < 6; i++) { + slotTableBuilder.getOrCreate(i); + slotTableBuilder.replaceLeader(i, leader); } - - @Test - public void testGetDataNodeSlotsLeaderBeyond() { - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(null, 6, 2); - List dataNodes = randomDataNodes(3); - String leader = dataNodes.get(0).getIp(); - for (int i = 0; i < 6; i++) { - slotTableBuilder.getOrCreate(i); - slotTableBuilder.replaceLeader(i, leader); - } - Assert.assertEquals(Lists.newArrayList(slotTableBuilder.getDataNodeSlot(leader)), - slotTableBuilder.getDataNodeSlotsLeaderBeyond(6 / 3)); - } - - @Test - public void testGetDataNodeSlotsLeaderBelow() { - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(null, 6, 2); - List dataNodes = randomDataNodes(3); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - String leader = dataNodes.get(0).getIp(); - for (int i = 0; i < 6; i++) { - slotTableBuilder.getOrCreate(i); - slotTableBuilder.replaceLeader(i, leader); - } - List expected = Lists.newArrayList( + List expected = + Lists.newArrayList( slotTableBuilder.getDataNodeSlot(dataNodes.get(1).getIp()), slotTableBuilder.getDataNodeSlot(dataNodes.get(2).getIp())); - expected.sort(new Comparator() { - @Override - public int compare(DataNodeSlot o1, DataNodeSlot o2) { - return o1.getDataNode().compareTo(o2.getDataNode()); - } + expected.sort( + new Comparator() { + @Override + public int compare(DataNodeSlot o1, DataNodeSlot o2) { + return o1.getDataNode().compareTo(o2.getDataNode()); + } }); - List actual = slotTableBuilder.getDataNodeSlotsLeaderBelow(6 / 3); - actual.sort(new Comparator() { - @Override - public int compare(DataNodeSlot o1, DataNodeSlot o2) { - return o1.getDataNode().compareTo(o2.getDataNode()); - } + List actual = slotTableBuilder.getDataNodeSlotsLeaderBelow(6 / 3); + actual.sort( + new Comparator() { + @Override + public int compare(DataNodeSlot o1, DataNodeSlot o2) { + return o1.getDataNode().compareTo(o2.getDataNode()); + } }); - Assert.assertEquals(expected, actual); - } - - @Test - public void testIncrEpoch() { - List dataNodes = randomDataNodes(6); - SlotTable slotTable = randomSlotTable(dataNodes); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 6, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - long prevEpoch = slotTableBuilder.build().getEpoch(); - slotTableBuilder.incrEpoch(); - Assert.assertTrue(slotTableBuilder.build().getEpoch() > prevEpoch); + Assert.assertEquals(expected, actual); + } + + @Test + public void testIncrEpoch() { + List dataNodes = randomDataNodes(6); + SlotTable slotTable = randomSlotTable(dataNodes); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 6, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + long prevEpoch = slotTableBuilder.build().getEpoch(); + slotTableBuilder.incrEpoch(); + Assert.assertTrue(slotTableBuilder.build().getEpoch() > prevEpoch); + } + + @Test + public void testBuild() { + List dataNodes = randomDataNodes(6); + SlotTable slotTable = randomSlotTable(dataNodes); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 6, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + long prevEpoch = slotTableBuilder.build().getEpoch(); + slotTableBuilder.incrEpoch(); + SlotTable slotTable1 = slotTableBuilder.build(); + assertSlotTableNoDupLeaderFollower(slotTable1); + } + + @Test + public void testGetDataNodeSlot() { + List dataNodes = randomDataNodes(6); + SlotTable slotTable = randomSlotTable(dataNodes); + SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 6, 2); + slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); + DataNodeSlot dataNodeSlot = null; + try { + dataNodeSlot = slotTableBuilder.getDataNodeSlot(randomIp()); + // should not reach that + Assert.assertTrue(false); + } catch (IllegalArgumentException e) { + Assert.assertTrue(e.getMessage().contains("no DataNodeSlot for")); } - - @Test - public void testBuild() { - List dataNodes = randomDataNodes(6); - SlotTable slotTable = randomSlotTable(dataNodes); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 6, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - long prevEpoch = slotTableBuilder.build().getEpoch(); - slotTableBuilder.incrEpoch(); - SlotTable slotTable1 = slotTableBuilder.build(); - assertSlotTableNoDupLeaderFollower(slotTable1); - } - - @Test - public void testGetDataNodeSlot() { - List dataNodes = randomDataNodes(6); - SlotTable slotTable = randomSlotTable(dataNodes); - SlotTableBuilder slotTableBuilder = new SlotTableBuilder(slotTable, 6, 2); - slotTableBuilder.init(NodeUtils.transferNodeToIpList(dataNodes)); - DataNodeSlot dataNodeSlot = null; - try { - dataNodeSlot = slotTableBuilder.getDataNodeSlot(randomIp()); - // should not reach that - Assert.assertTrue(false); - } catch (IllegalArgumentException e) { - Assert.assertTrue(e.getMessage().contains("no DataNodeSlot for")); - } - Assert.assertNull(dataNodeSlot); - dataNodeSlot = slotTableBuilder.getDataNodeSlot(dataNodes.get(0).getIp()); - Assert.assertNotNull(dataNodeSlot); - logger.info("[slotTableBuilder] {}", slotTableBuilder.toString()); - } - -} \ No newline at end of file + Assert.assertNull(dataNodeSlot); + dataNodeSlot = slotTableBuilder.getDataNodeSlot(dataNodes.get(0).getIp()); + Assert.assertNotNull(dataNodeSlot); + logger.info("[slotTableBuilder] {}", slotTableBuilder.toString()); + } +} diff --git a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/shared/slot/DiskSlotTableRecorderTest.java b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/shared/slot/DiskSlotTableRecorderTest.java index dea79bf8d..648103c4f 100644 --- a/server/server/meta/src/test/java/com/alipay/sofa/registry/server/shared/slot/DiskSlotTableRecorderTest.java +++ b/server/server/meta/src/test/java/com/alipay/sofa/registry/server/shared/slot/DiskSlotTableRecorderTest.java @@ -19,21 +19,22 @@ import com.alipay.sofa.registry.common.model.metaserver.nodes.DataNode; import com.alipay.sofa.registry.common.model.slot.SlotTable; import com.alipay.sofa.registry.server.meta.AbstractMetaServerTest; +import java.util.List; import org.assertj.core.util.Lists; import org.junit.Test; -import java.util.List; - public class DiskSlotTableRecorderTest extends AbstractMetaServerTest { - private DiskSlotTableRecorder recorder = new DiskSlotTableRecorder(); + private DiskSlotTableRecorder recorder = new DiskSlotTableRecorder(); - @Test - public void testRecord() { - List dataNodes = Lists.newArrayList(new DataNode(randomURL(randomIp()), getDc()), - new DataNode(randomURL(randomIp()), getDc()), new DataNode(randomURL(randomIp()), - getDc())); - SlotTable slotTable = new SlotTableGenerator(dataNodes).createSlotTable(); - recorder.record(slotTable); - } -} \ No newline at end of file + @Test + public void testRecord() { + List dataNodes = + Lists.newArrayList( + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc()), + new DataNode(randomURL(randomIp()), getDc())); + SlotTable slotTable = new SlotTableGenerator(dataNodes).createSlotTable(); + recorder.record(slotTable); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/SessionApplication.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/SessionApplication.java index 79783a0d0..dbd67c0b7 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/SessionApplication.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/SessionApplication.java @@ -24,22 +24,23 @@ import org.springframework.scheduling.annotation.EnableScheduling; /** - * * @author zhuoyu.sjw * @version $Id: SessionApplication.java, v 0.1 2017-11-13 20:19 zhuoyu.sjw Exp $$ */ -@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) +@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) @EnableScheduling public class SessionApplication { - private static final Logger LOGGER = LoggerFactory.getLogger(SessionApplication.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SessionApplication.class); - public static void main(String[] args) { - // setup DefaultUncaughtExceptionHandler - Thread.setDefaultUncaughtExceptionHandler((t, e) -> { - LOGGER.error(String.format("UncaughtException in Thread(%s): %s", t.getName(), e.getMessage()), e); + public static void main(String[] args) { + // setup DefaultUncaughtExceptionHandler + Thread.setDefaultUncaughtExceptionHandler( + (t, e) -> { + LOGGER.error( + String.format("UncaughtException in Thread(%s): %s", t.getName(), e.getMessage()), e); }); - SpringApplication.run(SessionApplication.class, args); - } + SpringApplication.run(SessionApplication.class, args); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/ClientOffWriteDataRequest.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/ClientOffWriteDataRequest.java index 049cca026..66f8c6f0e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/ClientOffWriteDataRequest.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/ClientOffWriteDataRequest.java @@ -19,37 +19,34 @@ import com.alipay.sofa.registry.common.model.ClientOffPublishers; import com.alipay.sofa.registry.common.model.ConnectId; import com.alipay.sofa.registry.common.model.store.Publisher; - import java.util.List; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-12 15:20 yuzhi.lyz Exp $ */ public final class ClientOffWriteDataRequest implements WriteDataRequest { - private final ConnectId connectId; - - private final ClientOffPublishers requestBody; + private final ConnectId connectId; - public ClientOffWriteDataRequest(ConnectId connectId, List publishers) { - this.connectId = connectId; - this.requestBody = new ClientOffPublishers(connectId, publishers); - } + private final ClientOffPublishers requestBody; - @Override - public ClientOffPublishers getRequestBody() { - return requestBody; - } + public ClientOffWriteDataRequest(ConnectId connectId, List publishers) { + this.connectId = connectId; + this.requestBody = new ClientOffPublishers(connectId, publishers); + } - @Override - public WriteDataRequestType getRequestType() { - return WriteDataRequestType.CLIENT_OFF; - } + @Override + public ClientOffPublishers getRequestBody() { + return requestBody; + } - @Override - public ConnectId getConnectId() { - return connectId; - } + @Override + public WriteDataRequestType getRequestType() { + return WriteDataRequestType.CLIENT_OFF; + } + @Override + public ConnectId getConnectId() { + return connectId; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/PublisherWriteDataRequest.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/PublisherWriteDataRequest.java index 6c532e942..1e728d35b 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/PublisherWriteDataRequest.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/PublisherWriteDataRequest.java @@ -20,32 +20,30 @@ import com.alipay.sofa.registry.common.model.store.Publisher; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-12 15:14 yuzhi.lyz Exp $ */ public final class PublisherWriteDataRequest implements WriteDataRequest { - private final Publisher publisher; - private final WriteDataRequestType type; - - public PublisherWriteDataRequest(Publisher publisher, WriteDataRequestType type) { - this.publisher = publisher; - this.type = type; - } + private final Publisher publisher; + private final WriteDataRequestType type; - @Override - public Publisher getRequestBody() { - return publisher; - } + public PublisherWriteDataRequest(Publisher publisher, WriteDataRequestType type) { + this.publisher = publisher; + this.type = type; + } - @Override - public WriteDataRequestType getRequestType() { - return type; - } + @Override + public Publisher getRequestBody() { + return publisher; + } - @Override - public ConnectId getConnectId() { - return publisher.connectId(); - } + @Override + public WriteDataRequestType getRequestType() { + return type; + } + @Override + public ConnectId getConnectId() { + return publisher.connectId(); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataAcceptor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataAcceptor.java index ca35bc817..659a1169e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataAcceptor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataAcceptor.java @@ -17,17 +17,16 @@ package com.alipay.sofa.registry.server.session.acceptor; /** - * * @author kezhu.wukz * @author shangyu.wh * @version 1.0: WriteDataAcceptor.java, v 0.1 2019-06-11 15:08 shangyu.wh Exp $ */ public interface WriteDataAcceptor { - /** - * accept all write data request - * - * @param request - */ - void accept(WriteDataRequest request); -} \ No newline at end of file + /** + * accept all write data request + * + * @param request + */ + void accept(WriteDataRequest request); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataAcceptorImpl.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataAcceptorImpl.java index c6a7da580..d44802447 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataAcceptorImpl.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataAcceptorImpl.java @@ -21,19 +21,17 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author kezhu.wukz * @author shangyu.wh * @version 1.0: WriteDataAcceptor.java, v 0.1 2019-06-06 12:45 shangyu.wh Exp $ */ public class WriteDataAcceptorImpl implements WriteDataAcceptor { - @Autowired - private DataNodeService dataNodeService; + @Autowired private DataNodeService dataNodeService; - public void accept(WriteDataRequest request) { - ConnectId connectId = request.getConnectId(); - WriteDataProcessor writeDataProcessor = new WriteDataProcessor(connectId, dataNodeService); - writeDataProcessor.process(request); - } -} \ No newline at end of file + public void accept(WriteDataRequest request) { + ConnectId connectId = request.getConnectId(); + WriteDataProcessor writeDataProcessor = new WriteDataProcessor(connectId, dataNodeService); + writeDataProcessor.process(request); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataProcessor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataProcessor.java index bf975dbfa..38490da89 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataProcessor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataProcessor.java @@ -22,90 +22,93 @@ import com.alipay.sofa.registry.server.session.node.service.DataNodeService; /** - * * @author kezhu.wukz * @author shangyu.wh - * @version 1.0: WriteDataProcessor.java, v 0.1 2019-06-06 12:50 shangyu.wh Exp - * $ + * @version 1.0: WriteDataProcessor.java, v 0.1 2019-06-06 12:50 shangyu.wh Exp $ */ public class WriteDataProcessor { - private static final Logger LOGGER = LoggerFactory - .getLogger(WriteDataProcessor.class); + private static final Logger LOGGER = LoggerFactory.getLogger(WriteDataProcessor.class); - private final ConnectId connectId; + private final ConnectId connectId; - private final DataNodeService dataNodeService; + private final DataNodeService dataNodeService; - public WriteDataProcessor(ConnectId connectId, - DataNodeService dataNodeService) { - this.connectId = connectId; - this.dataNodeService = dataNodeService; - } + public WriteDataProcessor(ConnectId connectId, DataNodeService dataNodeService) { + this.connectId = connectId; + this.dataNodeService = dataNodeService; + } - public void process(WriteDataRequest request) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug( - "process: connectId={}, requestType={}, requestBody={}", - connectId, request.getRequestType(), - request.getRequestBody()); - } - doHandle(request); - } + public void process(WriteDataRequest request) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "process: connectId={}, requestType={}, requestBody={}", + connectId, + request.getRequestType(), + request.getRequestBody()); + } + doHandle(request); + } - private void doHandle(WriteDataRequest request) { - switch (request.getRequestType()) { - case PUBLISHER : { - doPublishAsync(request); - } - break; - case UN_PUBLISHER : { - doUnPublishAsync(request); - } - break; - case CLIENT_OFF : { - doClientOffAsync(request); - } - break; - default : - LOGGER.warn( - "Unknown request type, connectId={}, requestType={}, requestBody={}", - connectId, request.getRequestType(), - request.getRequestBody()); + private void doHandle(WriteDataRequest request) { + switch (request.getRequestType()) { + case PUBLISHER: + { + doPublishAsync(request); + } + break; + case UN_PUBLISHER: + { + doUnPublishAsync(request); + } + break; + case CLIENT_OFF: + { + doClientOffAsync(request); + } + break; + default: + LOGGER.warn( + "Unknown request type, connectId={}, requestType={}, requestBody={}", + connectId, + request.getRequestType(), + request.getRequestBody()); + } + } - } - } + private void doClientOffAsync(WriteDataRequest request) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "doClientOffAsync: connectId={}, requestType={}, requestBody={}", + connectId, + request.getRequestType(), + request.getRequestBody()); + } + ClientOffWriteDataRequest req = (ClientOffWriteDataRequest) request; + dataNodeService.clientOff(req.getRequestBody()); + } - private void doClientOffAsync(WriteDataRequest request) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug( - "doClientOffAsync: connectId={}, requestType={}, requestBody={}", - connectId, request.getRequestType(), - request.getRequestBody()); - } - ClientOffWriteDataRequest req = (ClientOffWriteDataRequest) request; - dataNodeService.clientOff(req.getRequestBody()); - } + private void doUnPublishAsync(WriteDataRequest request) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "doUnPublishAsync: connectId={}, requestType={}, requestBody={}", + connectId, + request.getRequestType(), + request.getRequestBody()); + } + PublisherWriteDataRequest req = (PublisherWriteDataRequest) request; + dataNodeService.unregister(req.getRequestBody()); + } - private void doUnPublishAsync(WriteDataRequest request) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug( - "doUnPublishAsync: connectId={}, requestType={}, requestBody={}", - connectId, request.getRequestType(), - request.getRequestBody()); - } - PublisherWriteDataRequest req = (PublisherWriteDataRequest) request; - dataNodeService.unregister(req.getRequestBody()); - } - - private void doPublishAsync(WriteDataRequest request) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug( - "doPublishAsync: connectId={}, requestType={}, requestBody={}", - connectId, request.getRequestType(), - request.getRequestBody()); - } - PublisherWriteDataRequest req = (PublisherWriteDataRequest) request; - dataNodeService.register(req.getRequestBody()); - } -} \ No newline at end of file + private void doPublishAsync(WriteDataRequest request) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "doPublishAsync: connectId={}, requestType={}, requestBody={}", + connectId, + request.getRequestType(), + request.getRequestBody()); + } + PublisherWriteDataRequest req = (PublisherWriteDataRequest) request; + dataNodeService.register(req.getRequestBody()); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataRequest.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataRequest.java index fb589545e..570ff2111 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataRequest.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/acceptor/WriteDataRequest.java @@ -19,29 +19,27 @@ import com.alipay.sofa.registry.common.model.ConnectId; /** - * * @author kezhu.wukz * @author shangyu.wh * @version 1.0: WriteDataRequest.java, v 0.1 2019-06-06 18:42 shangyu.wh Exp $ */ public interface WriteDataRequest { - /** - * The enum for request type - */ - enum WriteDataRequestType { - PUBLISHER, UN_PUBLISHER, CLIENT_OFF - } - - /** - * Gets request body. - * - * @return the request body - */ - T getRequestBody(); + /** The enum for request type */ + enum WriteDataRequestType { + PUBLISHER, + UN_PUBLISHER, + CLIENT_OFF + } - WriteDataRequestType getRequestType(); + /** + * Gets request body. + * + * @return the request body + */ + T getRequestBody(); - ConnectId getConnectId(); + WriteDataRequestType getRequestType(); -} \ No newline at end of file + ConnectId getConnectId(); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/CommonConfig.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/CommonConfig.java index 7ae7a8cec..fa9a258e2 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/CommonConfig.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/CommonConfig.java @@ -18,78 +18,72 @@ import java.util.Collection; import java.util.Map; - import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.springframework.beans.factory.annotation.Value; /** - * * @author shangyu.wh * @version $Id: CommonConfig.java, v 0.1 2018-05-05 15:16 shangyu.wh Exp $ */ public class CommonConfig { - /** - * server local data center, get from System Property - * example: nodes.localDataCenter=DefaultDataCenter - */ - @Value("${nodes.localDataCenter}") - private String localDataCenter; - - /** - * server local region, get from System Property - * example: nodes.localRegion=DEFAULT_ZONE - */ - @Value("${nodes.localRegion}") - private String localRegion; + /** + * server local data center, get from System Property example: + * nodes.localDataCenter=DefaultDataCenter + */ + @Value("${nodes.localDataCenter}") + private String localDataCenter; - /** - * metaNodeInfo, get from System Property - * example: nodes.metaNode=DefaultDataCenter:192.168.xxx.xxx,192.168.xxx.xxx,192.168.xxx.xxx|AnotherDataCenter:192.168.xxx.xxx,192.168.xxx.xxx,192.168.xxx.xxx - */ - @Value("#{PropertySplitter.mapOfList('${nodes.metaNode}')}") - private Map> metaNode; + /** server local region, get from System Property example: nodes.localRegion=DEFAULT_ZONE */ + @Value("${nodes.localRegion}") + private String localRegion; - /** - * Getter method for property metaNode. - * - * @return property value of metaNode - */ - public Map> getMetaNode() { - return metaNode; - } + /** + * metaNodeInfo, get from System Property example: + * nodes.metaNode=DefaultDataCenter:192.168.xxx.xxx,192.168.xxx.xxx,192.168.xxx.xxx|AnotherDataCenter:192.168.xxx.xxx,192.168.xxx.xxx,192.168.xxx.xxx + */ + @Value("#{PropertySplitter.mapOfList('${nodes.metaNode}')}") + private Map> metaNode; - /** - * Setter method for property metaNode. - * - * @param metaNode value to be assigned to property metaNode - */ - public void setMetaNode(Map> metaNode) { - this.metaNode = metaNode; - } + /** + * Getter method for property metaNode. + * + * @return property value of metaNode + */ + public Map> getMetaNode() { + return metaNode; + } - /** - * Getter method for property localDataCenter. - * - * @return property value of localDataCenter - */ - public String getLocalDataCenter() { - return localDataCenter; - } + /** + * Setter method for property metaNode. + * + * @param metaNode value to be assigned to property metaNode + */ + public void setMetaNode(Map> metaNode) { + this.metaNode = metaNode; + } - /** - * Getter method for property localRegion. - * - * @return property value of localRegion - */ - public String getLocalRegion() { - return localRegion; - } + /** + * Getter method for property localDataCenter. + * + * @return property value of localDataCenter + */ + public String getLocalDataCenter() { + return localDataCenter; + } - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } + /** + * Getter method for property localRegion. + * + * @return property value of localRegion + */ + public String getLocalRegion() { + return localRegion; + } -} \ No newline at end of file + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerBootstrap.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerBootstrap.java index 0f44a45b7..22bfa6b8f 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerBootstrap.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerBootstrap.java @@ -45,19 +45,18 @@ import com.alipay.sofa.registry.task.batcher.TaskDispatchers; import com.github.rholder.retry.*; import com.google.common.base.Predicate; -import org.glassfish.jersey.server.ResourceConfig; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; - -import javax.annotation.Resource; -import javax.ws.rs.Path; -import javax.ws.rs.ext.Provider; import java.lang.annotation.Annotation; import java.util.Collection; import java.util.Date; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; +import javax.annotation.Resource; +import javax.ws.rs.Path; +import javax.ws.rs.ext.Provider; +import org.glassfish.jersey.server.ResourceConfig; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; /** * The type Session server bootstrap. @@ -67,383 +66,369 @@ */ public class SessionServerBootstrap { - private static final Logger LOGGER = LoggerFactory - .getLogger(SessionServerBootstrap.class); - - @Autowired - private SessionServerConfig sessionServerConfig; - - @Autowired - private Exchange boltExchange; + private static final Logger LOGGER = LoggerFactory.getLogger(SessionServerBootstrap.class); - @Autowired - private Exchange jerseyExchange; + @Autowired private SessionServerConfig sessionServerConfig; - @Autowired - private ExecutorManager executorManager; + @Autowired private Exchange boltExchange; - @Autowired - private SessionRegistry sessionRegistry; + @Autowired private Exchange jerseyExchange; - @Resource(name = "serverHandlers") - private Collection serverHandlers; + @Autowired private ExecutorManager executorManager; - @Autowired - protected MetaServerService mataNodeService; - @Autowired - private NodeExchanger dataNodeExchanger; + @Autowired private SessionRegistry sessionRegistry; - @Autowired - private ResourceConfig jerseyResourceConfig; + @Resource(name = "serverHandlers") + private Collection serverHandlers; - @Autowired - private ApplicationContext applicationContext; + @Autowired protected MetaServerService mataNodeService; + @Autowired private NodeExchanger dataNodeExchanger; - @Autowired - private BlacklistManager blacklistManager; + @Autowired private ResourceConfig jerseyResourceConfig; - @Autowired - private ProvideDataProcessor provideDataProcessorManager; + @Autowired private ApplicationContext applicationContext; - @Autowired - private SlotTableCache slotTableCache; + @Autowired private BlacklistManager blacklistManager; - private Server server; + @Autowired private ProvideDataProcessor provideDataProcessorManager; - private Server dataSyncServer; + @Autowired private SlotTableCache slotTableCache; - @Resource(name = "sessionSyncHandlers") - private Collection sessionSyncHandlers; + private Server server; - @Autowired - private AppRevisionCacheRegistry appRevisionCacheRegistry; + private Server dataSyncServer; - private Server httpServer; + @Resource(name = "sessionSyncHandlers") + private Collection sessionSyncHandlers; - private final AtomicBoolean metaStart = new AtomicBoolean(false); + @Autowired private AppRevisionCacheRegistry appRevisionCacheRegistry; - private final AtomicBoolean schedulerStart = new AtomicBoolean(false); + private Server httpServer; - private final AtomicBoolean httpStart = new AtomicBoolean(false); + private final AtomicBoolean metaStart = new AtomicBoolean(false); - private final AtomicBoolean serverStart = new AtomicBoolean(false); + private final AtomicBoolean schedulerStart = new AtomicBoolean(false); - private final AtomicBoolean dataStart = new AtomicBoolean(false); + private final AtomicBoolean httpStart = new AtomicBoolean(false); - private final AtomicBoolean serverForSessionSyncStart = new AtomicBoolean(false); + private final AtomicBoolean serverStart = new AtomicBoolean(false); - private final Retryer retryer = RetryerBuilder - . newBuilder() - .retryIfRuntimeException() - .retryIfResult(new Predicate() { - @Override - public boolean apply(Boolean input) { - return !input; - } - }) - .withWaitStrategy( - WaitStrategies - .exponentialWait( - 1000, - 10000, - TimeUnit.MILLISECONDS)) - .withStopStrategy( - StopStrategies - .stopAfterAttempt(10)) - .build(); + private final AtomicBoolean dataStart = new AtomicBoolean(false); - /** - * Do initialized. - */ - public void start() { - try { - LOGGER.info("the configuration items are as follows: " + sessionServerConfig.toString()); + private final AtomicBoolean serverForSessionSyncStart = new AtomicBoolean(false); - initEnvironment(); - ReporterUtils.enablePrometheusDefaultExports(); + private final Retryer retryer = + RetryerBuilder.newBuilder() + .retryIfRuntimeException() + .retryIfResult( + new Predicate() { + @Override + public boolean apply(Boolean input) { + return !input; + } + }) + .withWaitStrategy(WaitStrategies.exponentialWait(1000, 10000, TimeUnit.MILLISECONDS)) + .withStopStrategy(StopStrategies.stopAfterAttempt(10)) + .build(); - openSessionSyncServer(); + /** Do initialized. */ + public void start() { + try { + LOGGER.info("the configuration items are as follows: " + sessionServerConfig.toString()); + initEnvironment(); + ReporterUtils.enablePrometheusDefaultExports(); - retryer.call(() -> { - connectMetaServer(); - return true; - }); + openSessionSyncServer(); - // wait until slot table is get - retryer.call(() -> { - return slotTableCache.currentSlotTable().getEpoch() != SlotTable.INIT.getEpoch(); - }); + retryer.call( + () -> { + connectMetaServer(); + return true; + }); - // load metadata - appRevisionCacheRegistry.loadMetadata(); + // wait until slot table is get + retryer.call( + () -> { + return slotTableCache.currentSlotTable().getEpoch() != SlotTable.INIT.getEpoch(); + }); - startScheduler(); + // load metadata + appRevisionCacheRegistry.loadMetadata(); - openHttpServer(); + startScheduler(); - retryer.call(() -> { - connectDataServer(); - return true; - }); + openHttpServer(); - registerSerializer(); + retryer.call( + () -> { + connectDataServer(); + return true; + }); - openSessionServer(); + registerSerializer(); + openSessionServer(); - LOGGER.info("Initialized Session Server..."); + LOGGER.info("Initialized Session Server..."); - Runtime.getRuntime().addShutdownHook(new Thread(this::doStop)); - } catch (Throwable e) { - LOGGER.error("Cannot bootstrap session server :", e); - throw new RuntimeException("Cannot bootstrap session server :", e); - } + Runtime.getRuntime().addShutdownHook(new Thread(this::doStop)); + } catch (Throwable e) { + LOGGER.error("Cannot bootstrap session server :", e); + throw new RuntimeException("Cannot bootstrap session server :", e); } - - /** - * Destroy. - */ - public void destroy() { - doStop(); + } + + /** Destroy. */ + public void destroy() { + doStop(); + } + + private void doStop() { + try { + LOGGER.info("{} Shutting down Session Server..", new Date().toString()); + + executorManager.stopScheduler(); + TaskDispatchers.stopDefaultSingleTaskDispatcher(); + stopHttpServer(); + stopServer(); + stopDataSyncServer(); + } catch (Throwable e) { + LOGGER.error("Shutting down Session Server error!", e); } - - private void doStop() { - try { - LOGGER.info("{} Shutting down Session Server..", new Date().toString()); - - executorManager.stopScheduler(); - TaskDispatchers.stopDefaultSingleTaskDispatcher(); - stopHttpServer(); - stopServer(); - stopDataSyncServer(); - } catch (Throwable e) { - LOGGER.error("Shutting down Session Server error!", e); - } - LOGGER.info("{} Session server is now shutdown...", new Date().toString()); + LOGGER.info("{} Session server is now shutdown...", new Date().toString()); + } + + private void initEnvironment() { + LOGGER.info( + "Session server Environment: DataCenter {},Region {},ProcessId {}", + sessionServerConfig.getSessionServerDataCenter(), + sessionServerConfig.getSessionServerRegion(), + ServerEnv.PROCESS_ID); + } + + private void startScheduler() { + + try { + if (schedulerStart.compareAndSet(false, true)) { + executorManager.startScheduler(); + LOGGER.info("Session Scheduler started!"); + } + } catch (Exception e) { + schedulerStart.set(false); + LOGGER.error("Session Scheduler start error!", e); + throw new RuntimeException("Session Scheduler start error!", e); } - - private void initEnvironment() { - LOGGER.info("Session server Environment: DataCenter {},Region {},ProcessId {}", - sessionServerConfig.getSessionServerDataCenter(), - sessionServerConfig.getSessionServerRegion(), ServerEnv.PROCESS_ID); + } + + private void openSessionServer() { + try { + if (serverStart.compareAndSet(false, true)) { + server = + boltExchange.open( + new URL( + NetUtil.getLocalAddress().getHostAddress(), + sessionServerConfig.getServerPort()), + serverHandlers.toArray(new ChannelHandler[serverHandlers.size()])); + LOGGER.info("Session server started! port:{}", sessionServerConfig.getServerPort()); + } + } catch (Exception e) { + serverStart.set(false); + LOGGER.error("Session server start error! port:{}", sessionServerConfig.getServerPort(), e); + throw new RuntimeException("Session server start error!", e); } - - private void startScheduler() { - - try { - if (schedulerStart.compareAndSet(false, true)) { - executorManager.startScheduler(); - LOGGER.info("Session Scheduler started!"); - } - } catch (Exception e) { - schedulerStart.set(false); - LOGGER.error("Session Scheduler start error!", e); - throw new RuntimeException("Session Scheduler start error!", e); - } + } + + private void openSessionSyncServer() { + try { + if (serverForSessionSyncStart.compareAndSet(false, true)) { + dataSyncServer = + boltExchange.open( + new URL( + NetUtil.getLocalAddress().getHostAddress(), + sessionServerConfig.getSyncSessionPort()), + sessionSyncHandlers.toArray(new ChannelHandler[sessionSyncHandlers.size()])); + LOGGER.info( + "Data server for sync started! port:{}", sessionServerConfig.getSyncSessionPort()); + } + } catch (Exception e) { + serverForSessionSyncStart.set(false); + LOGGER.error( + "Data sync server start error! port:{}", sessionServerConfig.getSyncSessionPort(), e); + throw new RuntimeException("Data sync server start error!", e); } - - private void openSessionServer() { - try { - if (serverStart.compareAndSet(false, true)) { - server = boltExchange.open(new URL(NetUtil.getLocalAddress().getHostAddress(), - sessionServerConfig.getServerPort()), serverHandlers - .toArray(new ChannelHandler[serverHandlers.size()])); - LOGGER.info("Session server started! port:{}", sessionServerConfig.getServerPort()); - } - } catch (Exception e) { - serverStart.set(false); - LOGGER.error("Session server start error! port:{}", - sessionServerConfig.getServerPort(), e); - throw new RuntimeException("Session server start error!", e); - } + } + + private void connectDataServer() { + try { + dataNodeExchanger.connectServer(); + dataStart.set(true); + } catch (Exception e) { + dataStart.set(false); + LOGGER.error( + "Data server connected server error! port:{}", + sessionServerConfig.getDataServerPort(), + e); + throw new RuntimeException("Data server connected server error!", e); } - - private void openSessionSyncServer() { - try { - if (serverForSessionSyncStart.compareAndSet(false, true)) { - dataSyncServer = boltExchange.open(new URL(NetUtil.getLocalAddress() - .getHostAddress(), sessionServerConfig.getSyncSessionPort()), - sessionSyncHandlers.toArray(new ChannelHandler[sessionSyncHandlers.size()])); - LOGGER.info("Data server for sync started! port:{}", - sessionServerConfig.getSyncSessionPort()); - } - } catch (Exception e) { - serverForSessionSyncStart.set(false); - LOGGER.error("Data sync server start error! port:{}", - sessionServerConfig.getSyncSessionPort(), e); - throw new RuntimeException("Data sync server start error!", e); - } + } + + private void connectMetaServer() { + try { + // register node as renew node + mataNodeService.renewNode(); + // start sched renew + mataNodeService.startRenewer(sessionServerConfig.getSchedulerHeartbeatIntervalSecs() * 1000); + fetchStopPushSwitch(); + + fetchBlackList(); + metaStart.set(true); + + LOGGER.info( + "MetaServer connected meta server! Port:{}", sessionServerConfig.getMetaServerPort()); + } catch (Exception e) { + metaStart.set(false); + LOGGER.error( + "MetaServer connected server error! Port:{}", sessionServerConfig.getMetaServerPort(), e); + throw new RuntimeException("MetaServer connected server error!", e); } - - private void connectDataServer() { - try { - dataNodeExchanger.connectServer(); - dataStart.set(true); - } catch (Exception e) { - dataStart.set(false); - LOGGER.error("Data server connected server error! port:{}", - sessionServerConfig.getDataServerPort(), e); - throw new RuntimeException("Data server connected server error!", e); - } + } + + private void fetchStopPushSwitch() { + ProvideData data = mataNodeService.fetchData(ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID); + if (data != null) { + provideDataProcessorManager.fetchDataProcess(data); + } else { + LOGGER.info("Fetch session stop push switch data null,config not change!"); } - - private void connectMetaServer() { - try { - // register node as renew node - mataNodeService.renewNode(); - // start sched renew - mataNodeService - .startRenewer(sessionServerConfig.getSchedulerHeartbeatIntervalSecs() * 1000); - fetchStopPushSwitch(); - - fetchBlackList(); - metaStart.set(true); - - LOGGER.info("MetaServer connected meta server! Port:{}", - sessionServerConfig.getMetaServerPort()); - } catch (Exception e) { - metaStart.set(false); - LOGGER.error("MetaServer connected server error! Port:{}", - sessionServerConfig.getMetaServerPort(), e); - throw new RuntimeException("MetaServer connected server error!", e); - } + // start fetch change data after got the switch + sessionRegistry.fetchChangDataProcess(); + } + + private void fetchBlackList() { + blacklistManager.load(); + } + + private void openHttpServer() { + try { + if (httpStart.compareAndSet(false, true)) { + bindResourceConfig(); + httpServer = + jerseyExchange.open( + new URL( + NetUtil.getLocalAddress().getHostAddress(), + sessionServerConfig.getHttpServerPort()), + new ResourceConfig[] {jerseyResourceConfig}); + LOGGER.info("Open http server port {} success!", sessionServerConfig.getHttpServerPort()); + } + } catch (Exception e) { + LOGGER.error("Open http server port {} error!", sessionServerConfig.getHttpServerPort(), e); + httpStart.set(false); + throw new RuntimeException("Open http server error!", e); } - - private void fetchStopPushSwitch() { - ProvideData data = mataNodeService.fetchData(ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID); - if (data != null) { - provideDataProcessorManager.fetchDataProcess(data); - } else { - LOGGER.info("Fetch session stop push switch data null,config not change!"); - } - // start fetch change data after got the switch - sessionRegistry.fetchChangDataProcess(); + } + + private void bindResourceConfig() { + registerInstances(Path.class); + registerInstances(Provider.class); + } + + private void registerInstances(Class annotationType) { + Map beans = applicationContext.getBeansWithAnnotation(annotationType); + if (beans != null && !beans.isEmpty()) { + beans.forEach( + (beanName, bean) -> { + jerseyResourceConfig.registerInstances(bean); + jerseyResourceConfig.register(bean.getClass()); + }); } - - private void fetchBlackList() { - blacklistManager.load(); - } - - private void openHttpServer() { - try { - if (httpStart.compareAndSet(false, true)) { - bindResourceConfig(); - httpServer = jerseyExchange.open( - new URL(NetUtil.getLocalAddress().getHostAddress(), sessionServerConfig - .getHttpServerPort()), new ResourceConfig[] { jerseyResourceConfig }); - LOGGER.info("Open http server port {} success!", - sessionServerConfig.getHttpServerPort()); - } - } catch (Exception e) { - LOGGER.error("Open http server port {} error!", - sessionServerConfig.getHttpServerPort(), e); - httpStart.set(false); - throw new RuntimeException("Open http server error!", e); - } - } - - private void bindResourceConfig() { - registerInstances(Path.class); - registerInstances(Provider.class); - } - - private void registerInstances(Class annotationType) { - Map beans = applicationContext.getBeansWithAnnotation(annotationType); - if (beans != null && !beans.isEmpty()) { - beans.forEach((beanName, bean) -> { - jerseyResourceConfig.registerInstances(bean); - jerseyResourceConfig.register(bean.getClass()); - }); - } - } - - private void registerSerializer() { - ProtobufCustomSerializer serializer = new ProtobufCustomSerializer(); - CustomSerializerManager.registerCustomSerializer(PublisherRegisterPb.class.getName(), - serializer); - CustomSerializerManager.registerCustomSerializer(SubscriberRegisterPb.class.getName(), - serializer); - CustomSerializerManager.registerCustomSerializer(SyncConfigRequestPb.class.getName(), - serializer); - CustomSerializerManager.registerCustomSerializer(SyncConfigResponsePb.class.getName(), - serializer); - CustomSerializerManager.registerCustomSerializer(RegisterResponsePb.class.getName(), - serializer); - CustomSerializerManager.registerCustomSerializer(ResultPb.class.getName(), serializer); - CustomSerializerManager - .registerCustomSerializer(ReceivedDataPb.class.getName(), serializer); - CustomSerializerManager.registerCustomSerializer(ReceivedConfigDataPb.class.getName(), - serializer); - - SerializerManager.addSerializer(ProtobufSerializer.PROTOCOL_PROTOBUF, - ProtobufSerializer.getInstance()); - } - - private void stopServer() { - if (server != null && server.isOpen()) { - server.close(); - } - } - - private void stopDataSyncServer() { - if (dataSyncServer != null && dataSyncServer.isOpen()) { - dataSyncServer.close(); - } - } - - private void stopHttpServer() { - if (httpServer != null && httpServer.isOpen()) { - httpServer.close(); - } - } - - /** - * Getter method for property metaStart. - * - * @return property value of metaStart - */ - public boolean getMetaStart() { - return metaStart.get(); - } - - /** - * Getter method for property schedulerStart. - * - * @return property value of schedulerStart - */ - public boolean getSchedulerStart() { - return schedulerStart.get(); - } - - /** - * Getter method for property httpStart. - * - * @return property value of httpStart - */ - public boolean getHttpStart() { - return httpStart.get(); - } - - /** - * Getter method for property serverStart. - * - * @return property value of serverStart - */ - public boolean getServerStart() { - return serverStart.get(); + } + + private void registerSerializer() { + ProtobufCustomSerializer serializer = new ProtobufCustomSerializer(); + CustomSerializerManager.registerCustomSerializer( + PublisherRegisterPb.class.getName(), serializer); + CustomSerializerManager.registerCustomSerializer( + SubscriberRegisterPb.class.getName(), serializer); + CustomSerializerManager.registerCustomSerializer( + SyncConfigRequestPb.class.getName(), serializer); + CustomSerializerManager.registerCustomSerializer( + SyncConfigResponsePb.class.getName(), serializer); + CustomSerializerManager.registerCustomSerializer( + RegisterResponsePb.class.getName(), serializer); + CustomSerializerManager.registerCustomSerializer(ResultPb.class.getName(), serializer); + CustomSerializerManager.registerCustomSerializer(ReceivedDataPb.class.getName(), serializer); + CustomSerializerManager.registerCustomSerializer( + ReceivedConfigDataPb.class.getName(), serializer); + + SerializerManager.addSerializer( + ProtobufSerializer.PROTOCOL_PROTOBUF, ProtobufSerializer.getInstance()); + } + + private void stopServer() { + if (server != null && server.isOpen()) { + server.close(); } + } - /** - * Getter method for property dataStart. - * - * @return property value of dataStart - */ - public boolean getDataStart() { - return dataStart.get(); + private void stopDataSyncServer() { + if (dataSyncServer != null && dataSyncServer.isOpen()) { + dataSyncServer.close(); } + } - public boolean getServerForSessionSyncStart() { - return serverForSessionSyncStart.get(); + private void stopHttpServer() { + if (httpServer != null && httpServer.isOpen()) { + httpServer.close(); } -} \ No newline at end of file + } + + /** + * Getter method for property metaStart. + * + * @return property value of metaStart + */ + public boolean getMetaStart() { + return metaStart.get(); + } + + /** + * Getter method for property schedulerStart. + * + * @return property value of schedulerStart + */ + public boolean getSchedulerStart() { + return schedulerStart.get(); + } + + /** + * Getter method for property httpStart. + * + * @return property value of httpStart + */ + public boolean getHttpStart() { + return httpStart.get(); + } + + /** + * Getter method for property serverStart. + * + * @return property value of serverStart + */ + public boolean getServerStart() { + return serverStart.get(); + } + + /** + * Getter method for property dataStart. + * + * @return property value of dataStart + */ + public boolean getDataStart() { + return dataStart.get(); + } + + public boolean getServerForSessionSyncStart() { + return serverForSessionSyncStart.get(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfig.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfig.java index 194c3b7f8..8d2d4edc0 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfig.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfig.java @@ -20,130 +20,131 @@ /** * SessionServerConfig Interface + * * @author shangyu.wh * @version $Id: SessionServerConfig.java, v 0.1 2017-11-14 11:47 synex Exp $ */ public interface SessionServerConfig { - int getServerPort(); + int getServerPort(); - int getSyncSessionPort(); + int getSyncSessionPort(); - int getMetaServerPort(); + int getMetaServerPort(); - int getDataServerPort(); + int getDataServerPort(); - int getHttpServerPort(); + int getHttpServerPort(); - int getSchedulerHeartbeatIntervalSecs(); + int getSchedulerHeartbeatIntervalSecs(); - int getSchedulerScanVersionIntervalMillis(); + int getSchedulerScanVersionIntervalMillis(); - int getClientNodeExchangeTimeoutMillis(); + int getClientNodeExchangeTimeoutMillis(); - int getDataNodeExchangeTimeoutMillis(); + int getDataNodeExchangeTimeoutMillis(); - int getDataNodeExchangeForFetchDatumTimeoutMillis(); + int getDataNodeExchangeForFetchDatumTimeoutMillis(); - int getMetaNodeExchangeTimeoutMillis(); + int getMetaNodeExchangeTimeoutMillis(); - String getSessionServerRegion(); + String getSessionServerRegion(); - String getClientCell(String clientCell); + String getClientCell(String clientCell); - String getSessionServerDataCenter(); + String getSessionServerDataCenter(); - int getSubscriberRegisterFetchRetryTimes(); + int getSubscriberRegisterFetchRetryTimes(); - int getAccessDataExecutorMinPoolSize(); + int getAccessDataExecutorMinPoolSize(); - int getAccessDataExecutorMaxPoolSize(); + int getAccessDataExecutorMaxPoolSize(); - int getAccessDataExecutorQueueSize(); + int getAccessDataExecutorQueueSize(); - long getAccessDataExecutorKeepAliveTime(); + long getAccessDataExecutorKeepAliveTime(); - int getDataChangeExecutorMinPoolSize(); + int getDataChangeExecutorMinPoolSize(); - int getDataChangeExecutorMaxPoolSize(); + int getDataChangeExecutorMaxPoolSize(); - int getDataChangeExecutorQueueSize(); + int getDataChangeExecutorQueueSize(); - long getDataChangeExecutorKeepAliveTime(); + long getDataChangeExecutorKeepAliveTime(); - int getDataChangeDebouncingMillis(); + int getDataChangeDebouncingMillis(); - int getDataChangeMaxDebouncingMillis(); + int getDataChangeMaxDebouncingMillis(); - int getPushTaskExecutorPoolSize(); + int getPushTaskExecutorPoolSize(); - int getPushTaskExecutorQueueSize(); + int getPushTaskExecutorQueueSize(); - int getPushTaskRetryTimes(); + int getPushTaskRetryTimes(); - int getPushDataTaskRetryFirstDelayMillis(); + int getPushDataTaskRetryFirstDelayMillis(); - int getPushDataTaskRetryIncrementDelayMillis(); + int getPushDataTaskRetryIncrementDelayMillis(); - int getPushDataTaskDebouncingMillis(); + int getPushDataTaskDebouncingMillis(); - int getConnectClientExecutorMinPoolSize(); + int getConnectClientExecutorMinPoolSize(); - int getConnectClientExecutorMaxPoolSize(); + int getConnectClientExecutorMaxPoolSize(); - int getConnectClientExecutorQueueSize(); + int getConnectClientExecutorQueueSize(); - int getDataChangeFetchTaskMaxBufferSize(); + int getDataChangeFetchTaskMaxBufferSize(); - int getDataChangeFetchTaskWorkerSize(); + int getDataChangeFetchTaskWorkerSize(); - String getBlacklistPubDataIdRegex(); + String getBlacklistPubDataIdRegex(); - String getBlacklistSubDataIdRegex(); + String getBlacklistSubDataIdRegex(); - boolean isStopPushSwitch(); + boolean isStopPushSwitch(); - void setStopPushSwitch(boolean stopPushSwitch); + void setStopPushSwitch(boolean stopPushSwitch); - boolean isInvalidForeverZone(String zoneId); + boolean isInvalidForeverZone(String zoneId); - boolean isInvalidIgnored(String dataId); + boolean isInvalidIgnored(String dataId); - int getDataNodeRetryQueueSize(); + int getDataNodeRetryQueueSize(); - int getDataNodeRetryTimes(); + int getDataNodeRetryTimes(); - int getDataNodeRetryBackoffMillis(); + int getDataNodeRetryBackoffMillis(); - int getDataNodeExecutorWorkerSize(); + int getDataNodeExecutorWorkerSize(); - int getDataNodeExecutorQueueSize(); + int getDataNodeExecutorQueueSize(); - int getDataNodeMaxBatchSize(); + int getDataNodeMaxBatchSize(); - double getAccessLimitRate(); + double getAccessLimitRate(); - int getDataClientConnNum(); + int getDataClientConnNum(); - int getSessionSchedulerPoolSize(); + int getSessionSchedulerPoolSize(); - int getSlotSyncPublisherMaxNum(); + int getSlotSyncPublisherMaxNum(); - Collection getMetaServerAddresses(); + Collection getMetaServerAddresses(); - boolean isEnableSessionLoadbalancePolicy(); + boolean isEnableSessionLoadbalancePolicy(); - int getSlotSyncMaxBufferSize(); + int getSlotSyncMaxBufferSize(); - int getSlotSyncWorkerSize(); + int getSlotSyncWorkerSize(); - int getCacheDigestIntervalMinutes(); + int getCacheDigestIntervalMinutes(); - int getCacheCountIntervalSecs(); + int getCacheCountIntervalSecs(); - int getCacheDatumMaxNums(); + int getCacheDatumMaxNums(); - int getCacheDatumExpireSecs(); + int getCacheDatumExpireSecs(); - int getAppRevisionGcSilenceHour(); -} \ No newline at end of file + int getAppRevisionGcSilenceHour(); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfigBean.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfigBean.java index 845aeab9e..ba91e830a 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfigBean.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfigBean.java @@ -16,13 +16,12 @@ */ package com.alipay.sofa.registry.server.session.bootstrap; +import com.alipay.sofa.registry.server.shared.env.ServerEnv; +import com.alipay.sofa.registry.util.OsUtils; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; - -import com.alipay.sofa.registry.server.shared.env.ServerEnv; -import com.alipay.sofa.registry.util.OsUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -36,1089 +35,1091 @@ @ConfigurationProperties(prefix = SessionServerConfigBean.PREFIX) public class SessionServerConfigBean implements SessionServerConfig { - /** - * The constant PREFIX. - */ - public static final String PREFIX = "session.server"; - - private int serverPort = 9600; - - private int syncSessionPort = 9602; - - private int metaServerPort = 9610; - - private int dataServerPort = 9620; - - private int httpServerPort; - - private int schedulerHeartbeatIntervalSecs = 1; - - private int subscriberRegisterFetchRetryTimes = 3; - - private int accessDataExecutorMinPoolSize = OsUtils - .getCpuCount() * 10; - - private int accessDataExecutorMaxPoolSize = OsUtils - .getCpuCount() * 20; - - private int accessDataExecutorQueueSize = 10000; - - private long accessDataExecutorKeepAliveTime = 60; + /** The constant PREFIX. */ + public static final String PREFIX = "session.server"; - private int dataChangeExecutorMinPoolSize = OsUtils - .getCpuCount() * 2; + private int serverPort = 9600; - private int dataChangeExecutorMaxPoolSize = OsUtils - .getCpuCount() * 3; + private int syncSessionPort = 9602; - private int dataChangeExecutorQueueSize = 20000; + private int metaServerPort = 9610; - private long dataChangeExecutorKeepAliveTime = 60; + private int dataServerPort = 9620; - private int connectClientExecutorMinPoolSize = OsUtils - .getCpuCount(); + private int httpServerPort; - private int connectClientExecutorMaxPoolSize = OsUtils - .getCpuCount(); + private int schedulerHeartbeatIntervalSecs = 1; - private int connectClientExecutorQueueSize = 2000; + private int subscriberRegisterFetchRetryTimes = 3; - private int dataChangeFetchTaskMaxBufferSize = 30000; + private int accessDataExecutorMinPoolSize = OsUtils.getCpuCount() * 10; - private int dataChangeFetchTaskWorkerSize = OsUtils - .getCpuCount() * 5; + private int accessDataExecutorMaxPoolSize = OsUtils.getCpuCount() * 20; - private int dataChangeDebouncingMillis = 1000; - private int dataChangeMaxDebouncingMillis = 3000; + private int accessDataExecutorQueueSize = 10000; - private int slotSyncMaxBufferSize = 5000; + private long accessDataExecutorKeepAliveTime = 60; - private int slotSyncWorkerSize = OsUtils - .getCpuCount() * 4; + private int dataChangeExecutorMinPoolSize = OsUtils.getCpuCount() * 2; - private int clientNodeExchangeTimeoutMillis = 1000; //time out cause netty HashedWheelTimer occupy a lot of mem + private int dataChangeExecutorMaxPoolSize = OsUtils.getCpuCount() * 3; - private int dataNodeExchangeTimeoutMillis = 3000; + private int dataChangeExecutorQueueSize = 20000; - private int dataNodeExchangeForFetchDatumTimeoutMillis = 5000; + private long dataChangeExecutorKeepAliveTime = 60; - private int metaNodeExchangeTimeoutMillis = 3000; + private int connectClientExecutorMinPoolSize = OsUtils.getCpuCount(); - private int pushTaskExecutorPoolSize = OsUtils - .getCpuCount() * 3; + private int connectClientExecutorMaxPoolSize = OsUtils.getCpuCount(); - private int pushTaskExecutorQueueSize = pushTaskExecutorPoolSize * 3000; + private int connectClientExecutorQueueSize = 2000; - private int pushDataTaskRetryFirstDelayMillis = 500; + private int dataChangeFetchTaskMaxBufferSize = 30000; - private int pushDataTaskRetryIncrementDelayMillis = 500; + private int dataChangeFetchTaskWorkerSize = OsUtils.getCpuCount() * 5; - private int pushDataTaskDebouncingMillis = 500; + private int dataChangeDebouncingMillis = 1000; + private int dataChangeMaxDebouncingMillis = 3000; - private int pushTaskRetryTimes = 3; + private int slotSyncMaxBufferSize = 5000; - private int dataNodeExecutorWorkerSize = OsUtils - .getCpuCount() * 8; + private int slotSyncWorkerSize = OsUtils.getCpuCount() * 4; - private int dataNodeExecutorQueueSize = 20000; + private int clientNodeExchangeTimeoutMillis = + 1000; // time out cause netty HashedWheelTimer occupy a lot of mem - private int dataNodeRetryBackoffMillis = 1000; + private int dataNodeExchangeTimeoutMillis = 3000; - private int dataNodeRetryTimes = 5; + private int dataNodeExchangeForFetchDatumTimeoutMillis = 5000; - private int dataNodeRetryQueueSize = 1000; + private int metaNodeExchangeTimeoutMillis = 3000; - private int dataNodeMaxBatchSize = 100; + private int pushTaskExecutorPoolSize = OsUtils.getCpuCount() * 3; - private int schedulerScanVersionIntervalMillis = 1000 * 5; + private int pushTaskExecutorQueueSize = pushTaskExecutorPoolSize * 3000; - private double accessLimitRate = 100000.0; + private int pushDataTaskRetryFirstDelayMillis = 500; - private String sessionServerRegion; + private int pushDataTaskRetryIncrementDelayMillis = 500; - private String sessionServerDataCenter; + private int pushDataTaskDebouncingMillis = 500; - private volatile boolean stopPushSwitch = false; + private int pushTaskRetryTimes = 3; - //begin config for enterprise version + private int dataNodeExecutorWorkerSize = OsUtils.getCpuCount() * 8; - /** - * forever close push zone,such as:RZBETA - */ - private String invalidForeverZones = ""; - /** - * config regex,exception to the rule of forever close push zone - */ - private String invalidIgnoreDataidRegex = ""; + private int dataNodeExecutorQueueSize = 20000; - private volatile Set invalidForeverZonesSet; + private int dataNodeRetryBackoffMillis = 1000; - private Pattern invalidIgnoreDataIdPattern = null; + private int dataNodeRetryTimes = 5; - private String blacklistPubDataIdRegex = ""; + private int dataNodeRetryQueueSize = 1000; - private String blacklistSubDataIdRegex = ""; + private int dataNodeMaxBatchSize = 100; - private int dataClientConnNum = 10; + private int schedulerScanVersionIntervalMillis = 1000 * 5; - private int sessionSchedulerPoolSize = OsUtils - .getCpuCount(); + private double accessLimitRate = 100000.0; - private int slotSyncPublisherMaxNum = 512; + private String sessionServerRegion; - private boolean enableSessionLoadbalancePolicy = false; + private String sessionServerDataCenter; - private int cacheDigestIntervalMinutes = 15; + private volatile boolean stopPushSwitch = false; - private int cacheCountIntervalSecs = 30; + // begin config for enterprise version - private int cacheDatumMaxNums = 2000; + /** forever close push zone,such as:RZBETA */ + private String invalidForeverZones = ""; + /** config regex,exception to the rule of forever close push zone */ + private String invalidIgnoreDataidRegex = ""; - private int cacheDatumExpireSecs = 60 * 3; - private int silenceHour = 24; + private volatile Set invalidForeverZonesSet; - //end config for enterprise version + private Pattern invalidIgnoreDataIdPattern = null; - private CommonConfig commonConfig; + private String blacklistPubDataIdRegex = ""; - private volatile Collection metaAddresses; + private String blacklistSubDataIdRegex = ""; - /** - * constructor - * - * @param commonConfig - */ - public SessionServerConfigBean(CommonConfig commonConfig) { - this.commonConfig = commonConfig; - } - - /** - * Getter method for property serverPort. - * - * @return property value of serverPort - */ - @Override - public int getServerPort() { - return serverPort; - } - - @Override - public int getSyncSessionPort() { - return syncSessionPort; - } - - /** - * Setter method for property serverPort. - * - * @param serverPort value to be assigned to property serverPort - */ - public void setServerPort(int serverPort) { - this.serverPort = serverPort; - } - - /** - * Getter method for property schedulerHeartbeatIntervalSec. - * - * @return property value of schedulerHeartbeatIntervalSec - */ - @Override - public int getSchedulerHeartbeatIntervalSecs() { - return schedulerHeartbeatIntervalSecs; - } - - /** - * Setter method for property schedulerHeartbeatIntervalSec. - * - * @param schedulerHeartbeatIntervalSec value to be assigned to property schedulerHeartbeatIntervalSec - */ - public void setSchedulerHeartbeatTimeout(int schedulerHeartbeatIntervalSec) { - this.schedulerHeartbeatIntervalSecs = schedulerHeartbeatIntervalSec; - } - - @Override - public int getPushTaskRetryTimes() { - return pushTaskRetryTimes; - } + private int dataClientConnNum = 10; - public void setPushTaskRetryTimes(int pushTaskRetryTimes) { - this.pushTaskRetryTimes = pushTaskRetryTimes; - } + private int sessionSchedulerPoolSize = OsUtils.getCpuCount(); - /** - * Getter method for property subscriberRegisterFetchRetryTimes. - * - * @return property value of subscriberRegisterFetchRetryTimes - */ - @Override - public int getSubscriberRegisterFetchRetryTimes() { - return subscriberRegisterFetchRetryTimes; - } + private int slotSyncPublisherMaxNum = 512; - /** - * Setter method for property subscriberRegisterFetchRetryTimes. - * - * @param subscriberRegisterFetchRetryTimes value to be assigned to property subscriberRegisterFetchRetryTimes - */ - public void setSubscriberRegisterFetchRetryTimes(int subscriberRegisterFetchRetryTimes) { - this.subscriberRegisterFetchRetryTimes = subscriberRegisterFetchRetryTimes; - } + private boolean enableSessionLoadbalancePolicy = false; - /** - * Getter method for property clientNodeExchangeTimeOut. - * - * @return property value of clientNodeExchangeTimeOut - */ - @Override - public int getClientNodeExchangeTimeoutMillis() { - return clientNodeExchangeTimeoutMillis; - } + private int cacheDigestIntervalMinutes = 15; - /** - * Setter method for property clientNodeExchangeTimeOut. - * - * @param clientNodeExchangeTimeoutMillis value to be assigned to property clientNodeExchangeTimeOut - */ - public void setClientNodeExchangeTimeoutMillis(int clientNodeExchangeTimeoutMillis) { - this.clientNodeExchangeTimeoutMillis = clientNodeExchangeTimeoutMillis; - } + private int cacheCountIntervalSecs = 30; - /** - * Getter method for property dataNodeExchangeTimeOut. - * - * @return property value of dataNodeExchangeTimeOut - */ - @Override - public int getDataNodeExchangeTimeoutMillis() { - return dataNodeExchangeTimeoutMillis; - } + private int cacheDatumMaxNums = 2000; - /** - * Setter method for property dataNodeExchangeTimeOut. - * - * @param dataNodeExchangeTimeoutMillis value to be assigned to property dataNodeExchangeTimeOut - */ - public void setDataNodeExchangeTimeoutMillis(int dataNodeExchangeTimeoutMillis) { - this.dataNodeExchangeTimeoutMillis = dataNodeExchangeTimeoutMillis; - } + private int cacheDatumExpireSecs = 60 * 3; + private int silenceHour = 24; - /** - * Getter method for property metaServerPort. - * - * @return property value of metaServerPort - */ - @Override - public int getMetaServerPort() { - return metaServerPort; - } + // end config for enterprise version - /** - * Setter method for property metaServerPort. - * - * @param metaServerPort value to be assigned to property metaServerPort - */ - public void setMetaServerPort(int metaServerPort) { - this.metaServerPort = metaServerPort; - } + private CommonConfig commonConfig; - @Override - public String getSessionServerRegion() { - if (commonConfig != null) { - String region = commonConfig.getLocalRegion(); - if (region != null && !region.isEmpty()) { - return commonConfig.getLocalRegion().toUpperCase(); - } - } + private volatile Collection metaAddresses; - if (sessionServerRegion != null) { - sessionServerRegion = sessionServerRegion.toUpperCase(); - } - return sessionServerRegion; - } + /** + * constructor + * + * @param commonConfig + */ + public SessionServerConfigBean(CommonConfig commonConfig) { + this.commonConfig = commonConfig; + } - @Override - public String getClientCell(String subscriberCell) { - return this.getSessionServerRegion(); - } + /** + * Getter method for property serverPort. + * + * @return property value of serverPort + */ + @Override + public int getServerPort() { + return serverPort; + } - /** - * Setter method for property sessionServerRegion. - * - * @param sessionServerRegion value to be assigned to property sessionServerRegion - */ - public void setSessionServerRegion(String sessionServerRegion) { - if (sessionServerRegion != null) { - sessionServerRegion = sessionServerRegion.toUpperCase(); - } - this.sessionServerRegion = sessionServerRegion; - } + @Override + public int getSyncSessionPort() { + return syncSessionPort; + } - @Override - public String getSessionServerDataCenter() { - if (commonConfig != null) { - String dataCenter = commonConfig.getLocalDataCenter(); - if (dataCenter != null && !dataCenter.isEmpty()) { - return commonConfig.getLocalDataCenter(); - } + /** + * Setter method for property serverPort. + * + * @param serverPort value to be assigned to property serverPort + */ + public void setServerPort(int serverPort) { + this.serverPort = serverPort; + } + + /** + * Getter method for property schedulerHeartbeatIntervalSec. + * + * @return property value of schedulerHeartbeatIntervalSec + */ + @Override + public int getSchedulerHeartbeatIntervalSecs() { + return schedulerHeartbeatIntervalSecs; + } + + /** + * Setter method for property schedulerHeartbeatIntervalSec. + * + * @param schedulerHeartbeatIntervalSec value to be assigned to property + * schedulerHeartbeatIntervalSec + */ + public void setSchedulerHeartbeatTimeout(int schedulerHeartbeatIntervalSec) { + this.schedulerHeartbeatIntervalSecs = schedulerHeartbeatIntervalSec; + } + + @Override + public int getPushTaskRetryTimes() { + return pushTaskRetryTimes; + } + + public void setPushTaskRetryTimes(int pushTaskRetryTimes) { + this.pushTaskRetryTimes = pushTaskRetryTimes; + } + + /** + * Getter method for property subscriberRegisterFetchRetryTimes. + * + * @return property value of subscriberRegisterFetchRetryTimes + */ + @Override + public int getSubscriberRegisterFetchRetryTimes() { + return subscriberRegisterFetchRetryTimes; + } + + /** + * Setter method for property subscriberRegisterFetchRetryTimes. + * + * @param subscriberRegisterFetchRetryTimes value to be assigned to property + * subscriberRegisterFetchRetryTimes + */ + public void setSubscriberRegisterFetchRetryTimes(int subscriberRegisterFetchRetryTimes) { + this.subscriberRegisterFetchRetryTimes = subscriberRegisterFetchRetryTimes; + } + + /** + * Getter method for property clientNodeExchangeTimeOut. + * + * @return property value of clientNodeExchangeTimeOut + */ + @Override + public int getClientNodeExchangeTimeoutMillis() { + return clientNodeExchangeTimeoutMillis; + } + + /** + * Setter method for property clientNodeExchangeTimeOut. + * + * @param clientNodeExchangeTimeoutMillis value to be assigned to property + * clientNodeExchangeTimeOut + */ + public void setClientNodeExchangeTimeoutMillis(int clientNodeExchangeTimeoutMillis) { + this.clientNodeExchangeTimeoutMillis = clientNodeExchangeTimeoutMillis; + } + + /** + * Getter method for property dataNodeExchangeTimeOut. + * + * @return property value of dataNodeExchangeTimeOut + */ + @Override + public int getDataNodeExchangeTimeoutMillis() { + return dataNodeExchangeTimeoutMillis; + } + + /** + * Setter method for property dataNodeExchangeTimeOut. + * + * @param dataNodeExchangeTimeoutMillis value to be assigned to property dataNodeExchangeTimeOut + */ + public void setDataNodeExchangeTimeoutMillis(int dataNodeExchangeTimeoutMillis) { + this.dataNodeExchangeTimeoutMillis = dataNodeExchangeTimeoutMillis; + } + + /** + * Getter method for property metaServerPort. + * + * @return property value of metaServerPort + */ + @Override + public int getMetaServerPort() { + return metaServerPort; + } + + /** + * Setter method for property metaServerPort. + * + * @param metaServerPort value to be assigned to property metaServerPort + */ + public void setMetaServerPort(int metaServerPort) { + this.metaServerPort = metaServerPort; + } + + @Override + public String getSessionServerRegion() { + if (commonConfig != null) { + String region = commonConfig.getLocalRegion(); + if (region != null && !region.isEmpty()) { + return commonConfig.getLocalRegion().toUpperCase(); + } + } + + if (sessionServerRegion != null) { + sessionServerRegion = sessionServerRegion.toUpperCase(); + } + return sessionServerRegion; + } + + @Override + public String getClientCell(String subscriberCell) { + return this.getSessionServerRegion(); + } + + /** + * Setter method for property sessionServerRegion. + * + * @param sessionServerRegion value to be assigned to property sessionServerRegion + */ + public void setSessionServerRegion(String sessionServerRegion) { + if (sessionServerRegion != null) { + sessionServerRegion = sessionServerRegion.toUpperCase(); + } + this.sessionServerRegion = sessionServerRegion; + } + + @Override + public String getSessionServerDataCenter() { + if (commonConfig != null) { + String dataCenter = commonConfig.getLocalDataCenter(); + if (dataCenter != null && !dataCenter.isEmpty()) { + return commonConfig.getLocalDataCenter(); + } + } + + return sessionServerDataCenter; + } + + /** + * Setter method for property sessionServerDataCenter. + * + * @param sessionServerDataCenter value to be assigned to property sessionServerDataCenter + */ + public void setSessionServerDataCenter(String sessionServerDataCenter) { + this.sessionServerDataCenter = sessionServerDataCenter; + } + + /** + * Getter method for property metaNodeExchangeTimeOut. + * + * @return property value of metaNodeExchangeTimeOut + */ + @Override + public int getMetaNodeExchangeTimeoutMillis() { + return metaNodeExchangeTimeoutMillis; + } + + /** + * Setter method for property metaNodeExchangeTimeOut. + * + * @param metaNodeExchangeTimeoutMillis value to be assigned to property metaNodeExchangeTimeOut + */ + public void setMetaNodeExchangeTimeoutMillis(int metaNodeExchangeTimeoutMillis) { + this.metaNodeExchangeTimeoutMillis = metaNodeExchangeTimeoutMillis; + } + + /** + * Getter method for property dataServerPort. + * + * @return property value of dataServerPort + */ + @Override + public int getDataServerPort() { + return dataServerPort; + } + + /** + * Setter method for property dataServerPort. + * + * @param dataServerPort value to be assigned to property dataServerPort + */ + public void setDataServerPort(int dataServerPort) { + this.dataServerPort = dataServerPort; + } + + /** + * Getter method for property httpServerPort. + * + * @return property value of httpServerPort + */ + @Override + public int getHttpServerPort() { + return httpServerPort; + } + + /** + * Setter method for property httpServerPort. + * + * @param httpServerPort value to be assigned to property httpServerPort + */ + public void setHttpServerPort(int httpServerPort) { + this.httpServerPort = httpServerPort; + } + + /** + * Getter method for property stopPushSwitch. + * + * @return property value of stopPushSwitch + */ + @Override + public boolean isStopPushSwitch() { + return stopPushSwitch; + } + + /** + * Setter method for property stopPushSwitch. + * + * @param stopPushSwitch value to be assigned to property stopPushSwitch + */ + @Override + public void setStopPushSwitch(boolean stopPushSwitch) { + this.stopPushSwitch = stopPushSwitch; + } + + public String getInvalidForeverZones() { + return invalidForeverZones; + } + + /** + * Setter method for property invalidForeverZones. + * + * @param invalidForeverZones value to be assigned to property invalidForeverZones + */ + public void setInvalidForeverZones(String invalidForeverZones) { + this.invalidForeverZones = invalidForeverZones; + } + + public String getInvalidIgnoreDataidRegex() { + return invalidIgnoreDataidRegex; + } + + /** + * Setter method for property invalidIgnoreDataidRegex. + * + * @param invalidIgnoreDataidRegex value to be assigned to property invalidIgnoreDataidRegex + */ + public void setInvalidIgnoreDataidRegex(String invalidIgnoreDataidRegex) { + this.invalidIgnoreDataidRegex = invalidIgnoreDataidRegex; + } + + @Override + public int getAccessDataExecutorMinPoolSize() { + return accessDataExecutorMinPoolSize; + } + + /** + * Setter method for property accessDataExecutorMinPoolSize. + * + * @param accessDataExecutorMinPoolSize value to be assigned to property + * accessDataExecutorMinPoolSize + */ + public void setAccessDataExecutorMinPoolSize(int accessDataExecutorMinPoolSize) { + this.accessDataExecutorMinPoolSize = accessDataExecutorMinPoolSize; + } + + @Override + public int getAccessDataExecutorMaxPoolSize() { + return accessDataExecutorMaxPoolSize; + } + + /** + * Setter method for property accessDataExecutorMaxPoolSize. + * + * @param accessDataExecutorMaxPoolSize value to be assigned to property + * accessDataExecutorMaxPoolSize + */ + public void setAccessDataExecutorMaxPoolSize(int accessDataExecutorMaxPoolSize) { + this.accessDataExecutorMaxPoolSize = accessDataExecutorMaxPoolSize; + } + + @Override + public int getAccessDataExecutorQueueSize() { + return accessDataExecutorQueueSize; + } + + /** + * Setter method for property accessDataExecutorQueueSize. + * + * @param accessDataExecutorQueueSize value to be assigned to property accessDataExecutorQueueSize + */ + public void setAccessDataExecutorQueueSize(int accessDataExecutorQueueSize) { + this.accessDataExecutorQueueSize = accessDataExecutorQueueSize; + } + + @Override + public long getAccessDataExecutorKeepAliveTime() { + return accessDataExecutorKeepAliveTime; + } + + /** + * Setter method for property accessDataExecutorKeepAliveTime. + * + * @param accessDataExecutorKeepAliveTime value to be assigned to property + * accessDataExecutorKeepAliveTime + */ + public void setAccessDataExecutorKeepAliveTime(long accessDataExecutorKeepAliveTime) { + this.accessDataExecutorKeepAliveTime = accessDataExecutorKeepAliveTime; + } + + /** + * Getter method for property dataChangeExecutorMinPoolSize. + * + * @return property value of dataChangeExecutorMinPoolSize + */ + @Override + public int getDataChangeExecutorMinPoolSize() { + return dataChangeExecutorMinPoolSize; + } + + /** + * Getter method for property dataChangeExecutorMaxPoolSize. + * + * @return property value of dataChangeExecutorMaxPoolSize + */ + @Override + public int getDataChangeExecutorMaxPoolSize() { + return dataChangeExecutorMaxPoolSize; + } + + /** + * Getter method for property dataChangeExecutorQueueSize. + * + * @return property value of dataChangeExecutorQueueSize + */ + @Override + public int getDataChangeExecutorQueueSize() { + return dataChangeExecutorQueueSize; + } + + /** + * Getter method for property dataChangeExecutorKeepAliveTime. + * + * @return property value of dataChangeExecutorKeepAliveTime + */ + @Override + public long getDataChangeExecutorKeepAliveTime() { + return dataChangeExecutorKeepAliveTime; + } + + @Override + public int getDataChangeDebouncingMillis() { + return dataChangeDebouncingMillis; + } + + public void setDataChangeDebouncingMillis(int dataChangeDebouncingMillis) { + this.dataChangeDebouncingMillis = dataChangeDebouncingMillis; + } + + @Override + public int getDataChangeMaxDebouncingMillis() { + return dataChangeMaxDebouncingMillis; + } + + public void setDataChangeMaxDebouncingMillis(int dataChangeMaxDebouncingMillis) { + this.dataChangeMaxDebouncingMillis = dataChangeMaxDebouncingMillis; + } + + /** + * Setter method for property dataChangeExecutorMinPoolSize. + * + * @param dataChangeExecutorMinPoolSize value to be assigned to property + * dataChangeExecutorMinPoolSize + */ + public void setDataChangeExecutorMinPoolSize(int dataChangeExecutorMinPoolSize) { + this.dataChangeExecutorMinPoolSize = dataChangeExecutorMinPoolSize; + } + + /** + * Setter method for property dataChangeExecutorMaxPoolSize. + * + * @param dataChangeExecutorMaxPoolSize value to be assigned to property + * dataChangeExecutorMaxPoolSize + */ + public void setDataChangeExecutorMaxPoolSize(int dataChangeExecutorMaxPoolSize) { + this.dataChangeExecutorMaxPoolSize = dataChangeExecutorMaxPoolSize; + } + + /** + * Setter method for property dataChangeExecutorQueueSize. + * + * @param dataChangeExecutorQueueSize value to be assigned to property dataChangeExecutorQueueSize + */ + public void setDataChangeExecutorQueueSize(int dataChangeExecutorQueueSize) { + this.dataChangeExecutorQueueSize = dataChangeExecutorQueueSize; + } + + /** + * Setter method for property dataChangeExecutorKeepAliveTime. + * + * @param dataChangeExecutorKeepAliveTime value to be assigned to property + * dataChangeExecutorKeepAliveTime + */ + public void setDataChangeExecutorKeepAliveTime(long dataChangeExecutorKeepAliveTime) { + this.dataChangeExecutorKeepAliveTime = dataChangeExecutorKeepAliveTime; + } + + /** + * Getter method for property pushTaskExecutorMaxPoolSize. + * + * @return property value of pushTaskExecutorMaxPoolSize + */ + @Override + public int getPushTaskExecutorPoolSize() { + return pushTaskExecutorPoolSize; + } + + /** + * Getter method for property pushTaskExecutorQueueSize. + * + * @return property value of pushTaskExecutorQueueSize + */ + @Override + public int getPushTaskExecutorQueueSize() { + return pushTaskExecutorQueueSize; + } + + @Override + public int getPushDataTaskDebouncingMillis() { + return pushDataTaskDebouncingMillis; + } + + public void setPushDataTaskDebouncingMillis(int pushDataTaskDebouncingMillis) { + this.pushDataTaskDebouncingMillis = pushDataTaskDebouncingMillis; + } + + /** + * Setter method for property pushTaskExecutorPoolSize. + * + * @param pushTaskExecutorPoolSize value to be assigned to property pushTaskExecutorPoolSize + */ + public void setPushTaskExecutorPoolSize(int pushTaskExecutorPoolSize) { + this.pushTaskExecutorPoolSize = pushTaskExecutorPoolSize; + } + + /** + * Setter method for property pushTaskExecutorQueueSize. + * + * @param pushTaskExecutorQueueSize value to be assigned to property pushTaskExecutorQueueSize + */ + public void setPushTaskExecutorQueueSize(int pushTaskExecutorQueueSize) { + this.pushTaskExecutorQueueSize = pushTaskExecutorQueueSize; + } + + /** + * Getter method for property connectClientExecutorMinPoolSize. + * + * @return property value of connectClientExecutorMinPoolSize + */ + public int getConnectClientExecutorMinPoolSize() { + return connectClientExecutorMinPoolSize; + } + + /** + * Getter method for property connectClientExecutorMaxPoolSize. + * + * @return property value of connectClientExecutorMaxPoolSize + */ + public int getConnectClientExecutorMaxPoolSize() { + return connectClientExecutorMaxPoolSize; + } + + /** + * Getter method for property connectClientExecutorQueueSize. + * + * @return property value of connectClientExecutorQueueSize + */ + public int getConnectClientExecutorQueueSize() { + return connectClientExecutorQueueSize; + } + + /** + * Setter method for property connectClientExecutorMinPoolSize. + * + * @param connectClientExecutorMinPoolSize value to be assigned to property + * connectClientExecutorMinPoolSize + */ + public void setConnectClientExecutorMinPoolSize(int connectClientExecutorMinPoolSize) { + this.connectClientExecutorMinPoolSize = connectClientExecutorMinPoolSize; + } + + /** + * Setter method for property connectClientExecutorMaxPoolSize. + * + * @param connectClientExecutorMaxPoolSize value to be assigned to property + * connectClientExecutorMaxPoolSize + */ + public void setConnectClientExecutorMaxPoolSize(int connectClientExecutorMaxPoolSize) { + this.connectClientExecutorMaxPoolSize = connectClientExecutorMaxPoolSize; + } + + /** + * Setter method for property connectClientExecutorQueueSize. + * + * @param connectClientExecutorQueueSize value to be assigned to property + * connectClientExecutorQueueSize + */ + public void setConnectClientExecutorQueueSize(int connectClientExecutorQueueSize) { + this.connectClientExecutorQueueSize = connectClientExecutorQueueSize; + } + + /** + * Getter method for property dataChangeFetchTaskMaxBufferSize. + * + * @return property value of dataChangeFetchTaskMaxBufferSize + */ + @Override + public int getDataChangeFetchTaskMaxBufferSize() { + return dataChangeFetchTaskMaxBufferSize; + } + + /** + * Setter method for property dataChangeFetchTaskMaxBufferSize. + * + * @param dataChangeFetchTaskMaxBufferSize value to be assigned to property + * dataChangeFetchTaskMaxBufferSize + */ + public void setDataChangeFetchTaskMaxBufferSize(int dataChangeFetchTaskMaxBufferSize) { + this.dataChangeFetchTaskMaxBufferSize = dataChangeFetchTaskMaxBufferSize; + } + + /** + * Getter method for property dataChangeFetchTaskWorkerSize. + * + * @return property value of dataChangeFetchTaskWorkerSize + */ + @Override + public int getDataChangeFetchTaskWorkerSize() { + return dataChangeFetchTaskWorkerSize; + } + + /** + * Setter method for property dataChangeFetchTaskWorkerSize. + * + * @param dataChangeFetchTaskWorkerSize value to be assigned to property + * dataChangeFetchTaskWorkerSize + */ + public void setDataChangeFetchTaskWorkerSize(int dataChangeFetchTaskWorkerSize) { + this.dataChangeFetchTaskWorkerSize = dataChangeFetchTaskWorkerSize; + } + + /** + * Getter method for property pushDataTaskRetryFirstDelayMillis. + * + * @return property value of pushDataTaskRetryFirstDelayMillis + */ + @Override + public int getPushDataTaskRetryFirstDelayMillis() { + return pushDataTaskRetryFirstDelayMillis; + } + + /** + * Setter method for property pushDataTaskRetryFirstDelayMillis. + * + * @param pushDataTaskRetryFirstDelayMillis value to be assigned to property + * pushDataTaskRetryFirstDelayMillis + */ + public void setPushDataTaskRetryFirstDelayMillis(int pushDataTaskRetryFirstDelayMillis) { + this.pushDataTaskRetryFirstDelayMillis = pushDataTaskRetryFirstDelayMillis; + } + + /** + * Getter method for property pushDataTaskRetryIncrementDelayMillis. + * + * @return property value of pushDataTaskRetryIncrementDelayMillis + */ + @Override + public int getPushDataTaskRetryIncrementDelayMillis() { + return pushDataTaskRetryIncrementDelayMillis; + } + + /** + * Setter method for property pushDataTaskRetryIncrementDelayMillis. + * + * @param pushDataTaskRetryIncrementDelayMillis value to be assigned to property + * pushDataTaskRetryIncrementDelay + */ + public void setPushDataTaskRetryIncrementDelayMillis(int pushDataTaskRetryIncrementDelayMillis) { + this.pushDataTaskRetryIncrementDelayMillis = pushDataTaskRetryIncrementDelayMillis; + } + + /** + * Getter method for property blacklistPubDataIdRegex. + * + * @return property value of blacklistPubDataIdRegex + */ + public String getBlacklistPubDataIdRegex() { + return blacklistPubDataIdRegex; + } + + /** + * Getter method for property blacklistSubDataIdRegex. + * + * @return property value of blacklistSubDataIdRegex + */ + public String getBlacklistSubDataIdRegex() { + return blacklistSubDataIdRegex; + } + + /** + * Setter method for property blacklistPubDataIdRegex. + * + * @param blacklistPubDataIdRegex value to be assigned to property blacklistPubDataIdRegex + */ + public void setBlacklistPubDataIdRegex(String blacklistPubDataIdRegex) { + this.blacklistPubDataIdRegex = blacklistPubDataIdRegex; + } + + /** + * Setter method for property blacklistSubDataIdRegex. + * + * @param blacklistSubDataIdRegex value to be assigned to property blacklistSubDataIdRegex + */ + public void setBlacklistSubDataIdRegex(String blacklistSubDataIdRegex) { + this.blacklistSubDataIdRegex = blacklistSubDataIdRegex; + } + + /** + * Getter method for property accessLimitRate. + * + * @return property value of accessLimitRate + */ + public double getAccessLimitRate() { + return accessLimitRate; + } + + /** + * Setter method for property accessLimitRate. + * + * @param accessLimitRate value to be assigned to property accessLimitRate + */ + public void setAccessLimitRate(double accessLimitRate) { + this.accessLimitRate = accessLimitRate; + } + + /** + * Getter method for property dataClientConnNum. + * + * @return property value of dataClientConnNum + */ + @Override + public int getDataClientConnNum() { + return dataClientConnNum; + } + + /** + * Setter method for property dataClientConnNum . + * + * @param dataClientConnNum value to be assigned to property dataClientConnNum + */ + public void setDataClientConnNum(int dataClientConnNum) { + this.dataClientConnNum = dataClientConnNum; + } + + @Override + public boolean isInvalidForeverZone(String zoneId) { + if (invalidForeverZonesSet == null) { + String[] zoneNameArr = getInvalidForeverZones().split(";"); + Set set = new HashSet<>(); + for (String str : zoneNameArr) { + str = str.trim(); + if (str.length() != 0) { + set.add(str); } - - return sessionServerDataCenter; - } - - /** - * Setter method for property sessionServerDataCenter. - * - * @param sessionServerDataCenter value to be assigned to property sessionServerDataCenter - */ - public void setSessionServerDataCenter(String sessionServerDataCenter) { - this.sessionServerDataCenter = sessionServerDataCenter; - } - - /** - * Getter method for property metaNodeExchangeTimeOut. - * - * @return property value of metaNodeExchangeTimeOut - */ - @Override - public int getMetaNodeExchangeTimeoutMillis() { - return metaNodeExchangeTimeoutMillis; - } - - /** - * Setter method for property metaNodeExchangeTimeOut. - * - * @param metaNodeExchangeTimeoutMillis value to be assigned to property metaNodeExchangeTimeOut - */ - public void setMetaNodeExchangeTimeoutMillis(int metaNodeExchangeTimeoutMillis) { - this.metaNodeExchangeTimeoutMillis = metaNodeExchangeTimeoutMillis; - } - - /** - * Getter method for property dataServerPort. - * - * @return property value of dataServerPort - */ - @Override - public int getDataServerPort() { - return dataServerPort; - } - - /** - * Setter method for property dataServerPort. - * - * @param dataServerPort value to be assigned to property dataServerPort - */ - public void setDataServerPort(int dataServerPort) { - this.dataServerPort = dataServerPort; - } - - /** - * Getter method for property httpServerPort. - * - * @return property value of httpServerPort - */ - @Override - public int getHttpServerPort() { - return httpServerPort; - } - - /** - * Setter method for property httpServerPort. - * - * @param httpServerPort value to be assigned to property httpServerPort - */ - public void setHttpServerPort(int httpServerPort) { - this.httpServerPort = httpServerPort; - } - - /** - * Getter method for property stopPushSwitch. - * - * @return property value of stopPushSwitch - */ - @Override - public boolean isStopPushSwitch() { - return stopPushSwitch; - } - - /** - * Setter method for property stopPushSwitch. - * - * @param stopPushSwitch value to be assigned to property stopPushSwitch - */ - @Override - public void setStopPushSwitch(boolean stopPushSwitch) { - this.stopPushSwitch = stopPushSwitch; - } - - public String getInvalidForeverZones() { - return invalidForeverZones; - } - - /** - * Setter method for property invalidForeverZones. - * - * @param invalidForeverZones value to be assigned to property invalidForeverZones - */ - public void setInvalidForeverZones(String invalidForeverZones) { - this.invalidForeverZones = invalidForeverZones; - } - - public String getInvalidIgnoreDataidRegex() { - return invalidIgnoreDataidRegex; - } - - /** - * Setter method for property invalidIgnoreDataidRegex. - * - * @param invalidIgnoreDataidRegex value to be assigned to property invalidIgnoreDataidRegex - */ - public void setInvalidIgnoreDataidRegex(String invalidIgnoreDataidRegex) { - this.invalidIgnoreDataidRegex = invalidIgnoreDataidRegex; - } - - @Override - public int getAccessDataExecutorMinPoolSize() { - return accessDataExecutorMinPoolSize; - } - - /** - * Setter method for property accessDataExecutorMinPoolSize. - * - * @param accessDataExecutorMinPoolSize value to be assigned to property accessDataExecutorMinPoolSize - */ - public void setAccessDataExecutorMinPoolSize(int accessDataExecutorMinPoolSize) { - this.accessDataExecutorMinPoolSize = accessDataExecutorMinPoolSize; - } - - @Override - public int getAccessDataExecutorMaxPoolSize() { - return accessDataExecutorMaxPoolSize; - } - - /** - * Setter method for property accessDataExecutorMaxPoolSize. - * - * @param accessDataExecutorMaxPoolSize value to be assigned to property accessDataExecutorMaxPoolSize - */ - public void setAccessDataExecutorMaxPoolSize(int accessDataExecutorMaxPoolSize) { - this.accessDataExecutorMaxPoolSize = accessDataExecutorMaxPoolSize; - } - - @Override - public int getAccessDataExecutorQueueSize() { - return accessDataExecutorQueueSize; - } - - /** - * Setter method for property accessDataExecutorQueueSize. - * - * @param accessDataExecutorQueueSize value to be assigned to property accessDataExecutorQueueSize - */ - public void setAccessDataExecutorQueueSize(int accessDataExecutorQueueSize) { - this.accessDataExecutorQueueSize = accessDataExecutorQueueSize; - } - - @Override - public long getAccessDataExecutorKeepAliveTime() { - return accessDataExecutorKeepAliveTime; - } - - /** - * Setter method for property accessDataExecutorKeepAliveTime. - * - * @param accessDataExecutorKeepAliveTime value to be assigned to property accessDataExecutorKeepAliveTime - */ - public void setAccessDataExecutorKeepAliveTime(long accessDataExecutorKeepAliveTime) { - this.accessDataExecutorKeepAliveTime = accessDataExecutorKeepAliveTime; - } - - /** - * Getter method for property dataChangeExecutorMinPoolSize. - * - * @return property value of dataChangeExecutorMinPoolSize - */ - @Override - public int getDataChangeExecutorMinPoolSize() { - return dataChangeExecutorMinPoolSize; - } - - /** - * Getter method for property dataChangeExecutorMaxPoolSize. - * - * @return property value of dataChangeExecutorMaxPoolSize - */ - @Override - public int getDataChangeExecutorMaxPoolSize() { - return dataChangeExecutorMaxPoolSize; - } - - /** - * Getter method for property dataChangeExecutorQueueSize. - * - * @return property value of dataChangeExecutorQueueSize - */ - @Override - public int getDataChangeExecutorQueueSize() { - return dataChangeExecutorQueueSize; - } - - /** - * Getter method for property dataChangeExecutorKeepAliveTime. - * - * @return property value of dataChangeExecutorKeepAliveTime - */ - @Override - public long getDataChangeExecutorKeepAliveTime() { - return dataChangeExecutorKeepAliveTime; - } - - @Override - public int getDataChangeDebouncingMillis() { - return dataChangeDebouncingMillis; - } - - public void setDataChangeDebouncingMillis(int dataChangeDebouncingMillis) { - this.dataChangeDebouncingMillis = dataChangeDebouncingMillis; - } - - @Override - public int getDataChangeMaxDebouncingMillis() { - return dataChangeMaxDebouncingMillis; - } - - public void setDataChangeMaxDebouncingMillis(int dataChangeMaxDebouncingMillis) { - this.dataChangeMaxDebouncingMillis = dataChangeMaxDebouncingMillis; - } - - /** - * Setter method for property dataChangeExecutorMinPoolSize. - * - * @param dataChangeExecutorMinPoolSize value to be assigned to property dataChangeExecutorMinPoolSize - */ - public void setDataChangeExecutorMinPoolSize(int dataChangeExecutorMinPoolSize) { - this.dataChangeExecutorMinPoolSize = dataChangeExecutorMinPoolSize; - } - - /** - * Setter method for property dataChangeExecutorMaxPoolSize. - * - * @param dataChangeExecutorMaxPoolSize value to be assigned to property dataChangeExecutorMaxPoolSize - */ - public void setDataChangeExecutorMaxPoolSize(int dataChangeExecutorMaxPoolSize) { - this.dataChangeExecutorMaxPoolSize = dataChangeExecutorMaxPoolSize; - } - - /** - * Setter method for property dataChangeExecutorQueueSize. - * - * @param dataChangeExecutorQueueSize value to be assigned to property dataChangeExecutorQueueSize - */ - public void setDataChangeExecutorQueueSize(int dataChangeExecutorQueueSize) { - this.dataChangeExecutorQueueSize = dataChangeExecutorQueueSize; - } - - /** - * Setter method for property dataChangeExecutorKeepAliveTime. - * - * @param dataChangeExecutorKeepAliveTime value to be assigned to property dataChangeExecutorKeepAliveTime - */ - public void setDataChangeExecutorKeepAliveTime(long dataChangeExecutorKeepAliveTime) { - this.dataChangeExecutorKeepAliveTime = dataChangeExecutorKeepAliveTime; - } - - /** - * Getter method for property pushTaskExecutorMaxPoolSize. - * - * @return property value of pushTaskExecutorMaxPoolSize - */ - @Override - public int getPushTaskExecutorPoolSize() { - return pushTaskExecutorPoolSize; - } - - /** - * Getter method for property pushTaskExecutorQueueSize. - * - * @return property value of pushTaskExecutorQueueSize - */ - @Override - public int getPushTaskExecutorQueueSize() { - return pushTaskExecutorQueueSize; - } - - @Override - public int getPushDataTaskDebouncingMillis() { - return pushDataTaskDebouncingMillis; - } - - public void setPushDataTaskDebouncingMillis(int pushDataTaskDebouncingMillis) { - this.pushDataTaskDebouncingMillis = pushDataTaskDebouncingMillis; - } - - /** - * Setter method for property pushTaskExecutorPoolSize. - * - * @param pushTaskExecutorPoolSize value to be assigned to property pushTaskExecutorPoolSize - */ - public void setPushTaskExecutorPoolSize(int pushTaskExecutorPoolSize) { - this.pushTaskExecutorPoolSize = pushTaskExecutorPoolSize; - } - - /** - * Setter method for property pushTaskExecutorQueueSize. - * - * @param pushTaskExecutorQueueSize value to be assigned to property pushTaskExecutorQueueSize - */ - public void setPushTaskExecutorQueueSize(int pushTaskExecutorQueueSize) { - this.pushTaskExecutorQueueSize = pushTaskExecutorQueueSize; - } - - /** - * Getter method for property connectClientExecutorMinPoolSize. - * - * @return property value of connectClientExecutorMinPoolSize - */ - public int getConnectClientExecutorMinPoolSize() { - return connectClientExecutorMinPoolSize; - } - - /** - * Getter method for property connectClientExecutorMaxPoolSize. - * - * @return property value of connectClientExecutorMaxPoolSize - */ - public int getConnectClientExecutorMaxPoolSize() { - return connectClientExecutorMaxPoolSize; - } - - /** - * Getter method for property connectClientExecutorQueueSize. - * - * @return property value of connectClientExecutorQueueSize - */ - public int getConnectClientExecutorQueueSize() { - return connectClientExecutorQueueSize; - } - - /** - * Setter method for property connectClientExecutorMinPoolSize. - * - * @param connectClientExecutorMinPoolSize value to be assigned to property connectClientExecutorMinPoolSize - */ - public void setConnectClientExecutorMinPoolSize(int connectClientExecutorMinPoolSize) { - this.connectClientExecutorMinPoolSize = connectClientExecutorMinPoolSize; - } - - /** - * Setter method for property connectClientExecutorMaxPoolSize. - * - * @param connectClientExecutorMaxPoolSize value to be assigned to property connectClientExecutorMaxPoolSize - */ - public void setConnectClientExecutorMaxPoolSize(int connectClientExecutorMaxPoolSize) { - this.connectClientExecutorMaxPoolSize = connectClientExecutorMaxPoolSize; - } - - /** - * Setter method for property connectClientExecutorQueueSize. - * - * @param connectClientExecutorQueueSize value to be assigned to property connectClientExecutorQueueSize - */ - public void setConnectClientExecutorQueueSize(int connectClientExecutorQueueSize) { - this.connectClientExecutorQueueSize = connectClientExecutorQueueSize; - } - - /** - * Getter method for property dataChangeFetchTaskMaxBufferSize. - * - * @return property value of dataChangeFetchTaskMaxBufferSize - */ - @Override - public int getDataChangeFetchTaskMaxBufferSize() { - return dataChangeFetchTaskMaxBufferSize; - } - - /** - * Setter method for property dataChangeFetchTaskMaxBufferSize. - * - * @param dataChangeFetchTaskMaxBufferSize value to be assigned to property dataChangeFetchTaskMaxBufferSize - */ - public void setDataChangeFetchTaskMaxBufferSize(int dataChangeFetchTaskMaxBufferSize) { - this.dataChangeFetchTaskMaxBufferSize = dataChangeFetchTaskMaxBufferSize; - } - - /** - * Getter method for property dataChangeFetchTaskWorkerSize. - * - * @return property value of dataChangeFetchTaskWorkerSize - */ - @Override - public int getDataChangeFetchTaskWorkerSize() { - return dataChangeFetchTaskWorkerSize; - } - - /** - * Setter method for property dataChangeFetchTaskWorkerSize. - * - * @param dataChangeFetchTaskWorkerSize value to be assigned to property dataChangeFetchTaskWorkerSize - */ - public void setDataChangeFetchTaskWorkerSize(int dataChangeFetchTaskWorkerSize) { - this.dataChangeFetchTaskWorkerSize = dataChangeFetchTaskWorkerSize; - } - - /** - * Getter method for property pushDataTaskRetryFirstDelayMillis. - * - * @return property value of pushDataTaskRetryFirstDelayMillis - */ - @Override - public int getPushDataTaskRetryFirstDelayMillis() { - return pushDataTaskRetryFirstDelayMillis; - } - - /** - * Setter method for property pushDataTaskRetryFirstDelayMillis. - * - * @param pushDataTaskRetryFirstDelayMillis value to be assigned to property pushDataTaskRetryFirstDelayMillis - */ - public void setPushDataTaskRetryFirstDelayMillis(int pushDataTaskRetryFirstDelayMillis) { - this.pushDataTaskRetryFirstDelayMillis = pushDataTaskRetryFirstDelayMillis; - } - - /** - * Getter method for property pushDataTaskRetryIncrementDelayMillis. - * - * @return property value of pushDataTaskRetryIncrementDelayMillis - */ - @Override - public int getPushDataTaskRetryIncrementDelayMillis() { - return pushDataTaskRetryIncrementDelayMillis; - } - - /** - * Setter method for property pushDataTaskRetryIncrementDelayMillis. - * - * @param pushDataTaskRetryIncrementDelayMillis value to be assigned to property pushDataTaskRetryIncrementDelay - */ - public void setPushDataTaskRetryIncrementDelayMillis(int pushDataTaskRetryIncrementDelayMillis) { - this.pushDataTaskRetryIncrementDelayMillis = pushDataTaskRetryIncrementDelayMillis; - } - - /** - * Getter method for property blacklistPubDataIdRegex. - * - * @return property value of blacklistPubDataIdRegex - */ - public String getBlacklistPubDataIdRegex() { - return blacklistPubDataIdRegex; - } - - /** - * Getter method for property blacklistSubDataIdRegex. - * - * @return property value of blacklistSubDataIdRegex - */ - public String getBlacklistSubDataIdRegex() { - return blacklistSubDataIdRegex; - } - - /** - * Setter method for property blacklistPubDataIdRegex. - * - * @param blacklistPubDataIdRegex value to be assigned to property blacklistPubDataIdRegex - */ - public void setBlacklistPubDataIdRegex(String blacklistPubDataIdRegex) { - this.blacklistPubDataIdRegex = blacklistPubDataIdRegex; - } - - /** - * Setter method for property blacklistSubDataIdRegex. - * - * @param blacklistSubDataIdRegex value to be assigned to property blacklistSubDataIdRegex - */ - public void setBlacklistSubDataIdRegex(String blacklistSubDataIdRegex) { - this.blacklistSubDataIdRegex = blacklistSubDataIdRegex; - } - - /** - * Getter method for property accessLimitRate. - * - * @return property value of accessLimitRate - */ - public double getAccessLimitRate() { - return accessLimitRate; - } - - /** - * Setter method for property accessLimitRate. - * - * @param accessLimitRate value to be assigned to property accessLimitRate - */ - public void setAccessLimitRate(double accessLimitRate) { - this.accessLimitRate = accessLimitRate; - } - - /** - * Getter method for property dataClientConnNum. - * - * @return property value of dataClientConnNum - */ - @Override - public int getDataClientConnNum() { - return dataClientConnNum; - } - - /** - * Setter method for property dataClientConnNum . - * - * @param dataClientConnNum value to be assigned to property dataClientConnNum - */ - public void setDataClientConnNum(int dataClientConnNum) { - this.dataClientConnNum = dataClientConnNum; - } - - @Override - public boolean isInvalidForeverZone(String zoneId) { - if (invalidForeverZonesSet == null) { - String[] zoneNameArr = getInvalidForeverZones().split(";"); - Set set = new HashSet<>(); - for (String str : zoneNameArr) { - str = str.trim(); - if (str.length() != 0) { - set.add(str); - } - } - invalidForeverZonesSet = set; - } - return invalidForeverZonesSet.contains(zoneId); - } - - @Override - public boolean isInvalidIgnored(String dataId) { - - String invalidIgnoreDataidRegex = getInvalidIgnoreDataidRegex(); - if (null != invalidIgnoreDataidRegex && !invalidIgnoreDataidRegex.isEmpty()) { - invalidIgnoreDataIdPattern = Pattern.compile(invalidIgnoreDataidRegex); - } - - return null != invalidIgnoreDataIdPattern - && invalidIgnoreDataIdPattern.matcher(dataId).find(); - } - - /** - * Getter method for property sessionSchedulerPoolSize. - * - * @return property value of sessionSchedulerPoolSize - */ - @Override - public int getSessionSchedulerPoolSize() { - return sessionSchedulerPoolSize; - } - - /** - * Setter method for property sessionSchedulerPoolSize . - * - * @param sessionSchedulerPoolSize value to be assigned to property sessionSchedulerPoolSize - */ - public void setSessionSchedulerPoolSize(int sessionSchedulerPoolSize) { - this.sessionSchedulerPoolSize = sessionSchedulerPoolSize; - } - - /** - * Getter method for property dataNodeExchangeForFetchDatumTimeOut. - * - * @return property value of dataNodeExchangeForFetchDatumTimeOut - */ - public int getDataNodeExchangeForFetchDatumTimeoutMillis() { - return dataNodeExchangeForFetchDatumTimeoutMillis; - } - - /** - * Setter method for property dataNodeExchangeForFetchDatumTimeOut . - * - * @param dataNodeExchangeForFetchDatumTimeoutMillis value to be assigned to property dataNodeExchangeForFetchDatumTimeOut - */ - public void setDataNodeExchangeForFetchDatumTimeoutMillis(int dataNodeExchangeForFetchDatumTimeoutMillis) { - this.dataNodeExchangeForFetchDatumTimeoutMillis = dataNodeExchangeForFetchDatumTimeoutMillis; - } - - /** - * Getter method for property slotSyncPublisherMaxNum. - * - * @return property value of slotSyncPublisherMaxNum - */ - @Override - public int getSlotSyncPublisherMaxNum() { - return slotSyncPublisherMaxNum; - } - - @Override - public Collection getMetaServerAddresses() { - final Collection addresses = metaAddresses; - if (addresses != null) { - return addresses; - } - metaAddresses = ServerEnv.getMetaAddresses(commonConfig.getMetaNode(), - commonConfig.getLocalDataCenter()); - return metaAddresses; - } - - /** - * Setter method for property slotSyncPublisherMaxNum. - * - * @param slotSyncPublisherMaxNum value to be assigned to property slotSyncPublisherMaxNum - */ - public void setSlotSyncPublisherMaxNum(int slotSyncPublisherMaxNum) { - this.slotSyncPublisherMaxNum = slotSyncPublisherMaxNum; - } - - /** - * Getter method for property schedulerScanVersionIntervalMs. - * - * @return property value of schedulerScanVersionIntervalMs - */ - @Override - public int getSchedulerScanVersionIntervalMillis() { - return schedulerScanVersionIntervalMillis; - } - - /** - * Setter method for property schedulerScanVersionIntervalMs. - * - * @param schedulerScanVersionIntervalMs value to be assigned to property schedulerScanVersionIntervalMs - */ - public void setSchedulerFetchDataVersionIntervalMs(int schedulerScanVersionIntervalMs) { - this.schedulerScanVersionIntervalMillis = schedulerScanVersionIntervalMs; - } - - public int getSlotSyncMaxBufferSize() { - return slotSyncMaxBufferSize; - } - - public void setSlotSyncMaxBufferSize(int slotSyncMaxBufferSize) { - this.slotSyncMaxBufferSize = slotSyncMaxBufferSize; - } - - public int getSlotSyncWorkerSize() { - return slotSyncWorkerSize; - } - - @Override - public int getCacheDigestIntervalMinutes() { - return cacheDigestIntervalMinutes; - } - - public void setCacheDigestIntervalMinutes(int cacheDigestIntervalMinutes) { - this.cacheDigestIntervalMinutes = cacheDigestIntervalMinutes; - } - - public void setSlotSyncWorkerSize(int slotSyncWorkerSize) { - this.slotSyncWorkerSize = slotSyncWorkerSize; - } - - @Override - public String toString() { - return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); - } - - public boolean isEnableSessionLoadbalancePolicy() { - return enableSessionLoadbalancePolicy; - } - - public void setEnableSessionLoadbalancePolicy(boolean enableSessionLoadbalancePolicy) { - this.enableSessionLoadbalancePolicy = enableSessionLoadbalancePolicy; - } - - @Override - public int getDataNodeExecutorWorkerSize() { - return dataNodeExecutorWorkerSize; - } - - public void setDataNodeExecutorWorkerSize(int dataNodeExecutorWorkerSize) { - this.dataNodeExecutorWorkerSize = dataNodeExecutorWorkerSize; - } - - @Override - public int getDataNodeExecutorQueueSize() { - return dataNodeExecutorQueueSize; - } - - public void setDataNodeExecutorQueueSize(int dataNodeExecutorQueueSize) { - this.dataNodeExecutorQueueSize = dataNodeExecutorQueueSize; - } - - @Override - public int getDataNodeRetryBackoffMillis() { - return dataNodeRetryBackoffMillis; - } - - public void setDataNodeRetryBackoffMillis(int dataNodeRetryBackoffMillis) { - this.dataNodeRetryBackoffMillis = dataNodeRetryBackoffMillis; - } - - @Override - public int getDataNodeRetryTimes() { - return dataNodeRetryTimes; - } - - public void setDataNodeRetryTimes(int dataNodeRetryTimes) { - this.dataNodeRetryTimes = dataNodeRetryTimes; - } - - @Override - public int getDataNodeRetryQueueSize() { - return dataNodeRetryQueueSize; - } - - public void setDataNodeRetryQueueSize(int dataNodeRetryQueueSize) { - this.dataNodeRetryQueueSize = dataNodeRetryQueueSize; - } - - @Override - public int getDataNodeMaxBatchSize() { - return dataNodeMaxBatchSize; - } - - public void setDataNodeMaxBatchSize(int dataNodeMaxBatchSize) { - this.dataNodeMaxBatchSize = dataNodeMaxBatchSize; - } - - @Override - public int getCacheCountIntervalSecs() { - return cacheCountIntervalSecs; - } - - public void setCacheCountIntervalSecs(int cacheCountIntervalSecs) { - this.cacheCountIntervalSecs = cacheCountIntervalSecs; - } - - @Override - public int getCacheDatumMaxNums() { - return cacheDatumMaxNums; - } - - public void setCacheDatumMaxNums(int cacheDatumMaxNums) { - this.cacheDatumMaxNums = cacheDatumMaxNums; - } - - @Override - public int getCacheDatumExpireSecs() { - return cacheDatumExpireSecs; - } - - public void setCacheDatumExpireSecs(int cacheDatumExpireSecs) { - this.cacheDatumExpireSecs = cacheDatumExpireSecs; - } - - public int getAppRevisionGcSilenceHour() { - return silenceHour; - } - - /** - * Setter method for property silenceHour. - * - * @param silenceHour value to be assigned to property silenceHour - */ - public void setSilenceHour(int silenceHour) { - this.silenceHour = silenceHour; - } -} \ No newline at end of file + } + invalidForeverZonesSet = set; + } + return invalidForeverZonesSet.contains(zoneId); + } + + @Override + public boolean isInvalidIgnored(String dataId) { + + String invalidIgnoreDataidRegex = getInvalidIgnoreDataidRegex(); + if (null != invalidIgnoreDataidRegex && !invalidIgnoreDataidRegex.isEmpty()) { + invalidIgnoreDataIdPattern = Pattern.compile(invalidIgnoreDataidRegex); + } + + return null != invalidIgnoreDataIdPattern && invalidIgnoreDataIdPattern.matcher(dataId).find(); + } + + /** + * Getter method for property sessionSchedulerPoolSize. + * + * @return property value of sessionSchedulerPoolSize + */ + @Override + public int getSessionSchedulerPoolSize() { + return sessionSchedulerPoolSize; + } + + /** + * Setter method for property sessionSchedulerPoolSize . + * + * @param sessionSchedulerPoolSize value to be assigned to property sessionSchedulerPoolSize + */ + public void setSessionSchedulerPoolSize(int sessionSchedulerPoolSize) { + this.sessionSchedulerPoolSize = sessionSchedulerPoolSize; + } + + /** + * Getter method for property dataNodeExchangeForFetchDatumTimeOut. + * + * @return property value of dataNodeExchangeForFetchDatumTimeOut + */ + public int getDataNodeExchangeForFetchDatumTimeoutMillis() { + return dataNodeExchangeForFetchDatumTimeoutMillis; + } + + /** + * Setter method for property dataNodeExchangeForFetchDatumTimeOut . + * + * @param dataNodeExchangeForFetchDatumTimeoutMillis value to be assigned to property + * dataNodeExchangeForFetchDatumTimeOut + */ + public void setDataNodeExchangeForFetchDatumTimeoutMillis( + int dataNodeExchangeForFetchDatumTimeoutMillis) { + this.dataNodeExchangeForFetchDatumTimeoutMillis = dataNodeExchangeForFetchDatumTimeoutMillis; + } + + /** + * Getter method for property slotSyncPublisherMaxNum. + * + * @return property value of slotSyncPublisherMaxNum + */ + @Override + public int getSlotSyncPublisherMaxNum() { + return slotSyncPublisherMaxNum; + } + + @Override + public Collection getMetaServerAddresses() { + final Collection addresses = metaAddresses; + if (addresses != null) { + return addresses; + } + metaAddresses = + ServerEnv.getMetaAddresses(commonConfig.getMetaNode(), commonConfig.getLocalDataCenter()); + return metaAddresses; + } + + /** + * Setter method for property slotSyncPublisherMaxNum. + * + * @param slotSyncPublisherMaxNum value to be assigned to property slotSyncPublisherMaxNum + */ + public void setSlotSyncPublisherMaxNum(int slotSyncPublisherMaxNum) { + this.slotSyncPublisherMaxNum = slotSyncPublisherMaxNum; + } + + /** + * Getter method for property schedulerScanVersionIntervalMs. + * + * @return property value of schedulerScanVersionIntervalMs + */ + @Override + public int getSchedulerScanVersionIntervalMillis() { + return schedulerScanVersionIntervalMillis; + } + + /** + * Setter method for property schedulerScanVersionIntervalMs. + * + * @param schedulerScanVersionIntervalMs value to be assigned to property + * schedulerScanVersionIntervalMs + */ + public void setSchedulerFetchDataVersionIntervalMs(int schedulerScanVersionIntervalMs) { + this.schedulerScanVersionIntervalMillis = schedulerScanVersionIntervalMs; + } + + public int getSlotSyncMaxBufferSize() { + return slotSyncMaxBufferSize; + } + + public void setSlotSyncMaxBufferSize(int slotSyncMaxBufferSize) { + this.slotSyncMaxBufferSize = slotSyncMaxBufferSize; + } + + public int getSlotSyncWorkerSize() { + return slotSyncWorkerSize; + } + + @Override + public int getCacheDigestIntervalMinutes() { + return cacheDigestIntervalMinutes; + } + + public void setCacheDigestIntervalMinutes(int cacheDigestIntervalMinutes) { + this.cacheDigestIntervalMinutes = cacheDigestIntervalMinutes; + } + + public void setSlotSyncWorkerSize(int slotSyncWorkerSize) { + this.slotSyncWorkerSize = slotSyncWorkerSize; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); + } + + public boolean isEnableSessionLoadbalancePolicy() { + return enableSessionLoadbalancePolicy; + } + + public void setEnableSessionLoadbalancePolicy(boolean enableSessionLoadbalancePolicy) { + this.enableSessionLoadbalancePolicy = enableSessionLoadbalancePolicy; + } + + @Override + public int getDataNodeExecutorWorkerSize() { + return dataNodeExecutorWorkerSize; + } + + public void setDataNodeExecutorWorkerSize(int dataNodeExecutorWorkerSize) { + this.dataNodeExecutorWorkerSize = dataNodeExecutorWorkerSize; + } + + @Override + public int getDataNodeExecutorQueueSize() { + return dataNodeExecutorQueueSize; + } + + public void setDataNodeExecutorQueueSize(int dataNodeExecutorQueueSize) { + this.dataNodeExecutorQueueSize = dataNodeExecutorQueueSize; + } + + @Override + public int getDataNodeRetryBackoffMillis() { + return dataNodeRetryBackoffMillis; + } + + public void setDataNodeRetryBackoffMillis(int dataNodeRetryBackoffMillis) { + this.dataNodeRetryBackoffMillis = dataNodeRetryBackoffMillis; + } + + @Override + public int getDataNodeRetryTimes() { + return dataNodeRetryTimes; + } + + public void setDataNodeRetryTimes(int dataNodeRetryTimes) { + this.dataNodeRetryTimes = dataNodeRetryTimes; + } + + @Override + public int getDataNodeRetryQueueSize() { + return dataNodeRetryQueueSize; + } + + public void setDataNodeRetryQueueSize(int dataNodeRetryQueueSize) { + this.dataNodeRetryQueueSize = dataNodeRetryQueueSize; + } + + @Override + public int getDataNodeMaxBatchSize() { + return dataNodeMaxBatchSize; + } + + public void setDataNodeMaxBatchSize(int dataNodeMaxBatchSize) { + this.dataNodeMaxBatchSize = dataNodeMaxBatchSize; + } + + @Override + public int getCacheCountIntervalSecs() { + return cacheCountIntervalSecs; + } + + public void setCacheCountIntervalSecs(int cacheCountIntervalSecs) { + this.cacheCountIntervalSecs = cacheCountIntervalSecs; + } + + @Override + public int getCacheDatumMaxNums() { + return cacheDatumMaxNums; + } + + public void setCacheDatumMaxNums(int cacheDatumMaxNums) { + this.cacheDatumMaxNums = cacheDatumMaxNums; + } + + @Override + public int getCacheDatumExpireSecs() { + return cacheDatumExpireSecs; + } + + public void setCacheDatumExpireSecs(int cacheDatumExpireSecs) { + this.cacheDatumExpireSecs = cacheDatumExpireSecs; + } + + public int getAppRevisionGcSilenceHour() { + return silenceHour; + } + + /** + * Setter method for property silenceHour. + * + * @param silenceHour value to be assigned to property silenceHour + */ + public void setSilenceHour(int silenceHour) { + this.silenceHour = silenceHour; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfiguration.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfiguration.java index 1a0877ef6..4193f6bdb 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfiguration.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerConfiguration.java @@ -16,41 +16,8 @@ */ package com.alipay.sofa.registry.server.session.bootstrap; -import java.util.ArrayList; -import java.util.Collection; - import com.alipay.sofa.registry.jdbc.config.JdbcConfiguration; import com.alipay.sofa.registry.jraft.config.RaftConfiguration; -import com.alipay.sofa.registry.server.session.connections.ConnectionsService; -import com.alipay.sofa.registry.server.session.metadata.AppRevisionCacheRegistry; -import com.alipay.sofa.registry.server.session.metadata.AppRevisionHeartbeatRegistry; -import com.alipay.sofa.registry.server.session.node.repository.AppRevisionRaftRepository; -import com.alipay.sofa.registry.server.session.node.service.*; -import com.alipay.sofa.registry.server.session.push.ChangeProcessor; -import com.alipay.sofa.registry.server.session.push.FirePushService; -import com.alipay.sofa.registry.server.session.push.PushDataGenerator; -import com.alipay.sofa.registry.server.session.push.PushProcessor; -import com.alipay.sofa.registry.server.session.remoting.handler.*; -import com.alipay.sofa.registry.server.session.resource.*; -import com.alipay.sofa.registry.server.session.scheduler.timertask.CacheCountTask; -import com.alipay.sofa.registry.server.session.scheduler.timertask.SessionCacheDigestTask; -import com.alipay.sofa.registry.server.session.strategy.*; -import com.alipay.sofa.registry.server.shared.meta.MetaServerManager; -import com.alipay.sofa.registry.server.shared.remoting.SlotTableChangeEventHandler; -import com.alipay.sofa.registry.server.shared.resource.MetricsResource; -import com.alipay.sofa.registry.server.shared.resource.SlotGenericResource; -import com.alipay.sofa.registry.store.api.driver.RepositoryConfig; -import com.alipay.sofa.registry.store.api.driver.RepositoryManager; -import com.alipay.sofa.registry.store.api.repository.AppRevisionRepository; -import org.glassfish.jersey.jackson.JacksonFeature; -import org.glassfish.jersey.server.ResourceConfig; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; -import org.springframework.context.annotation.Import; - import com.alipay.sofa.registry.remoting.bolt.exchange.BoltExchange; import com.alipay.sofa.registry.remoting.exchange.Exchange; import com.alipay.sofa.registry.remoting.exchange.NodeExchanger; @@ -61,6 +28,7 @@ import com.alipay.sofa.registry.server.session.cache.CacheService; import com.alipay.sofa.registry.server.session.cache.DatumCacheGenerator; import com.alipay.sofa.registry.server.session.cache.SessionCacheService; +import com.alipay.sofa.registry.server.session.connections.ConnectionsService; import com.alipay.sofa.registry.server.session.filter.DataIdMatchStrategy; import com.alipay.sofa.registry.server.session.filter.IPMatchStrategy; import com.alipay.sofa.registry.server.session.filter.ProcessFilter; @@ -68,31 +36,41 @@ import com.alipay.sofa.registry.server.session.limit.AccessLimitService; import com.alipay.sofa.registry.server.session.limit.AccessLimitServiceImpl; import com.alipay.sofa.registry.server.session.listener.*; +import com.alipay.sofa.registry.server.session.metadata.AppRevisionCacheRegistry; +import com.alipay.sofa.registry.server.session.metadata.AppRevisionHeartbeatRegistry; import com.alipay.sofa.registry.server.session.node.processor.ClientNodeSingleTaskProcessor; import com.alipay.sofa.registry.server.session.node.processor.ConsoleSyncSingleTaskProcessor; import com.alipay.sofa.registry.server.session.node.processor.DataNodeSingleTaskProcessor; import com.alipay.sofa.registry.server.session.node.processor.MetaNodeSingleTaskProcessor; +import com.alipay.sofa.registry.server.session.node.repository.AppRevisionRaftRepository; +import com.alipay.sofa.registry.server.session.node.service.*; import com.alipay.sofa.registry.server.session.provideData.ProvideDataProcessor; import com.alipay.sofa.registry.server.session.provideData.ProvideDataProcessorManager; import com.alipay.sofa.registry.server.session.provideData.processor.BlackListProvideDataProcessor; import com.alipay.sofa.registry.server.session.provideData.processor.StopPushProvideDataProcessor; +import com.alipay.sofa.registry.server.session.push.ChangeProcessor; +import com.alipay.sofa.registry.server.session.push.FirePushService; +import com.alipay.sofa.registry.server.session.push.PushDataGenerator; +import com.alipay.sofa.registry.server.session.push.PushProcessor; import com.alipay.sofa.registry.server.session.registry.Registry; import com.alipay.sofa.registry.server.session.registry.SessionRegistry; import com.alipay.sofa.registry.server.session.remoting.ClientNodeExchanger; import com.alipay.sofa.registry.server.session.remoting.DataNodeExchanger; +import com.alipay.sofa.registry.server.session.remoting.handler.*; +import com.alipay.sofa.registry.server.session.resource.*; import com.alipay.sofa.registry.server.session.scheduler.ExecutorManager; +import com.alipay.sofa.registry.server.session.scheduler.timertask.CacheCountTask; +import com.alipay.sofa.registry.server.session.scheduler.timertask.SessionCacheDigestTask; import com.alipay.sofa.registry.server.session.scheduler.timertask.SyncClientsHeartbeatTask; import com.alipay.sofa.registry.server.session.slot.SlotTableCache; import com.alipay.sofa.registry.server.session.slot.SlotTableCacheImpl; import com.alipay.sofa.registry.server.session.store.*; -import com.alipay.sofa.registry.server.shared.meta.MetaServerService; -import com.alipay.sofa.registry.server.shared.remoting.AbstractClientHandler; -import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; import com.alipay.sofa.registry.server.session.store.DataStore; import com.alipay.sofa.registry.server.session.store.Interests; import com.alipay.sofa.registry.server.session.store.SessionInterests; import com.alipay.sofa.registry.server.session.store.SessionWatchers; import com.alipay.sofa.registry.server.session.store.Watchers; +import com.alipay.sofa.registry.server.session.strategy.*; import com.alipay.sofa.registry.server.session.strategy.impl.DefaultPublisherHandlerStrategy; import com.alipay.sofa.registry.server.session.strategy.impl.DefaultReceivedConfigDataPushTaskStrategy; import com.alipay.sofa.registry.server.session.strategy.impl.DefaultSessionRegistryStrategy; @@ -104,649 +82,682 @@ import com.alipay.sofa.registry.server.session.wrapper.ClientCheckWrapperInterceptor; import com.alipay.sofa.registry.server.session.wrapper.WrapperInterceptor; import com.alipay.sofa.registry.server.session.wrapper.WrapperInterceptorManager; +import com.alipay.sofa.registry.server.shared.meta.MetaServerManager; +import com.alipay.sofa.registry.server.shared.meta.MetaServerService; +import com.alipay.sofa.registry.server.shared.remoting.AbstractClientHandler; +import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; +import com.alipay.sofa.registry.server.shared.remoting.SlotTableChangeEventHandler; +import com.alipay.sofa.registry.server.shared.resource.MetricsResource; +import com.alipay.sofa.registry.server.shared.resource.SlotGenericResource; +import com.alipay.sofa.registry.store.api.driver.RepositoryConfig; +import com.alipay.sofa.registry.store.api.driver.RepositoryManager; +import com.alipay.sofa.registry.store.api.repository.AppRevisionRepository; import com.alipay.sofa.registry.task.batcher.TaskProcessor; import com.alipay.sofa.registry.task.listener.DefaultTaskListenerManager; import com.alipay.sofa.registry.task.listener.TaskListener; import com.alipay.sofa.registry.task.listener.TaskListenerManager; import com.alipay.sofa.registry.util.PropertySplitter; +import java.util.ArrayList; +import java.util.Collection; +import org.glassfish.jersey.jackson.JacksonFeature; +import org.glassfish.jersey.server.ResourceConfig; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.DependsOn; +import org.springframework.context.annotation.Import; /** * @author shangyu.wh * @version $Id: SessionServerConfiguration.java, v 0.1 2017-11-14 11:39 synex Exp $ */ @Configuration -@Import({ SessionServerInitializer.class, JdbcConfiguration.class, RaftConfiguration.class }) +@Import({SessionServerInitializer.class, JdbcConfiguration.class, RaftConfiguration.class}) @EnableConfigurationProperties public class SessionServerConfiguration { + @Bean + @ConditionalOnMissingBean + public SessionServerBootstrap sessionServerBootstrap() { + return new SessionServerBootstrap(); + } + + @Configuration + public static class SessionServerConfigBeanConfiguration { + @Bean + public CommonConfig commonConfig() { + return new CommonConfig(); + } + + @Bean + @ConditionalOnMissingBean + public SessionServerConfig sessionServerConfig(CommonConfig commonConfig) { + return new SessionServerConfigBean(commonConfig); + } + + @Bean(name = "PropertySplitter") + public PropertySplitter propertySplitter() { + return new PropertySplitter(); + } + } + + @Configuration + public static class SessionRemotingConfiguration { + + @Bean + @ConditionalOnMissingBean(name = "boltExchange") + public Exchange boltExchange() { + return new BoltExchange(); + } + + @Bean + public Exchange jerseyExchange() { + return new JerseyExchange(); + } + + @Bean + public NodeExchanger clientNodeExchanger() { + return new ClientNodeExchanger(); + } + + @Bean + public DataNodeExchanger dataNodeExchanger() { + return new DataNodeExchanger(); + } + + @Bean + public MetaServerManager metaServerManager() { + return new SessionMetaServerManager(); + } + + @Bean + public SlotTableCache slotTableCache() { + return new SlotTableCacheImpl(); + } + + @Bean(name = "serverHandlers") + public Collection serverHandlers() { + Collection list = new ArrayList<>(); + list.add(publisherHandler()); + list.add(subscriberHandler()); + list.add(watcherHandler()); + list.add(clientNodeConnectionHandler()); + list.add(cancelAddressRequestHandler()); + list.add(syncConfigHandler()); + list.add(publisherPbHandler()); + list.add(subscriberPbHandler()); + list.add(syncConfigPbHandler()); + list.add(metadataRegisterPbHandler()); + list.add(serviceAppMappingHandler()); + list.add(metaRevisionHeartbeatHandler()); + list.add(getRevisionHandler()); + + return list; + } + + @Bean(name = "sessionSyncHandlers") + public Collection serverSyncHandlers() { + Collection list = new ArrayList<>(); + list.add(dataSlotDiffDigestRequestHandler()); + list.add(dataSlotDiffPublisherRequestHandler()); + return list; + } + + @Bean + public AbstractServerHandler publisherHandler() { + return new PublisherHandler(); + } + + @Bean + public AbstractServerHandler syncConfigHandler() { + return new SyncConfigHandler(); + } + + @Bean + public AbstractServerHandler subscriberHandler() { + return new SubscriberHandler(); + } + + @Bean + public AbstractServerHandler watcherHandler() { + return new WatcherHandler(); + } + + @Bean + public AbstractServerHandler clientNodeConnectionHandler() { + return new ClientNodeConnectionHandler(); + } + + @Bean + public AbstractServerHandler cancelAddressRequestHandler() { + return new CancelAddressRequestHandler(); + } + + @Bean + public AbstractServerHandler dataSlotDiffDigestRequestHandler() { + return new DataSlotDiffDigestRequestHandler(); + } + + @Bean + public AbstractServerHandler dataSlotDiffPublisherRequestHandler() { + return new DataSlotDiffPublisherRequestHandler(); + } + + @Bean + public AbstractServerHandler publisherPbHandler() { + return new PublisherPbHandler(); + } + + @Bean + public AbstractServerHandler metadataRegisterPbHandler() { + return new MetadataRegisterPbHandler(); + } + + @Bean + public AbstractServerHandler serviceAppMappingHandler() { + return new ServiceAppMappingPbHandler(); + } + + @Bean + public AbstractServerHandler getRevisionHandler() { + return new GetRevisionPbHandler(); + } + + @Bean + public AbstractServerHandler metaRevisionHeartbeatHandler() { + return new MetaRevisionHeartbeatPbHandler(); + } + + @Bean + public AbstractServerHandler subscriberPbHandler() { + return new SubscriberPbHandler(); + } + + @Bean + public AbstractServerHandler syncConfigPbHandler() { + return new SyncConfigPbHandler(); + } + + @Bean(name = "dataClientHandlers") + public Collection dataClientHandlers() { + Collection list = new ArrayList<>(); + list.add(dataChangeRequestHandler()); + list.add(dataPushRequestHandler()); + return list; + } + + @Bean(name = "metaClientHandlers") + public Collection metaClientHandlers() { + Collection list = new ArrayList<>(); + list.add(metaNodeConnectionHandler()); + list.add(notifyProvideDataChangeHandler()); + list.add(loadbalanceMetricsHandler()); + list.add(configureLoadbalanceHandler()); + list.add(slotTableChangeEventHandler()); + return list; + } + + @Bean + public AbstractClientHandler metaNodeConnectionHandler() { + return new MetaNodeConnectionHandler(); + } + + @Bean + public AbstractClientHandler dataChangeRequestHandler() { + return new DataChangeRequestHandler(); + } + + @Bean + public AbstractClientHandler dataPushRequestHandler() { + return new DataPushRequestHandler(); + } + + @Bean + public AbstractClientHandler notifyProvideDataChangeHandler() { + return new NotifyProvideDataChangeHandler(); + } + + @Bean + public AbstractClientHandler loadbalanceMetricsHandler() { + return new LoadbalanceMetricsHandler(); + } + + @Bean + public AbstractClientHandler configureLoadbalanceHandler() { + return new ConfigureLoadbalanceHandler(); + } + + @Bean + public SlotTableChangeEventHandler slotTableChangeEventHandler() { + return new SlotTableChangeEventHandler(); + } + } + + @Configuration + public static class ResourceConfiguration { + + @Bean + public ResourceConfig jerseyResourceConfig() { + ResourceConfig resourceConfig = new ResourceConfig(); + resourceConfig.register(JacksonFeature.class); + return resourceConfig; + } + + @Bean + @ConditionalOnMissingBean(name = "sessionOpenResource") + public SessionOpenResource sessionOpenResource() { + return new SessionOpenResource(); + } + + @Bean + public SessionDigestResource sessionDigestResource() { + return new SessionDigestResource(); + } + + @Bean + @ConditionalOnMissingBean(name = "healthResource") + public HealthResource healthResource() { + return new HealthResource(); + } + + @Bean + public ClientsOpenResource clientsOpenResource() { + return new ClientsOpenResource(); + } + + @Bean + public ConnectionsResource connectionsResource() { + return new ConnectionsResource(); + } + + @Bean + public SlotGenericResource slotGenericResource() { + return new SlotGenericResource(); + } + + @Bean + public MetricsResource metricsResource() { + return new MetricsResource(); + } + } + + @Configuration + public static class SessionRegistryConfiguration { + @Bean + @ConditionalOnMissingBean(name = "sessionRegistry") + public Registry sessionRegistry() { + return new SessionRegistry(); + } + + @Bean + @ConditionalOnMissingBean + public Interests sessionInterests() { + return new SessionInterests(); + } + + @Bean + @ConditionalOnMissingBean + public Watchers sessionWatchers() { + return new SessionWatchers(); + } + + @Bean + @ConditionalOnMissingBean + public DataStore sessionDataStore() { + return new SlotSessionDataStore(); + } + } + + @Configuration + public static class SessionNodeConfiguration { + + @Bean + @ConditionalOnMissingBean + public DataNodeService dataNodeService() { + return new DataNodeServiceImpl(); + } + + @Bean + @ConditionalOnMissingBean + public MetaServerService metaServerService() { + return new MetaServerServiceImpl(); + } + + @Bean + @ConditionalOnMissingBean + public ClientNodeService clientNodeService() { + return new ClientNodeServiceImpl(); + } + + @Bean + public AppRevisionNodeService appRevisionNodeService() { + return new AppRevisionNodeServiceImpl(); + } + + @Bean + @ConditionalOnMissingBean + public FirePushService firePushService() { + return new FirePushService(); + } + + @Bean + @ConditionalOnMissingBean + public PushProcessor pushProcessor() { + return new PushProcessor(); + } + + @Bean + @ConditionalOnMissingBean + public ChangeProcessor changeProcessor() { + return new ChangeProcessor(); + } + @Bean @ConditionalOnMissingBean - public SessionServerBootstrap sessionServerBootstrap() { - return new SessionServerBootstrap(); - } - - @Configuration - public static class SessionServerConfigBeanConfiguration { - @Bean - public CommonConfig commonConfig() { - return new CommonConfig(); - } - - @Bean - @ConditionalOnMissingBean - public SessionServerConfig sessionServerConfig(CommonConfig commonConfig) { - return new SessionServerConfigBean(commonConfig); - } - - @Bean(name = "PropertySplitter") - public PropertySplitter propertySplitter() { - return new PropertySplitter(); - } - - } - - @Configuration - public static class SessionRemotingConfiguration { - - @Bean - @ConditionalOnMissingBean(name = "boltExchange") - public Exchange boltExchange() { - return new BoltExchange(); - } - - @Bean - public Exchange jerseyExchange() { - return new JerseyExchange(); - } - - @Bean - public NodeExchanger clientNodeExchanger() { - return new ClientNodeExchanger(); - } - - @Bean - public DataNodeExchanger dataNodeExchanger() { - return new DataNodeExchanger(); - } - - @Bean - public MetaServerManager metaServerManager() { - return new SessionMetaServerManager(); - } - - @Bean - public SlotTableCache slotTableCache() { - return new SlotTableCacheImpl(); - } - - @Bean(name = "serverHandlers") - public Collection serverHandlers() { - Collection list = new ArrayList<>(); - list.add(publisherHandler()); - list.add(subscriberHandler()); - list.add(watcherHandler()); - list.add(clientNodeConnectionHandler()); - list.add(cancelAddressRequestHandler()); - list.add(syncConfigHandler()); - list.add(publisherPbHandler()); - list.add(subscriberPbHandler()); - list.add(syncConfigPbHandler()); - list.add(metadataRegisterPbHandler()); - list.add(serviceAppMappingHandler()); - list.add(metaRevisionHeartbeatHandler()); - list.add(getRevisionHandler()); - - return list; - } - - @Bean(name = "sessionSyncHandlers") - public Collection serverSyncHandlers() { - Collection list = new ArrayList<>(); - list.add(dataSlotDiffDigestRequestHandler()); - list.add(dataSlotDiffPublisherRequestHandler()); - return list; - } - - @Bean - public AbstractServerHandler publisherHandler() { - return new PublisherHandler(); - } - - @Bean - public AbstractServerHandler syncConfigHandler() { - return new SyncConfigHandler(); - } - - @Bean - public AbstractServerHandler subscriberHandler() { - return new SubscriberHandler(); - } - - @Bean - public AbstractServerHandler watcherHandler() { - return new WatcherHandler(); - } - - @Bean - public AbstractServerHandler clientNodeConnectionHandler() { - return new ClientNodeConnectionHandler(); - } - - @Bean - public AbstractServerHandler cancelAddressRequestHandler() { - return new CancelAddressRequestHandler(); - } - - @Bean - public AbstractServerHandler dataSlotDiffDigestRequestHandler() { - return new DataSlotDiffDigestRequestHandler(); - } - - @Bean - public AbstractServerHandler dataSlotDiffPublisherRequestHandler() { - return new DataSlotDiffPublisherRequestHandler(); - } - - @Bean - public AbstractServerHandler publisherPbHandler() { - return new PublisherPbHandler(); - } - - @Bean - public AbstractServerHandler metadataRegisterPbHandler() { - return new MetadataRegisterPbHandler(); - } - - @Bean - public AbstractServerHandler serviceAppMappingHandler() { - return new ServiceAppMappingPbHandler(); - } - - @Bean - public AbstractServerHandler getRevisionHandler() { - return new GetRevisionPbHandler(); - } - - @Bean - public AbstractServerHandler metaRevisionHeartbeatHandler() { - return new MetaRevisionHeartbeatPbHandler(); - } - - @Bean - public AbstractServerHandler subscriberPbHandler() { - return new SubscriberPbHandler(); - } - - @Bean - public AbstractServerHandler syncConfigPbHandler() { - return new SyncConfigPbHandler(); - } - - @Bean(name = "dataClientHandlers") - public Collection dataClientHandlers() { - Collection list = new ArrayList<>(); - list.add(dataChangeRequestHandler()); - list.add(dataPushRequestHandler()); - return list; - } - - @Bean(name = "metaClientHandlers") - public Collection metaClientHandlers() { - Collection list = new ArrayList<>(); - list.add(metaNodeConnectionHandler()); - list.add(notifyProvideDataChangeHandler()); - list.add(loadbalanceMetricsHandler()); - list.add(configureLoadbalanceHandler()); - list.add(slotTableChangeEventHandler()); - return list; - } - - @Bean - public AbstractClientHandler metaNodeConnectionHandler() { - return new MetaNodeConnectionHandler(); - } - - @Bean - public AbstractClientHandler dataChangeRequestHandler() { - return new DataChangeRequestHandler(); - } - - @Bean - public AbstractClientHandler dataPushRequestHandler() { - return new DataPushRequestHandler(); - } - - @Bean - public AbstractClientHandler notifyProvideDataChangeHandler() { - return new NotifyProvideDataChangeHandler(); - } - - @Bean - public AbstractClientHandler loadbalanceMetricsHandler() { - return new LoadbalanceMetricsHandler(); - } - - @Bean - public AbstractClientHandler configureLoadbalanceHandler() { - return new ConfigureLoadbalanceHandler(); - } - - @Bean - public SlotTableChangeEventHandler slotTableChangeEventHandler() { - return new SlotTableChangeEventHandler(); - } - } - - @Configuration - public static class ResourceConfiguration { - - @Bean - public ResourceConfig jerseyResourceConfig() { - ResourceConfig resourceConfig = new ResourceConfig(); - resourceConfig.register(JacksonFeature.class); - return resourceConfig; - } - - @Bean - @ConditionalOnMissingBean(name = "sessionOpenResource") - public SessionOpenResource sessionOpenResource() { - return new SessionOpenResource(); - } - - @Bean - public SessionDigestResource sessionDigestResource() { - return new SessionDigestResource(); - } - - @Bean - @ConditionalOnMissingBean(name = "healthResource") - public HealthResource healthResource() { - return new HealthResource(); - } - - @Bean - public ClientsOpenResource clientsOpenResource() { - return new ClientsOpenResource(); - } - - @Bean - public ConnectionsResource connectionsResource() { - return new ConnectionsResource(); - } - - @Bean - public SlotGenericResource slotGenericResource() { - return new SlotGenericResource(); - } - - @Bean - public MetricsResource metricsResource() { - return new MetricsResource(); - } - } - - @Configuration - public static class SessionRegistryConfiguration { - @Bean - @ConditionalOnMissingBean(name = "sessionRegistry") - public Registry sessionRegistry() { - return new SessionRegistry(); - } - - @Bean - @ConditionalOnMissingBean - public Interests sessionInterests() { - return new SessionInterests(); - } - - @Bean - @ConditionalOnMissingBean - public Watchers sessionWatchers() { - return new SessionWatchers(); - } - - @Bean - @ConditionalOnMissingBean - public DataStore sessionDataStore() { - return new SlotSessionDataStore(); - } - } - - @Configuration - public static class SessionNodeConfiguration { - - @Bean - @ConditionalOnMissingBean - public DataNodeService dataNodeService() { - return new DataNodeServiceImpl(); - } - - @Bean - @ConditionalOnMissingBean - public MetaServerService metaServerService() { - return new MetaServerServiceImpl(); - } - - @Bean - @ConditionalOnMissingBean - public ClientNodeService clientNodeService() { - return new ClientNodeServiceImpl(); - } - - @Bean - public AppRevisionNodeService appRevisionNodeService() { - return new AppRevisionNodeServiceImpl(); - } - - @Bean - @ConditionalOnMissingBean - public FirePushService firePushService() { - return new FirePushService(); - } - - @Bean - @ConditionalOnMissingBean - public PushProcessor pushProcessor() { - return new PushProcessor(); - } - - @Bean - @ConditionalOnMissingBean - public ChangeProcessor changeProcessor() { - return new ChangeProcessor(); - } - - @Bean - @ConditionalOnMissingBean - public PushDataGenerator pushDataGenerator() { - return new PushDataGenerator(); - } - } - - @Configuration - public static class SessionCacheConfiguration { - - @Bean - public CacheService sessionCacheService() { - return new SessionCacheService(); - } - - @Bean(name = "com.alipay.sofa.registry.server.session.cache.DatumKey") - public CacheGenerator datumCacheGenerator() { - return new DatumCacheGenerator(); - } - - @Bean - @DependsOn({ "appRevisionJdbcRepository", "appRevisionRaftRepository", - "interfaceAppsJdbcRepository", "interfaceAppsRaftRepository" }) - public AppRevisionCacheRegistry appRevisionCacheRegistry(RepositoryManager repositoryManager) { - return new AppRevisionCacheRegistry(repositoryManager); - } - - @Bean - @DependsOn({ "appRevisionJdbcRepository", "appRevisionRaftRepository", - "appRevisionHeartbeatJdbcRepository", "appRevisionHeartbeatRaftRepository" }) - public AppRevisionHeartbeatRegistry appRevisionHeartbeatRegistry(RepositoryManager repositoryManager) { - return new AppRevisionHeartbeatRegistry(repositoryManager); - } - } - - @Configuration - public static class SessionTaskConfiguration { - - @Bean - public TaskProcessor dataNodeSingleTaskProcessor() { - return new DataNodeSingleTaskProcessor(); - } - - @Bean - public TaskProcessor metaNodeSingleTaskProcessor() { - return new MetaNodeSingleTaskProcessor(); - } - - @Bean - public TaskProcessor clientNodeSingleTaskProcessor() { - return new ClientNodeSingleTaskProcessor(); - } - - @Bean - public TaskProcessor consoleSyncSingleTaskProcessor() { - return new ConsoleSyncSingleTaskProcessor(); - } - - @Bean - public TaskListener watcherRegisterFetchTaskListener(TaskListenerManager taskListenerManager) { - TaskListener taskListener = new WatcherRegisterFetchTaskListener( - metaNodeSingleTaskProcessor()); - taskListenerManager.addTaskListener(taskListener); - return taskListener; - } - - @Bean - public TaskListener provideDataChangeFetchTaskListener(TaskListenerManager taskListenerManager) { - TaskListener taskListener = new ProvideDataChangeFetchTaskListener( - metaNodeSingleTaskProcessor()); - taskListenerManager.addTaskListener(taskListener); - return taskListener; - } - - @Bean - public TaskListener receivedConfigDataPushTaskListener(TaskListenerManager taskListenerManager) { - TaskListener taskListener = new ReceivedConfigDataPushTaskListener( - clientNodeSingleTaskProcessor()); - taskListenerManager.addTaskListener(taskListener); - return taskListener; - } - - @Bean - public TaskListenerManager taskListenerManager() { - return new DefaultTaskListenerManager(); - } - - } - - @Configuration - public static class ExecutorConfiguration { - - @Bean - public ExecutorManager executorManager(SessionServerConfig sessionServerConfig) { - return new ExecutorManager(sessionServerConfig); - } - - } - - @Configuration - public static class SessionTimerTaskConfiguration { - - @Bean - public SyncClientsHeartbeatTask syncClientsHeartbeatTask() { - return new SyncClientsHeartbeatTask(); - } - - @Bean - public SessionCacheDigestTask sessionCacheDigestTask() { - return new SessionCacheDigestTask(); - } - - @Bean - public CacheCountTask cacheCountTask() { - return new CacheCountTask(); - } - } - - @Configuration - public static class SessionStrategyConfiguration { - @Bean - @ConditionalOnMissingBean - public SessionRegistryStrategy sessionRegistryStrategy() { - return new DefaultSessionRegistryStrategy(); - } - - @Bean - @ConditionalOnMissingBean - public SyncConfigHandlerStrategy syncConfigHandlerStrategy() { - return new DefaultSyncConfigHandlerStrategy(); - } - - @Bean - @ConditionalOnMissingBean - public PublisherHandlerStrategy publisherHandlerStrategy() { - return new DefaultPublisherHandlerStrategy(); - } - - @Bean - @ConditionalOnMissingBean - public SubscriberHandlerStrategy subscriberHandlerStrategy() { - return new DefaultSubscriberHandlerStrategy(); - } - - @Bean - @ConditionalOnMissingBean - public WatcherHandlerStrategy watcherHandlerStrategy() { - return new DefaultWatcherHandlerStrategy(); - } - - @Bean - @ConditionalOnMissingBean - public ReceivedConfigDataPushTaskStrategy receivedConfigDataPushTaskStrategy() { - return new DefaultReceivedConfigDataPushTaskStrategy(); - } - - @Bean - public AppRevisionHandlerStrategy appRevisionHandlerStrategy() { - return new DefaultAppRevisionHandlerStrategy(); - } - } - - @Configuration - public static class AccessLimitServiceConfiguration { - @Bean - public AccessLimitService accessLimitService(SessionServerConfig sessionServerConfig) { - return new AccessLimitServiceImpl(sessionServerConfig); - } - } - - @Configuration - public static class SessionFilterConfiguration { - - @Bean - public IPMatchStrategy ipMatchStrategy() { - return new DefaultIPMatchStrategy(); - } - - @Bean - public DataIdMatchStrategy dataIdMatchStrategy() { - return new DefaultDataIdMatchStrategy(); - } - - @Bean - @ConditionalOnMissingBean - public ProcessFilter processFilter() { - return new BlacklistMatchProcessFilter(); - } - - @Bean - public BlacklistManager blacklistManager() { - return new BlacklistManagerImpl(); - } - - @Bean - public WrapperInterceptorManager wrapperInterceptorManager() { - return new WrapperInterceptorManager(); - } - - @Bean - public WrapperInterceptor clientCheckWrapperInterceptor(WrapperInterceptorManager wrapperInterceptorManager) { - ClientCheckWrapperInterceptor clientCheckWrapperInterceptor = new ClientCheckWrapperInterceptor(); - wrapperInterceptorManager.addInterceptor(clientCheckWrapperInterceptor); - return clientCheckWrapperInterceptor; - } - - @Bean - public WrapperInterceptor blacklistWrapperInterceptor(WrapperInterceptorManager wrapperInterceptorManager) { - BlacklistWrapperInterceptor blacklistWrapperInterceptor = new BlacklistWrapperInterceptor(); - wrapperInterceptorManager.addInterceptor(blacklistWrapperInterceptor); - return blacklistWrapperInterceptor; - } - - @Bean - public WrapperInterceptor accessLimitWrapperInterceptor(WrapperInterceptorManager wrapperInterceptorManager) { - AccessLimitWrapperInterceptor accessLimitWrapperInterceptor = new AccessLimitWrapperInterceptor(); - wrapperInterceptorManager.addInterceptor(accessLimitWrapperInterceptor); - return accessLimitWrapperInterceptor; - } - - } - - @Configuration - public static class SessionRenewDatumConfiguration { - - @Bean - public WriteDataAcceptor writeDataAcceptor() { - return new WriteDataAcceptorImpl(); - } - } - - @Configuration - public static class SessionConnectionsConfiguration { - @Bean - public ConnectionsService connectionsService() { - return new ConnectionsService(); - } - } - - @Configuration - public static class SessionProvideDataConfiguration { - - @Bean - public ProvideDataProcessor provideDataProcessorManager() { - return new ProvideDataProcessorManager(); - } - - @Bean - public ProvideDataProcessor blackListProvideDataProcessor(ProvideDataProcessor provideDataProcessorManager) { - ProvideDataProcessor blackListProvideDataProcessor = new BlackListProvideDataProcessor(); - ((ProvideDataProcessorManager) provideDataProcessorManager) - .addProvideDataProcessor(blackListProvideDataProcessor); - return blackListProvideDataProcessor; - } - - @Bean - public ProvideDataProcessor stopPushProvideDataProcessor(ProvideDataProcessor provideDataProcessorManager) { - ProvideDataProcessor stopPushProvideDataProcessor = new StopPushProvideDataProcessor(); - ((ProvideDataProcessorManager) provideDataProcessorManager) - .addProvideDataProcessor(stopPushProvideDataProcessor); - return stopPushProvideDataProcessor; - } - } - - @Configuration - public static class SessionPersistenceConfiguration { - - @Bean - public RepositoryConfig repositoryConfig() { - return new RepositoryConfig(); - } - - @Bean - public RepositoryManager repositoryManager() { - return new RepositoryManager(); - } - - @Bean - public JdbcConfiguration jdbcConfiguration() { - return new JdbcConfiguration(); - } - - @Bean - public AppRevisionRepository appRevisionRaftRepository() { - return new AppRevisionRaftRepository(); - } - - @Bean - public RaftConfiguration raftConfiguration() { - return new RaftConfiguration(); - } - } - -} \ No newline at end of file + public PushDataGenerator pushDataGenerator() { + return new PushDataGenerator(); + } + } + + @Configuration + public static class SessionCacheConfiguration { + + @Bean + public CacheService sessionCacheService() { + return new SessionCacheService(); + } + + @Bean(name = "com.alipay.sofa.registry.server.session.cache.DatumKey") + public CacheGenerator datumCacheGenerator() { + return new DatumCacheGenerator(); + } + + @Bean + @DependsOn({ + "appRevisionJdbcRepository", + "appRevisionRaftRepository", + "interfaceAppsJdbcRepository", + "interfaceAppsRaftRepository" + }) + public AppRevisionCacheRegistry appRevisionCacheRegistry(RepositoryManager repositoryManager) { + return new AppRevisionCacheRegistry(repositoryManager); + } + + @Bean + @DependsOn({ + "appRevisionJdbcRepository", + "appRevisionRaftRepository", + "appRevisionHeartbeatJdbcRepository", + "appRevisionHeartbeatRaftRepository" + }) + public AppRevisionHeartbeatRegistry appRevisionHeartbeatRegistry( + RepositoryManager repositoryManager) { + return new AppRevisionHeartbeatRegistry(repositoryManager); + } + } + + @Configuration + public static class SessionTaskConfiguration { + + @Bean + public TaskProcessor dataNodeSingleTaskProcessor() { + return new DataNodeSingleTaskProcessor(); + } + + @Bean + public TaskProcessor metaNodeSingleTaskProcessor() { + return new MetaNodeSingleTaskProcessor(); + } + + @Bean + public TaskProcessor clientNodeSingleTaskProcessor() { + return new ClientNodeSingleTaskProcessor(); + } + + @Bean + public TaskProcessor consoleSyncSingleTaskProcessor() { + return new ConsoleSyncSingleTaskProcessor(); + } + + @Bean + public TaskListener watcherRegisterFetchTaskListener(TaskListenerManager taskListenerManager) { + TaskListener taskListener = + new WatcherRegisterFetchTaskListener(metaNodeSingleTaskProcessor()); + taskListenerManager.addTaskListener(taskListener); + return taskListener; + } + + @Bean + public TaskListener provideDataChangeFetchTaskListener( + TaskListenerManager taskListenerManager) { + TaskListener taskListener = + new ProvideDataChangeFetchTaskListener(metaNodeSingleTaskProcessor()); + taskListenerManager.addTaskListener(taskListener); + return taskListener; + } + + @Bean + public TaskListener receivedConfigDataPushTaskListener( + TaskListenerManager taskListenerManager) { + TaskListener taskListener = + new ReceivedConfigDataPushTaskListener(clientNodeSingleTaskProcessor()); + taskListenerManager.addTaskListener(taskListener); + return taskListener; + } + + @Bean + public TaskListenerManager taskListenerManager() { + return new DefaultTaskListenerManager(); + } + } + + @Configuration + public static class ExecutorConfiguration { + + @Bean + public ExecutorManager executorManager(SessionServerConfig sessionServerConfig) { + return new ExecutorManager(sessionServerConfig); + } + } + + @Configuration + public static class SessionTimerTaskConfiguration { + + @Bean + public SyncClientsHeartbeatTask syncClientsHeartbeatTask() { + return new SyncClientsHeartbeatTask(); + } + + @Bean + public SessionCacheDigestTask sessionCacheDigestTask() { + return new SessionCacheDigestTask(); + } + + @Bean + public CacheCountTask cacheCountTask() { + return new CacheCountTask(); + } + } + + @Configuration + public static class SessionStrategyConfiguration { + @Bean + @ConditionalOnMissingBean + public SessionRegistryStrategy sessionRegistryStrategy() { + return new DefaultSessionRegistryStrategy(); + } + + @Bean + @ConditionalOnMissingBean + public SyncConfigHandlerStrategy syncConfigHandlerStrategy() { + return new DefaultSyncConfigHandlerStrategy(); + } + + @Bean + @ConditionalOnMissingBean + public PublisherHandlerStrategy publisherHandlerStrategy() { + return new DefaultPublisherHandlerStrategy(); + } + + @Bean + @ConditionalOnMissingBean + public SubscriberHandlerStrategy subscriberHandlerStrategy() { + return new DefaultSubscriberHandlerStrategy(); + } + + @Bean + @ConditionalOnMissingBean + public WatcherHandlerStrategy watcherHandlerStrategy() { + return new DefaultWatcherHandlerStrategy(); + } + + @Bean + @ConditionalOnMissingBean + public ReceivedConfigDataPushTaskStrategy receivedConfigDataPushTaskStrategy() { + return new DefaultReceivedConfigDataPushTaskStrategy(); + } + + @Bean + public AppRevisionHandlerStrategy appRevisionHandlerStrategy() { + return new DefaultAppRevisionHandlerStrategy(); + } + } + + @Configuration + public static class AccessLimitServiceConfiguration { + @Bean + public AccessLimitService accessLimitService(SessionServerConfig sessionServerConfig) { + return new AccessLimitServiceImpl(sessionServerConfig); + } + } + + @Configuration + public static class SessionFilterConfiguration { + + @Bean + public IPMatchStrategy ipMatchStrategy() { + return new DefaultIPMatchStrategy(); + } + + @Bean + public DataIdMatchStrategy dataIdMatchStrategy() { + return new DefaultDataIdMatchStrategy(); + } + + @Bean + @ConditionalOnMissingBean + public ProcessFilter processFilter() { + return new BlacklistMatchProcessFilter(); + } + + @Bean + public BlacklistManager blacklistManager() { + return new BlacklistManagerImpl(); + } + + @Bean + public WrapperInterceptorManager wrapperInterceptorManager() { + return new WrapperInterceptorManager(); + } + + @Bean + public WrapperInterceptor clientCheckWrapperInterceptor( + WrapperInterceptorManager wrapperInterceptorManager) { + ClientCheckWrapperInterceptor clientCheckWrapperInterceptor = + new ClientCheckWrapperInterceptor(); + wrapperInterceptorManager.addInterceptor(clientCheckWrapperInterceptor); + return clientCheckWrapperInterceptor; + } + + @Bean + public WrapperInterceptor blacklistWrapperInterceptor( + WrapperInterceptorManager wrapperInterceptorManager) { + BlacklistWrapperInterceptor blacklistWrapperInterceptor = new BlacklistWrapperInterceptor(); + wrapperInterceptorManager.addInterceptor(blacklistWrapperInterceptor); + return blacklistWrapperInterceptor; + } + + @Bean + public WrapperInterceptor accessLimitWrapperInterceptor( + WrapperInterceptorManager wrapperInterceptorManager) { + AccessLimitWrapperInterceptor accessLimitWrapperInterceptor = + new AccessLimitWrapperInterceptor(); + wrapperInterceptorManager.addInterceptor(accessLimitWrapperInterceptor); + return accessLimitWrapperInterceptor; + } + } + + @Configuration + public static class SessionRenewDatumConfiguration { + + @Bean + public WriteDataAcceptor writeDataAcceptor() { + return new WriteDataAcceptorImpl(); + } + } + + @Configuration + public static class SessionConnectionsConfiguration { + @Bean + public ConnectionsService connectionsService() { + return new ConnectionsService(); + } + } + + @Configuration + public static class SessionProvideDataConfiguration { + + @Bean + public ProvideDataProcessor provideDataProcessorManager() { + return new ProvideDataProcessorManager(); + } + + @Bean + public ProvideDataProcessor blackListProvideDataProcessor( + ProvideDataProcessor provideDataProcessorManager) { + ProvideDataProcessor blackListProvideDataProcessor = new BlackListProvideDataProcessor(); + ((ProvideDataProcessorManager) provideDataProcessorManager) + .addProvideDataProcessor(blackListProvideDataProcessor); + return blackListProvideDataProcessor; + } + + @Bean + public ProvideDataProcessor stopPushProvideDataProcessor( + ProvideDataProcessor provideDataProcessorManager) { + ProvideDataProcessor stopPushProvideDataProcessor = new StopPushProvideDataProcessor(); + ((ProvideDataProcessorManager) provideDataProcessorManager) + .addProvideDataProcessor(stopPushProvideDataProcessor); + return stopPushProvideDataProcessor; + } + } + + @Configuration + public static class SessionPersistenceConfiguration { + + @Bean + public RepositoryConfig repositoryConfig() { + return new RepositoryConfig(); + } + + @Bean + public RepositoryManager repositoryManager() { + return new RepositoryManager(); + } + + @Bean + public JdbcConfiguration jdbcConfiguration() { + return new JdbcConfiguration(); + } + + @Bean + public AppRevisionRepository appRevisionRaftRepository() { + return new AppRevisionRaftRepository(); + } + + @Bean + public RaftConfiguration raftConfiguration() { + return new RaftConfiguration(); + } + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerInitializer.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerInitializer.java index c3b07bf78..714e53b79 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerInitializer.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/bootstrap/SessionServerInitializer.java @@ -16,14 +16,12 @@ */ package com.alipay.sofa.registry.server.session.bootstrap; +import com.alipay.sofa.registry.log.Logger; +import com.alipay.sofa.registry.log.LoggerFactory; import java.util.concurrent.atomic.AtomicBoolean; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.SmartLifecycle; -import com.alipay.sofa.registry.log.Logger; -import com.alipay.sofa.registry.log.LoggerFactory; - /** * SmartLifecycle for SessionServerBootstrap * @@ -32,52 +30,50 @@ */ public class SessionServerInitializer implements SmartLifecycle { - private static final Logger LOGGER = LoggerFactory - .getLogger(SessionServerInitializer.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SessionServerInitializer.class); - @Autowired - private SessionServerBootstrap sessionServerBootstrap; + @Autowired private SessionServerBootstrap sessionServerBootstrap; - private AtomicBoolean running = new AtomicBoolean(false); + private AtomicBoolean running = new AtomicBoolean(false); - @Override - public boolean isAutoStartup() { - return true; - } + @Override + public boolean isAutoStartup() { + return true; + } - @Override - public void start() { - try { - sessionServerBootstrap.start(); - LOGGER.info("Started SessionServer"); + @Override + public void start() { + try { + sessionServerBootstrap.start(); + LOGGER.info("Started SessionServer"); - SessionServerInitializer.this.running.set(true); - } catch (Throwable ex) { - SessionServerInitializer.this.running.set(false); - LOGGER.error("Could not initialize Session server!", ex); - System.exit(-1); - } + SessionServerInitializer.this.running.set(true); + } catch (Throwable ex) { + SessionServerInitializer.this.running.set(false); + LOGGER.error("Could not initialize Session server!", ex); + System.exit(-1); } + } - @Override - public void stop() { - this.running.set(false); - sessionServerBootstrap.destroy(); - } + @Override + public void stop() { + this.running.set(false); + sessionServerBootstrap.destroy(); + } - @Override - public boolean isRunning() { - return this.running.get(); - } + @Override + public boolean isRunning() { + return this.running.get(); + } - @Override - public int getPhase() { - return 0; - } + @Override + public int getPhase() { + return 0; + } - @Override - public void stop(Runnable callback) { - callback.run(); - this.running.set(false); - } -} \ No newline at end of file + @Override + public void stop(Runnable callback) { + callback.run(); + this.running.set(false); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheAccessException.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheAccessException.java index a38122ab4..a42ceeb30 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheAccessException.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheAccessException.java @@ -18,24 +18,22 @@ /** * exception inner cache, e.g. remote invoke error - * + * * @author kezhu.wukz - * @version $Id: CacheAccessException.java, v 0.1 2019-09-02 17:55 kezhu.wukz - * Exp $ + * @version $Id: CacheAccessException.java, v 0.1 2019-09-02 17:55 kezhu.wukz Exp $ */ public class CacheAccessException extends RuntimeException { - public CacheAccessException() { - } + public CacheAccessException() {} - public CacheAccessException(String message) { - super(message); - } + public CacheAccessException(String message) { + super(message); + } - public CacheAccessException(String message, Throwable cause) { - super(message, cause); - } + public CacheAccessException(String message, Throwable cause) { + super(message, cause); + } - public CacheAccessException(Throwable cause) { - super(cause); - } -} \ No newline at end of file + public CacheAccessException(Throwable cause) { + super(cause); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheGenerator.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheGenerator.java index 13a17dcd7..636ef87b0 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheGenerator.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheGenerator.java @@ -17,18 +17,16 @@ package com.alipay.sofa.registry.server.session.cache; /** - * * @author shangyu.wh * @version $Id: CacheGenerator.java, v 0.1 2017-12-06 17:29 shangyu.wh Exp $ */ public interface CacheGenerator { - /** - * generator cache on write request - * - * @param key - * @return - */ - Value generatePayload(Key key); - -} \ No newline at end of file + /** + * generator cache on write request + * + * @param key + * @return + */ + Value generatePayload(Key key); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheService.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheService.java index 71f41abe1..c860f3c38 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheService.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/CacheService.java @@ -19,26 +19,27 @@ import java.util.Map; /** - * * @author shangyu.wh * @version $Id: CacheService.java, v 0.1 2017-12-06 20:19 shangyu.wh Exp $ */ public interface CacheService { - /** - * get cache by key - * @param key - * @return - */ - Value getValue(Key key) throws CacheAccessException; + /** + * get cache by key + * + * @param key + * @return + */ + Value getValue(Key key) throws CacheAccessException; - Value getValueIfPresent(Key key); + Value getValueIfPresent(Key key); - Map getValues(final Iterable keys) throws CacheAccessException; + Map getValues(final Iterable keys) throws CacheAccessException; - /** - * invalidate cache by keys - * @param keys - */ - void invalidate(Key... keys); -} \ No newline at end of file + /** + * invalidate cache by keys + * + * @param keys + */ + void invalidate(Key... keys); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/DatumCacheGenerator.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/DatumCacheGenerator.java index 881440772..d7feea82d 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/DatumCacheGenerator.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/DatumCacheGenerator.java @@ -28,32 +28,33 @@ * @version $Id: DatumCacheGenerator.java, v 0.1 2018-11-19 16:15 shangyu.wh Exp $ */ public class DatumCacheGenerator implements CacheGenerator { - private static final Logger LOGGER = LoggerFactory.getLogger("CACHE-GEN"); - /** - * DataNode service - */ - @Autowired - private DataNodeService dataNodeService; + private static final Logger LOGGER = LoggerFactory.getLogger("CACHE-GEN"); + /** DataNode service */ + @Autowired private DataNodeService dataNodeService; - @Override - public Value generatePayload(Key key) { - EntityType entityType = key.getEntityType(); - if (entityType instanceof DatumKey) { - DatumKey datumKey = (DatumKey) entityType; + @Override + public Value generatePayload(Key key) { + EntityType entityType = key.getEntityType(); + if (entityType instanceof DatumKey) { + DatumKey datumKey = (DatumKey) entityType; - final String dataCenter = datumKey.getDataCenter(); - final String dataInfoId = datumKey.getDataInfoId(); - ParaCheckUtil.checkNotBlank(dataCenter, "dataCenter"); - ParaCheckUtil.checkNotBlank(dataInfoId, "dataInfoId"); - SubDatum datum = dataNodeService.fetch(dataInfoId, dataCenter); - if (datum == null) { - LOGGER.info("loadNil,{},{}", dataInfoId, dataCenter); - } else { - LOGGER.info("load,{},{},{},{}", dataInfoId, dataCenter, datum.getPublishers() - .size(), datum.getVersion()); - } - return new Value(datum); - } - throw new IllegalArgumentException("unsupported key type:" + entityType); + final String dataCenter = datumKey.getDataCenter(); + final String dataInfoId = datumKey.getDataInfoId(); + ParaCheckUtil.checkNotBlank(dataCenter, "dataCenter"); + ParaCheckUtil.checkNotBlank(dataInfoId, "dataInfoId"); + SubDatum datum = dataNodeService.fetch(dataInfoId, dataCenter); + if (datum == null) { + LOGGER.info("loadNil,{},{}", dataInfoId, dataCenter); + } else { + LOGGER.info( + "load,{},{},{},{}", + dataInfoId, + dataCenter, + datum.getPublishers().size(), + datum.getVersion()); + } + return new Value(datum); } -} \ No newline at end of file + throw new IllegalArgumentException("unsupported key type:" + entityType); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/DatumKey.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/DatumKey.java index 7239f29c8..14a69e9d4 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/DatumKey.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/DatumKey.java @@ -19,67 +19,66 @@ import com.alipay.sofa.registry.common.model.store.WordCache; /** - * * @author shangyu.wh * @version $Id: DatumKey.java, v 0.1 2018-11-19 16:08 shangyu.wh Exp $ */ public class DatumKey implements EntityType { - private final String dataInfoId; + private final String dataInfoId; - private final String dataCenter; + private final String dataCenter; - public DatumKey(String dataInfoId, String dataCenter) { - this.dataInfoId = WordCache.getWordCache(dataInfoId); - this.dataCenter = WordCache.getWordCache(dataCenter); - } + public DatumKey(String dataInfoId, String dataCenter) { + this.dataInfoId = WordCache.getWordCache(dataInfoId); + this.dataCenter = WordCache.getWordCache(dataCenter); + } - @Override - public String getUniqueKey() { - StringBuilder sb = new StringBuilder(dataCenter); - sb.append(COMMA).append(dataInfoId); - return sb.toString(); - } + @Override + public String getUniqueKey() { + StringBuilder sb = new StringBuilder(dataCenter); + sb.append(COMMA).append(dataInfoId); + return sb.toString(); + } - @Override - public int hashCode() { - String hashKey = getUniqueKey(); - return hashKey.hashCode(); - } + @Override + public int hashCode() { + String hashKey = getUniqueKey(); + return hashKey.hashCode(); + } - @Override - public boolean equals(Object other) { - if (other instanceof DatumKey) { - return getUniqueKey().equals(((DatumKey) other).getUniqueKey()); - } else { - return false; - } + @Override + public boolean equals(Object other) { + if (other instanceof DatumKey) { + return getUniqueKey().equals(((DatumKey) other).getUniqueKey()); + } else { + return false; } + } - /** - * Getter method for property dataInfoId. - * - * @return property value of dataInfoId - */ - public String getDataInfoId() { - return dataInfoId; - } + /** + * Getter method for property dataInfoId. + * + * @return property value of dataInfoId + */ + public String getDataInfoId() { + return dataInfoId; + } - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("DatumKey{"); - sb.append("dataInfoId='").append(dataInfoId).append('\''); - sb.append(", dataCenter='").append(dataCenter).append('\''); - sb.append('}'); - return sb.toString(); - } -} \ No newline at end of file + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("DatumKey{"); + sb.append("dataInfoId='").append(dataInfoId).append('\''); + sb.append(", dataCenter='").append(dataCenter).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/EntityType.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/EntityType.java index 319df59ea..f08dc544a 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/EntityType.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/EntityType.java @@ -17,20 +17,18 @@ package com.alipay.sofa.registry.server.session.cache; /** - * * @author shangyu.wh * @version $Id: EntityType.java, v 0.1 2017-12-06 15:52 shangyu.wh Exp $ */ public interface EntityType { - /** symbol : */ - char COMMA = ','; + /** symbol : */ + char COMMA = ','; - /** - * cache contents uniqueKey,use for make up Key' hash code - * - * @return - */ - String getUniqueKey(); - -} \ No newline at end of file + /** + * cache contents uniqueKey,use for make up Key' hash code + * + * @return + */ + String getUniqueKey(); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/Key.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/Key.java index bc77f2e12..a5f243737 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/Key.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/Key.java @@ -26,63 +26,61 @@ */ public final class Key { - private final String entityName; - private final String hashKey; - private final EntityType entityType; + private final String entityName; + private final String hashKey; + private final EntityType entityType; - /** - * construct func - */ - public Key(String entityName, EntityType entityType) { - this.entityName = entityName; - this.entityType = entityType; - this.hashKey = this.entityName + this.entityType.getUniqueKey(); - } + /** construct func */ + public Key(String entityName, EntityType entityType) { + this.entityName = entityName; + this.entityType = entityType; + this.hashKey = this.entityName + this.entityType.getUniqueKey(); + } - /** - * Getter method for property entityName. - * - * @return property value of entityName - */ - public String getEntityName() { - return entityName; - } + /** + * Getter method for property entityName. + * + * @return property value of entityName + */ + public String getEntityName() { + return entityName; + } - /** - * Getter method for property hashKey. - * - * @return property value of hashKey - */ - public String getHashKey() { - return hashKey; - } + /** + * Getter method for property hashKey. + * + * @return property value of hashKey + */ + public String getHashKey() { + return hashKey; + } - /** - * Getter method for property entityType. - * - * @return property value of entityType - */ - public EntityType getEntityType() { - return entityType; - } + /** + * Getter method for property entityType. + * + * @return property value of entityType + */ + public EntityType getEntityType() { + return entityType; + } - @Override - public int hashCode() { - String hashKey = getHashKey(); - return hashKey.hashCode(); - } + @Override + public int hashCode() { + String hashKey = getHashKey(); + return hashKey.hashCode(); + } - @Override - public boolean equals(Object other) { - if (other instanceof Key) { - return getHashKey().equals(((Key) other).getHashKey()); - } else { - return false; - } + @Override + public boolean equals(Object other) { + if (other instanceof Key) { + return getHashKey().equals(((Key) other).getHashKey()); + } else { + return false; } + } - @Override - public String toString() { - return StringFormatter.format("Key{{}, type={}}", entityName, entityType); - } -} \ No newline at end of file + @Override + public String toString() { + return StringFormatter.format("Key{{}, type={}}", entityName, entityType); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/SessionCacheService.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/SessionCacheService.java index e2396baa0..70e9e02c2 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/SessionCacheService.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/SessionCacheService.java @@ -16,119 +16,113 @@ */ package com.alipay.sofa.registry.server.session.cache; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig; -import com.google.common.cache.*; -import org.springframework.beans.factory.annotation.Autowired; - import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; - +import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig; +import com.google.common.cache.*; +import java.util.Map; +import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: CacheService.java, v 0.1 2017-12-06 18:22 shangyu.wh Exp $ */ public class SessionCacheService implements CacheService { - private static final Logger CACHE_LOGGER = LoggerFactory.getLogger("CACHE-GEN"); - private static final Logger LOGGER = LoggerFactory - .getLogger(SessionCacheService.class); - - private LoadingCache readWriteCacheMap; - @Autowired - private SessionServerConfig sessionServerConfig; - /** - * injectQ - */ - private Map cacheGenerators; - - @PostConstruct - public void init() { - this.readWriteCacheMap = CacheBuilder.newBuilder() + private static final Logger CACHE_LOGGER = LoggerFactory.getLogger("CACHE-GEN"); + private static final Logger LOGGER = LoggerFactory.getLogger(SessionCacheService.class); + + private LoadingCache readWriteCacheMap; + @Autowired private SessionServerConfig sessionServerConfig; + /** injectQ */ + private Map cacheGenerators; + + @PostConstruct + public void init() { + this.readWriteCacheMap = + CacheBuilder.newBuilder() .maximumSize(sessionServerConfig.getCacheDatumMaxNums()) .expireAfterWrite(sessionServerConfig.getCacheDatumExpireSecs(), TimeUnit.SECONDS) - .removalListener(new RemoveListener()).build(new CacheLoader() { - @Override - public Value load(Key key) { + .removalListener(new RemoveListener()) + .build( + new CacheLoader() { + @Override + public Value load(Key key) { return generatePayload(key); - } - }); - } + } + }); + } - private final class RemoveListener implements RemovalListener { - - @Override - public void onRemoval(RemovalNotification notification) { - final RemovalCause cause = notification.getCause(); - if (cause == RemovalCause.SIZE || cause == RemovalCause.COLLECTED) { - Key key = notification.getKey(); - EntityType entityType = key.getEntityType(); - if (entityType instanceof DatumKey) { - DatumKey datumKey = (DatumKey) entityType; - CACHE_LOGGER.info("remove,{},{},{}", datumKey.getDataInfoId(), - datumKey.getDataCenter(), cause); - } - } - } - } - - private Value generatePayload(Key key) { - if (key == null || key.getEntityType() == null) { - throw new IllegalArgumentException("Generator key input error!"); - } - - EntityType entityType = key.getEntityType(); - CacheGenerator cacheGenerator = cacheGenerators.get(entityType.getClass().getName()); - return cacheGenerator.generatePayload(key); - } + private final class RemoveListener implements RemovalListener { @Override - public Value getValue(final Key key) throws CacheAccessException { - try { - return readWriteCacheMap.get(key); - } catch (Throwable e) { - String msg = "Cannot get value for key is:" + key; - throw new CacheAccessException(msg, e); + public void onRemoval(RemovalNotification notification) { + final RemovalCause cause = notification.getCause(); + if (cause == RemovalCause.SIZE || cause == RemovalCause.COLLECTED) { + Key key = notification.getKey(); + EntityType entityType = key.getEntityType(); + if (entityType instanceof DatumKey) { + DatumKey datumKey = (DatumKey) entityType; + CACHE_LOGGER.info( + "remove,{},{},{}", datumKey.getDataInfoId(), datumKey.getDataCenter(), cause); } + } } + } - @Override - public Value getValueIfPresent(Key key) { - return readWriteCacheMap.getIfPresent(key); + private Value generatePayload(Key key) { + if (key == null || key.getEntityType() == null) { + throw new IllegalArgumentException("Generator key input error!"); } - @Override - public Map getValues(final Iterable keys) throws CacheAccessException { - try { - return readWriteCacheMap.getAll(keys); - } catch (Throwable e) { - String msg = "Cannot get value for keys are:" + keys; - throw new CacheAccessException(msg, e); - } + EntityType entityType = key.getEntityType(); + CacheGenerator cacheGenerator = cacheGenerators.get(entityType.getClass().getName()); + return cacheGenerator.generatePayload(key); + } + + @Override + public Value getValue(final Key key) throws CacheAccessException { + try { + return readWriteCacheMap.get(key); + } catch (Throwable e) { + String msg = "Cannot get value for key is:" + key; + throw new CacheAccessException(msg, e); } - - @Override - public void invalidate(Key... keys) { - for (Key key : keys) { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("Invalidating cache key: {} {}", key.getEntityType(), - key.getEntityName()); - } - readWriteCacheMap.invalidate(key); - } + } + + @Override + public Value getValueIfPresent(Key key) { + return readWriteCacheMap.getIfPresent(key); + } + + @Override + public Map getValues(final Iterable keys) throws CacheAccessException { + try { + return readWriteCacheMap.getAll(keys); + } catch (Throwable e) { + String msg = "Cannot get value for keys are:" + keys; + throw new CacheAccessException(msg, e); } - - /** - * Setter method for property cacheGenerators. - * - * @param cacheGenerators value to be assigned to property cacheGenerators - */ - @Autowired - public void setCacheGenerators(Map cacheGenerators) { - this.cacheGenerators = cacheGenerators; + } + + @Override + public void invalidate(Key... keys) { + for (Key key : keys) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("Invalidating cache key: {} {}", key.getEntityType(), key.getEntityName()); + } + readWriteCacheMap.invalidate(key); } -} \ No newline at end of file + } + + /** + * Setter method for property cacheGenerators. + * + * @param cacheGenerators value to be assigned to property cacheGenerators + */ + @Autowired + public void setCacheGenerators(Map cacheGenerators) { + this.cacheGenerators = cacheGenerators; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/Value.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/Value.java index a867d24ae..f0f2c980a 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/Value.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/cache/Value.java @@ -24,22 +24,23 @@ */ public class Value { - private final T payload; + private final T payload; - /** - * constructor - * @param payload - */ - public Value(T payload) { - this.payload = payload; - } + /** + * constructor + * + * @param payload + */ + public Value(T payload) { + this.payload = payload; + } - /** - * Getter method for property payload. - * - * @return property value of payload - */ - public T getPayload() { - return payload; - } -} \ No newline at end of file + /** + * Getter method for property payload. + * + * @return property value of payload + */ + public T getPayload() { + return payload; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/connections/ConnectionsService.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/connections/ConnectionsService.java index 8ce93be83..725942f53 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/connections/ConnectionsService.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/connections/ConnectionsService.java @@ -26,67 +26,75 @@ import com.alipay.sofa.registry.server.session.store.DataStore; import com.alipay.sofa.registry.server.session.store.Interests; import com.alipay.sofa.registry.server.session.store.Watchers; -import org.springframework.beans.factory.annotation.Autowired; - import java.net.InetSocketAddress; import java.util.*; import java.util.stream.Collectors; +import org.springframework.beans.factory.annotation.Autowired; public class ConnectionsService { - private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionsResource.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionsResource.class); - @Autowired - private Exchange boltExchange; + @Autowired private Exchange boltExchange; - @Autowired - private DataStore sessionDataStore; + @Autowired private DataStore sessionDataStore; - @Autowired - private Interests sessionInterests; + @Autowired private Interests sessionInterests; - @Autowired - private Watchers sessionWatchers; + @Autowired private Watchers sessionWatchers; - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - public List getConnections() { - Server server = boltExchange.getServer(sessionServerConfig.getServerPort()); - Set boltConnectIds = server.getChannels().stream().map( - channel -> channel.getRemoteAddress().getAddress().getHostAddress() + ":" + channel.getRemoteAddress().getPort() - ).collect(Collectors.toSet()); - Set connectIds = new HashSet<>(); - connectIds.addAll(sessionDataStore.getConnectIds().stream().map(connectId -> connectId.clientAddress()).collect(Collectors.toList())); - connectIds.addAll(sessionInterests.getConnectIds().stream().map(connectId -> connectId.clientAddress()).collect(Collectors.toList())); - connectIds.addAll(sessionWatchers.getConnectIds().stream().map(connectId -> connectId.clientAddress()).collect(Collectors.toList())); - connectIds.retainAll(boltConnectIds); - return new ArrayList<>(connectIds); - } + public List getConnections() { + Server server = boltExchange.getServer(sessionServerConfig.getServerPort()); + Set boltConnectIds = + server.getChannels().stream() + .map( + channel -> + channel.getRemoteAddress().getAddress().getHostAddress() + + ":" + + channel.getRemoteAddress().getPort()) + .collect(Collectors.toSet()); + Set connectIds = new HashSet<>(); + connectIds.addAll( + sessionDataStore.getConnectIds().stream() + .map(connectId -> connectId.clientAddress()) + .collect(Collectors.toList())); + connectIds.addAll( + sessionInterests.getConnectIds().stream() + .map(connectId -> connectId.clientAddress()) + .collect(Collectors.toList())); + connectIds.addAll( + sessionWatchers.getConnectIds().stream() + .map(connectId -> connectId.clientAddress()) + .collect(Collectors.toList())); + connectIds.retainAll(boltConnectIds); + return new ArrayList<>(connectIds); + } - public void setMaxConnections(int connections) { - if (!sessionServerConfig.isEnableSessionLoadbalancePolicy()) { - throw new RuntimeException("drop connections is not allowed"); - } - List connectionIds = getConnections(); + public void setMaxConnections(int connections) { + if (!sessionServerConfig.isEnableSessionLoadbalancePolicy()) { + throw new RuntimeException("drop connections is not allowed"); + } + List connectionIds = getConnections(); - int needDropped = connectionIds.size() - connections; - if (needDropped <= 0) { - return; - } - Collections.shuffle(connectionIds); - connectionIds = connectionIds.subList(0, needDropped); - for (String ipAddress : connectionIds) { - Server server = boltExchange.getServer(sessionServerConfig.getServerPort()); - String[] parts = ipAddress.split(":"); - String host = parts[0]; - int port = Integer.parseInt(parts[1]); - InetSocketAddress address = new InetSocketAddress(host, port); - Channel connection = server.getChannel(address); - if (connection != null && connection.isConnected()) { - LOGGER.info("close connection {}", ipAddress); - server.close(connection); - } - } + int needDropped = connectionIds.size() - connections; + if (needDropped <= 0) { + return; + } + Collections.shuffle(connectionIds); + connectionIds = connectionIds.subList(0, needDropped); + for (String ipAddress : connectionIds) { + Server server = boltExchange.getServer(sessionServerConfig.getServerPort()); + String[] parts = ipAddress.split(":"); + String host = parts[0]; + int port = Integer.parseInt(parts[1]); + InetSocketAddress address = new InetSocketAddress(host, port); + Channel connection = server.getChannel(address); + if (connection != null && connection.isConnected()) { + LOGGER.info("close connection {}", ipAddress); + server.close(connection); + } } + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/AppRegisterConstant.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/AppRegisterConstant.java index 55e16b41e..26304e7c0 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/AppRegisterConstant.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/AppRegisterConstant.java @@ -17,19 +17,16 @@ package com.alipay.sofa.registry.server.session.converter; /** - * * @author xiaojian.xj - * @version $Id: AppRegisterConstant.java, v 0.1 2020年11月12日 15:47 xiaojian.xj - * Exp $ + * @version $Id: AppRegisterConstant.java, v 0.1 2020年11月12日 15:47 xiaojian.xj Exp $ */ public class AppRegisterConstant { - public static final String URL_KEY = "url"; + public static final String URL_KEY = "url"; - public static final String REVISION_KEY = "revision"; + public static final String REVISION_KEY = "revision"; - public static final String BASE_PARAMS_KEY = "baseParams"; + public static final String BASE_PARAMS_KEY = "baseParams"; - public static final String INTERFACE_PARAMS_KEY = "interfaceParams"; - -} \ No newline at end of file + public static final String INTERFACE_PARAMS_KEY = "interfaceParams"; +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/Converter.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/Converter.java index 698871dc6..0d834fc7c 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/Converter.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/Converter.java @@ -17,14 +17,11 @@ package com.alipay.sofa.registry.server.session.converter; /** - * * @author shangyu.wh * @version $Id: Converter.java, v 0.1 2017-11-29 11:55 shangyu.wh Exp $ - * - * source type - * target type + *

source type target type */ public interface Converter { - T convert(S source); -} \ No newline at end of file + T convert(S source); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/PublisherConverter.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/PublisherConverter.java index de9bdb149..3cdf98aa1 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/PublisherConverter.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/PublisherConverter.java @@ -23,71 +23,68 @@ import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.core.model.DataBox; import com.alipay.sofa.registry.core.model.PublisherRegister; - import java.util.ArrayList; import java.util.List; - /** * @author shangyu.wh * @version $Id: PublisherConvert.java, v 0.1 2017-11-30 17:54 shangyu.wh Exp $ */ public class PublisherConverter { - private static final Converter publisherConverter = source -> { + private static final Converter publisherConverter = + source -> { Publisher publisher = new Publisher(); fillCommonRegion(publisher, source); publisher.setDataList(convert(source.getDataList())); return publisher; - }; + }; + public static void fillCommonRegion(Publisher publisher, PublisherRegister source) { + publisher.setAppName(source.getAppName()); + // ZONE MUST BE CURRENT SESSION ZONE + publisher.setCell(source.getZone()); + publisher.setClientId(source.getClientId()); + publisher.setDataId(source.getDataId()); + publisher.setGroup(source.getGroup()); + publisher.setInstanceId(source.getInstanceId()); + publisher.setRegisterId(source.getRegistId()); + publisher.setProcessId(source.getProcessId()); + publisher.setVersion(source.getVersion()); - public static void fillCommonRegion(Publisher publisher, PublisherRegister source) { - publisher.setAppName(source.getAppName()); - //ZONE MUST BE CURRENT SESSION ZONE - publisher.setCell(source.getZone()); - publisher.setClientId(source.getClientId()); - publisher.setDataId(source.getDataId()); - publisher.setGroup(source.getGroup()); - publisher.setInstanceId(source.getInstanceId()); - publisher.setRegisterId(source.getRegistId()); - publisher.setProcessId(source.getProcessId()); - publisher.setVersion(source.getVersion()); + // registerTimestamp must happen from server,client time maybe different cause pub and + // unPublisher fail + publisher.setRegisterTimestamp(System.currentTimeMillis()); - //registerTimestamp must happen from server,client time maybe different cause pub and unPublisher fail - publisher.setRegisterTimestamp(System.currentTimeMillis()); + publisher.setClientRegisterTimestamp(source.getTimestamp()); + publisher.setSourceAddress(new URL(source.getIp(), source.getPort())); - publisher.setClientRegisterTimestamp(source.getTimestamp()); - publisher.setSourceAddress(new URL(source.getIp(), source.getPort())); + publisher.setClientVersion(ClientVersion.StoreData); - publisher.setClientVersion(ClientVersion.StoreData); + DataInfo dataInfo = new DataInfo(source.getInstanceId(), source.getDataId(), source.getGroup()); + publisher.setDataInfoId(dataInfo.getDataInfoId()); + } - DataInfo dataInfo = new DataInfo(source.getInstanceId(), source.getDataId(), - source.getGroup()); - publisher.setDataInfoId(dataInfo.getDataInfoId()); - } - - /** - * PublisherRegister to Publisher - * - * @param publisherRegister - * @return - */ - public static Publisher convert(PublisherRegister publisherRegister) { - return publisherConverter.convert(publisherRegister); - } + /** + * PublisherRegister to Publisher + * + * @param publisherRegister + * @return + */ + public static Publisher convert(PublisherRegister publisherRegister) { + return publisherConverter.convert(publisherRegister); + } - public static List convert(List boxList) { - List serverDataBoxes = new ArrayList<>(); - if (null != boxList) { - for (DataBox dataBox : boxList) { - ServerDataBox serverDataBox = new ServerDataBox(ServerDataBox.getBytes(dataBox - .getData())); - serverDataBoxes.add(serverDataBox); - } - } - return serverDataBoxes; + public static List convert(List boxList) { + List serverDataBoxes = new ArrayList<>(); + if (null != boxList) { + for (DataBox dataBox : boxList) { + ServerDataBox serverDataBox = new ServerDataBox(ServerDataBox.getBytes(dataBox.getData())); + serverDataBoxes.add(serverDataBox); + } } -} \ No newline at end of file + return serverDataBoxes; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/ReceivedDataConverter.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/ReceivedDataConverter.java index fb2e6a39a..5f640ce3d 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/ReceivedDataConverter.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/ReceivedDataConverter.java @@ -26,7 +26,6 @@ import com.alipay.sofa.registry.core.model.ScopeEnum; import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -40,97 +39,98 @@ * @version $Id : ReceivedDataConverter.java, v 0.1 2017-12-13 13:42 shangyu.wh Exp $ */ public class ReceivedDataConverter { - private static final Logger LOGGER = LoggerFactory.getLogger(ReceivedDataConverter.class); - - /** - * Standard RunEnv - * - * @param datum the datum - * @param scope the scope - * @param subscriberRegisterIdList the subscriber register id list - * @param regionLocal the region local - * @return received data multi - */ - public static ReceivedData getReceivedDataMulti(SubDatum datum, ScopeEnum scope, - List subscriberRegisterIdList, - String regionLocal, - Predicate zonePredicate) { - - if (null == datum) { - return null; - } - - // todo judge server mode to decide local region - ReceivedData receivedData = new ReceivedData(); - receivedData.setDataId(datum.getDataId()); - receivedData.setGroup(datum.getGroup()); - receivedData.setInstanceId(datum.getInstanceId()); - receivedData.setSubscriberRegistIds(subscriberRegisterIdList); - receivedData.setSegment(datum.getDataCenter()); - receivedData.setScope(scope.name()); - - receivedData.setVersion(datum.getVersion()); - - receivedData.setLocalZone(regionLocal); - - Map> swizzMap = new HashMap<>(); - - List publishers = datum.getPublishers(); - if (publishers.isEmpty()) { - receivedData.setData(swizzMap); - return receivedData; - } - for (SubPublisher publisher : publishers) { - List datas = publisher.getDataList(); - - String region = publisher.getCell(); - - if (zonePredicate.test(region)) { - continue; - } - - if (null == datas) { - datas = new ArrayList<>(); - } - - List regionDatas = swizzMap.computeIfAbsent(region, k -> new ArrayList<>()); - fillRegionDatas(regionDatas, datas); - - } - - receivedData.setData(swizzMap); - - return receivedData; + private static final Logger LOGGER = LoggerFactory.getLogger(ReceivedDataConverter.class); + + /** + * Standard RunEnv + * + * @param datum the datum + * @param scope the scope + * @param subscriberRegisterIdList the subscriber register id list + * @param regionLocal the region local + * @return received data multi + */ + public static ReceivedData getReceivedDataMulti( + SubDatum datum, + ScopeEnum scope, + List subscriberRegisterIdList, + String regionLocal, + Predicate zonePredicate) { + + if (null == datum) { + return null; } - private static void fillRegionDatas(List regionDatas, List datas) { - for (ServerDataBox data : datas) { - DataBox box = new DataBox(); - try { - String dataString = (String) data.extract(); - box.setData(dataString); - regionDatas.add(box); - } catch (Exception e) { - LOGGER.error("ReceivedData convert error", e); - } - } + // todo judge server mode to decide local region + ReceivedData receivedData = new ReceivedData(); + receivedData.setDataId(datum.getDataId()); + receivedData.setGroup(datum.getGroup()); + receivedData.setInstanceId(datum.getInstanceId()); + receivedData.setSubscriberRegistIds(subscriberRegisterIdList); + receivedData.setSegment(datum.getDataCenter()); + receivedData.setScope(scope.name()); + + receivedData.setVersion(datum.getVersion()); + + receivedData.setLocalZone(regionLocal); + + Map> swizzMap = new HashMap<>(); + + List publishers = datum.getPublishers(); + if (publishers.isEmpty()) { + receivedData.setData(swizzMap); + return receivedData; } + for (SubPublisher publisher : publishers) { + List datas = publisher.getDataList(); + + String region = publisher.getCell(); + + if (zonePredicate.test(region)) { + continue; + } + + if (null == datas) { + datas = new ArrayList<>(); + } + + List regionDatas = swizzMap.computeIfAbsent(region, k -> new ArrayList<>()); + fillRegionDatas(regionDatas, datas); + } + + receivedData.setData(swizzMap); + + return receivedData; + } + + private static void fillRegionDatas(List regionDatas, List datas) { + for (ServerDataBox data : datas) { + DataBox box = new DataBox(); + try { + String dataString = (String) data.extract(); + box.setData(dataString); + regionDatas.add(box); + } catch (Exception e) { + LOGGER.error("ReceivedData convert error", e); + } + } + } + + public static ReceivedConfigData getReceivedConfigData( + ServerDataBox dataBox, DataInfo dataInfo, Long version) { + ReceivedConfigData receivedConfigData = new ReceivedConfigData(); - public static ReceivedConfigData getReceivedConfigData(ServerDataBox dataBox, - DataInfo dataInfo, Long version) { - ReceivedConfigData receivedConfigData = new ReceivedConfigData(); - - if (dataBox != null) { - DataBox box = new DataBox(); - String dataString = (String) dataBox.getObject(); - box.setData(dataString); - receivedConfigData.setDataBox(box); - } - receivedConfigData.setDataId(dataInfo.getDataId()); - receivedConfigData.setGroup(dataInfo.getGroup()); - receivedConfigData.setInstanceId(dataInfo.getInstanceId()); - receivedConfigData.setVersion(version); - - return receivedConfigData; + if (dataBox != null) { + DataBox box = new DataBox(); + String dataString = (String) dataBox.getObject(); + box.setData(dataString); + receivedConfigData.setDataBox(box); } -} \ No newline at end of file + receivedConfigData.setDataId(dataInfo.getDataId()); + receivedConfigData.setGroup(dataInfo.getGroup()); + receivedConfigData.setInstanceId(dataInfo.getInstanceId()); + receivedConfigData.setVersion(version); + + return receivedConfigData; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/SubscriberConverter.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/SubscriberConverter.java index 55249ed91..d35384aa0 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/SubscriberConverter.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/SubscriberConverter.java @@ -27,81 +27,81 @@ /** * The type Subscriber converter. - * + * * @author shangyu.wh - * @version $Id : SubscriberConverter.java, v 0.1 2017-12-05 11:00 shangyu.wh - * Exp $ + * @version $Id : SubscriberConverter.java, v 0.1 2017-12-05 11:00 shangyu.wh Exp $ */ public class SubscriberConverter { - /** - * Convert subscriber. - * - * @param subscriberRegister - * the subscriber register - * @return the subscriber - */ - public static Subscriber convert(SubscriberRegister subscriberRegister) { + /** + * Convert subscriber. + * + * @param subscriberRegister the subscriber register + * @return the subscriber + */ + public static Subscriber convert(SubscriberRegister subscriberRegister) { - Converter converter = source -> { - Subscriber subscriber = new Subscriber(); + Converter converter = + source -> { + Subscriber subscriber = new Subscriber(); - subscriber.setAppName(source.getAppName()); - subscriber.setCell(source.getZone()); - subscriber.setClientId(source.getClientId()); - subscriber.setDataId(source.getDataId()); - subscriber.setGroup(source.getGroup()); - subscriber.setInstanceId(source.getInstanceId()); - subscriber.setRegisterId(source.getRegistId()); - subscriber.setProcessId(source.getProcessId()); - subscriber.setVersion(source.getVersion()); - subscriber.setRegisterTimestamp(System.currentTimeMillis()); - subscriber.setClientRegisterTimestamp(source.getTimestamp()); - subscriber.setScope(ScopeEnumConverter.convertToScope(source.getScope())); - subscriber.setSourceAddress(new URL(source.getIp(), source.getPort())); + subscriber.setAppName(source.getAppName()); + subscriber.setCell(source.getZone()); + subscriber.setClientId(source.getClientId()); + subscriber.setDataId(source.getDataId()); + subscriber.setGroup(source.getGroup()); + subscriber.setInstanceId(source.getInstanceId()); + subscriber.setRegisterId(source.getRegistId()); + subscriber.setProcessId(source.getProcessId()); + subscriber.setVersion(source.getVersion()); + subscriber.setRegisterTimestamp(System.currentTimeMillis()); + subscriber.setClientRegisterTimestamp(source.getTimestamp()); + subscriber.setScope(ScopeEnumConverter.convertToScope(source.getScope())); + subscriber.setSourceAddress(new URL(source.getIp(), source.getPort())); - subscriber.setClientVersion(ClientVersion.StoreData); + subscriber.setClientVersion(ClientVersion.StoreData); - DataInfo dataInfo = new DataInfo(source.getInstanceId(), source.getDataId(), - source.getGroup()); + DataInfo dataInfo = + new DataInfo(source.getInstanceId(), source.getDataId(), source.getGroup()); - subscriber.setDataInfoId(dataInfo.getDataInfoId()); + subscriber.setDataInfoId(dataInfo.getDataInfoId()); - return subscriber; + return subscriber; }; - return converter.convert(subscriberRegister); - } - /** - * Convert watcher. - * - * @param configuratorRegister - * @return - */ - public static Watcher convert(ConfiguratorRegister configuratorRegister) { - Converter converter = source -> { - Watcher watcher = new Watcher(); + return converter.convert(subscriberRegister); + } + /** + * Convert watcher. + * + * @param configuratorRegister + * @return + */ + public static Watcher convert(ConfiguratorRegister configuratorRegister) { + Converter converter = + source -> { + Watcher watcher = new Watcher(); - watcher.setAppName(source.getAppName()); - watcher.setCell(source.getZone()); - watcher.setClientId(source.getClientId()); - watcher.setDataId(source.getDataId()); - watcher.setGroup(source.getGroup()); - watcher.setInstanceId(source.getInstanceId()); - watcher.setRegisterId(source.getRegistId()); - watcher.setProcessId(source.getProcessId()); - watcher.setVersion(source.getVersion()); - watcher.setRegisterTimestamp(source.getTimestamp()); - watcher.setSourceAddress(new URL(source.getIp(), source.getPort())); + watcher.setAppName(source.getAppName()); + watcher.setCell(source.getZone()); + watcher.setClientId(source.getClientId()); + watcher.setDataId(source.getDataId()); + watcher.setGroup(source.getGroup()); + watcher.setInstanceId(source.getInstanceId()); + watcher.setRegisterId(source.getRegistId()); + watcher.setProcessId(source.getProcessId()); + watcher.setVersion(source.getVersion()); + watcher.setRegisterTimestamp(source.getTimestamp()); + watcher.setSourceAddress(new URL(source.getIp(), source.getPort())); - watcher.setClientVersion(ClientVersion.StoreData); + watcher.setClientVersion(ClientVersion.StoreData); - DataInfo dataInfo = new DataInfo(source.getInstanceId(), source.getDataId(), - source.getGroup()); + DataInfo dataInfo = + new DataInfo(source.getInstanceId(), source.getDataId(), source.getGroup()); - watcher.setDataInfoId(dataInfo.getDataInfoId()); + watcher.setDataInfoId(dataInfo.getDataInfoId()); - return watcher; + return watcher; }; - return converter.convert(configuratorRegister); - } -} \ No newline at end of file + return converter.convert(configuratorRegister); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/AppRevisionConvertor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/AppRevisionConvertor.java index 52a3c420b..942c54c9b 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/AppRevisionConvertor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/AppRevisionConvertor.java @@ -21,7 +21,6 @@ import com.alipay.sofa.registry.common.model.client.pb.StringList; import com.alipay.sofa.registry.common.model.store.AppRevision; import com.alipay.sofa.registry.core.model.AppRevisionInterface; - import java.util.HashMap; import java.util.List; import java.util.Map; @@ -29,52 +28,50 @@ import java.util.Optional; /** - * * @author xiaojian.xj - * @version $Id: AppRevisionConvertor.java, v 0.1 2021年02月04日 17:34 xiaojian.xj - * Exp $ + * @version $Id: AppRevisionConvertor.java, v 0.1 2021年02月04日 17:34 xiaojian.xj Exp $ */ public class AppRevisionConvertor { - public static AppRevision convert2Java(MetaRegister metaRegister) { + public static AppRevision convert2Java(MetaRegister metaRegister) { - AppRevision revision = new AppRevision(); - String appName = metaRegister.getApplication(); - revision.setAppName(appName); - revision.setRevision(metaRegister.getRevision()); - revision.setClientVersion(metaRegister.getClientVersion()); + AppRevision revision = new AppRevision(); + String appName = metaRegister.getApplication(); + revision.setAppName(appName); + revision.setRevision(metaRegister.getRevision()); + revision.setClientVersion(metaRegister.getClientVersion()); - Map> baseParams = new HashMap<>(); - for (Entry entry : metaRegister.getBaseParamsMap().entrySet()) { - StringList value = entry.getValue(); - baseParams - .put(entry.getKey(), value.getValuesList().subList(0, value.getValuesCount())); - } - revision.setBaseParams(baseParams); + Map> baseParams = new HashMap<>(); + for (Entry entry : metaRegister.getBaseParamsMap().entrySet()) { + StringList value = entry.getValue(); + baseParams.put(entry.getKey(), value.getValuesList().subList(0, value.getValuesCount())); + } + revision.setBaseParams(baseParams); - Map interfaceMap = new HashMap<>(); - for (Entry entry : metaRegister.getServicesMap().entrySet()) { - interfaceMap.put(entry.getKey(), MetaServiceConvertor.convert2Java(entry.getValue())); - } - revision.setInterfaceMap(interfaceMap); - return revision; + Map interfaceMap = new HashMap<>(); + for (Entry entry : metaRegister.getServicesMap().entrySet()) { + interfaceMap.put(entry.getKey(), MetaServiceConvertor.convert2Java(entry.getValue())); } - public static MetaRegister convert2Pb(AppRevision appRevision) { - MetaRegister.Builder builder = MetaRegister.newBuilder(); + revision.setInterfaceMap(interfaceMap); + return revision; + } - builder.setApplication(appRevision.getAppName()); - builder.setRevision(appRevision.getRevision()); + public static MetaRegister convert2Pb(AppRevision appRevision) { + MetaRegister.Builder builder = MetaRegister.newBuilder(); - for (Entry> entry : Optional.ofNullable(appRevision.getBaseParams()) - .orElse(new HashMap<>()).entrySet()) { - StringList.Builder listBuilder = StringList.newBuilder().addAllValues(entry.getValue()); - builder.putBaseParams(entry.getKey(), listBuilder.build()); - } + builder.setApplication(appRevision.getAppName()); + builder.setRevision(appRevision.getRevision()); + + for (Entry> entry : + Optional.ofNullable(appRevision.getBaseParams()).orElse(new HashMap<>()).entrySet()) { + StringList.Builder listBuilder = StringList.newBuilder().addAllValues(entry.getValue()); + builder.putBaseParams(entry.getKey(), listBuilder.build()); + } - for (Entry entry : Optional - .ofNullable(appRevision.getInterfaceMap()).orElse(new HashMap<>()).entrySet()) { - builder.putServices(entry.getKey(), MetaServiceConvertor.convert2Pb(entry.getValue())); - } - return builder.build(); + for (Entry entry : + Optional.ofNullable(appRevision.getInterfaceMap()).orElse(new HashMap<>()).entrySet()) { + builder.putServices(entry.getKey(), MetaServiceConvertor.convert2Pb(entry.getValue())); } + return builder.build(); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/DataBoxConvertor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/DataBoxConvertor.java index b111d680d..4941b8a52 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/DataBoxConvertor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/DataBoxConvertor.java @@ -19,7 +19,6 @@ import com.alipay.sofa.registry.common.model.client.pb.DataBoxPb; import com.alipay.sofa.registry.common.model.client.pb.DataBoxesPb; import com.alipay.sofa.registry.core.model.DataBox; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -32,103 +31,101 @@ */ public class DataBoxConvertor { - public static DataBox convert2Java(DataBoxPb dataBoxPb) { + public static DataBox convert2Java(DataBoxPb dataBoxPb) { - if (dataBoxPb == null) { - return null; - } else { - DataBox dataBoxJava = new DataBox(); - dataBoxJava.setData(dataBoxPb.getData()); - return dataBoxJava; - } + if (dataBoxPb == null) { + return null; + } else { + DataBox dataBoxJava = new DataBox(); + dataBoxJava.setData(dataBoxPb.getData()); + return dataBoxJava; } + } - public static DataBoxPb convert2Pb(DataBox dataBoxJava) { - - if (dataBoxJava == null) { - return null; - } else { - DataBoxPb.Builder builder = DataBoxPb.newBuilder(); + public static DataBoxPb convert2Pb(DataBox dataBoxJava) { - if (dataBoxJava.getData() != null) { - builder.setData(dataBoxJava.getData()); - } - return builder.build(); + if (dataBoxJava == null) { + return null; + } else { + DataBoxPb.Builder builder = DataBoxPb.newBuilder(); - } + if (dataBoxJava.getData() != null) { + builder.setData(dataBoxJava.getData()); + } + return builder.build(); } + } - public static List convertBoxes2Javas(List dataBoxPbs) { + public static List convertBoxes2Javas(List dataBoxPbs) { - List result = new ArrayList<>(); - if (dataBoxPbs == null) { - return null; - } else { + List result = new ArrayList<>(); + if (dataBoxPbs == null) { + return null; + } else { - for (DataBoxPb dataBoxPb : dataBoxPbs) { - result.add(convert2Java(dataBoxPb)); - } - - return result; - } + for (DataBoxPb dataBoxPb : dataBoxPbs) { + result.add(convert2Java(dataBoxPb)); + } + return result; } + } - public static List convert2Pbs(List dataBoxJavas) { + public static List convert2Pbs(List dataBoxJavas) { - List result = new ArrayList<>(); - if (dataBoxJavas == null) { - return null; - } else { + List result = new ArrayList<>(); + if (dataBoxJavas == null) { + return null; + } else { - for (DataBox dataBoxJava : dataBoxJavas) { - result.add(convert2Pb(dataBoxJava)); - } + for (DataBox dataBoxJava : dataBoxJavas) { + result.add(convert2Pb(dataBoxJava)); + } - return result; - } + return result; } + } - public static List convertBoxes2Javas(DataBoxesPb dataBoxesPb) { - if (dataBoxesPb == null) { - return null; - } else { + public static List convertBoxes2Javas(DataBoxesPb dataBoxesPb) { + if (dataBoxesPb == null) { + return null; + } else { - return convertBoxes2Javas(dataBoxesPb.getDataList()); - } + return convertBoxes2Javas(dataBoxesPb.getDataList()); } + } - public static Map> convert2JavaMaps(Map mapPb) { - if (mapPb == null) { - return null; - } else { - Map> mapJava = new HashMap<>(); + public static Map> convert2JavaMaps(Map mapPb) { + if (mapPb == null) { + return null; + } else { + Map> mapJava = new HashMap<>(); - for (Entry entry : mapPb.entrySet()) { - mapJava.put(entry.getKey(), convertBoxes2Javas(entry.getValue())); - } + for (Entry entry : mapPb.entrySet()) { + mapJava.put(entry.getKey(), convertBoxes2Javas(entry.getValue())); + } - return mapJava; - } + return mapJava; } + } - private static DataBoxesPb convertBoxes2Pbs(List dataBoxes) { - if (dataBoxes == null) { - return null; - } - return DataBoxesPb.newBuilder().addAllData(convert2Pbs(dataBoxes)).build(); + private static DataBoxesPb convertBoxes2Pbs(List dataBoxes) { + if (dataBoxes == null) { + return null; } + return DataBoxesPb.newBuilder().addAllData(convert2Pbs(dataBoxes)).build(); + } - public static Map convert2PbMaps(Map> mapJava) { - if (null == mapJava) { - return null; - } + public static Map convert2PbMaps(Map> mapJava) { + if (null == mapJava) { + return null; + } - Map mapPb = new HashMap<>(); + Map mapPb = new HashMap<>(); - for (Entry> entry : mapJava.entrySet()) { - mapPb.put(entry.getKey(), convertBoxes2Pbs(entry.getValue())); - } - return mapPb; + for (Entry> entry : mapJava.entrySet()) { + mapPb.put(entry.getKey(), convertBoxes2Pbs(entry.getValue())); } -} \ No newline at end of file + return mapPb; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/ListStringConvertor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/ListStringConvertor.java index 5c3b70ead..26e849ec6 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/ListStringConvertor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/ListStringConvertor.java @@ -17,7 +17,6 @@ package com.alipay.sofa.registry.server.session.converter.pb; import com.google.protobuf.ProtocolStringList; - import java.util.ArrayList; import java.util.List; @@ -27,12 +26,12 @@ */ public class ListStringConvertor { - public static List convert2Java(ProtocolStringList list) { + public static List convert2Java(ProtocolStringList list) { - if (list == null) { - return null; - } else { - return new ArrayList<>(list); - } + if (list == null) { + return null; + } else { + return new ArrayList<>(list); } -} \ No newline at end of file + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/MetaServiceConvertor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/MetaServiceConvertor.java index 4b58142ac..0c8cd243e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/MetaServiceConvertor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/MetaServiceConvertor.java @@ -19,7 +19,6 @@ import com.alipay.sofa.registry.common.model.client.pb.MetaService; import com.alipay.sofa.registry.common.model.client.pb.StringList; import com.alipay.sofa.registry.core.model.AppRevisionInterface; - import java.util.HashMap; import java.util.List; import java.util.Map; @@ -28,37 +27,37 @@ /** * @author xiaojian.xj - * @version $Id: MetaServiceConvertor.java, v 0.1 2021年02月04日 22:27 xiaojian.xj - * Exp $ + * @version $Id: MetaServiceConvertor.java, v 0.1 2021年02月04日 22:27 xiaojian.xj Exp $ */ public class MetaServiceConvertor { - public static MetaService convert2Pb(AppRevisionInterface service) { - - MetaService.Builder serviceBuilder = MetaService.newBuilder(); - serviceBuilder.setId(service.getId()); + public static MetaService convert2Pb(AppRevisionInterface service) { - for (Entry> entry : Optional.ofNullable(service.getServiceParams()) - .orElse(new HashMap<>()).entrySet()) { - StringList.Builder listBuilder = StringList.newBuilder().addAllValues(entry.getValue()); - serviceBuilder.putParams(entry.getKey(), listBuilder.build()); - } + MetaService.Builder serviceBuilder = MetaService.newBuilder(); + serviceBuilder.setId(service.getId()); - return serviceBuilder.build(); + for (Entry> entry : + Optional.ofNullable(service.getServiceParams()).orElse(new HashMap<>()).entrySet()) { + StringList.Builder listBuilder = StringList.newBuilder().addAllValues(entry.getValue()); + serviceBuilder.putParams(entry.getKey(), listBuilder.build()); } - public static AppRevisionInterface convert2Java(MetaService metaService) { - AppRevisionInterface appRevisionInterface = new AppRevisionInterface(); - appRevisionInterface.setId(metaService.getId()); - Map> serviceParams = new HashMap<>(); - for (Entry paramEntry : Optional.ofNullable(metaService.getParamsMap()) - .orElse(new HashMap<>()).entrySet()) { - StringList value = paramEntry.getValue(); - serviceParams.put(paramEntry.getKey(), - value.getValuesList().subList(0, value.getValuesCount())); - } - appRevisionInterface.setServiceParams(serviceParams); + return serviceBuilder.build(); + } - return appRevisionInterface; + public static AppRevisionInterface convert2Java(MetaService metaService) { + + AppRevisionInterface appRevisionInterface = new AppRevisionInterface(); + appRevisionInterface.setId(metaService.getId()); + Map> serviceParams = new HashMap<>(); + for (Entry paramEntry : + Optional.ofNullable(metaService.getParamsMap()).orElse(new HashMap<>()).entrySet()) { + StringList value = paramEntry.getValue(); + serviceParams.put( + paramEntry.getKey(), value.getValuesList().subList(0, value.getValuesCount())); } -} \ No newline at end of file + appRevisionInterface.setServiceParams(serviceParams); + + return appRevisionInterface; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/PublisherRegisterConvertor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/PublisherRegisterConvertor.java index cc4d38fec..670b4920e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/PublisherRegisterConvertor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/PublisherRegisterConvertor.java @@ -22,91 +22,73 @@ /** * @author bystander - * @version $Id: PublisherRegisterConvertor.java, v 0.1 2018年03月21日 2:06 PM - * bystander Exp $ + * @version $Id: PublisherRegisterConvertor.java, v 0.1 2018年03月21日 2:06 PM bystander Exp $ */ public class PublisherRegisterConvertor { - public static PublisherRegisterPb convert2Pb( - PublisherRegister publisherRegisterJava) { + public static PublisherRegisterPb convert2Pb(PublisherRegister publisherRegisterJava) { - if (publisherRegisterJava == null) { - return null; - } + if (publisherRegisterJava == null) { + return null; + } - PublisherRegisterPb.Builder builder = PublisherRegisterPb.newBuilder(); + PublisherRegisterPb.Builder builder = PublisherRegisterPb.newBuilder(); - BaseRegisterPb.Builder baseRegisterBuilder = BaseRegisterPb - .newBuilder(); + BaseRegisterPb.Builder baseRegisterBuilder = BaseRegisterPb.newBuilder(); - baseRegisterBuilder.setAppName(publisherRegisterJava.getAppName()) - .setClientId(publisherRegisterJava.getClientId()) - .setDataId(publisherRegisterJava.getDataId()) - .setDataInfoId(publisherRegisterJava.getDataInfoId()) - .setEventType(publisherRegisterJava.getEventType()) - .setGroup(publisherRegisterJava.getGroup()) - .setInstanceId(publisherRegisterJava.getInstanceId()) - .setIp(publisherRegisterJava.getIp()) - .setPort(publisherRegisterJava.getPort()) - .setProcessId(publisherRegisterJava.getProcessId()) - .setRegistId(publisherRegisterJava.getRegistId()) - .setVersion(publisherRegisterJava.getVersion()) - .setTimestamp(publisherRegisterJava.getTimestamp()) - .putAllAttributes(publisherRegisterJava.getAttributes()); + baseRegisterBuilder + .setAppName(publisherRegisterJava.getAppName()) + .setClientId(publisherRegisterJava.getClientId()) + .setDataId(publisherRegisterJava.getDataId()) + .setDataInfoId(publisherRegisterJava.getDataInfoId()) + .setEventType(publisherRegisterJava.getEventType()) + .setGroup(publisherRegisterJava.getGroup()) + .setInstanceId(publisherRegisterJava.getInstanceId()) + .setIp(publisherRegisterJava.getIp()) + .setPort(publisherRegisterJava.getPort()) + .setProcessId(publisherRegisterJava.getProcessId()) + .setRegistId(publisherRegisterJava.getRegistId()) + .setVersion(publisherRegisterJava.getVersion()) + .setTimestamp(publisherRegisterJava.getTimestamp()) + .putAllAttributes(publisherRegisterJava.getAttributes()); - if (publisherRegisterJava.getZone() != null) { - baseRegisterBuilder.setZone(publisherRegisterJava.getZone()); - } + if (publisherRegisterJava.getZone() != null) { + baseRegisterBuilder.setZone(publisherRegisterJava.getZone()); + } - builder.setBaseRegister(baseRegisterBuilder.build()); + builder.setBaseRegister(baseRegisterBuilder.build()); - builder.addAllDataList(DataBoxConvertor - .convert2Pbs(publisherRegisterJava.getDataList())); - return builder.build(); - } + builder.addAllDataList(DataBoxConvertor.convert2Pbs(publisherRegisterJava.getDataList())); + return builder.build(); + } - public static PublisherRegister convert2Java( - PublisherRegisterPb publisherRegisterPb) { + public static PublisherRegister convert2Java(PublisherRegisterPb publisherRegisterPb) { - if (publisherRegisterPb == null) { - return null; - } + if (publisherRegisterPb == null) { + return null; + } - PublisherRegister publisherRegister = new PublisherRegister(); + PublisherRegister publisherRegister = new PublisherRegister(); - publisherRegister.setAppName(publisherRegisterPb.getBaseRegister() - .getAppName()); - publisherRegister.setClientId(publisherRegisterPb.getBaseRegister() - .getClientId()); - publisherRegister.setDataId(publisherRegisterPb.getBaseRegister() - .getDataId()); - publisherRegister.setDataInfoId(publisherRegisterPb.getBaseRegister() - .getDataInfoId()); - publisherRegister.setEventType(publisherRegisterPb.getBaseRegister() - .getEventType()); - publisherRegister.setGroup(publisherRegisterPb.getBaseRegister() - .getGroup()); - publisherRegister.setInstanceId(publisherRegisterPb.getBaseRegister() - .getInstanceId()); - publisherRegister.setIp(publisherRegisterPb.getBaseRegister().getIp()); - publisherRegister.setPort(publisherRegisterPb.getBaseRegister() - .getPort()); - publisherRegister.setProcessId(publisherRegisterPb.getBaseRegister() - .getProcessId()); - publisherRegister.setRegistId(publisherRegisterPb.getBaseRegister() - .getRegistId()); - publisherRegister.setTimestamp(publisherRegisterPb.getBaseRegister() - .getTimestamp()); - publisherRegister.setVersion(publisherRegisterPb.getBaseRegister() - .getVersion()); - publisherRegister.setDataList(DataBoxConvertor - .convertBoxes2Javas(publisherRegisterPb.getDataListList())); - publisherRegister.setAttributes(publisherRegisterPb.getBaseRegister() - .getAttributesMap()); - if (publisherRegisterPb.getBaseRegister().getZone() != null) { - publisherRegister.setZone(publisherRegisterPb.getBaseRegister() - .getZone()); - } - return publisherRegister; - } -} \ No newline at end of file + publisherRegister.setAppName(publisherRegisterPb.getBaseRegister().getAppName()); + publisherRegister.setClientId(publisherRegisterPb.getBaseRegister().getClientId()); + publisherRegister.setDataId(publisherRegisterPb.getBaseRegister().getDataId()); + publisherRegister.setDataInfoId(publisherRegisterPb.getBaseRegister().getDataInfoId()); + publisherRegister.setEventType(publisherRegisterPb.getBaseRegister().getEventType()); + publisherRegister.setGroup(publisherRegisterPb.getBaseRegister().getGroup()); + publisherRegister.setInstanceId(publisherRegisterPb.getBaseRegister().getInstanceId()); + publisherRegister.setIp(publisherRegisterPb.getBaseRegister().getIp()); + publisherRegister.setPort(publisherRegisterPb.getBaseRegister().getPort()); + publisherRegister.setProcessId(publisherRegisterPb.getBaseRegister().getProcessId()); + publisherRegister.setRegistId(publisherRegisterPb.getBaseRegister().getRegistId()); + publisherRegister.setTimestamp(publisherRegisterPb.getBaseRegister().getTimestamp()); + publisherRegister.setVersion(publisherRegisterPb.getBaseRegister().getVersion()); + publisherRegister.setDataList( + DataBoxConvertor.convertBoxes2Javas(publisherRegisterPb.getDataListList())); + publisherRegister.setAttributes(publisherRegisterPb.getBaseRegister().getAttributesMap()); + if (publisherRegisterPb.getBaseRegister().getZone() != null) { + publisherRegister.setZone(publisherRegisterPb.getBaseRegister().getZone()); + } + return publisherRegister; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/ReceivedDataConvertor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/ReceivedDataConvertor.java index 08a90d9bf..8cc76c268 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/ReceivedDataConvertor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/ReceivedDataConvertor.java @@ -23,80 +23,70 @@ /** * @author bystander - * @version $Id: ReceivedDataConvertor.java, v 0.1 2018年03月21日 2:07 PM bystander - * Exp $ + * @version $Id: ReceivedDataConvertor.java, v 0.1 2018年03月21日 2:07 PM bystander Exp $ */ public class ReceivedDataConvertor { - public static ReceivedData convert2Java(ReceivedDataPb receivedDataPb) { - - if (receivedDataPb == null) { - return null; - } - - ReceivedData receivedData = new ReceivedData(); - - receivedData.setData(DataBoxConvertor.convert2JavaMaps(receivedDataPb - .getDataMap())); - receivedData.setDataId(receivedDataPb.getDataId()); - receivedData.setGroup(receivedDataPb.getGroup()); - receivedData.setInstanceId(receivedDataPb.getInstanceId()); - receivedData.setLocalZone(receivedDataPb.getLocalZone()); - receivedData.setScope(receivedDataPb.getScope()); - receivedData.setSegment(receivedDataPb.getSegment()); - receivedData.setSubscriberRegistIds(ListStringConvertor - .convert2Java(receivedDataPb.getSubscriberRegistIdsList())); - receivedData.setVersion(receivedDataPb.getVersion()); - - return receivedData; - } - - public static ReceivedDataPb convert2Pb(ReceivedData receivedDataJava) { - - if (receivedDataJava == null) { - return null; - } - - ReceivedDataPb.Builder builder = ReceivedDataPb.newBuilder(); - - builder.setDataId(receivedDataJava.getDataId()) - .setGroup(receivedDataJava.getGroup()) - .setInstanceId(receivedDataJava.getInstanceId()) - .setLocalZone(receivedDataJava.getLocalZone()) - .setScope(receivedDataJava.getScope()) - .setSegment(receivedDataJava.getSegment()) - .setVersion(receivedDataJava.getVersion()) - .addAllSubscriberRegistIds( - receivedDataJava.getSubscriberRegistIds()) - .putAllData( - DataBoxConvertor.convert2PbMaps(receivedDataJava - .getData())); - - return builder.build(); - - } - - public static ReceivedConfigDataPb convert2Pb( - ReceivedConfigData receivedConfigData) { - - if (receivedConfigData == null) { - return null; - } - - ReceivedConfigDataPb.Builder builder = ReceivedConfigDataPb - .newBuilder(); - - builder.setDataId(receivedConfigData.getDataId()) - .setGroup(receivedConfigData.getGroup()) - .setInstanceId(receivedConfigData.getInstanceId()) - .setVersion(receivedConfigData.getVersion()) - .addAllConfiguratorRegistIds( - receivedConfigData.getConfiguratorRegistIds()) - .setDataBox( - DataBoxConvertor.convert2Pb(receivedConfigData - .getDataBox())); - - return builder.build(); - - } -} \ No newline at end of file + public static ReceivedData convert2Java(ReceivedDataPb receivedDataPb) { + + if (receivedDataPb == null) { + return null; + } + + ReceivedData receivedData = new ReceivedData(); + + receivedData.setData(DataBoxConvertor.convert2JavaMaps(receivedDataPb.getDataMap())); + receivedData.setDataId(receivedDataPb.getDataId()); + receivedData.setGroup(receivedDataPb.getGroup()); + receivedData.setInstanceId(receivedDataPb.getInstanceId()); + receivedData.setLocalZone(receivedDataPb.getLocalZone()); + receivedData.setScope(receivedDataPb.getScope()); + receivedData.setSegment(receivedDataPb.getSegment()); + receivedData.setSubscriberRegistIds( + ListStringConvertor.convert2Java(receivedDataPb.getSubscriberRegistIdsList())); + receivedData.setVersion(receivedDataPb.getVersion()); + + return receivedData; + } + + public static ReceivedDataPb convert2Pb(ReceivedData receivedDataJava) { + + if (receivedDataJava == null) { + return null; + } + + ReceivedDataPb.Builder builder = ReceivedDataPb.newBuilder(); + + builder + .setDataId(receivedDataJava.getDataId()) + .setGroup(receivedDataJava.getGroup()) + .setInstanceId(receivedDataJava.getInstanceId()) + .setLocalZone(receivedDataJava.getLocalZone()) + .setScope(receivedDataJava.getScope()) + .setSegment(receivedDataJava.getSegment()) + .setVersion(receivedDataJava.getVersion()) + .addAllSubscriberRegistIds(receivedDataJava.getSubscriberRegistIds()) + .putAllData(DataBoxConvertor.convert2PbMaps(receivedDataJava.getData())); + + return builder.build(); + } + + public static ReceivedConfigDataPb convert2Pb(ReceivedConfigData receivedConfigData) { + + if (receivedConfigData == null) { + return null; + } + + ReceivedConfigDataPb.Builder builder = ReceivedConfigDataPb.newBuilder(); + + builder + .setDataId(receivedConfigData.getDataId()) + .setGroup(receivedConfigData.getGroup()) + .setInstanceId(receivedConfigData.getInstanceId()) + .setVersion(receivedConfigData.getVersion()) + .addAllConfiguratorRegistIds(receivedConfigData.getConfiguratorRegistIds()) + .setDataBox(DataBoxConvertor.convert2Pb(receivedConfigData.getDataBox())); + + return builder.build(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/RegisterResponseConvertor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/RegisterResponseConvertor.java index 024d2dd39..74c016343 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/RegisterResponseConvertor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/RegisterResponseConvertor.java @@ -21,48 +21,45 @@ /** * @author bystander - * @version $Id: RegisterResponseConvertor.java, v 0.1 2018年03月21日 2:07 PM - * bystander Exp $ + * @version $Id: RegisterResponseConvertor.java, v 0.1 2018年03月21日 2:07 PM bystander Exp $ */ public class RegisterResponseConvertor { - public static RegisterResponse convert2Java( - RegisterResponsePb registerResponsePb) { + public static RegisterResponse convert2Java(RegisterResponsePb registerResponsePb) { - if (registerResponsePb == null) { - return null; - } + if (registerResponsePb == null) { + return null; + } - RegisterResponse registerResponse = new RegisterResponse(); + RegisterResponse registerResponse = new RegisterResponse(); - registerResponse.setMessage(registerResponsePb.getMessage()); - registerResponse.setRefused(registerResponsePb.getRefused()); - registerResponse.setRegistId(registerResponsePb.getRegistId()); - registerResponse.setSuccess(registerResponsePb.getSuccess()); - registerResponse.setVersion(registerResponsePb.getVersion()); + registerResponse.setMessage(registerResponsePb.getMessage()); + registerResponse.setRefused(registerResponsePb.getRefused()); + registerResponse.setRegistId(registerResponsePb.getRegistId()); + registerResponse.setSuccess(registerResponsePb.getSuccess()); + registerResponse.setVersion(registerResponsePb.getVersion()); - return registerResponse; - } + return registerResponse; + } - public static RegisterResponsePb convert2Pb( - RegisterResponse registerResponseJava) { + public static RegisterResponsePb convert2Pb(RegisterResponse registerResponseJava) { - if (registerResponseJava == null) { - return null; - } + if (registerResponseJava == null) { + return null; + } - RegisterResponsePb.Builder builder = RegisterResponsePb.newBuilder(); + RegisterResponsePb.Builder builder = RegisterResponsePb.newBuilder(); - if (null != registerResponseJava.getMessage()) { - builder.setMessage(registerResponseJava.getMessage()); - } - if (null != registerResponseJava.getRegistId()) { - builder.setRegistId(registerResponseJava.getRegistId()); - } - builder.setVersion(registerResponseJava.getVersion()); - builder.setRefused(registerResponseJava.isRefused()); - builder.setSuccess(registerResponseJava.isSuccess()); + if (null != registerResponseJava.getMessage()) { + builder.setMessage(registerResponseJava.getMessage()); + } + if (null != registerResponseJava.getRegistId()) { + builder.setRegistId(registerResponseJava.getRegistId()); + } + builder.setVersion(registerResponseJava.getVersion()); + builder.setRefused(registerResponseJava.isRefused()); + builder.setSuccess(registerResponseJava.isSuccess()); - return builder.build(); - } -} \ No newline at end of file + return builder.build(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SubscriberRegisterConvertor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SubscriberRegisterConvertor.java index dd472c593..29b77814c 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SubscriberRegisterConvertor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SubscriberRegisterConvertor.java @@ -22,88 +22,70 @@ /** * @author bystander - * @version $Id: SubscriberRegisterConvertor.java, v 0.1 2018年03月21日 2:07 PM - * bystander Exp $ + * @version $Id: SubscriberRegisterConvertor.java, v 0.1 2018年03月21日 2:07 PM bystander Exp $ */ public class SubscriberRegisterConvertor { - public static SubscriberRegister convert2Java( - SubscriberRegisterPb subscriberRegisterPb) { + public static SubscriberRegister convert2Java(SubscriberRegisterPb subscriberRegisterPb) { - if (subscriberRegisterPb == null) { - return null; - } + if (subscriberRegisterPb == null) { + return null; + } - SubscriberRegister subscriberRegister = new SubscriberRegister(); + SubscriberRegister subscriberRegister = new SubscriberRegister(); - subscriberRegister.setAppName(subscriberRegisterPb.getBaseRegister() - .getAppName()); - subscriberRegister.setClientId(subscriberRegisterPb.getBaseRegister() - .getClientId()); - subscriberRegister.setDataId(subscriberRegisterPb.getBaseRegister() - .getDataId()); - subscriberRegister.setDataInfoId(subscriberRegisterPb.getBaseRegister() - .getDataInfoId()); - subscriberRegister.setEventType(subscriberRegisterPb.getBaseRegister() - .getEventType()); - subscriberRegister.setGroup(subscriberRegisterPb.getBaseRegister() - .getGroup()); - subscriberRegister.setZone(subscriberRegisterPb.getBaseRegister() - .getZone()); - subscriberRegister.setInstanceId(subscriberRegisterPb.getBaseRegister() - .getInstanceId()); - subscriberRegister - .setIp(subscriberRegisterPb.getBaseRegister().getIp()); - subscriberRegister.setPort(subscriberRegisterPb.getBaseRegister() - .getPort()); - subscriberRegister.setProcessId(subscriberRegisterPb.getBaseRegister() - .getProcessId()); - subscriberRegister.setRegistId(subscriberRegisterPb.getBaseRegister() - .getRegistId()); - subscriberRegister.setTimestamp(subscriberRegisterPb.getBaseRegister() - .getTimestamp()); - subscriberRegister.setVersion(subscriberRegisterPb.getBaseRegister() - .getVersion()); + subscriberRegister.setAppName(subscriberRegisterPb.getBaseRegister().getAppName()); + subscriberRegister.setClientId(subscriberRegisterPb.getBaseRegister().getClientId()); + subscriberRegister.setDataId(subscriberRegisterPb.getBaseRegister().getDataId()); + subscriberRegister.setDataInfoId(subscriberRegisterPb.getBaseRegister().getDataInfoId()); + subscriberRegister.setEventType(subscriberRegisterPb.getBaseRegister().getEventType()); + subscriberRegister.setGroup(subscriberRegisterPb.getBaseRegister().getGroup()); + subscriberRegister.setZone(subscriberRegisterPb.getBaseRegister().getZone()); + subscriberRegister.setInstanceId(subscriberRegisterPb.getBaseRegister().getInstanceId()); + subscriberRegister.setIp(subscriberRegisterPb.getBaseRegister().getIp()); + subscriberRegister.setPort(subscriberRegisterPb.getBaseRegister().getPort()); + subscriberRegister.setProcessId(subscriberRegisterPb.getBaseRegister().getProcessId()); + subscriberRegister.setRegistId(subscriberRegisterPb.getBaseRegister().getRegistId()); + subscriberRegister.setTimestamp(subscriberRegisterPb.getBaseRegister().getTimestamp()); + subscriberRegister.setVersion(subscriberRegisterPb.getBaseRegister().getVersion()); - subscriberRegister.setAttributes(subscriberRegisterPb.getBaseRegister() - .getAttributesMap()); + subscriberRegister.setAttributes(subscriberRegisterPb.getBaseRegister().getAttributesMap()); - subscriberRegister.setScope(subscriberRegisterPb.getScope()); - return subscriberRegister; - } + subscriberRegister.setScope(subscriberRegisterPb.getScope()); + return subscriberRegister; + } - public static SubscriberRegisterPb convert2Pb( - SubscriberRegister subscriberRegisterJava) { + public static SubscriberRegisterPb convert2Pb(SubscriberRegister subscriberRegisterJava) { - if (subscriberRegisterJava == null) { - return null; - } + if (subscriberRegisterJava == null) { + return null; + } - SubscriberRegisterPb.Builder builder = SubscriberRegisterPb - .newBuilder(); + SubscriberRegisterPb.Builder builder = SubscriberRegisterPb.newBuilder(); - BaseRegisterPb.Builder baseRegisterBuilder = BaseRegisterPb - .newBuilder(); + BaseRegisterPb.Builder baseRegisterBuilder = BaseRegisterPb.newBuilder(); - baseRegisterBuilder.setAppName(subscriberRegisterJava.getAppName()) - .setClientId(subscriberRegisterJava.getClientId()) - .setDataId(subscriberRegisterJava.getDataId()) - .setDataInfoId(subscriberRegisterJava.getDataInfoId()) - .setEventType(subscriberRegisterJava.getEventType()) - .setGroup(subscriberRegisterJava.getGroup()) - .setZone(subscriberRegisterJava.getZone()) - .setInstanceId(subscriberRegisterJava.getInstanceId()) - .setIp(subscriberRegisterJava.getIp()) - .setPort(subscriberRegisterJava.getPort()) - .setProcessId(subscriberRegisterJava.getProcessId()) - .setRegistId(subscriberRegisterJava.getRegistId()) - .setVersion(subscriberRegisterJava.getVersion()) - .setTimestamp(subscriberRegisterJava.getTimestamp()) - .putAllAttributes(subscriberRegisterJava.getAttributes()); + baseRegisterBuilder + .setAppName(subscriberRegisterJava.getAppName()) + .setClientId(subscriberRegisterJava.getClientId()) + .setDataId(subscriberRegisterJava.getDataId()) + .setDataInfoId(subscriberRegisterJava.getDataInfoId()) + .setEventType(subscriberRegisterJava.getEventType()) + .setGroup(subscriberRegisterJava.getGroup()) + .setZone(subscriberRegisterJava.getZone()) + .setInstanceId(subscriberRegisterJava.getInstanceId()) + .setIp(subscriberRegisterJava.getIp()) + .setPort(subscriberRegisterJava.getPort()) + .setProcessId(subscriberRegisterJava.getProcessId()) + .setRegistId(subscriberRegisterJava.getRegistId()) + .setVersion(subscriberRegisterJava.getVersion()) + .setTimestamp(subscriberRegisterJava.getTimestamp()) + .putAllAttributes(subscriberRegisterJava.getAttributes()); - builder.setScope(subscriberRegisterJava.getScope()).setBaseRegister( - baseRegisterBuilder.build()); + builder + .setScope(subscriberRegisterJava.getScope()) + .setBaseRegister(baseRegisterBuilder.build()); - return builder.build(); - } -} \ No newline at end of file + return builder.build(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SyncConfigRequestConvertor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SyncConfigRequestConvertor.java index 2c242a958..8aaaef885 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SyncConfigRequestConvertor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SyncConfigRequestConvertor.java @@ -21,36 +21,33 @@ /** * @author bystander - * @version $Id: SyncConfigRequestConvertor.java, v 0.1 2018年03月21日 2:07 PM - * bystander Exp $ + * @version $Id: SyncConfigRequestConvertor.java, v 0.1 2018年03月21日 2:07 PM bystander Exp $ */ public class SyncConfigRequestConvertor { - public static SyncConfigRequest convert2Java( - SyncConfigRequestPb syncConfigRequestPb) { + public static SyncConfigRequest convert2Java(SyncConfigRequestPb syncConfigRequestPb) { - if (syncConfigRequestPb == null) { - return null; - } + if (syncConfigRequestPb == null) { + return null; + } - SyncConfigRequest syncConfigRequest = new SyncConfigRequest(); - syncConfigRequest.setZone(syncConfigRequestPb.getZone()); - syncConfigRequest.setDataCenter(syncConfigRequestPb.getDataCenter()); + SyncConfigRequest syncConfigRequest = new SyncConfigRequest(); + syncConfigRequest.setZone(syncConfigRequestPb.getZone()); + syncConfigRequest.setDataCenter(syncConfigRequestPb.getDataCenter()); - return syncConfigRequest; - } + return syncConfigRequest; + } - public static SyncConfigRequestPb convert2Pb( - SyncConfigRequest syncConfigRequestJava) { + public static SyncConfigRequestPb convert2Pb(SyncConfigRequest syncConfigRequestJava) { - if (syncConfigRequestJava == null) { - return null; - } + if (syncConfigRequestJava == null) { + return null; + } - SyncConfigRequestPb.Builder builder = SyncConfigRequestPb.newBuilder(); - builder.setZone(syncConfigRequestJava.getZone()); - builder.setDataCenter(syncConfigRequestJava.getDataCenter()); + SyncConfigRequestPb.Builder builder = SyncConfigRequestPb.newBuilder(); + builder.setZone(syncConfigRequestJava.getZone()); + builder.setDataCenter(syncConfigRequestJava.getDataCenter()); - return builder.build(); - } -} \ No newline at end of file + return builder.build(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SyncConfigResponseConvertor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SyncConfigResponseConvertor.java index 511fb9729..6a82a6b8b 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SyncConfigResponseConvertor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/converter/pb/SyncConfigResponseConvertor.java @@ -22,54 +22,46 @@ /** * @author bystander - * @version $Id: SyncConfigResponseConvertor.java, v 0.1 2018年03月21日 2:06 PM - * bystander Exp $ + * @version $Id: SyncConfigResponseConvertor.java, v 0.1 2018年03月21日 2:06 PM bystander Exp $ */ public class SyncConfigResponseConvertor { - public static SyncConfigResponse convert2Java( - SyncConfigResponsePb syncConfigResponsePb) { + public static SyncConfigResponse convert2Java(SyncConfigResponsePb syncConfigResponsePb) { - if (syncConfigResponsePb == null) { - return null; - } + if (syncConfigResponsePb == null) { + return null; + } - SyncConfigResponse syncConfigResponse = new SyncConfigResponse(); + SyncConfigResponse syncConfigResponse = new SyncConfigResponse(); - syncConfigResponse.setAvailableSegments(ListStringConvertor - .convert2Java(syncConfigResponsePb.getAvailableSegmentsList())); + syncConfigResponse.setAvailableSegments( + ListStringConvertor.convert2Java(syncConfigResponsePb.getAvailableSegmentsList())); - syncConfigResponse.setRetryInterval(syncConfigResponsePb - .getRetryInterval()); - syncConfigResponse.setMessage(syncConfigResponsePb.getResult() - .getMessage()); - syncConfigResponse.setSuccess(syncConfigResponsePb.getResult() - .getSuccess()); + syncConfigResponse.setRetryInterval(syncConfigResponsePb.getRetryInterval()); + syncConfigResponse.setMessage(syncConfigResponsePb.getResult().getMessage()); + syncConfigResponse.setSuccess(syncConfigResponsePb.getResult().getSuccess()); - return syncConfigResponse; - } + return syncConfigResponse; + } - public static SyncConfigResponsePb convert2Pb( - SyncConfigResponse syncConfigResponseJava) { + public static SyncConfigResponsePb convert2Pb(SyncConfigResponse syncConfigResponseJava) { - if (syncConfigResponseJava == null) { - return null; - } + if (syncConfigResponseJava == null) { + return null; + } - SyncConfigResponsePb.Builder builder = SyncConfigResponsePb - .newBuilder(); - builder.setRetryInterval(syncConfigResponseJava.getRetryInterval()); - builder.addAllAvailableSegments(syncConfigResponseJava - .getAvailableSegments()); + SyncConfigResponsePb.Builder builder = SyncConfigResponsePb.newBuilder(); + builder.setRetryInterval(syncConfigResponseJava.getRetryInterval()); + builder.addAllAvailableSegments(syncConfigResponseJava.getAvailableSegments()); - ResultPb.Builder resultPbBuilder = ResultPb.newBuilder(); - if (syncConfigResponseJava.getMessage() != null) { - resultPbBuilder.setMessage(syncConfigResponseJava.getMessage()); - } - resultPbBuilder.setSuccess(syncConfigResponseJava.isSuccess()); + ResultPb.Builder resultPbBuilder = ResultPb.newBuilder(); + if (syncConfigResponseJava.getMessage() != null) { + resultPbBuilder.setMessage(syncConfigResponseJava.getMessage()); + } + resultPbBuilder.setSuccess(syncConfigResponseJava.isSuccess()); - builder.setResult(resultPbBuilder.build()); + builder.setResult(resultPbBuilder.build()); - return builder.build(); - } -} \ No newline at end of file + return builder.build(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/DataIdMatchStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/DataIdMatchStrategy.java index 4f06c85e1..33e0bf7cf 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/DataIdMatchStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/DataIdMatchStrategy.java @@ -19,11 +19,10 @@ import java.util.function.Supplier; /** - * * @author shangyu.wh * @version 1.0: DataIdMatchStrategy.java, v 0.1 2019-06-19 22:12 shangyu.wh Exp $ */ public interface DataIdMatchStrategy { - boolean match(String dataId, Supplier getOperatorType); -} \ No newline at end of file + boolean match(String dataId, Supplier getOperatorType); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/IPMatchStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/IPMatchStrategy.java index 76697a5af..fde8a4aec 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/IPMatchStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/IPMatchStrategy.java @@ -19,11 +19,10 @@ import java.util.function.Supplier; /** - * * @author shangyu.wh * @version 1.0: IPMatchStrategy.java, v 0.1 2019-06-19 22:14 shangyu.wh Exp $ */ public interface IPMatchStrategy { - boolean match(String IP, Supplier getOperatorType); -} \ No newline at end of file + boolean match(String IP, Supplier getOperatorType); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/ProcessFilter.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/ProcessFilter.java index 040db92c5..a67ca44d4 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/ProcessFilter.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/ProcessFilter.java @@ -17,11 +17,10 @@ package com.alipay.sofa.registry.server.session.filter; /** - * * @author shangyu.wh * @version 1.0: ProcessFilter.java, v 0.1 2019-06-19 17:01 shangyu.wh Exp $ */ public interface ProcessFilter { - boolean match(T input); -} \ No newline at end of file + boolean match(T input); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistConfig.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistConfig.java index 7e63e6bd2..a6cd10b2e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistConfig.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistConfig.java @@ -20,57 +20,56 @@ import java.util.List; /** - * * @author shangyu.wh * @version 1.0: BlacklistConfig.java, v 0.1 2019-06-19 17:23 shangyu.wh Exp $ */ public class BlacklistConfig implements Serializable { - /** UID*/ - private static final long serialVersionUID = -7607561981062791932L; + /** UID */ + private static final long serialVersionUID = -7607561981062791932L; - /** blacklist type */ - private String type; + /** blacklist type */ + private String type; - /** match type */ - @SuppressWarnings("rawtypes") - private List matchTypes; + /** match type */ + @SuppressWarnings("rawtypes") + private List matchTypes; - /** - * Getter method for property type. - * - * @return property value of type - */ - public String getType() { - return type; - } + /** + * Getter method for property type. + * + * @return property value of type + */ + public String getType() { + return type; + } - /** - * Setter method for property type. - * - * @param type value to be assigned to property type - */ - public void setType(String type) { - this.type = type; - } + /** + * Setter method for property type. + * + * @param type value to be assigned to property type + */ + public void setType(String type) { + this.type = type; + } - /** - * Getter method for property matchTypes. - * - * @return property value of matchTypes - */ - @SuppressWarnings("rawtypes") - public List getMatchTypes() { - return matchTypes; - } + /** + * Getter method for property matchTypes. + * + * @return property value of matchTypes + */ + @SuppressWarnings("rawtypes") + public List getMatchTypes() { + return matchTypes; + } - /** - * Setter method for property matchTypes. - * - * @param matchTypes value to be assigned to property matchTypes - */ - @SuppressWarnings("rawtypes") - public void setMatchTypes(List matchTypes) { - this.matchTypes = matchTypes; - } -} \ No newline at end of file + /** + * Setter method for property matchTypes. + * + * @param matchTypes value to be assigned to property matchTypes + */ + @SuppressWarnings("rawtypes") + public void setMatchTypes(List matchTypes) { + this.matchTypes = matchTypes; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistConstants.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistConstants.java index 7b1325059..29160bf7a 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistConstants.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistConstants.java @@ -17,22 +17,20 @@ package com.alipay.sofa.registry.server.session.filter.blacklist; /** - * * @author shangyu.wh - * @version 1.0: BlacklistConstants.java, v 0.1 2019-06-19 17:56 shangyu.wh Exp - * $ + * @version 1.0: BlacklistConstants.java, v 0.1 2019-06-19 17:56 shangyu.wh Exp $ */ public class BlacklistConstants { - // *********************** Blacklist type ***********************// - /** forbidden pub */ - public static final String FORBIDDEN_PUB = "FORBIDDEN_PUB"; + // *********************** Blacklist type ***********************// + /** forbidden pub */ + public static final String FORBIDDEN_PUB = "FORBIDDEN_PUB"; - /** forbidden sub by prefix */ - public static final String FORBIDDEN_SUB_BY_PREFIX = "FORBIDDEN_SUB_BY_PREFIX"; + /** forbidden sub by prefix */ + public static final String FORBIDDEN_SUB_BY_PREFIX = "FORBIDDEN_SUB_BY_PREFIX"; - // *********************** match type ***********************// + // *********************** match type ***********************// - /** match full ip */ - public static final String IP_FULL = "IP_FULL"; -} \ No newline at end of file + /** match full ip */ + public static final String IP_FULL = "IP_FULL"; +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistManager.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistManager.java index cf9a9733e..4c78eeb13 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistManager.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistManager.java @@ -21,35 +21,33 @@ import java.util.Set; /** - * * @author shangyu.wh * @version 1.0: BlacklistManager.java, v 0.1 2019-06-19 18:27 shangyu.wh Exp $ */ public interface BlacklistManager { - /** - * load list first - */ - void load(); + /** load list first */ + void load(); - /** - * get list - * @return - */ - List getBlacklistConfigList(); + /** + * get list + * + * @return + */ + List getBlacklistConfigList(); - /** - * set list - * @param blacklistConfigList - */ - void setBlacklistConfigList(List blacklistConfigList); + /** + * set list + * + * @param blacklistConfigList + */ + void setBlacklistConfigList(List blacklistConfigList); - /** - * convert blacklist map to blacklist config list - * @param config - * @return - * blacklistConfigMap key:blacklist type - * Map> key:MatchType - * set:match patterns - */ - Map>> convertBlacklistConfig(String config); -} \ No newline at end of file + /** + * convert blacklist map to blacklist config list + * + * @param config + * @return blacklistConfigMap key:blacklist type Map> key:MatchType set:match + * patterns + */ + Map>> convertBlacklistConfig(String config); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistManagerImpl.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistManagerImpl.java index 1beaa8c1d..4c636be65 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistManagerImpl.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistManagerImpl.java @@ -33,176 +33,176 @@ import com.alipay.sofa.registry.util.OsUtils; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; import java.io.IOException; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version 1.0: BlacklistManagerImpl.java, v 0.1 2019-06-19 18:30 shangyu.wh Exp $ */ public class BlacklistManagerImpl extends AbstractLifecycle implements BlacklistManager { - private static final Logger LOGGER = LoggerFactory - .getLogger(BlacklistManagerImpl.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BlacklistManagerImpl.class); - private static final Logger EXCHANGE_LOGGER = LoggerFactory - .getLogger("SESSION-EXCHANGE"); + private static final Logger EXCHANGE_LOGGER = LoggerFactory.getLogger("SESSION-EXCHANGE"); - @Autowired - protected MetaServerService metaNodeService; + @Autowired protected MetaServerService metaNodeService; - private List blacklistConfigList = new ArrayList(); + private List blacklistConfigList = new ArrayList(); - private ScheduledExecutorService scheduled; + private ScheduledExecutorService scheduled; - private ScheduledFuture future; + private ScheduledFuture future; - @PostConstruct - public void postConstruct() throws Exception { - LifecycleHelper.initializeIfPossible(this); - LifecycleHelper.startIfPossible(this); - } + @PostConstruct + public void postConstruct() throws Exception { + LifecycleHelper.initializeIfPossible(this); + LifecycleHelper.startIfPossible(this); + } - @PreDestroy - public void preDestroy() throws Exception { - LifecycleHelper.stopIfPossible(this); - LifecycleHelper.disposeIfPossible(this); - } + @PreDestroy + public void preDestroy() throws Exception { + LifecycleHelper.stopIfPossible(this); + LifecycleHelper.disposeIfPossible(this); + } - @Override - protected void doInitialize() throws InitializeException { - super.doInitialize(); - scheduled = ThreadPoolUtil.newScheduledBuilder() - .coreThreads(Math.min(2, OsUtils.getCpuCount())).enableMetric(true) + @Override + protected void doInitialize() throws InitializeException { + super.doInitialize(); + scheduled = + ThreadPoolUtil.newScheduledBuilder() + .coreThreads(Math.min(2, OsUtils.getCpuCount())) + .enableMetric(true) .poolName(BlacklistManager.class.getSimpleName()) - .threadFactory(new NamedThreadFactory(BlacklistManager.class.getSimpleName())).build(); - } - - @Override - protected void doStart() throws StartException { - super.doStart(); - future = scheduled.scheduleWithFixedDelay(new Runnable() { - @Override - public void run() { + .threadFactory(new NamedThreadFactory(BlacklistManager.class.getSimpleName())) + .build(); + } + + @Override + protected void doStart() throws StartException { + super.doStart(); + future = + scheduled.scheduleWithFixedDelay( + new Runnable() { + @Override + public void run() { fetchStopPushSwitch(); - } - }, getIntervalMilli(), getIntervalMilli(), TimeUnit.MILLISECONDS); + } + }, + getIntervalMilli(), + getIntervalMilli(), + TimeUnit.MILLISECONDS); + } + + @Override + protected void doStop() throws StopException { + if (future != null) { + future.cancel(true); + future = null; } - - @Override - protected void doStop() throws StopException { - if (future != null) { - future.cancel(true); - future = null; - } - super.doStop(); + super.doStop(); + } + + @Override + protected void doDispose() throws DisposeException { + if (scheduled != null) { + scheduled.shutdownNow(); + scheduled = null; } - - @Override - protected void doDispose() throws DisposeException { - if (scheduled != null) { - scheduled.shutdownNow(); - scheduled = null; - } - super.doDispose(); + super.doDispose(); + } + + private int getIntervalMilli() { + return 30 * 1000; + } + + @Override + public void load() { + fetchStopPushSwitch(); + } + + @Override + public List getBlacklistConfigList() { + return blacklistConfigList; + } + + @Override + public void setBlacklistConfigList(List blacklistConfigList) { + this.blacklistConfigList = blacklistConfigList; + } + + private void fetchStopPushSwitch() { + ProvideData provideData = metaNodeService.fetchData(ValueConstants.BLACK_LIST_DATA_ID); + if (provideData != null) { + if (provideData.getProvideData() == null + || provideData.getProvideData().getObject() == null) { + LOGGER.info("Fetch session blacklist no data existed,current config not change!"); + return; + } + String data = (String) provideData.getProvideData().getObject(); + if (data != null) { + convertBlacklistConfig(data); + EXCHANGE_LOGGER.info("Fetch session blacklist data switch {} success!", data); + } else { + LOGGER.info("Fetch session blacklist data null,current config not change!"); + } + } else { + LOGGER.info("Fetch session blacklist data null,config not change!"); } + } - private int getIntervalMilli() { - return 30 * 1000; - } + /** @see BlacklistManager#convertBlacklistConfig(String) */ + public Map>> convertBlacklistConfig(String config) { - @Override - public void load() { - fetchStopPushSwitch(); - } + TypeReference>>> typeReference = + new TypeReference>>>() {}; - @Override - public List getBlacklistConfigList() { - return blacklistConfigList; - } + ObjectMapper mapper = JsonUtils.getJacksonObjectMapper(); - @Override - public void setBlacklistConfigList(List blacklistConfigList) { - this.blacklistConfigList = blacklistConfigList; + Map>> blacklistConfigMap; + try { + blacklistConfigMap = mapper.readValue(config, typeReference); + } catch (IOException e) { + LOGGER.error("Parser config json error!", e); + return null; } - - private void fetchStopPushSwitch() { - ProvideData provideData = metaNodeService.fetchData(ValueConstants.BLACK_LIST_DATA_ID); - if (provideData != null) { - if (provideData.getProvideData() == null - || provideData.getProvideData().getObject() == null) { - LOGGER.info("Fetch session blacklist no data existed,current config not change!"); - return; - } - String data = (String) provideData.getProvideData().getObject(); - if (data != null) { - convertBlacklistConfig(data); - EXCHANGE_LOGGER.info("Fetch session blacklist data switch {} success!", data); - } else { - LOGGER.info("Fetch session blacklist data null,current config not change!"); - } - } else { - LOGGER.info("Fetch session blacklist data null,config not change!"); - } + if (null == blacklistConfigMap) { + LOGGER.info("[cmd] setBlacklistConfig fail, params is null"); + return null; } - - /** - * @see BlacklistManager#convertBlacklistConfig(String) - */ - public Map>> convertBlacklistConfig(String config) { - - TypeReference>>> typeReference = new TypeReference>>>() { - }; - - ObjectMapper mapper = JsonUtils.getJacksonObjectMapper(); - - Map>> blacklistConfigMap; - try { - blacklistConfigMap = mapper.readValue(config, typeReference); - } catch (IOException e) { - LOGGER.error("Parser config json error!", e); - return null; - } - if (null == blacklistConfigMap) { - LOGGER.info("[cmd] setBlacklistConfig fail, params is null"); - return null; - } - try { - List blacklistConfigs = new ArrayList(); - for (Entry>> configEntry : blacklistConfigMap - .entrySet()) { - BlacklistConfig blacklistConfig = new BlacklistConfig(); - blacklistConfig.setType(configEntry.getKey()); - - List matchTypeList = new ArrayList(); - - Map> matchTypeMap = configEntry.getValue(); - for (Entry> typeEntry : matchTypeMap.entrySet()) { - String type = typeEntry.getKey(); - - MatchType ipFullMatchType = new MatchType(); - ipFullMatchType.setType(type); - ipFullMatchType.setPatternSet(typeEntry.getValue()); - matchTypeList.add(ipFullMatchType); - } - blacklistConfig.setMatchTypes(matchTypeList); - blacklistConfigs.add(blacklistConfig); - } - - setBlacklistConfigList(blacklistConfigs); - return blacklistConfigMap; - } catch (Exception e) { - LOGGER.error("[cmd] setBlacklistConfig error", e); - return null; + try { + List blacklistConfigs = new ArrayList(); + for (Entry>> configEntry : blacklistConfigMap.entrySet()) { + BlacklistConfig blacklistConfig = new BlacklistConfig(); + blacklistConfig.setType(configEntry.getKey()); + + List matchTypeList = new ArrayList(); + + Map> matchTypeMap = configEntry.getValue(); + for (Entry> typeEntry : matchTypeMap.entrySet()) { + String type = typeEntry.getKey(); + + MatchType ipFullMatchType = new MatchType(); + ipFullMatchType.setType(type); + ipFullMatchType.setPatternSet(typeEntry.getValue()); + matchTypeList.add(ipFullMatchType); } + blacklistConfig.setMatchTypes(matchTypeList); + blacklistConfigs.add(blacklistConfig); + } + + setBlacklistConfigList(blacklistConfigs); + return blacklistConfigMap; + } catch (Exception e) { + LOGGER.error("[cmd] setBlacklistConfig error", e); + return null; } -} \ No newline at end of file + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistMatchProcessFilter.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistMatchProcessFilter.java index 5f1845915..2707b041c 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistMatchProcessFilter.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/BlacklistMatchProcessFilter.java @@ -22,111 +22,108 @@ import com.alipay.sofa.registry.server.session.filter.DataIdMatchStrategy; import com.alipay.sofa.registry.server.session.filter.IPMatchStrategy; import com.alipay.sofa.registry.server.session.filter.ProcessFilter; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version 1.0: BlacklistMatchProcessFilter.java, v 0.1 2019-06-19 22:01 shangyu.wh Exp $ */ public class BlacklistMatchProcessFilter implements ProcessFilter { - @Autowired - private DataIdMatchStrategy dataIdMatchStrategy; - - @Autowired - private IPMatchStrategy ipMatchStrategy; - - @Autowired - private BlacklistManager blacklistManager; - - @Autowired - private SessionServerConfig sessionServerConfig; - - @Override - public boolean match(BaseInfo storeData) { - - final List configList = blacklistManager.getBlacklistConfigList(); + @Autowired private DataIdMatchStrategy dataIdMatchStrategy; - // empty list proceed - if (null == configList || configList.size() == 0) { - return false; - } + @Autowired private IPMatchStrategy ipMatchStrategy; - URL url = storeData.getSourceAddress(); + @Autowired private BlacklistManager blacklistManager; - if (url != null) { + @Autowired private SessionServerConfig sessionServerConfig; - switch (storeData.getDataType()) { - case PUBLISHER: - if(dataIdMatchStrategy.match(storeData.getDataId(),()-> sessionServerConfig.getBlacklistPubDataIdRegex())){ - return ipMatchStrategy.match(url.getIpAddress(),()-> BlacklistConstants.FORBIDDEN_PUB); - } - case SUBSCRIBER: - if(dataIdMatchStrategy.match(storeData.getDataId(),()-> sessionServerConfig.getBlacklistSubDataIdRegex())){ - return ipMatchStrategy.match(url.getIpAddress(),()-> BlacklistConstants.FORBIDDEN_SUB_BY_PREFIX); - } - default: - return false; - } + @Override + public boolean match(BaseInfo storeData) { - } - return false; - } - - /** - * Getter method for property dataIdMatchStrategy. - * - * @return property value of dataIdMatchStrategy - */ - public DataIdMatchStrategy getDataIdMatchStrategy() { - return dataIdMatchStrategy; - } - - /** - * Setter method for property dataIdMatchStrategy. - * - * @param dataIdMatchStrategy value to be assigned to property dataIdMatchStrategy - */ - public void setDataIdMatchStrategy(DataIdMatchStrategy dataIdMatchStrategy) { - this.dataIdMatchStrategy = dataIdMatchStrategy; - } - - /** - * Getter method for property ipMatchStrategy. - * - * @return property value of ipMatchStrategy - */ - public IPMatchStrategy getIpMatchStrategy() { - return ipMatchStrategy; - } - - /** - * Setter method for property ipMatchStrategy. - * - * @param ipMatchStrategy value to be assigned to property ipMatchStrategy - */ - public void setIpMatchStrategy(IPMatchStrategy ipMatchStrategy) { - this.ipMatchStrategy = ipMatchStrategy; - } + final List configList = blacklistManager.getBlacklistConfigList(); - /** - * Getter method for property blacklistManager. - * - * @return property value of blacklistManager - */ - public BlacklistManager getBlacklistManager() { - return blacklistManager; + // empty list proceed + if (null == configList || configList.size() == 0) { + return false; } - /** - * Setter method for property blacklistManager. - * - * @param blacklistManager value to be assigned to property blacklistManager - */ - public void setBlacklistManager(BlacklistManager blacklistManager) { - this.blacklistManager = blacklistManager; + URL url = storeData.getSourceAddress(); + + if (url != null) { + + switch (storeData.getDataType()) { + case PUBLISHER: + if (dataIdMatchStrategy.match( + storeData.getDataId(), () -> sessionServerConfig.getBlacklistPubDataIdRegex())) { + return ipMatchStrategy.match( + url.getIpAddress(), () -> BlacklistConstants.FORBIDDEN_PUB); + } + case SUBSCRIBER: + if (dataIdMatchStrategy.match( + storeData.getDataId(), () -> sessionServerConfig.getBlacklistSubDataIdRegex())) { + return ipMatchStrategy.match( + url.getIpAddress(), () -> BlacklistConstants.FORBIDDEN_SUB_BY_PREFIX); + } + default: + return false; + } } -} \ No newline at end of file + return false; + } + + /** + * Getter method for property dataIdMatchStrategy. + * + * @return property value of dataIdMatchStrategy + */ + public DataIdMatchStrategy getDataIdMatchStrategy() { + return dataIdMatchStrategy; + } + + /** + * Setter method for property dataIdMatchStrategy. + * + * @param dataIdMatchStrategy value to be assigned to property dataIdMatchStrategy + */ + public void setDataIdMatchStrategy(DataIdMatchStrategy dataIdMatchStrategy) { + this.dataIdMatchStrategy = dataIdMatchStrategy; + } + + /** + * Getter method for property ipMatchStrategy. + * + * @return property value of ipMatchStrategy + */ + public IPMatchStrategy getIpMatchStrategy() { + return ipMatchStrategy; + } + + /** + * Setter method for property ipMatchStrategy. + * + * @param ipMatchStrategy value to be assigned to property ipMatchStrategy + */ + public void setIpMatchStrategy(IPMatchStrategy ipMatchStrategy) { + this.ipMatchStrategy = ipMatchStrategy; + } + + /** + * Getter method for property blacklistManager. + * + * @return property value of blacklistManager + */ + public BlacklistManager getBlacklistManager() { + return blacklistManager; + } + + /** + * Setter method for property blacklistManager. + * + * @param blacklistManager value to be assigned to property blacklistManager + */ + public void setBlacklistManager(BlacklistManager blacklistManager) { + this.blacklistManager = blacklistManager; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/DefaultDataIdMatchStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/DefaultDataIdMatchStrategy.java index 23abfaecd..b91fcad6b 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/DefaultDataIdMatchStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/DefaultDataIdMatchStrategy.java @@ -17,23 +17,21 @@ package com.alipay.sofa.registry.server.session.filter.blacklist; import com.alipay.sofa.registry.server.session.filter.DataIdMatchStrategy; -import org.springframework.util.StringUtils; - import java.util.function.Supplier; import java.util.regex.Pattern; +import org.springframework.util.StringUtils; /** - * * @author shangyu.wh * @version 1.0: DefaultDataIdMatchStrategy.java, v 0.1 2019-06-19 22:15 shangyu.wh Exp $ */ public class DefaultDataIdMatchStrategy implements DataIdMatchStrategy { - @Override - public boolean match(String dataId, Supplier getOperatorType) { - if (StringUtils.hasText(dataId) && StringUtils.hasText(getOperatorType.get())) { - return Pattern.matches(getOperatorType.get(), dataId); - } - return true; + @Override + public boolean match(String dataId, Supplier getOperatorType) { + if (StringUtils.hasText(dataId) && StringUtils.hasText(getOperatorType.get())) { + return Pattern.matches(getOperatorType.get(), dataId); } -} \ No newline at end of file + return true; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/DefaultIPMatchStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/DefaultIPMatchStrategy.java index f4289f374..503b0af68 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/DefaultIPMatchStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/DefaultIPMatchStrategy.java @@ -17,66 +17,62 @@ package com.alipay.sofa.registry.server.session.filter.blacklist; import com.alipay.sofa.registry.server.session.filter.IPMatchStrategy; -import org.apache.commons.lang.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.List; import java.util.Set; import java.util.function.Supplier; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version 1.0: DefaultIPMatchStrategy.java, v 0.1 2019-06-19 22:16 shangyu.wh Exp $ */ public class DefaultIPMatchStrategy implements IPMatchStrategy { - @Autowired - private BlacklistManager blacklistManager; + @Autowired private BlacklistManager blacklistManager; - @Override - public boolean match(String IP, Supplier getOperatorType) { - return match(getOperatorType.get(), IP); - } + @Override + public boolean match(String IP, Supplier getOperatorType) { + return match(getOperatorType.get(), IP); + } - private boolean match(String type, String matchPattern) { + private boolean match(String type, String matchPattern) { - List configList = blacklistManager.getBlacklistConfigList(); - for (BlacklistConfig blacklistConfig : configList) { + List configList = blacklistManager.getBlacklistConfigList(); + for (BlacklistConfig blacklistConfig : configList) { - // 如黑名单类型不匹配则跳过 - if (!StringUtils.equals(type, blacklistConfig.getType())) { - continue; - } + // 如黑名单类型不匹配则跳过 + if (!StringUtils.equals(type, blacklistConfig.getType())) { + continue; + } - List matchTypeList = blacklistConfig.getMatchTypes(); + List matchTypeList = blacklistConfig.getMatchTypes(); - // 匹配规则为空跳过 - if (null == matchTypeList || matchTypeList.size() == 0) { - continue; - } + // 匹配规则为空跳过 + if (null == matchTypeList || matchTypeList.size() == 0) { + continue; + } - for (MatchType matchType : matchTypeList) { - if (null == matchType) { - continue; - } + for (MatchType matchType : matchTypeList) { + if (null == matchType) { + continue; + } - if (BlacklistConstants.IP_FULL.equals(matchType.getType())) { - // IP 全匹配时判断当前发布者IP是否在IP列表中,如命中则拒绝发布 - @SuppressWarnings("unchecked") - Set patterns = matchType.getPatternSet(); + if (BlacklistConstants.IP_FULL.equals(matchType.getType())) { + // IP 全匹配时判断当前发布者IP是否在IP列表中,如命中则拒绝发布 + @SuppressWarnings("unchecked") + Set patterns = matchType.getPatternSet(); - if (null == patterns || patterns.size() == 0) { - continue; - } + if (null == patterns || patterns.size() == 0) { + continue; + } - if (patterns.contains(matchPattern)) { - return true; - } - } - } + if (patterns.contains(matchPattern)) { + return true; + } } - return false; + } } - -} \ No newline at end of file + return false; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/MatchType.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/MatchType.java index 6a1318770..c1332312f 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/MatchType.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/filter/blacklist/MatchType.java @@ -20,61 +20,58 @@ import java.util.Set; /** - * * @author shangyu.wh * @version 1.0: MatchType.java, v 0.1 2019-06-19 17:25 shangyu.wh Exp $ */ public class MatchType implements Serializable { - /** UID */ - private static final long serialVersionUID = 4015181538538056685L; + /** UID */ + private static final long serialVersionUID = 4015181538538056685L; - /** match type */ - private String type; + /** match type */ + private String type; - /** match patterns */ - private Set patternSet; + /** match patterns */ + private Set patternSet; - /** - * Getter method for property type. - * - * @return property value of type - */ - public String getType() { - return type; - } + /** + * Getter method for property type. + * + * @return property value of type + */ + public String getType() { + return type; + } - /** - * Setter method for property type. - * - * @param type value to be assigned to property type - */ - public void setType(String type) { - this.type = type; - } + /** + * Setter method for property type. + * + * @param type value to be assigned to property type + */ + public void setType(String type) { + this.type = type; + } - /** - * Getter method for property patternSet. - * - * @return property value of patternSet - */ - public Set getPatternSet() { - return patternSet; - } + /** + * Getter method for property patternSet. + * + * @return property value of patternSet + */ + public Set getPatternSet() { + return patternSet; + } - /** - * Setter method for property patternSet. - * - * @param patternSet value to be assigned to property patternSet - */ - public void setPatternSet(Set patternSet) { - this.patternSet = patternSet; - } + /** + * Setter method for property patternSet. + * + * @param patternSet value to be assigned to property patternSet + */ + public void setPatternSet(Set patternSet) { + this.patternSet = patternSet; + } - /** - * @see Object#toString() - */ - @Override - public String toString() { - return "MatchType{" + "type='" + type + '\'' + ", patternSet=" + patternSet + '}'; - } -} \ No newline at end of file + /** @see Object#toString() */ + @Override + public String toString() { + return "MatchType{" + "type='" + type + '\'' + ", patternSet=" + patternSet + '}'; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/limit/AccessLimitService.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/limit/AccessLimitService.java index a52069230..7e2646abf 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/limit/AccessLimitService.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/limit/AccessLimitService.java @@ -17,11 +17,9 @@ package com.alipay.sofa.registry.server.session.limit; /** - * * @author shangyu.wh - * @version 1.0: AccessLimitService.java, v 0.1 2019-08-26 20:35 shangyu.wh Exp - * $ + * @version 1.0: AccessLimitService.java, v 0.1 2019-08-26 20:35 shangyu.wh Exp $ */ public interface AccessLimitService { - boolean tryAcquire(); -} \ No newline at end of file + boolean tryAcquire(); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/limit/AccessLimitServiceImpl.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/limit/AccessLimitServiceImpl.java index 4ea248415..28b7cf21f 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/limit/AccessLimitServiceImpl.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/limit/AccessLimitServiceImpl.java @@ -20,20 +20,19 @@ import com.google.common.util.concurrent.RateLimiter; /** - * * @author shangyu.wh * @version 1.0: AccessLimitServiceImpl.java, v 0.1 2019-08-26 20:37 shangyu.wh Exp $ */ public class AccessLimitServiceImpl implements AccessLimitService { - private RateLimiter rateLimiter; + private RateLimiter rateLimiter; - public AccessLimitServiceImpl(SessionServerConfig sessionServerConfig) { - rateLimiter = RateLimiter.create(sessionServerConfig.getAccessLimitRate()); - } + public AccessLimitServiceImpl(SessionServerConfig sessionServerConfig) { + rateLimiter = RateLimiter.create(sessionServerConfig.getAccessLimitRate()); + } - @Override - public boolean tryAcquire() { - return rateLimiter.tryAcquire(); - } -} \ No newline at end of file + @Override + public boolean tryAcquire() { + return rateLimiter.tryAcquire(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/ProvideDataChangeFetchTaskListener.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/ProvideDataChangeFetchTaskListener.java index d17aeff3d..5bcece892 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/ProvideDataChangeFetchTaskListener.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/ProvideDataChangeFetchTaskListener.java @@ -30,71 +30,66 @@ import com.alipay.sofa.registry.task.listener.TaskEvent.TaskType; import com.alipay.sofa.registry.task.listener.TaskListener; import com.alipay.sofa.registry.task.listener.TaskListenerManager; -import org.springframework.beans.factory.annotation.Autowired; - import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: SubscriberRegisterFetchTaskListener.java, v 0.1 2017-12-07 19:53 shangyu.wh Exp $ */ public class ProvideDataChangeFetchTaskListener implements TaskListener { - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - /** - * trigger push client process - */ - @Autowired - private TaskListenerManager taskListenerManager; + /** trigger push client process */ + @Autowired private TaskListenerManager taskListenerManager; - /** - * MetaNode service - */ - @Autowired - private MetaServerService metaServerService; + /** MetaNode service */ + @Autowired private MetaServerService metaServerService; - @Autowired - private Exchange boltExchange; + @Autowired private Exchange boltExchange; - @Autowired - private Watchers sessionWatchers; + @Autowired private Watchers sessionWatchers; - @Autowired - private ProvideDataProcessor provideDataProcessorManager; + @Autowired private ProvideDataProcessor provideDataProcessorManager; - private TaskDispatcher singleTaskDispatcher; + private TaskDispatcher singleTaskDispatcher; - private TaskProcessor dataNodeSingleTaskProcessor; + private TaskProcessor dataNodeSingleTaskProcessor; - public ProvideDataChangeFetchTaskListener(TaskProcessor dataNodeSingleTaskProcessor) { - this.dataNodeSingleTaskProcessor = dataNodeSingleTaskProcessor; - } + public ProvideDataChangeFetchTaskListener(TaskProcessor dataNodeSingleTaskProcessor) { + this.dataNodeSingleTaskProcessor = dataNodeSingleTaskProcessor; + } - @PostConstruct - public void init() { - singleTaskDispatcher = TaskDispatchers.createDefaultSingleTaskDispatcher( + @PostConstruct + public void init() { + singleTaskDispatcher = + TaskDispatchers.createDefaultSingleTaskDispatcher( TaskType.PROVIDE_DATA_CHANGE_FETCH_TASK.getName(), dataNodeSingleTaskProcessor); - } - - @Override - public TaskType support() { - return TaskType.PROVIDE_DATA_CHANGE_FETCH_TASK; - } - - @Override - public void handleEvent(TaskEvent event) { - - SessionTask provideDataChangeFetchTask = new ProvideDataChangeFetchTask( - sessionServerConfig, taskListenerManager, metaServerService, sessionWatchers, - boltExchange, provideDataProcessorManager); - - provideDataChangeFetchTask.setTaskEvent(event); - - singleTaskDispatcher.dispatch(provideDataChangeFetchTask.getTaskId(), - provideDataChangeFetchTask, provideDataChangeFetchTask.getExpiryTime()); - } - -} \ No newline at end of file + } + + @Override + public TaskType support() { + return TaskType.PROVIDE_DATA_CHANGE_FETCH_TASK; + } + + @Override + public void handleEvent(TaskEvent event) { + + SessionTask provideDataChangeFetchTask = + new ProvideDataChangeFetchTask( + sessionServerConfig, + taskListenerManager, + metaServerService, + sessionWatchers, + boltExchange, + provideDataProcessorManager); + + provideDataChangeFetchTask.setTaskEvent(event); + + singleTaskDispatcher.dispatch( + provideDataChangeFetchTask.getTaskId(), + provideDataChangeFetchTask, + provideDataChangeFetchTask.getExpiryTime()); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/ReceivedConfigDataPushTaskListener.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/ReceivedConfigDataPushTaskListener.java index 5103ae201..21982ea2b 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/ReceivedConfigDataPushTaskListener.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/ReceivedConfigDataPushTaskListener.java @@ -16,8 +16,6 @@ */ package com.alipay.sofa.registry.server.session.listener; -import org.springframework.beans.factory.annotation.Autowired; - import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig; import com.alipay.sofa.registry.server.session.node.service.ClientNodeService; import com.alipay.sofa.registry.server.session.scheduler.task.ReceivedConfigDataPushTask; @@ -29,58 +27,58 @@ import com.alipay.sofa.registry.task.listener.TaskEvent; import com.alipay.sofa.registry.task.listener.TaskEvent.TaskType; import com.alipay.sofa.registry.task.listener.TaskListener; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: SubscriberRegisterPushTaskListener.java, v 0.1 2017-12-11 20:44 shangyu.wh Exp $ */ public class ReceivedConfigDataPushTaskListener implements TaskListener { - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Autowired - private ClientNodeService clientNodeService; + @Autowired private ClientNodeService clientNodeService; - @Autowired - private ReceivedConfigDataPushTaskStrategy receivedConfigDataPushTaskStrategy; + @Autowired private ReceivedConfigDataPushTaskStrategy receivedConfigDataPushTaskStrategy; - private volatile TaskDispatcher singleTaskDispatcher; + private volatile TaskDispatcher singleTaskDispatcher; - private TaskProcessor clientNodeSingleTaskProcessor; + private TaskProcessor clientNodeSingleTaskProcessor; - public ReceivedConfigDataPushTaskListener(TaskProcessor clientNodeSingleTaskProcessor) { + public ReceivedConfigDataPushTaskListener(TaskProcessor clientNodeSingleTaskProcessor) { - this.clientNodeSingleTaskProcessor = clientNodeSingleTaskProcessor; - } + this.clientNodeSingleTaskProcessor = clientNodeSingleTaskProcessor; + } - public TaskDispatcher getSingleTaskDispatcher() { + public TaskDispatcher getSingleTaskDispatcher() { + if (singleTaskDispatcher == null) { + synchronized (this) { if (singleTaskDispatcher == null) { - synchronized (this) { - if (singleTaskDispatcher == null) { - singleTaskDispatcher = TaskDispatchers.createDefaultSingleTaskDispatcher( - TaskType.RECEIVED_DATA_CONFIG_PUSH_TASK.getName(), - clientNodeSingleTaskProcessor); - } - } + singleTaskDispatcher = + TaskDispatchers.createDefaultSingleTaskDispatcher( + TaskType.RECEIVED_DATA_CONFIG_PUSH_TASK.getName(), clientNodeSingleTaskProcessor); } - return singleTaskDispatcher; + } } + return singleTaskDispatcher; + } - @Override - public TaskType support() { - return TaskType.RECEIVED_DATA_CONFIG_PUSH_TASK; - } + @Override + public TaskType support() { + return TaskType.RECEIVED_DATA_CONFIG_PUSH_TASK; + } - @Override - public void handleEvent(TaskEvent event) { + @Override + public void handleEvent(TaskEvent event) { - SessionTask receivedConfigDataPushTask = new ReceivedConfigDataPushTask( + SessionTask receivedConfigDataPushTask = + new ReceivedConfigDataPushTask( sessionServerConfig, clientNodeService, receivedConfigDataPushTaskStrategy); - receivedConfigDataPushTask.setTaskEvent(event); - getSingleTaskDispatcher().dispatch(receivedConfigDataPushTask.getTaskId(), - receivedConfigDataPushTask, receivedConfigDataPushTask.getExpiryTime()); - - } -} \ No newline at end of file + receivedConfigDataPushTask.setTaskEvent(event); + getSingleTaskDispatcher() + .dispatch( + receivedConfigDataPushTask.getTaskId(), + receivedConfigDataPushTask, + receivedConfigDataPushTask.getExpiryTime()); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/WatcherRegisterFetchTaskListener.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/WatcherRegisterFetchTaskListener.java index c5dd8b39c..772d5a473 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/WatcherRegisterFetchTaskListener.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/listener/WatcherRegisterFetchTaskListener.java @@ -30,64 +30,57 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: SubscriberRegisterFetchTaskListener.java, v 0.1 2017-12-07 19:53 shangyu.wh Exp $ */ public class WatcherRegisterFetchTaskListener implements TaskListener { - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - /** - * trigger push client process - */ - @Autowired - private TaskListenerManager taskListenerManager; + /** trigger push client process */ + @Autowired private TaskListenerManager taskListenerManager; - /** - * MetaNode service - */ - @Autowired - private MetaServerService metaServerService; + /** MetaNode service */ + @Autowired private MetaServerService metaServerService; - private volatile TaskDispatcher singleTaskDispatcher; + private volatile TaskDispatcher singleTaskDispatcher; - private TaskProcessor dataNodeSingleTaskProcessor; + private TaskProcessor dataNodeSingleTaskProcessor; - public WatcherRegisterFetchTaskListener(TaskProcessor dataNodeSingleTaskProcessor) { - this.dataNodeSingleTaskProcessor = dataNodeSingleTaskProcessor; - } + public WatcherRegisterFetchTaskListener(TaskProcessor dataNodeSingleTaskProcessor) { + this.dataNodeSingleTaskProcessor = dataNodeSingleTaskProcessor; + } - public TaskDispatcher getSingleTaskDispatcher() { + public TaskDispatcher getSingleTaskDispatcher() { + if (singleTaskDispatcher == null) { + synchronized (this) { if (singleTaskDispatcher == null) { - synchronized (this) { - if (singleTaskDispatcher == null) { - singleTaskDispatcher = TaskDispatchers - .createDefaultSingleTaskDispatcher( - TaskType.WATCHER_REGISTER_FETCH_TASK.getName(), - dataNodeSingleTaskProcessor); - } - } + singleTaskDispatcher = + TaskDispatchers.createDefaultSingleTaskDispatcher( + TaskType.WATCHER_REGISTER_FETCH_TASK.getName(), dataNodeSingleTaskProcessor); } - return singleTaskDispatcher; + } } + return singleTaskDispatcher; + } - @Override - public TaskType support() { - return TaskType.WATCHER_REGISTER_FETCH_TASK; - } + @Override + public TaskType support() { + return TaskType.WATCHER_REGISTER_FETCH_TASK; + } - @Override - public void handleEvent(TaskEvent event) { + @Override + public void handleEvent(TaskEvent event) { - SessionTask watcherRegisterFetchTask = new WatcherRegisterFetchTask(sessionServerConfig, - taskListenerManager, metaServerService); + SessionTask watcherRegisterFetchTask = + new WatcherRegisterFetchTask(sessionServerConfig, taskListenerManager, metaServerService); - watcherRegisterFetchTask.setTaskEvent(event); - - getSingleTaskDispatcher().dispatch(watcherRegisterFetchTask.getTaskId(), - watcherRegisterFetchTask, watcherRegisterFetchTask.getExpiryTime()); - } + watcherRegisterFetchTask.setTaskEvent(event); -} \ No newline at end of file + getSingleTaskDispatcher() + .dispatch( + watcherRegisterFetchTask.getTaskId(), + watcherRegisterFetchTask, + watcherRegisterFetchTask.getExpiryTime()); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/AppRevisionCacheRegistry.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/AppRevisionCacheRegistry.java index 7e6fcbbf2..ecf9720b5 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/AppRevisionCacheRegistry.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/AppRevisionCacheRegistry.java @@ -26,75 +26,71 @@ import com.alipay.sofa.registry.store.api.repository.InterfaceAppsRepository; import com.alipay.sofa.registry.util.ConcurrentUtils; import com.alipay.sofa.registry.util.LoopRunnable; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.util.concurrent.TimeUnit; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; public class AppRevisionCacheRegistry { - private static final Logger LOGGER = LoggerFactory - .getLogger(AppRevisionCacheRegistry.class); - private final AppRevisionRepository appRevisionRepository; - - private final InterfaceAppsRepository interfaceAppsRepository; + private static final Logger LOGGER = LoggerFactory.getLogger(AppRevisionCacheRegistry.class); + private final AppRevisionRepository appRevisionRepository; - @Autowired - private SessionServerConfig sessionServerConfig; + private final InterfaceAppsRepository interfaceAppsRepository; - private volatile boolean startWatch; + @Autowired private SessionServerConfig sessionServerConfig; - private final class RevisionWatchDog extends LoopRunnable { - @Override - public void runUnthrowable() { - if (!startWatch) { - LOGGER.info("not start watch"); - return; - } - try { - appRevisionRepository.refresh(sessionServerConfig.getSessionServerDataCenter()); - } catch (Throwable e) { - LOGGER.error("failed to watch", e); - } - } + private volatile boolean startWatch; - @Override - public void waitingUnthrowable() { - ConcurrentUtils.sleepUninterruptibly(5, TimeUnit.SECONDS); - } + private final class RevisionWatchDog extends LoopRunnable { + @Override + public void runUnthrowable() { + if (!startWatch) { + LOGGER.info("not start watch"); + return; + } + try { + appRevisionRepository.refresh(sessionServerConfig.getSessionServerDataCenter()); + } catch (Throwable e) { + LOGGER.error("failed to watch", e); + } } - @PostConstruct - public void init() { - // fixme bean加载时raftClient还未完成初始化 - ConcurrentUtils - .createDaemonThread("SessionRefreshRevisionWatchDog", new RevisionWatchDog()).start(); + @Override + public void waitingUnthrowable() { + ConcurrentUtils.sleepUninterruptibly(5, TimeUnit.SECONDS); } + } - public AppRevisionCacheRegistry(RepositoryManager repositoryManager) { - appRevisionRepository = (AppRevisionRepository) repositoryManager - .getRepository(AppRevisionRepository.class); - interfaceAppsRepository = (InterfaceAppsRepository) repositoryManager - .getRepository(InterfaceAppsRepository.class); - } + @PostConstruct + public void init() { + // fixme bean加载时raftClient还未完成初始化 + ConcurrentUtils.createDaemonThread("SessionRefreshRevisionWatchDog", new RevisionWatchDog()) + .start(); + } - public void loadMetadata() { - interfaceAppsRepository.loadMetadata(sessionServerConfig.getSessionServerDataCenter()); - startWatch = true; - } + public AppRevisionCacheRegistry(RepositoryManager repositoryManager) { + appRevisionRepository = + (AppRevisionRepository) repositoryManager.getRepository(AppRevisionRepository.class); + interfaceAppsRepository = + (InterfaceAppsRepository) repositoryManager.getRepository(InterfaceAppsRepository.class); + } - public void register(AppRevision appRevision) throws Exception { - appRevision.setDataCenter(sessionServerConfig.getSessionServerDataCenter()); - appRevisionRepository.register(appRevision); - } + public void loadMetadata() { + interfaceAppsRepository.loadMetadata(sessionServerConfig.getSessionServerDataCenter()); + startWatch = true; + } - public InterfaceMapping getAppNames(String dataInfoId) { - return interfaceAppsRepository.getAppNames( - sessionServerConfig.getSessionServerDataCenter(), dataInfoId); - } + public void register(AppRevision appRevision) throws Exception { + appRevision.setDataCenter(sessionServerConfig.getSessionServerDataCenter()); + appRevisionRepository.register(appRevision); + } - public AppRevision getRevision(String revision) { - return appRevisionRepository.queryRevision( - sessionServerConfig.getSessionServerDataCenter(), revision); - } + public InterfaceMapping getAppNames(String dataInfoId) { + return interfaceAppsRepository.getAppNames( + sessionServerConfig.getSessionServerDataCenter(), dataInfoId); + } + public AppRevision getRevision(String revision) { + return appRevisionRepository.queryRevision( + sessionServerConfig.getSessionServerDataCenter(), revision); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/AppRevisionHeartbeatRegistry.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/AppRevisionHeartbeatRegistry.java index 7997e9b35..038fd701d 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/AppRevisionHeartbeatRegistry.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/AppRevisionHeartbeatRegistry.java @@ -24,38 +24,37 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author xiaojian.xj * @version $Id: AppRevisionHeartbeatRegistry.java, v 0.1 2021年02月09日 15:47 xiaojian.xj Exp $ */ public class AppRevisionHeartbeatRegistry { - private AppRevisionRepository appRevisionRepository; + private AppRevisionRepository appRevisionRepository; - private AppRevisionHeartbeatRepository appRevisionHeartbeatRepository; + private AppRevisionHeartbeatRepository appRevisionHeartbeatRepository; - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - public AppRevisionHeartbeatRegistry(RepositoryManager repositoryManager) { - appRevisionRepository = (AppRevisionRepository) repositoryManager - .getRepository(AppRevisionRepository.class); - appRevisionHeartbeatRepository = (AppRevisionHeartbeatRepository) repositoryManager - .getRepository(AppRevisionHeartbeatRepository.class); - } + public AppRevisionHeartbeatRegistry(RepositoryManager repositoryManager) { + appRevisionRepository = + (AppRevisionRepository) repositoryManager.getRepository(AppRevisionRepository.class); + appRevisionHeartbeatRepository = + (AppRevisionHeartbeatRepository) + repositoryManager.getRepository(AppRevisionHeartbeatRepository.class); + } - public AppRevision heartbeat(String revision) { - return appRevisionRepository.heartbeat(sessionServerConfig.getSessionServerDataCenter(), - revision); - } + public AppRevision heartbeat(String revision) { + return appRevisionRepository.heartbeat( + sessionServerConfig.getSessionServerDataCenter(), revision); + } - public void doRevisionHeartbeat() { - appRevisionHeartbeatRepository.doAppRevisionHeartbeat(); - } + public void doRevisionHeartbeat() { + appRevisionHeartbeatRepository.doAppRevisionHeartbeat(); + } - public void doRevisionGc() { - appRevisionHeartbeatRepository.doAppRevisionGc( - sessionServerConfig.getSessionServerDataCenter(), - sessionServerConfig.getAppRevisionGcSilenceHour()); - } -} \ No newline at end of file + public void doRevisionGc() { + appRevisionHeartbeatRepository.doAppRevisionGc( + sessionServerConfig.getSessionServerDataCenter(), + sessionServerConfig.getAppRevisionGcSilenceHour()); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/MetadataMetrics.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/MetadataMetrics.java index 070d36500..608bc5347 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/MetadataMetrics.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/metadata/MetadataMetrics.java @@ -19,40 +19,40 @@ import io.prometheus.client.Counter; /** - * * @author xiaojian.xj * @version $Id: MetadataMetrics.java, v 0.1 2021年02月25日 16:34 xiaojian.xj Exp $ */ public class MetadataMetrics { - private MetadataMetrics() { - - } - - static final class Fetch { - static final Counter METADATA_FETCH_COUNTER = Counter.build() - .namespace("metadata").subsystem("fetch") - .name("metadata_fetch_total") - .help("metadata query revision and apps").register(); - - static final Counter.Child FETCH_REVISION_COUNTER = METADATA_FETCH_COUNTER - .labels("revision"); - static final Counter.Child FETCH_APPS_COUNTER = METADATA_FETCH_COUNTER - .labels("apps"); - } - - static final class Register { - - static final Counter METADATA_REGISTER_COUNTER = Counter.build() - .namespace("metadata").subsystem("register") - .name("metadata_register_total") - .help("metadata revision register and heartbeat").register(); - - static final Counter.Child REVISION_REGISTER_COUNTER = METADATA_REGISTER_COUNTER - .labels("register"); - - static final Counter.Child REVISION_HEARTBEAT_COUNTER = METADATA_REGISTER_COUNTER - .labels("heartbeat"); - - } -} \ No newline at end of file + private MetadataMetrics() {} + + static final class Fetch { + static final Counter METADATA_FETCH_COUNTER = + Counter.build() + .namespace("metadata") + .subsystem("fetch") + .name("metadata_fetch_total") + .help("metadata query revision and apps") + .register(); + + static final Counter.Child FETCH_REVISION_COUNTER = METADATA_FETCH_COUNTER.labels("revision"); + static final Counter.Child FETCH_APPS_COUNTER = METADATA_FETCH_COUNTER.labels("apps"); + } + + static final class Register { + + static final Counter METADATA_REGISTER_COUNTER = + Counter.build() + .namespace("metadata") + .subsystem("register") + .name("metadata_register_total") + .help("metadata revision register and heartbeat") + .register(); + + static final Counter.Child REVISION_REGISTER_COUNTER = + METADATA_REGISTER_COUNTER.labels("register"); + + static final Counter.Child REVISION_HEARTBEAT_COUNTER = + METADATA_REGISTER_COUNTER.labels("heartbeat"); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/ClientNodeSingleTaskProcessor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/ClientNodeSingleTaskProcessor.java index 0dcc28a69..c096a3f62 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/ClientNodeSingleTaskProcessor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/ClientNodeSingleTaskProcessor.java @@ -20,32 +20,30 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.server.session.scheduler.task.SessionTask; import com.alipay.sofa.registry.task.batcher.TaskProcessor; - import java.util.List; /** - * * @author shangyu.wh * @version $Id: ClientNodeSingleTaskProcessor.java, v 0.1 2017-12-11 19:47 shangyu.wh Exp $ */ public class ClientNodeSingleTaskProcessor implements TaskProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger("SESSION-PUSH", "[Task]"); + private static final Logger LOGGER = LoggerFactory.getLogger("SESSION-PUSH", "[Task]"); - @Override - public ProcessingResult process(SessionTask task) { - try { - task.execute(); - return ProcessingResult.Success; - } catch (Throwable throwable) { - LOGGER.error("Client node SingleTask Process error! Task:" + task, throwable); + @Override + public ProcessingResult process(SessionTask task) { + try { + task.execute(); + return ProcessingResult.Success; + } catch (Throwable throwable) { + LOGGER.error("Client node SingleTask Process error! Task:" + task, throwable); - return ProcessingResult.PermanentError; - } + return ProcessingResult.PermanentError; } + } - @Override - public ProcessingResult process(List tasks) { - return null; - } -} \ No newline at end of file + @Override + public ProcessingResult process(List tasks) { + return null; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/ConsoleSyncSingleTaskProcessor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/ConsoleSyncSingleTaskProcessor.java index 1273789d1..184b03527 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/ConsoleSyncSingleTaskProcessor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/ConsoleSyncSingleTaskProcessor.java @@ -21,40 +21,36 @@ import com.alipay.sofa.registry.server.session.scheduler.task.SessionTask; import com.alipay.sofa.registry.task.Retryable; import com.alipay.sofa.registry.task.batcher.TaskProcessor; - import java.util.List; /** - * * @author zhuoyu.sjw * @version $Id: ConsoleSyncSingleTaskProcessor.java, v 0.1 2018-03-31 16:46 zhuoyu.sjw Exp $$ */ public class ConsoleSyncSingleTaskProcessor implements TaskProcessor { - private static final Logger CONSOLE_LOGGER = LoggerFactory.getLogger("SESSION-CONSOLE", - "[Sync]"); + private static final Logger CONSOLE_LOGGER = LoggerFactory.getLogger("SESSION-CONSOLE", "[Sync]"); - @Override - public ProcessingResult process(SessionTask task) { - try { - CONSOLE_LOGGER.info("execute {}", task); - task.execute(); - CONSOLE_LOGGER.info("end {}", task); - return ProcessingResult.Success; - } catch (Throwable throwable) { - CONSOLE_LOGGER.error("Sync to console SingleTask Process error! Task:" + task, - throwable); - if (task instanceof Retryable) { - Retryable retryAbleTask = (Retryable) task; - if (retryAbleTask.checkRetryTimes()) { - return ProcessingResult.TransientError; - } - } - return ProcessingResult.PermanentError; + @Override + public ProcessingResult process(SessionTask task) { + try { + CONSOLE_LOGGER.info("execute {}", task); + task.execute(); + CONSOLE_LOGGER.info("end {}", task); + return ProcessingResult.Success; + } catch (Throwable throwable) { + CONSOLE_LOGGER.error("Sync to console SingleTask Process error! Task:" + task, throwable); + if (task instanceof Retryable) { + Retryable retryAbleTask = (Retryable) task; + if (retryAbleTask.checkRetryTimes()) { + return ProcessingResult.TransientError; } + } + return ProcessingResult.PermanentError; } + } - @Override - public ProcessingResult process(List tasks) { - return null; - } + @Override + public ProcessingResult process(List tasks) { + return null; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/DataNodeSingleTaskProcessor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/DataNodeSingleTaskProcessor.java index 74d6c9c43..eedf910b8 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/DataNodeSingleTaskProcessor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/DataNodeSingleTaskProcessor.java @@ -21,40 +21,38 @@ import com.alipay.sofa.registry.server.session.scheduler.task.SessionTask; import com.alipay.sofa.registry.task.Retryable; import com.alipay.sofa.registry.task.batcher.TaskProcessor; - import java.util.List; /** - * * @author shangyu.wh * @version $Id: DataNodeSingleTaskProcessor.java, v 0.1 2017-12-11 19:35 shangyu.wh Exp $ */ public class DataNodeSingleTaskProcessor implements TaskProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(DataNodeSingleTaskProcessor.class, - "[Task]"); + private static final Logger LOGGER = + LoggerFactory.getLogger(DataNodeSingleTaskProcessor.class, "[Task]"); - @Override - public ProcessingResult process(SessionTask task) { - try { - LOGGER.info("execute " + task); - task.execute(); - LOGGER.info("end " + task); - return ProcessingResult.Success; - } catch (Throwable throwable) { - LOGGER.error("Data node SingleTask Process error! Task:" + task, throwable); - if (task instanceof Retryable) { - Retryable retryAbleTask = (Retryable) task; - if (retryAbleTask.checkRetryTimes()) { - return ProcessingResult.TransientError; - } - } - return ProcessingResult.PermanentError; + @Override + public ProcessingResult process(SessionTask task) { + try { + LOGGER.info("execute " + task); + task.execute(); + LOGGER.info("end " + task); + return ProcessingResult.Success; + } catch (Throwable throwable) { + LOGGER.error("Data node SingleTask Process error! Task:" + task, throwable); + if (task instanceof Retryable) { + Retryable retryAbleTask = (Retryable) task; + if (retryAbleTask.checkRetryTimes()) { + return ProcessingResult.TransientError; } + } + return ProcessingResult.PermanentError; } + } - @Override - public ProcessingResult process(List tasks) { - return null; - } -} \ No newline at end of file + @Override + public ProcessingResult process(List tasks) { + return null; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/MetaNodeSingleTaskProcessor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/MetaNodeSingleTaskProcessor.java index 927cc5ea2..f7440385b 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/MetaNodeSingleTaskProcessor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/processor/MetaNodeSingleTaskProcessor.java @@ -21,40 +21,38 @@ import com.alipay.sofa.registry.server.session.scheduler.task.SessionTask; import com.alipay.sofa.registry.task.Retryable; import com.alipay.sofa.registry.task.batcher.TaskProcessor; - import java.util.List; /** - * * @author shangyu.wh * @version $Id: DataNodeSingleTaskProcessor.java, v 0.1 2017-12-11 19:35 shangyu.wh Exp $ */ public class MetaNodeSingleTaskProcessor implements TaskProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(MetaNodeSingleTaskProcessor.class, - "[Task]"); + private static final Logger LOGGER = + LoggerFactory.getLogger(MetaNodeSingleTaskProcessor.class, "[Task]"); - @Override - public ProcessingResult process(SessionTask task) { - try { - LOGGER.info("execute " + task); - task.execute(); - LOGGER.info("end " + task); - return ProcessingResult.Success; - } catch (Throwable throwable) { - LOGGER.error("Meta node SingleTask Process error! Task:" + task, throwable); - if (task instanceof Retryable) { - Retryable retryAbleTask = (Retryable) task; - if (retryAbleTask.checkRetryTimes()) { - return ProcessingResult.TransientError; - } - } - return ProcessingResult.PermanentError; + @Override + public ProcessingResult process(SessionTask task) { + try { + LOGGER.info("execute " + task); + task.execute(); + LOGGER.info("end " + task); + return ProcessingResult.Success; + } catch (Throwable throwable) { + LOGGER.error("Meta node SingleTask Process error! Task:" + task, throwable); + if (task instanceof Retryable) { + Retryable retryAbleTask = (Retryable) task; + if (retryAbleTask.checkRetryTimes()) { + return ProcessingResult.TransientError; } + } + return ProcessingResult.PermanentError; } + } - @Override - public ProcessingResult process(List tasks) { - return null; - } -} \ No newline at end of file + @Override + public ProcessingResult process(List tasks) { + return null; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/repository/AppRevisionRaftRepository.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/repository/AppRevisionRaftRepository.java index 80d6c9167..d5c53d173 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/repository/AppRevisionRaftRepository.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/repository/AppRevisionRaftRepository.java @@ -26,8 +26,6 @@ import com.alipay.sofa.registry.util.RevisionUtils; import com.alipay.sofa.registry.util.SingleFlight; import com.google.common.collect.Sets; -import org.springframework.beans.factory.annotation.Autowired; -import javax.annotation.Resource; import java.util.ArrayList; import java.util.Collections; import java.util.Date; @@ -36,103 +34,105 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import javax.annotation.Resource; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author xiaojian.xj * @version $Id: AppRevisionRaftRepository.java, v 0.1 2021年01月17日 15:57 xiaojian.xj Exp $ */ public class AppRevisionRaftRepository implements AppRevisionRepository, RaftRepository { - private static final Logger LOG = LoggerFactory - .getLogger(AppRevisionRaftRepository.class); - - @Autowired - private AppRevisionNodeService appRevisionNodeService; + private static final Logger LOG = LoggerFactory.getLogger(AppRevisionRaftRepository.class); - @Resource - private InterfaceAppsRaftRepository interfaceAppsRaftRepository; + @Autowired private AppRevisionNodeService appRevisionNodeService; - /** - * map: - */ - private final Map registry = new ConcurrentHashMap<>(); + @Resource private InterfaceAppsRaftRepository interfaceAppsRaftRepository; - private volatile String keysDigest = ""; + /** map: */ + private final Map registry = new ConcurrentHashMap<>(); - private SingleFlight singleFlight = new SingleFlight(); + private volatile String keysDigest = ""; - @Override - public void register(AppRevision appRevision) throws Exception { - if (this.registry.containsKey(appRevision.getRevision())) { - return; - } + private SingleFlight singleFlight = new SingleFlight(); - singleFlight.execute("revisionRegister" + appRevision.getRevision(), () -> { - appRevisionNodeService.register(appRevision); - interfaceAppsRaftRepository.onNewRevision(appRevision); - registry.putIfAbsent(appRevision.getRevision(), appRevision); - return null; - }); + @Override + public void register(AppRevision appRevision) throws Exception { + if (this.registry.containsKey(appRevision.getRevision())) { + return; } - @Override - public void refresh(String dataCenter) { - try { - singleFlight.execute("refreshAll", () -> { - List allRevisionIds = appRevisionNodeService.checkRevisions(keysDigest); - if (allRevisionIds == null || allRevisionIds.size() == 0) { - return Collections.emptyList(); - } - Set newRevisionIds = Sets.difference(new HashSet<>(allRevisionIds), registry.keySet()); - LOG.info("refresh revisions: {}, newRevisionIds: {} ", keysDigest, newRevisionIds); - List query = appRevisionNodeService.fetchMulti(new ArrayList<>(newRevisionIds)); - for (AppRevision rev : query) { - interfaceAppsRaftRepository.onNewRevision(rev); - registry.putIfAbsent(rev.getRevision(), rev); - } - if (query.size() > 0) { - keysDigest = generateKeysDigest(query); - } - return query; - }); - - } catch (Exception e) { - LOG.error("refresh revisions failed ", e); - throw new RuntimeException("refresh revision failed", e); - } - } - - @Override - public AppRevision queryRevision(String dataCenter, String revision) { - - for (int i = 0; i < 2; i++) { - // 第一次可能会被前一个revision的请求合并到导致虽然在meta内没有fetch回来,第二个fetch肯定能拿到对应 revisipn - AppRevision revisionRegister = registry.get(revision); - if (revisionRegister != null) { - return revisionRegister; + singleFlight.execute( + "revisionRegister" + appRevision.getRevision(), + () -> { + appRevisionNodeService.register(appRevision); + interfaceAppsRaftRepository.onNewRevision(appRevision); + registry.putIfAbsent(appRevision.getRevision(), appRevision); + return null; + }); + } + + @Override + public void refresh(String dataCenter) { + try { + singleFlight.execute( + "refreshAll", + () -> { + List allRevisionIds = appRevisionNodeService.checkRevisions(keysDigest); + if (allRevisionIds == null || allRevisionIds.size() == 0) { + return Collections.emptyList(); + } + Set newRevisionIds = + Sets.difference(new HashSet<>(allRevisionIds), registry.keySet()); + LOG.info("refresh revisions: {}, newRevisionIds: {} ", keysDigest, newRevisionIds); + List query = + appRevisionNodeService.fetchMulti(new ArrayList<>(newRevisionIds)); + for (AppRevision rev : query) { + interfaceAppsRaftRepository.onNewRevision(rev); + registry.putIfAbsent(rev.getRevision(), rev); } - // sync from meta raftdata - refresh(dataCenter); - } + if (query.size() > 0) { + keysDigest = generateKeysDigest(query); + } + return query; + }); - return registry.get(revision); + } catch (Exception e) { + LOG.error("refresh revisions failed ", e); + throw new RuntimeException("refresh revision failed", e); + } + } + + @Override + public AppRevision queryRevision(String dataCenter, String revision) { + + for (int i = 0; i < 2; i++) { + // 第一次可能会被前一个revision的请求合并到导致虽然在meta内没有fetch回来,第二个fetch肯定能拿到对应 revisipn + AppRevision revisionRegister = registry.get(revision); + if (revisionRegister != null) { + return revisionRegister; + } + // sync from meta raftdata + refresh(dataCenter); } - @Override - public AppRevision heartbeat(String dataCenter, String revision) { - AppRevision appRevision = registry.get(revision); - if (appRevision != null) { - appRevision.setLastHeartbeat(new Date()); - } - return appRevision; + return registry.get(revision); + } + + @Override + public AppRevision heartbeat(String dataCenter, String revision) { + AppRevision appRevision = registry.get(revision); + if (appRevision != null) { + appRevision.setLastHeartbeat(new Date()); } + return appRevision; + } - private String generateKeysDigest(List revisions) { - List keys = new ArrayList<>(); - for (AppRevision appRevision : revisions) { - keys.add(appRevision.getRevision()); - } - return RevisionUtils.revisionsDigest(keys); + private String generateKeysDigest(List revisions) { + List keys = new ArrayList<>(); + for (AppRevision appRevision : revisions) { + keys.add(appRevision.getRevision()); } -} \ No newline at end of file + return RevisionUtils.revisionsDigest(keys); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/AppRevisionNodeService.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/AppRevisionNodeService.java index 65d91a52a..146320639 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/AppRevisionNodeService.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/AppRevisionNodeService.java @@ -17,14 +17,13 @@ package com.alipay.sofa.registry.server.session.node.service; import com.alipay.sofa.registry.common.model.store.AppRevision; - import java.util.List; public interface AppRevisionNodeService { - void register(AppRevision appRevision); + void register(AppRevision appRevision); - List fetchMulti(List keys); + List fetchMulti(List keys); - List checkRevisions(String keysDigest); + List checkRevisions(String keysDigest); } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/AppRevisionNodeServiceImpl.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/AppRevisionNodeServiceImpl.java index 034eeb5a5..7fd75330e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/AppRevisionNodeServiceImpl.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/AppRevisionNodeServiceImpl.java @@ -27,85 +27,83 @@ import com.alipay.sofa.registry.remoting.exchange.message.Response; import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig; import com.alipay.sofa.registry.server.shared.meta.MetaServerManager; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; public class AppRevisionNodeServiceImpl implements AppRevisionNodeService { - private static final Logger LOGGER = LoggerFactory.getLogger( - AppRevisionNodeServiceImpl.class, - "[AppRevisionService]"); + private static final Logger LOGGER = + LoggerFactory.getLogger(AppRevisionNodeServiceImpl.class, "[AppRevisionService]"); - @Autowired - protected SessionServerConfig sessionServerConfig; + @Autowired protected SessionServerConfig sessionServerConfig; - @Autowired - private MetaServerManager metaServerManager; + @Autowired private MetaServerManager metaServerManager; - public void register(AppRevision appRevision) { - Request request = new Request() { - @Override - public AppRevision getRequestBody() { - return appRevision; - } + public void register(AppRevision appRevision) { + Request request = + new Request() { + @Override + public AppRevision getRequestBody() { + return appRevision; + } - @Override - public URL getRequestUrl() { - return new URL(metaServerManager.getMetaServerLeader(), - sessionServerConfig.getMetaServerPort()); - } + @Override + public URL getRequestUrl() { + return new URL( + metaServerManager.getMetaServerLeader(), sessionServerConfig.getMetaServerPort()); + } }; - try { - metaServerManager.sendRequest(request); - } catch (RequestException e) { - LOGGER.error("add app revision error! " + e.getMessage(), e); - throw new RuntimeException("add app revision error! " + e.getMessage(), e); - } + try { + metaServerManager.sendRequest(request); + } catch (RequestException e) { + LOGGER.error("add app revision error! " + e.getMessage(), e); + throw new RuntimeException("add app revision error! " + e.getMessage(), e); } + } - public List checkRevisions(String keysDigest) { - Request request = new Request() { - @Override - public CheckRevisionsRequest getRequestBody() { - return new CheckRevisionsRequest(keysDigest); - } + public List checkRevisions(String keysDigest) { + Request request = + new Request() { + @Override + public CheckRevisionsRequest getRequestBody() { + return new CheckRevisionsRequest(keysDigest); + } - @Override - public URL getRequestUrl() { - return new URL(metaServerManager.getMetaServerLeader(), - sessionServerConfig.getMetaServerPort()); - } + @Override + public URL getRequestUrl() { + return new URL( + metaServerManager.getMetaServerLeader(), sessionServerConfig.getMetaServerPort()); + } }; - try { - Response response = metaServerManager.sendRequest(request); - return (List) response.getResult(); - } catch (RequestException e) { - LOGGER.error("check app revisions error! " + e.getMessage(), e); - throw new RuntimeException("check app revisions error! " + e.getMessage(), e); - } - + try { + Response response = metaServerManager.sendRequest(request); + return (List) response.getResult(); + } catch (RequestException e) { + LOGGER.error("check app revisions error! " + e.getMessage(), e); + throw new RuntimeException("check app revisions error! " + e.getMessage(), e); } + } - public List fetchMulti(List keys) { - Request request = new Request() { - @Override - public FetchRevisionsRequest getRequestBody() { - return new FetchRevisionsRequest(keys); - } + public List fetchMulti(List keys) { + Request request = + new Request() { + @Override + public FetchRevisionsRequest getRequestBody() { + return new FetchRevisionsRequest(keys); + } - @Override - public URL getRequestUrl() { - return new URL(metaServerManager.getMetaServerLeader(), - sessionServerConfig.getMetaServerPort()); - } + @Override + public URL getRequestUrl() { + return new URL( + metaServerManager.getMetaServerLeader(), sessionServerConfig.getMetaServerPort()); + } }; - try { - Response response = metaServerManager.sendRequest(request); - Object result = response.getResult(); - return (List) result; - } catch (RequestException e) { - LOGGER.error("fetch app revision error! " + e.getMessage(), e); - throw new RuntimeException("fetch app revision error! " + e.getMessage(), e); - } + try { + Response response = metaServerManager.sendRequest(request); + Object result = response.getResult(); + return (List) result; + } catch (RequestException e) { + LOGGER.error("fetch app revision error! " + e.getMessage(), e); + throw new RuntimeException("fetch app revision error! " + e.getMessage(), e); } + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/ClientNodeService.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/ClientNodeService.java index dcc7b58e9..ee3976a39 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/ClientNodeService.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/ClientNodeService.java @@ -25,6 +25,5 @@ */ public interface ClientNodeService { - void pushWithCallback(Object object, URL url, - CallbackHandler callbackHandler); -} \ No newline at end of file + void pushWithCallback(Object object, URL url, CallbackHandler callbackHandler); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/ClientNodeServiceImpl.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/ClientNodeServiceImpl.java index d07e0753d..9345dae29 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/ClientNodeServiceImpl.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/ClientNodeServiceImpl.java @@ -16,40 +16,38 @@ */ package com.alipay.sofa.registry.server.session.node.service; -import org.springframework.beans.factory.annotation.Autowired; - import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.remoting.CallbackHandler; import com.alipay.sofa.registry.remoting.exchange.NodeExchanger; import com.alipay.sofa.registry.remoting.exchange.message.Request; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: ClientNode.java, v 0.1 2017-12-12 11:56 shangyu.wh Exp $ */ public class ClientNodeServiceImpl implements ClientNodeService { - @Autowired - private NodeExchanger clientNodeExchanger; + @Autowired private NodeExchanger clientNodeExchanger; - @Override - public void pushWithCallback(Object object, URL url, CallbackHandler callbackHandler) { - Request request = new Request() { - @Override - public Object getRequestBody() { - return object; - } + @Override + public void pushWithCallback(Object object, URL url, CallbackHandler callbackHandler) { + Request request = + new Request() { + @Override + public Object getRequestBody() { + return object; + } - @Override - public URL getRequestUrl() { - return url; - } + @Override + public URL getRequestUrl() { + return url; + } - @Override - public CallbackHandler getCallBackHandler() { - return callbackHandler; - } + @Override + public CallbackHandler getCallBackHandler() { + return callbackHandler; + } }; - clientNodeExchanger.request(request); - } -} \ No newline at end of file + clientNodeExchanger.request(request); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/DataNodeService.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/DataNodeService.java index 573005ea1..61f3bc65f 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/DataNodeService.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/DataNodeService.java @@ -20,54 +20,51 @@ import com.alipay.sofa.registry.common.model.dataserver.DatumVersion; import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.common.model.store.SubDatum; - import java.util.Map; /** - * * @author shangyu.wh * @version $Id: NodeService.java, v 0.1 2017-11-28 11:09 shangyu.wh Exp $ */ public interface DataNodeService { - /** - * new publisher data transform to data server - * - * @param publisher - */ - void register(Publisher publisher); - - /** - * remove publisher data from data server - * - * @param publisher - */ - void unregister(Publisher publisher); + /** + * new publisher data transform to data server + * + * @param publisher + */ + void register(Publisher publisher); - /** - * session server support api to stop some client node,all register data on data server will be removed - * data on session server will be remove too - * - * @param clientOffPublishers - */ - void clientOff(ClientOffPublishers clientOffPublishers); + /** + * remove publisher data from data server + * + * @param publisher + */ + void unregister(Publisher publisher); - /** - * Get some dataInfoId version from one data server - * - * @param slotId - * @return - */ - Map fetchDataVersion(String dataCenter, int slotId, - Map interests); + /** + * session server support api to stop some client node,all register data on data server will be + * removed data on session server will be remove too + * + * @param clientOffPublishers + */ + void clientOff(ClientOffPublishers clientOffPublishers); - /** - * fetch one dataCenter publisher data from data server - * - * @param dataInfoId - * @param dataCenterId - * @return - */ - SubDatum fetch(String dataInfoId, String dataCenterId); + /** + * Get some dataInfoId version from one data server + * + * @param slotId + * @return + */ + Map fetchDataVersion( + String dataCenter, int slotId, Map interests); -} \ No newline at end of file + /** + * fetch one dataCenter publisher data from data server + * + * @param dataInfoId + * @param dataCenterId + * @return + */ + SubDatum fetch(String dataInfoId, String dataCenterId); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/DataNodeServiceImpl.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/DataNodeServiceImpl.java index 7c2dd2579..b6f70fc27 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/DataNodeServiceImpl.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/DataNodeServiceImpl.java @@ -41,13 +41,12 @@ import com.alipay.sofa.registry.util.StringFormatter; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.apache.commons.lang.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.util.*; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; +import javax.annotation.PostConstruct; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; /** * @author shangyu.wh @@ -55,340 +54,364 @@ */ public class DataNodeServiceImpl implements DataNodeService { - private static final Logger LOGGER = LoggerFactory.getLogger(DataNodeServiceImpl.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DataNodeServiceImpl.class); - @Autowired - private NodeExchanger dataNodeExchanger; + @Autowired private NodeExchanger dataNodeExchanger; - @Autowired - private SlotTableCache slotTableCache; + @Autowired private SlotTableCache slotTableCache; - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - private Worker[] workers; - private BlockingQueues blockingQueues; + private Worker[] workers; + private BlockingQueues blockingQueues; - @PostConstruct - public void init() { - this.workers = new Worker[sessionServerConfig.getDataNodeExecutorWorkerSize()]; - blockingQueues = new BlockingQueues<>(sessionServerConfig.getDataNodeExecutorWorkerSize(), - sessionServerConfig.getDataNodeExecutorQueueSize(), false); - for (int i = 0; i < workers.length; i++) { - workers[i] = new Worker(blockingQueues.getQueue(i)); - ConcurrentUtils.createDaemonThread("req-data-worker-" + i, workers[i]).start(); - } + @PostConstruct + public void init() { + this.workers = new Worker[sessionServerConfig.getDataNodeExecutorWorkerSize()]; + blockingQueues = + new BlockingQueues<>( + sessionServerConfig.getDataNodeExecutorWorkerSize(), + sessionServerConfig.getDataNodeExecutorQueueSize(), + false); + for (int i = 0; i < workers.length; i++) { + workers[i] = new Worker(blockingQueues.getQueue(i)); + ConcurrentUtils.createDaemonThread("req-data-worker-" + i, workers[i]).start(); } - - private void commitReq(int slotId, Req req) { - int idx = slotId % blockingQueues.queueNum(); - try { - blockingQueues.put(idx, req); - } catch (FastRejectedExecutionException e) { - throw new FastRejectedExecutionException(String.format( - "commit req overflow, slotId=%d, %s", slotId, e.getMessage())); - } + } + + private void commitReq(int slotId, Req req) { + int idx = slotId % blockingQueues.queueNum(); + try { + blockingQueues.put(idx, req); + } catch (FastRejectedExecutionException e) { + throw new FastRejectedExecutionException( + String.format("commit req overflow, slotId=%d, %s", slotId, e.getMessage())); } - - @Override - public void register(final Publisher publisher) { - final int slotId = slotTableCache.slotOf(publisher.getDataInfoId()); - commitReq(slotId, new Req(slotId, publisher)); + } + + @Override + public void register(final Publisher publisher) { + final int slotId = slotTableCache.slotOf(publisher.getDataInfoId()); + commitReq(slotId, new Req(slotId, publisher)); + } + + @Override + public void unregister(final Publisher publisher) { + final int slotId = slotTableCache.slotOf(publisher.getDataInfoId()); + UnPublisher unPublisher = UnPublisher.of(publisher); + commitReq(slotId, new Req(slotId, unPublisher)); + } + + @Override + public void clientOff(ClientOffPublishers clientOffPublishers) { + if (clientOffPublishers.isEmpty()) { + return; } - - @Override - public void unregister(final Publisher publisher) { - final int slotId = slotTableCache.slotOf(publisher.getDataInfoId()); - UnPublisher unPublisher = UnPublisher.of(publisher); - commitReq(slotId, new Req(slotId, unPublisher)); + Map groups = groupBySlot(clientOffPublishers); + for (Map.Entry group : groups.entrySet()) { + final int slotId = group.getKey(); + final ClientOffPublisher clientOff = group.getValue(); + commitReq(slotId, new Req(slotId, clientOff)); } + } + + @Override + public Map fetchDataVersion( + String dataCenter, int slotId, Map interests) { + String dataNodeIp = null; + try { + final Slot slot = getSlot(slotId); + dataNodeIp = slot.getLeader(); + final GetDataVersionRequest request = + new GetDataVersionRequest(dataCenter, ServerEnv.PROCESS_ID, slotId, interests); + request.setSlotTableEpoch(slotTableCache.getEpoch()); + request.setSlotLeaderEpoch(slot.getLeaderEpoch()); + Request getDataVersionRequestRequest = + new Request() { + @Override + public GetDataVersionRequest getRequestBody() { + return request; + } - @Override - public void clientOff(ClientOffPublishers clientOffPublishers) { - if (clientOffPublishers.isEmpty()) { - return; - } - Map groups = groupBySlot(clientOffPublishers); - for (Map.Entry group : groups.entrySet()) { - final int slotId = group.getKey(); - final ClientOffPublisher clientOff = group.getValue(); - commitReq(slotId, new Req(slotId, clientOff)); - } + @Override + public URL getRequestUrl() { + return getUrl(slot); + } + }; + + Response response = dataNodeExchanger.request(getDataVersionRequestRequest); + Object result = response.getResult(); + SlotAccessGenericResponse> genericResponse = + (SlotAccessGenericResponse>) result; + if (genericResponse.isSuccess()) { + Map map = genericResponse.getData(); + return DatumUtils.intern(map); + } else { + throw new RuntimeException( + StringFormatter.format( + "GetDataVersion got fail response {}, {}, slotId={}, access={}, msg:{}", + dataNodeIp, + dataCenter, + slotId, + genericResponse.getSlotAccess(), + genericResponse.getMessage())); + } + } catch (RequestException e) { + throw new RuntimeException( + StringFormatter.format( + "GetDataVersion fail {}, slotId={}", dataNodeIp, dataCenter, slotId, e)); } + } + + @Override + public SubDatum fetch(String dataInfoId, String dataCenter) { + String dataNodeIp = null; + int slotId = -1; + try { + final Slot slot = getSlot(dataInfoId); + dataNodeIp = slot.getLeader(); + slotId = slot.getId(); + GetDataRequest getDataRequest = + new GetDataRequest(ServerEnv.PROCESS_ID, dataInfoId, dataCenter, slot.getId()); + getDataRequest.setSlotTableEpoch(slotTableCache.getEpoch()); + getDataRequest.setSlotLeaderEpoch(slot.getLeaderEpoch()); + Request getDataRequestStringRequest = + new Request() { + + @Override + public GetDataRequest getRequestBody() { + return getDataRequest; + } - @Override - public Map fetchDataVersion(String dataCenter, - int slotId, - Map interests) { - String dataNodeIp = null; - try { - final Slot slot = getSlot(slotId); - dataNodeIp = slot.getLeader(); - final GetDataVersionRequest request = new GetDataVersionRequest(dataCenter, - ServerEnv.PROCESS_ID, slotId, interests); - request.setSlotTableEpoch(slotTableCache.getEpoch()); - request.setSlotLeaderEpoch(slot.getLeaderEpoch()); - Request getDataVersionRequestRequest = new Request() { - @Override - public GetDataVersionRequest getRequestBody() { - return request; - } - - @Override - public URL getRequestUrl() { - return getUrl(slot); - } - }; - - Response response = dataNodeExchanger.request(getDataVersionRequestRequest); - Object result = response.getResult(); - SlotAccessGenericResponse> genericResponse = (SlotAccessGenericResponse>) result; - if (genericResponse.isSuccess()) { - Map map = genericResponse.getData(); - return DatumUtils.intern(map); - } else { - throw new RuntimeException(StringFormatter.format( - "GetDataVersion got fail response {}, {}, slotId={}, access={}, msg:{}", - dataNodeIp, dataCenter, slotId, genericResponse.getSlotAccess(), - genericResponse.getMessage())); + @Override + public URL getRequestUrl() { + return getUrl(slot); } - } catch (RequestException e) { - throw new RuntimeException(StringFormatter.format("GetDataVersion fail {}, slotId={}", - dataNodeIp, dataCenter, slotId, e)); - } - } - @Override - public SubDatum fetch(String dataInfoId, String dataCenter) { - String dataNodeIp = null; - int slotId = -1; - try { - final Slot slot = getSlot(dataInfoId); - dataNodeIp = slot.getLeader(); - slotId = slot.getId(); - GetDataRequest getDataRequest = new GetDataRequest(ServerEnv.PROCESS_ID, dataInfoId, - dataCenter, slot.getId()); - getDataRequest.setSlotTableEpoch(slotTableCache.getEpoch()); - getDataRequest.setSlotLeaderEpoch(slot.getLeaderEpoch()); - Request getDataRequestStringRequest = new Request() { - - @Override - public GetDataRequest getRequestBody() { - return getDataRequest; - } - - @Override - public URL getRequestUrl() { - return getUrl(slot); - } - - @Override - public Integer getTimeout() { - return sessionServerConfig.getDataNodeExchangeForFetchDatumTimeoutMillis(); - } - }; - - Response response = dataNodeExchanger.request(getDataRequestStringRequest); - Object result = response.getResult(); - SlotAccessGenericResponse genericResponse = (SlotAccessGenericResponse) result; - if (genericResponse.isSuccess()) { - final SubDatum datum = genericResponse.getData(); - return SubDatum.intern(datum); - } else { - throw new RuntimeException(StringFormatter.format( - "GetData got fail response {}, {}, {}, slotId={} msg:{}", dataNodeIp, - dataInfoId, dataCenter, slotId, genericResponse.getMessage())); + @Override + public Integer getTimeout() { + return sessionServerConfig.getDataNodeExchangeForFetchDatumTimeoutMillis(); } - } catch (RequestException e) { - throw new RuntimeException(StringFormatter.format("GetData fail {}, {}, {}, slotId={}", - dataNodeIp, dataInfoId, dataCenter, slotId), e); - } + }; + + Response response = dataNodeExchanger.request(getDataRequestStringRequest); + Object result = response.getResult(); + SlotAccessGenericResponse genericResponse = + (SlotAccessGenericResponse) result; + if (genericResponse.isSuccess()) { + final SubDatum datum = genericResponse.getData(); + return SubDatum.intern(datum); + } else { + throw new RuntimeException( + StringFormatter.format( + "GetData got fail response {}, {}, {}, slotId={} msg:{}", + dataNodeIp, + dataInfoId, + dataCenter, + slotId, + genericResponse.getMessage())); + } + } catch (RequestException e) { + throw new RuntimeException( + StringFormatter.format( + "GetData fail {}, {}, {}, slotId={}", dataNodeIp, dataInfoId, dataCenter, slotId), + e); } - - private CommonResponse sendRequest(Request request) throws RequestException { - Response response = dataNodeExchanger.request(request); - Object result = response.getResult(); - SlotAccessGenericResponse resp = (SlotAccessGenericResponse) result; - if (!resp.isSuccess()) { - throw new RuntimeException(String.format( - "response failed, target: %s, request: %s, message: %s", request.getRequestUrl(), - request.getRequestBody(), resp.getMessage())); - } - return resp; + } + + private CommonResponse sendRequest(Request request) throws RequestException { + Response response = dataNodeExchanger.request(request); + Object result = response.getResult(); + SlotAccessGenericResponse resp = (SlotAccessGenericResponse) result; + if (!resp.isSuccess()) { + throw new RuntimeException( + String.format( + "response failed, target: %s, request: %s, message: %s", + request.getRequestUrl(), request.getRequestBody(), resp.getMessage())); } - - private Slot getSlot(String dataInfoId) { - final int slotId = slotTableCache.slotOf(dataInfoId); - Slot slot = slotTableCache.getSlot(slotId); - if (slot == null) { - throw new RequestException(StringFormatter.format("slot not found for {}, slotId={}", - dataInfoId, slotId)); - } - return slot; + return resp; + } + + private Slot getSlot(String dataInfoId) { + final int slotId = slotTableCache.slotOf(dataInfoId); + Slot slot = slotTableCache.getSlot(slotId); + if (slot == null) { + throw new RequestException( + StringFormatter.format("slot not found for {}, slotId={}", dataInfoId, slotId)); } + return slot; + } - private Slot getSlot(int slotId) { - Slot slot = slotTableCache.getSlot(slotId); - if (slot == null) { - throw new RequestException(StringFormatter.format("slot not found, slotId={}", slotId)); - } - return slot; + private Slot getSlot(int slotId) { + Slot slot = slotTableCache.getSlot(slotId); + if (slot == null) { + throw new RequestException(StringFormatter.format("slot not found, slotId={}", slotId)); } + return slot; + } - private URL getUrl(Slot slot) { - final String dataIp = slot.getLeader(); - if (StringUtils.isBlank(dataIp)) { - throw new RequestException(String.format("slot has no leader, slotId=%s", slot)); - } - return new URL(dataIp, sessionServerConfig.getDataServerPort()); + private URL getUrl(Slot slot) { + final String dataIp = slot.getLeader(); + if (StringUtils.isBlank(dataIp)) { + throw new RequestException(String.format("slot has no leader, slotId=%s", slot)); } - - private Map groupBySlot(ClientOffPublishers clientOffPublishers) { - List publishers = clientOffPublishers.getPublishers(); - Map ret = Maps.newHashMap(); - for (Publisher publisher : publishers) { - final String dataInfoId = publisher.getDataInfoId(); - int slotId = slotTableCache.slotOf(dataInfoId); - ClientOffPublisher request = ret.computeIfAbsent(slotId, - k -> new ClientOffPublisher(clientOffPublishers.getConnectId())); - request.addPublisher(publisher); - } - return ret; + return new URL(dataIp, sessionServerConfig.getDataServerPort()); + } + + private Map groupBySlot(ClientOffPublishers clientOffPublishers) { + List publishers = clientOffPublishers.getPublishers(); + Map ret = Maps.newHashMap(); + for (Publisher publisher : publishers) { + final String dataInfoId = publisher.getDataInfoId(); + int slotId = slotTableCache.slotOf(dataInfoId); + ClientOffPublisher request = + ret.computeIfAbsent( + slotId, k -> new ClientOffPublisher(clientOffPublishers.getConnectId())); + request.addPublisher(publisher); } + return ret; + } - private static final class Req { - final int slotId; - final Object req; + private static final class Req { + final int slotId; + final Object req; - Req(int slotId, Object req) { - this.slotId = slotId; - this.req = req; - } + Req(int slotId, Object req) { + this.slotId = slotId; + this.req = req; } + } - private static final class RetryBatch { - final BatchRequest batch; - long expireTimestamp; - int retryCount; + private static final class RetryBatch { + final BatchRequest batch; + long expireTimestamp; + int retryCount; - RetryBatch(BatchRequest batch) { - this.batch = batch; - } + RetryBatch(BatchRequest batch) { + this.batch = batch; + } - @Override - public String toString() { - return "RetryBatch{" + "batch=" + batch + ", retry=" + retryCount + ", expire=" - + expireTimestamp + '}'; - } + @Override + public String toString() { + return "RetryBatch{" + + "batch=" + + batch + + ", retry=" + + retryCount + + ", expire=" + + expireTimestamp + + '}'; } + } - private final class Worker implements Runnable { - final BlockingQueue queue; - final LinkedList retryBatches = Lists.newLinkedList(); + private final class Worker implements Runnable { + final BlockingQueue queue; + final LinkedList retryBatches = Lists.newLinkedList(); - Worker(BlockingQueue queue) { - this.queue = queue; - } + Worker(BlockingQueue queue) { + this.queue = queue; + } - @Override - public void run() { - for (;;) { - try { - final Req firstReq = queue.poll(200, TimeUnit.MILLISECONDS); - if (firstReq != null) { - // TODO config max - Map> reqs = drainReq(queue, 100); - // send by order, firstReq.slotId is the first one - LinkedList firstBatch = reqs.remove(firstReq.slotId); - if (firstBatch == null) { - firstBatch = Lists.newLinkedList(); - } - firstBatch.addFirst(firstReq.req); - request(firstReq.slotId, firstBatch); - for (Map.Entry> batch : reqs.entrySet()) { - request(batch.getKey(), batch.getValue()); - } - } - // check the retry - if (!retryBatches.isEmpty()) { - final Iterator it = retryBatches.iterator(); - List retries = Lists.newArrayList(); - while (it.hasNext()) { - RetryBatch batch = it.next(); - it.remove(); - if (!DataNodeServiceImpl.this.request(batch.batch)) { - retries.add(batch); - } - } - for (RetryBatch retry : retries) { - retry(retry); - } - } - } catch (Throwable e) { - LOGGER.error("failed to request batch", e); - } + @Override + public void run() { + for (; ; ) { + try { + final Req firstReq = queue.poll(200, TimeUnit.MILLISECONDS); + if (firstReq != null) { + // TODO config max + Map> reqs = drainReq(queue, 100); + // send by order, firstReq.slotId is the first one + LinkedList firstBatch = reqs.remove(firstReq.slotId); + if (firstBatch == null) { + firstBatch = Lists.newLinkedList(); } - } - - private boolean retry(RetryBatch retry) { - retry.retryCount++; - if (retry.retryCount <= sessionServerConfig.getDataNodeRetryTimes()) { - if (retryBatches.size() >= sessionServerConfig.getDataNodeRetryQueueSize()) { - // remove the oldest - retryBatches.removeFirst(); - } - retry.expireTimestamp = System.currentTimeMillis() - + sessionServerConfig.getDataNodeRetryBackoffMillis(); - retryBatches.add(retry); - return true; + firstBatch.addFirst(firstReq.req); + request(firstReq.slotId, firstBatch); + for (Map.Entry> batch : reqs.entrySet()) { + request(batch.getKey(), batch.getValue()); } - return false; - } - - private boolean request(int slotId, List reqs) { - final BatchRequest batch = new BatchRequest(ServerEnv.PROCESS_ID, slotId, reqs); - if (!DataNodeServiceImpl.this.request(batch)) { - retry(new RetryBatch(batch)); - return false; + } + // check the retry + if (!retryBatches.isEmpty()) { + final Iterator it = retryBatches.iterator(); + List retries = Lists.newArrayList(); + while (it.hasNext()) { + RetryBatch batch = it.next(); + it.remove(); + if (!DataNodeServiceImpl.this.request(batch.batch)) { + retries.add(batch); + } } - return true; + for (RetryBatch retry : retries) { + retry(retry); + } + } + } catch (Throwable e) { + LOGGER.error("failed to request batch", e); } + } } - private boolean request(BatchRequest batch) { - try { - final Slot slot = getSlot(batch.getSlotId()); - batch.setSlotTableEpoch(slotTableCache.getEpoch()); - batch.setSlotLeaderEpoch(slot.getLeaderEpoch()); - sendRequest(new Request() { - @Override - public Object getRequestBody() { - return batch; - } - - @Override - public URL getRequestUrl() { - return getUrl(slot); - } - }); - return true; - } catch (Throwable e) { - LOGGER.error("failed to request batch, {}", batch, e); - return false; + private boolean retry(RetryBatch retry) { + retry.retryCount++; + if (retry.retryCount <= sessionServerConfig.getDataNodeRetryTimes()) { + if (retryBatches.size() >= sessionServerConfig.getDataNodeRetryQueueSize()) { + // remove the oldest + retryBatches.removeFirst(); } + retry.expireTimestamp = + System.currentTimeMillis() + sessionServerConfig.getDataNodeRetryBackoffMillis(); + retryBatches.add(retry); + return true; + } + return false; } - private Map> drainReq(BlockingQueue queue, int max) { - List reqs = new ArrayList<>(max); - queue.drainTo(reqs, max); - if (reqs.isEmpty()) { - return Collections.emptyMap(); - } - Map> ret = Maps.newLinkedHashMap(); - for (Req req : reqs) { - LinkedList objects = ret.computeIfAbsent(req.slotId, k -> Lists.newLinkedList()); - objects.add(req.req); - } - return ret; + private boolean request(int slotId, List reqs) { + final BatchRequest batch = new BatchRequest(ServerEnv.PROCESS_ID, slotId, reqs); + if (!DataNodeServiceImpl.this.request(batch)) { + retry(new RetryBatch(batch)); + return false; + } + return true; + } + } + + private boolean request(BatchRequest batch) { + try { + final Slot slot = getSlot(batch.getSlotId()); + batch.setSlotTableEpoch(slotTableCache.getEpoch()); + batch.setSlotLeaderEpoch(slot.getLeaderEpoch()); + sendRequest( + new Request() { + @Override + public Object getRequestBody() { + return batch; + } + + @Override + public URL getRequestUrl() { + return getUrl(slot); + } + }); + return true; + } catch (Throwable e) { + LOGGER.error("failed to request batch, {}", batch, e); + return false; + } + } + + private Map> drainReq(BlockingQueue queue, int max) { + List reqs = new ArrayList<>(max); + queue.drainTo(reqs, max); + if (reqs.isEmpty()) { + return Collections.emptyMap(); + } + Map> ret = Maps.newLinkedHashMap(); + for (Req req : reqs) { + LinkedList objects = ret.computeIfAbsent(req.slotId, k -> Lists.newLinkedList()); + objects.add(req.req); } -} \ No newline at end of file + return ret; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/MetaServerServiceImpl.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/MetaServerServiceImpl.java index 77017c47a..15692b9ba 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/MetaServerServiceImpl.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/MetaServerServiceImpl.java @@ -28,56 +28,55 @@ import com.alipay.sofa.registry.server.session.slot.SlotTableCache; import com.alipay.sofa.registry.server.shared.env.ServerEnv; import com.alipay.sofa.registry.server.shared.meta.AbstractMetaServerService; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Set; +import org.springframework.beans.factory.annotation.Autowired; /** * @author yuzhi.lyz * @version v 0.1 2020-11-28 20:05 yuzhi.lyz Exp $ */ -public final class MetaServerServiceImpl extends - AbstractMetaServerService { +public final class MetaServerServiceImpl + extends AbstractMetaServerService { - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Autowired - private SlotTableCache slotTableCache; + @Autowired private SlotTableCache slotTableCache; - @Autowired - private DataNodeExchanger dataNodeExchanger; + @Autowired private DataNodeExchanger dataNodeExchanger; - @Override - protected long getCurrentSlotTableEpoch() { - return slotTableCache.getEpoch(); - } + @Override + protected long getCurrentSlotTableEpoch() { + return slotTableCache.getEpoch(); + } - @Override - protected void handleRenewResult(SessionHeartBeatResponse result) { - Set dataServerList = getDataServerList(); - if (dataServerList != null && !dataServerList.isEmpty()) { - dataNodeExchanger.setServerIps(dataServerList); - dataNodeExchanger.notifyConnectServerAsync(); - } - if (result.getSlotTable() != null && result.getSlotTable() != SlotTable.INIT) { - slotTableCache.updateSlotTable(result.getSlotTable()); - } else { - LOGGER.warn("[handleRenewResult] no slot table result"); - } + @Override + protected void handleRenewResult(SessionHeartBeatResponse result) { + Set dataServerList = getDataServerList(); + if (dataServerList != null && !dataServerList.isEmpty()) { + dataNodeExchanger.setServerIps(dataServerList); + dataNodeExchanger.notifyConnectServerAsync(); } - - @Override - protected HeartbeatRequest createRequest() { - return new HeartbeatRequest(createNode(), slotTableCache.getEpoch(), - sessionServerConfig.getSessionServerDataCenter(), System.currentTimeMillis(), - new SlotConfig.SlotBasicInfo(SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, - SlotConfig.FUNC)).setSlotTable(slotTableCache.currentSlotTable()); + if (result.getSlotTable() != null && result.getSlotTable() != SlotTable.INIT) { + slotTableCache.updateSlotTable(result.getSlotTable()); + } else { + LOGGER.warn("[handleRenewResult] no slot table result"); } + } - private Node createNode() { - return new SessionNode(new URL(ServerEnv.IP), sessionServerConfig.getSessionServerRegion()) - .setProcessId(ServerEnv.PROCESS_ID); - } + @Override + protected HeartbeatRequest createRequest() { + return new HeartbeatRequest( + createNode(), + slotTableCache.getEpoch(), + sessionServerConfig.getSessionServerDataCenter(), + System.currentTimeMillis(), + new SlotConfig.SlotBasicInfo( + SlotConfig.SLOT_NUM, SlotConfig.SLOT_REPLICAS, SlotConfig.FUNC)) + .setSlotTable(slotTableCache.currentSlotTable()); + } + private Node createNode() { + return new SessionNode(new URL(ServerEnv.IP), sessionServerConfig.getSessionServerRegion()) + .setProcessId(ServerEnv.PROCESS_ID); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/SessionMetaServerManager.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/SessionMetaServerManager.java index 367682613..50b2290fd 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/SessionMetaServerManager.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/node/service/SessionMetaServerManager.java @@ -18,32 +18,29 @@ import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig; import com.alipay.sofa.registry.server.shared.meta.AbstractMetaServerManager; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Collection; +import org.springframework.beans.factory.annotation.Autowired; /** * @author chen.zhu - *

- * Mar 15, 2021 + *

Mar 15, 2021 */ public class SessionMetaServerManager extends AbstractMetaServerManager { - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Override - protected Collection getConfiguredMetaServerDomains() { - return sessionServerConfig.getMetaServerAddresses(); - } + @Override + protected Collection getConfiguredMetaServerDomains() { + return sessionServerConfig.getMetaServerAddresses(); + } - @Override - public int getRpcTimeoutMillis() { - return sessionServerConfig.getMetaNodeExchangeTimeoutMillis(); - } + @Override + public int getRpcTimeoutMillis() { + return sessionServerConfig.getMetaNodeExchangeTimeoutMillis(); + } - @Override - public int getServerPort() { - return sessionServerConfig.getMetaServerPort(); - } + @Override + public int getServerPort() { + return sessionServerConfig.getMetaServerPort(); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/predicate/ZonePredicate.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/predicate/ZonePredicate.java index 0219dd7e7..fc441c338 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/predicate/ZonePredicate.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/predicate/ZonePredicate.java @@ -18,35 +18,36 @@ import com.alipay.sofa.registry.core.model.ScopeEnum; import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig; - import java.util.function.Predicate; /** - * * @author xiaojian.xj * @version $Id: ZonePredicate.java, v 0.1 2020年11月12日 21:57 xiaojian.xj Exp $ */ public class ZonePredicate { - public static Predicate zonePredicate(String dataId, String clientCell, - ScopeEnum scopeEnum, SessionServerConfig sessionServerConfig) { - Predicate zonePredicate = (zone) -> { - if (!clientCell.equals(zone)) { - if (ScopeEnum.zone == scopeEnum) { - // zone scope subscribe only return zone list - return true; + public static Predicate zonePredicate( + String dataId, + String clientCell, + ScopeEnum scopeEnum, + SessionServerConfig sessionServerConfig) { + Predicate zonePredicate = + (zone) -> { + if (!clientCell.equals(zone)) { + if (ScopeEnum.zone == scopeEnum) { + // zone scope subscribe only return zone list + return true; - } else if (ScopeEnum.dataCenter == scopeEnum || ScopeEnum.global == scopeEnum) { - // disable zone config - if (sessionServerConfig.isInvalidForeverZone(zone) && !sessionServerConfig - .isInvalidIgnored(dataId)) { - return true; - } - } + } else if (ScopeEnum.dataCenter == scopeEnum || ScopeEnum.global == scopeEnum) { + // disable zone config + if (sessionServerConfig.isInvalidForeverZone(zone) + && !sessionServerConfig.isInvalidIgnored(dataId)) { + return true; + } } - return false; - + } + return false; }; - return zonePredicate; - } -} \ No newline at end of file + return zonePredicate; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/ProvideDataProcessor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/ProvideDataProcessor.java index 19cca6ebf..1824e6f2c 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/ProvideDataProcessor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/ProvideDataProcessor.java @@ -19,16 +19,14 @@ import com.alipay.sofa.registry.common.model.metaserver.ProvideData; /** - * * @author shangyu.wh - * @version 1.0: ProvideDataProcessor.java, v 0.1 2019-10-09 17:26 shangyu.wh - * Exp $ + * @version 1.0: ProvideDataProcessor.java, v 0.1 2019-10-09 17:26 shangyu.wh Exp $ */ public interface ProvideDataProcessor { - void changeDataProcess(ProvideData provideData); + void changeDataProcess(ProvideData provideData); - void fetchDataProcess(ProvideData provideData); + void fetchDataProcess(ProvideData provideData); - boolean support(ProvideData provideData); -} \ No newline at end of file + boolean support(ProvideData provideData); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/ProvideDataProcessorManager.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/ProvideDataProcessorManager.java index c68dafc46..5f48f4f68 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/ProvideDataProcessorManager.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/ProvideDataProcessorManager.java @@ -17,43 +17,41 @@ package com.alipay.sofa.registry.server.session.provideData; import com.alipay.sofa.registry.common.model.metaserver.ProvideData; - import java.util.ArrayList; import java.util.Collection; /** - * * @author shangyu.wh * @version 1.0: ProvideDataProcessorManager.java, v 0.1 2019-10-09 17:39 shangyu.wh Exp $ */ public class ProvideDataProcessorManager implements ProvideDataProcessor { - private Collection provideDataProcessors = new ArrayList<>(); + private Collection provideDataProcessors = new ArrayList<>(); - public void addProvideDataProcessor(ProvideDataProcessor provideDataProcessor) { - provideDataProcessors.add(provideDataProcessor); - } + public void addProvideDataProcessor(ProvideDataProcessor provideDataProcessor) { + provideDataProcessors.add(provideDataProcessor); + } - @Override - public void changeDataProcess(ProvideData provideData) { - for (ProvideDataProcessor provideDataProcessor : provideDataProcessors) { - if (provideDataProcessor.support(provideData)) { - provideDataProcessor.changeDataProcess(provideData); - } - } + @Override + public void changeDataProcess(ProvideData provideData) { + for (ProvideDataProcessor provideDataProcessor : provideDataProcessors) { + if (provideDataProcessor.support(provideData)) { + provideDataProcessor.changeDataProcess(provideData); + } } - - @Override - public void fetchDataProcess(ProvideData provideData) { - for (ProvideDataProcessor provideDataProcessor : provideDataProcessors) { - if (provideDataProcessor.support(provideData)) { - provideDataProcessor.fetchDataProcess(provideData); - } - } + } + + @Override + public void fetchDataProcess(ProvideData provideData) { + for (ProvideDataProcessor provideDataProcessor : provideDataProcessors) { + if (provideDataProcessor.support(provideData)) { + provideDataProcessor.fetchDataProcess(provideData); + } } + } - @Override - public boolean support(ProvideData provideData) { - return false; - } -} \ No newline at end of file + @Override + public boolean support(ProvideData provideData) { + return false; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/processor/BlackListProvideDataProcessor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/processor/BlackListProvideDataProcessor.java index fc00f8bcc..ec64542ac 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/processor/BlackListProvideDataProcessor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/processor/BlackListProvideDataProcessor.java @@ -29,106 +29,95 @@ import com.alipay.sofa.registry.server.session.filter.blacklist.BlacklistManager; import com.alipay.sofa.registry.server.session.provideData.ProvideDataProcessor; import com.alipay.sofa.registry.server.session.registry.Registry; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.*; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version 1.0: BlackListProvideDataProcessor.java, v 0.1 2019-10-09 20:21 shangyu.wh Exp $ */ public class BlackListProvideDataProcessor implements ProvideDataProcessor { - private static final Logger LOGGER = LoggerFactory - .getLogger(BlackListProvideDataProcessor.class); + private static final Logger LOGGER = LoggerFactory.getLogger(BlackListProvideDataProcessor.class); - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Autowired - private Registry sessionRegistry; + @Autowired private Registry sessionRegistry; - @Autowired - private Exchange boltExchange; + @Autowired private Exchange boltExchange; - @Autowired - private BlacklistManager blacklistManager; + @Autowired private BlacklistManager blacklistManager; - @Override - public void changeDataProcess(ProvideData provideData) { - if (provideData == null) { - LOGGER.warn("Fetch session blacklist data null"); - return; - } - //black list data - final String data = ProvideData.toString(provideData); - if (data == null) { - LOGGER.warn("Fetch session blacklist content null"); - return; - } - LOGGER.info("Fetch session blacklist {}", data); - - Map>> blacklistConfigMap = blacklistManager - .convertBlacklistConfig(data); - clientOffBlackIp(blacklistConfigMap); - LOGGER.info("update BlacklistConfig", blacklistConfigMap); + @Override + public void changeDataProcess(ProvideData provideData) { + if (provideData == null) { + LOGGER.warn("Fetch session blacklist data null"); + return; } - - private void clientOffBlackIp(Map>> blacklistConfigMap) { - - if (blacklistConfigMap != null) { - Set ipSet = new HashSet(); - - for (Map.Entry>> configEntry : blacklistConfigMap - .entrySet()) { - if (BlacklistConstants.FORBIDDEN_PUB.equals(configEntry.getKey()) - || BlacklistConstants.FORBIDDEN_SUB_BY_PREFIX.equals(configEntry.getKey())) { - Map> typeMap = configEntry.getValue(); - if (typeMap != null) { - for (Map.Entry> typeEntry : typeMap.entrySet()) { - if (BlacklistConstants.IP_FULL.equals(typeEntry.getKey())) { - if (typeEntry.getValue() != null) { - ipSet.addAll(typeEntry.getValue()); - } - } - } - } + // black list data + final String data = ProvideData.toString(provideData); + if (data == null) { + LOGGER.warn("Fetch session blacklist content null"); + return; + } + LOGGER.info("Fetch session blacklist {}", data); + + Map>> blacklistConfigMap = + blacklistManager.convertBlacklistConfig(data); + clientOffBlackIp(blacklistConfigMap); + LOGGER.info("update BlacklistConfig", blacklistConfigMap); + } + + private void clientOffBlackIp(Map>> blacklistConfigMap) { + + if (blacklistConfigMap != null) { + Set ipSet = new HashSet(); + + for (Map.Entry>> configEntry : + blacklistConfigMap.entrySet()) { + if (BlacklistConstants.FORBIDDEN_PUB.equals(configEntry.getKey()) + || BlacklistConstants.FORBIDDEN_SUB_BY_PREFIX.equals(configEntry.getKey())) { + Map> typeMap = configEntry.getValue(); + if (typeMap != null) { + for (Map.Entry> typeEntry : typeMap.entrySet()) { + if (BlacklistConstants.IP_FULL.equals(typeEntry.getKey())) { + if (typeEntry.getValue() != null) { + ipSet.addAll(typeEntry.getValue()); } - + } } - - sessionRegistry.remove(getIpConnects(ipSet)); + } } + } + + sessionRegistry.remove(getIpConnects(ipSet)); } + } - public List getIpConnects(Set _ipList) { + public List getIpConnects(Set _ipList) { - Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort()); + Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort()); - List connections = new ArrayList<>(); + List connections = new ArrayList<>(); - if (sessionServer != null) { - Collection channels = sessionServer.getChannels(); - for (Channel channel : channels) { - String ip = channel.getRemoteAddress().getAddress().getHostAddress(); - if (_ipList.contains(ip)) { - connections.add(ConnectId.of(channel.getRemoteAddress(), - channel.getLocalAddress())); - } - } + if (sessionServer != null) { + Collection channels = sessionServer.getChannels(); + for (Channel channel : channels) { + String ip = channel.getRemoteAddress().getAddress().getHostAddress(); + if (_ipList.contains(ip)) { + connections.add(ConnectId.of(channel.getRemoteAddress(), channel.getLocalAddress())); } - - return connections; + } } - @Override - public void fetchDataProcess(ProvideData provideData) { + return connections; + } - } + @Override + public void fetchDataProcess(ProvideData provideData) {} - @Override - public boolean support(ProvideData provideData) { - return ValueConstants.BLACK_LIST_DATA_ID.equals(provideData.getDataInfoId()); - } -} \ No newline at end of file + @Override + public boolean support(ProvideData provideData) { + return ValueConstants.BLACK_LIST_DATA_ID.equals(provideData.getDataInfoId()); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/processor/StopPushProvideDataProcessor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/processor/StopPushProvideDataProcessor.java index 7fd644dce..37d55c209 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/processor/StopPushProvideDataProcessor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/provideData/processor/StopPushProvideDataProcessor.java @@ -26,52 +26,50 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version 1.0: StopPushProvideDataProcessor.java, v 0.1 2019-10-09 18:53 shangyu.wh Exp $ */ public class StopPushProvideDataProcessor implements ProvideDataProcessor { - private static final Logger LOGGER = LoggerFactory - .getLogger(StopPushProvideDataProcessor.class); - - @Autowired - private SessionServerConfig sessionServerConfig; - - @Autowired - private Registry sessionRegistry; + private static final Logger LOGGER = LoggerFactory.getLogger(StopPushProvideDataProcessor.class); - @Override - public void changeDataProcess(ProvideData provideData) { - if (provideData == null) { - LOGGER.info("Fetch session stopPushSwitch null"); - return; - } + @Autowired private SessionServerConfig sessionServerConfig; - //push stop switch - final Boolean stop = ProvideData.toBool(provideData); - if (stop == null) { - LOGGER.info("Fetch session stopPushSwitch content null"); - return; - } - boolean prev = sessionServerConfig.isStopPushSwitch(); - sessionServerConfig.setStopPushSwitch(stop); - if (prev && !stop) { - // prev is stop, now close stop, trigger push - sessionRegistry.fetchChangDataProcess(); - } - LOGGER.info("Fetch session stopPushSwitch={}, prev={}, current={}", stop, prev, - sessionServerConfig.isStopPushSwitch()); + @Autowired private Registry sessionRegistry; + @Override + public void changeDataProcess(ProvideData provideData) { + if (provideData == null) { + LOGGER.info("Fetch session stopPushSwitch null"); + return; } - @Override - public void fetchDataProcess(ProvideData provideData) { - changeDataProcess(provideData); + // push stop switch + final Boolean stop = ProvideData.toBool(provideData); + if (stop == null) { + LOGGER.info("Fetch session stopPushSwitch content null"); + return; } - - @Override - public boolean support(ProvideData provideData) { - return ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID.equals(provideData.getDataInfoId()); + boolean prev = sessionServerConfig.isStopPushSwitch(); + sessionServerConfig.setStopPushSwitch(stop); + if (prev && !stop) { + // prev is stop, now close stop, trigger push + sessionRegistry.fetchChangDataProcess(); } + LOGGER.info( + "Fetch session stopPushSwitch={}, prev={}, current={}", + stop, + prev, + sessionServerConfig.isStopPushSwitch()); + } + + @Override + public void fetchDataProcess(ProvideData provideData) { + changeDataProcess(provideData); + } + + @Override + public boolean support(ProvideData provideData) { + return ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID.equals(provideData.getDataInfoId()); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/ChangeProcessor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/ChangeProcessor.java index 5c7f54b2b..5013cd822 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/ChangeProcessor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/ChangeProcessor.java @@ -22,173 +22,177 @@ import com.alipay.sofa.registry.util.ConcurrentUtils; import com.alipay.sofa.registry.util.WakeUpLoopRunnable; import com.google.common.collect.Maps; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Objects; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; public class ChangeProcessor { - private static final Logger LOGGER = LoggerFactory.getLogger(ChangeProcessor.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ChangeProcessor.class); - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - private Worker[] workers; - private int changeDebouncingMillis; - private int changeDebouncingMaxMillis; + private Worker[] workers; + private int changeDebouncingMillis; + private int changeDebouncingMaxMillis; - @PostConstruct - public void init() { - this.changeDebouncingMillis = sessionServerConfig.getDataChangeDebouncingMillis(); - this.changeDebouncingMaxMillis = sessionServerConfig.getDataChangeMaxDebouncingMillis(); + @PostConstruct + public void init() { + this.changeDebouncingMillis = sessionServerConfig.getDataChangeDebouncingMillis(); + this.changeDebouncingMaxMillis = sessionServerConfig.getDataChangeMaxDebouncingMillis(); - this.workers = new Worker[sessionServerConfig.getDataChangeFetchTaskWorkerSize()]; - for (int i = 0; i < workers.length; i++) { - workers[i] = new Worker(); - ConcurrentUtils.createDaemonThread("ChangeExecutor-" + i, workers[i]).start(); - } + this.workers = new Worker[sessionServerConfig.getDataChangeFetchTaskWorkerSize()]; + for (int i = 0; i < workers.length; i++) { + workers[i] = new Worker(); + ConcurrentUtils.createDaemonThread("ChangeExecutor-" + i, workers[i]).start(); } - - boolean fireChange(String dataCenter, String dataInfoId, ChangeHandler handler, - long expectDatumVersion) { - ChangeKey key = new ChangeKey(dataCenter, dataInfoId); - Worker worker = workerOf(key); - return worker.commitChange(key, handler, expectDatumVersion); + } + + boolean fireChange( + String dataCenter, String dataInfoId, ChangeHandler handler, long expectDatumVersion) { + ChangeKey key = new ChangeKey(dataCenter, dataInfoId); + Worker worker = workerOf(key); + return worker.commitChange(key, handler, expectDatumVersion); + } + + interface ChangeHandler { + void onChange(String dataCenter, String dataInfoId, long expectDatumVersion); + } + + private static final class ChangeTask { + final ChangeKey key; + final ChangeHandler changeHandler; + long expectDatumVersion; + final long expireTimestamp; + long expireDeadlineTimestamp; + + ChangeTask( + ChangeKey key, long expectDatumVersion, ChangeHandler changeHandler, long expireTimestamp) { + this.key = key; + this.changeHandler = changeHandler; + this.expectDatumVersion = expectDatumVersion; + this.expireTimestamp = expireTimestamp; } - interface ChangeHandler { - void onChange(String dataCenter, String dataInfoId, long expectDatumVersion); + void doChange() { + changeHandler.onChange(key.dataCenter, key.dataInfoId, expectDatumVersion); } - private static final class ChangeTask { - final ChangeKey key; - final ChangeHandler changeHandler; - long expectDatumVersion; - final long expireTimestamp; - long expireDeadlineTimestamp; - - ChangeTask(ChangeKey key, long expectDatumVersion, ChangeHandler changeHandler, - long expireTimestamp) { - this.key = key; - this.changeHandler = changeHandler; - this.expectDatumVersion = expectDatumVersion; - this.expireTimestamp = expireTimestamp; + @Override + public String toString() { + return "ChangeTask{" + + "key=" + + key + + ", version=" + + expectDatumVersion + + ", expire=" + + expireTimestamp + + ", deadline=" + + expireDeadlineTimestamp + + '}'; + } + } + + private final class Worker extends WakeUpLoopRunnable { + final LinkedHashMap tasks = Maps.newLinkedHashMap(); + + boolean commitChange(ChangeKey key, ChangeHandler handler, long expectDatumVersion) { + synchronized (tasks) { + final long now = System.currentTimeMillis(); + final ChangeTask task = + new ChangeTask(key, expectDatumVersion, handler, now + changeDebouncingMillis); + final ChangeTask exist = tasks.get(key); + if (exist == null) { + task.expireDeadlineTimestamp = now + changeDebouncingMaxMillis; + tasks.put(key, task); + return true; } - - void doChange() { - changeHandler.onChange(key.dataCenter, key.dataInfoId, expectDatumVersion); + if (task.expectDatumVersion <= exist.expectDatumVersion) { + return false; } - @Override - public String toString() { - return "ChangeTask{" + "key=" + key + ", version=" + expectDatumVersion + ", expire=" - + expireTimestamp + ", deadline=" + expireDeadlineTimestamp + '}'; + if (task.expireTimestamp <= exist.expireDeadlineTimestamp) { + // requeue, expire is before deadline, remove first, unlink the list + task.expireDeadlineTimestamp = exist.expireDeadlineTimestamp; + tasks.remove(key); + tasks.put(key, task); + } else { + // reach deadline, could not requeue, replace the exist + exist.expectDatumVersion = task.expectDatumVersion; } + return true; + } } - private final class Worker extends WakeUpLoopRunnable { - final LinkedHashMap tasks = Maps.newLinkedHashMap(); - - boolean commitChange(ChangeKey key, ChangeHandler handler, long expectDatumVersion) { - synchronized (tasks) { - final long now = System.currentTimeMillis(); - final ChangeTask task = new ChangeTask(key, expectDatumVersion, handler, - now + changeDebouncingMillis); - final ChangeTask exist = tasks.get(key); - if (exist == null) { - task.expireDeadlineTimestamp = now + changeDebouncingMaxMillis; - tasks.put(key, task); - return true; - } - if (task.expectDatumVersion <= exist.expectDatumVersion) { - return false; - } - - if (task.expireTimestamp <= exist.expireDeadlineTimestamp) { - // requeue, expire is before deadline, remove first, unlink the list - task.expireDeadlineTimestamp = exist.expireDeadlineTimestamp; - tasks.remove(key); - tasks.put(key, task); - } else { - // reach deadline, could not requeue, replace the exist - exist.expectDatumVersion = task.expectDatumVersion; - } - return true; - } + ChangeTask getExpire() { + final long now = System.currentTimeMillis(); + synchronized (tasks) { + if (tasks.isEmpty()) { + return null; } - - ChangeTask getExpire() { - final long now = System.currentTimeMillis(); - synchronized (tasks) { - if (tasks.isEmpty()) { - return null; - } - Iterator it = tasks.values().iterator(); - final ChangeTask first = it.next(); - if (first.expireTimestamp <= now) { - it.remove(); - return first; - } - return null; - } + Iterator it = tasks.values().iterator(); + final ChangeTask first = it.next(); + if (first.expireTimestamp <= now) { + it.remove(); + return first; } + return null; + } + } - @Override - public void runUnthrowable() { - for (;;) { - final ChangeTask task = getExpire(); - if (task == null) { - break; - } - try { - task.doChange(); - } catch (Throwable e) { - LOGGER.error("failed to doChange, {}", task); - } - } + @Override + public void runUnthrowable() { + for (; ; ) { + final ChangeTask task = getExpire(); + if (task == null) { + break; } - - @Override - public int getWaitingMillis() { - return 100; + try { + task.doChange(); + } catch (Throwable e) { + LOGGER.error("failed to doChange, {}", task); } + } } - private static final class ChangeKey { - final String dataInfoId; - final String dataCenter; + @Override + public int getWaitingMillis() { + return 100; + } + } - ChangeKey(String dataCenter, String dataInfoId) { - this.dataCenter = dataCenter; - this.dataInfoId = dataInfoId; - } + private static final class ChangeKey { + final String dataInfoId; + final String dataCenter; - @Override - public String toString() { - return dataInfoId + "@" + dataCenter; - } + ChangeKey(String dataCenter, String dataInfoId) { + this.dataCenter = dataCenter; + this.dataInfoId = dataInfoId; + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - ChangeKey changeKey = (ChangeKey) o; - return Objects.equals(dataInfoId, changeKey.dataInfoId) - && Objects.equals(dataCenter, changeKey.dataCenter); - } + @Override + public String toString() { + return dataInfoId + "@" + dataCenter; + } - @Override - public int hashCode() { - return Objects.hash(dataInfoId, dataCenter); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ChangeKey changeKey = (ChangeKey) o; + return Objects.equals(dataInfoId, changeKey.dataInfoId) + && Objects.equals(dataCenter, changeKey.dataCenter); } - private Worker workerOf(ChangeKey key) { - int n = (key.hashCode() & 0x7fffffff) % workers.length; - return workers[n]; + @Override + public int hashCode() { + return Objects.hash(dataInfoId, dataCenter); } + } + + private Worker workerOf(ChangeKey key) { + int n = (key.hashCode() & 0x7fffffff) % workers.length; + return workers[n]; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/FirePushService.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/FirePushService.java index 7ead2bca0..9094d96c2 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/FirePushService.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/FirePushService.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.session.push; +import static com.alipay.sofa.registry.server.session.push.PushMetrics.Fetch.*; + import com.alipay.sofa.registry.common.model.SubscriberUtils; import com.alipay.sofa.registry.common.model.store.DataInfo; import com.alipay.sofa.registry.common.model.store.SubDatum; @@ -28,212 +30,218 @@ import com.alipay.sofa.registry.server.session.store.Interests; import com.alipay.sofa.registry.server.shared.util.DatumUtils; import com.alipay.sofa.registry.task.KeyedThreadPoolExecutor; - -import static com.alipay.sofa.registry.server.session.push.PushMetrics.Fetch.*; - import com.google.common.collect.Lists; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.CollectionUtils; - -import javax.annotation.PostConstruct; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.RejectedExecutionException; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; public class FirePushService { - private static final Logger LOGGER = LoggerFactory.getLogger(FirePushService.class); + private static final Logger LOGGER = LoggerFactory.getLogger(FirePushService.class); - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Autowired - private CacheService sessionCacheService; + @Autowired private CacheService sessionCacheService; - @Autowired - private Interests sessionInterests; + @Autowired private Interests sessionInterests; - private KeyedThreadPoolExecutor registerFetchExecutor; + private KeyedThreadPoolExecutor registerFetchExecutor; - @Autowired - private PushProcessor pushProcessor; - @Autowired - private ChangeProcessor changeProcessor; - private final ChangeHandler changeHandler = new ChangeHandler(); + @Autowired private PushProcessor pushProcessor; + @Autowired private ChangeProcessor changeProcessor; + private final ChangeHandler changeHandler = new ChangeHandler(); - @PostConstruct - public void init() { - registerFetchExecutor = new KeyedThreadPoolExecutor("RegisterFetchExecutor", + @PostConstruct + public void init() { + registerFetchExecutor = + new KeyedThreadPoolExecutor( + "RegisterFetchExecutor", sessionServerConfig.getDataChangeFetchTaskWorkerSize(), sessionServerConfig.getDataChangeFetchTaskMaxBufferSize()); + } + + public boolean fireOnChange(String dataCenter, String dataInfoId, long expectVersion) { + try { + // TODO only supported local dataCenter + changeProcessor.fireChange(dataCenter, dataInfoId, changeHandler, expectVersion); + CHANGE_TASK_COUNTER.inc(); + return true; + } catch (Throwable e) { + LOGGER.error( + "failed to exec ChangeHandler {}, dataCenter={}, expectVer={}, {}", + dataInfoId, + dataCenter, + expectVersion, + e); + return false; } - - public boolean fireOnChange(String dataCenter, String dataInfoId, long expectVersion) { - try { - // TODO only supported local dataCenter - changeProcessor.fireChange(dataCenter, dataInfoId, changeHandler, expectVersion); - CHANGE_TASK_COUNTER.inc(); - return true; - } catch (Throwable e) { - LOGGER.error("failed to exec ChangeHandler {}, dataCenter={}, expectVer={}, {}", - dataInfoId, dataCenter, expectVersion, e); - return false; - } + } + + public boolean fireOnPushEmpty(Subscriber subscriber) { + SubDatum emptyDatum = DatumUtils.newEmptySubDatum(subscriber, getDataCenterWhenPushEmpty()); + processPush(true, emptyDatum, Collections.singletonList(subscriber)); + PUSH_EMPTY_COUNTER.inc(); + LOGGER.info("firePushEmpty, {}", subscriber); + return true; + } + + public boolean fireOnRegister(Subscriber subscriber) { + try { + registerFetchExecutor.execute(subscriber.getDataInfoId(), new RegisterTask(subscriber)); + REGISTER_TASK_COUNTER.inc(); + return true; + } catch (RejectedExecutionException e) { + LOGGER.error( + "failed to exec SubscriberTask {}, {}, {}", + subscriber.getDataInfoId(), + subscriber, + e.getMessage()); + return false; + } catch (Throwable e) { + LOGGER.error( + "failed to exec SubscriberTask {}, {}", subscriber.getDataInfoId(), subscriber, e); + return false; } - - public boolean fireOnPushEmpty(Subscriber subscriber) { - SubDatum emptyDatum = DatumUtils.newEmptySubDatum(subscriber, getDataCenterWhenPushEmpty()); - processPush(true, emptyDatum, Collections.singletonList(subscriber)); - PUSH_EMPTY_COUNTER.inc(); - LOGGER.info("firePushEmpty, {}", subscriber); - return true; + } + + public boolean fireOnDatum(SubDatum datum) { + DataInfo dataInfo = DataInfo.valueOf(datum.getDataInfoId()); + Collection subscribers = sessionInterests.getInterests(dataInfo.getDataInfoId()); + processPush(true, datum, subscribers); + PUSH_TEMP_COUNTER.inc(); + return true; + } + + protected String getDataCenterWhenPushEmpty() { + // TODO cloud mode use default.datacenter? + return sessionServerConfig.getSessionServerDataCenter(); + } + + private void doExecuteOnChange(String dataCenter, String changeDataInfoId, long expectVersion) { + final SubDatum datum = getDatum(dataCenter, changeDataInfoId, expectVersion); + if (datum == null) { + // datum change, but get null datum, should not happen + LOGGER.error("[changeNil] {},{},{}", dataCenter, changeDataInfoId, expectVersion); + return; } - - public boolean fireOnRegister(Subscriber subscriber) { - try { - registerFetchExecutor.execute(subscriber.getDataInfoId(), new RegisterTask(subscriber)); - REGISTER_TASK_COUNTER.inc(); - return true; - } catch (RejectedExecutionException e) { - LOGGER.error("failed to exec SubscriberTask {}, {}, {}", subscriber.getDataInfoId(), - subscriber, e.getMessage()); - return false; - } catch (Throwable e) { - LOGGER.error("failed to exec SubscriberTask {}, {}", subscriber.getDataInfoId(), - subscriber, e); - return false; - } + if (datum.getVersion() < expectVersion) { + LOGGER.error( + "[changeLessVer] {},{},{}<{}", + dataCenter, + changeDataInfoId, + datum.getVersion(), + expectVersion); + return; } - - public boolean fireOnDatum(SubDatum datum) { - DataInfo dataInfo = DataInfo.valueOf(datum.getDataInfoId()); - Collection subscribers = sessionInterests - .getInterests(dataInfo.getDataInfoId()); - processPush(true, datum, subscribers); - PUSH_TEMP_COUNTER.inc(); - return true; + onDatumChange(datum); + } + + private void onDatumChange(SubDatum datum) { + Map> scopes = + SubscriberUtils.groupByScope(sessionInterests.getDatas(datum.getDataInfoId())); + for (Map.Entry> scope : scopes.entrySet()) { + processPush(false, datum, scope.getValue()); } + } - protected String getDataCenterWhenPushEmpty() { - // TODO cloud mode use default.datacenter? - return sessionServerConfig.getSessionServerDataCenter(); + private void processPush(boolean noDelay, SubDatum datum, Collection subscriberList) { + if (subscriberList.isEmpty()) { + return; } - - private void doExecuteOnChange(String dataCenter, String changeDataInfoId, long expectVersion) { - final SubDatum datum = getDatum(dataCenter, changeDataInfoId, expectVersion); - if (datum == null) { - // datum change, but get null datum, should not happen - LOGGER.error("[changeNil] {},{},{}", dataCenter, changeDataInfoId, expectVersion); - return; - } - if (datum.getVersion() < expectVersion) { - LOGGER.error("[changeLessVer] {},{},{}<{}", dataCenter, changeDataInfoId, - datum.getVersion(), expectVersion); - return; - } - onDatumChange(datum); + subscriberList = + subscribersPushCheck(datum.getDataCenter(), datum.getVersion(), subscriberList); + if (CollectionUtils.isEmpty(subscriberList)) { + return; } - - private void onDatumChange(SubDatum datum) { - Map> scopes = SubscriberUtils.groupByScope(sessionInterests - .getDatas(datum.getDataInfoId())); - for (Map.Entry> scope : scopes.entrySet()) { - processPush(false, datum, scope.getValue()); - } + Map> group = + SubscriberUtils.groupBySourceAddress(subscriberList); + for (Map.Entry> e : group.entrySet()) { + final InetSocketAddress addr = e.getKey(); + final Map subscriberMap = e.getValue(); + pushProcessor.firePush(noDelay, addr, subscriberMap, datum); } - - private void processPush(boolean noDelay, SubDatum datum, Collection subscriberList) { - if (subscriberList.isEmpty()) { - return; - } - subscriberList = subscribersPushCheck(datum.getDataCenter(), datum.getVersion(), - subscriberList); - if (CollectionUtils.isEmpty(subscriberList)) { - return; - } - Map> group = SubscriberUtils - .groupBySourceAddress(subscriberList); - for (Map.Entry> e : group.entrySet()) { - final InetSocketAddress addr = e.getKey(); - final Map subscriberMap = e.getValue(); - pushProcessor.firePush(noDelay, addr, subscriberMap, datum); - } + } + + private SubDatum getDatum(String dataCenter, String dataInfoId, long expectVersion) { + Key key = new Key(DatumKey.class.getName(), new DatumKey(dataInfoId, dataCenter)); + Value value = sessionCacheService.getValueIfPresent(key); + if (value != null) { + SubDatum datum = (SubDatum) value.getPayload(); + if (datum != null && datum.getVersion() >= expectVersion) { + // the expect version got + CACHE_HIT_COUNTER.inc(); + return datum; + } } - - private SubDatum getDatum(String dataCenter, String dataInfoId, long expectVersion) { - Key key = new Key(DatumKey.class.getName(), new DatumKey(dataInfoId, dataCenter)); - Value value = sessionCacheService.getValueIfPresent(key); - if (value != null) { - SubDatum datum = (SubDatum) value.getPayload(); - if (datum != null && datum.getVersion() >= expectVersion) { - // the expect version got - CACHE_HIT_COUNTER.inc(); - return datum; - } - } - CACHE_MISS_COUNTER.inc(); - // the cache is too old - sessionCacheService.invalidate(key); - value = sessionCacheService.getValue(key); - return value == null ? null : (SubDatum) value.getPayload(); + CACHE_MISS_COUNTER.inc(); + // the cache is too old + sessionCacheService.invalidate(key); + value = sessionCacheService.getValue(key); + return value == null ? null : (SubDatum) value.getPayload(); + } + + private List subscribersPushCheck( + String dataCenter, Long version, Collection subscribers) { + List subscribersSend = Lists.newArrayList(); + for (Subscriber subscriber : subscribers) { + if (subscriber.checkVersion(dataCenter, version)) { + subscribersSend.add(subscriber); + } } - - private List subscribersPushCheck(String dataCenter, Long version, - Collection subscribers) { - List subscribersSend = Lists.newArrayList(); - for (Subscriber subscriber : subscribers) { - if (subscriber.checkVersion(dataCenter, version)) { - subscribersSend.add(subscriber); - } - } - return subscribersSend; + return subscribersSend; + } + + private final class ChangeHandler implements ChangeProcessor.ChangeHandler { + + @Override + public void onChange(String dataCenter, String dataInfoId, long expectDatumVersion) { + try { + CHANGE_TASK_EXEC_COUNTER.inc(); + doExecuteOnChange(dataCenter, dataInfoId, expectDatumVersion); + } catch (Throwable e) { + LOGGER.error( + "failed to do change Task, {}, dataCenter={}, expectVersion={}", + dataInfoId, + dataCenter, + expectDatumVersion, + e); + } } - - private final class ChangeHandler implements ChangeProcessor.ChangeHandler { - - @Override - public void onChange(String dataCenter, String dataInfoId, long expectDatumVersion) { - try { - CHANGE_TASK_EXEC_COUNTER.inc(); - doExecuteOnChange(dataCenter, dataInfoId, expectDatumVersion); - } catch (Throwable e) { - LOGGER.error("failed to do change Task, {}, dataCenter={}, expectVersion={}", - dataInfoId, dataCenter, expectDatumVersion, e); - } - } + } + + private void doExecuteOnSubscriber(String dataCenter, Subscriber subscriber) { + final String subDataInfoId = subscriber.getDataInfoId(); + SubDatum datum = getDatum(dataCenter, subDataInfoId, Long.MIN_VALUE); + if (datum == null) { + datum = DatumUtils.newEmptySubDatum(subscriber, dataCenter); + LOGGER.warn("[registerEmptyPush] {},{},{}", subDataInfoId, dataCenter, subscriber); } - - private void doExecuteOnSubscriber(String dataCenter, Subscriber subscriber) { - final String subDataInfoId = subscriber.getDataInfoId(); - SubDatum datum = getDatum(dataCenter, subDataInfoId, Long.MIN_VALUE); - if (datum == null) { - datum = DatumUtils.newEmptySubDatum(subscriber, dataCenter); - LOGGER.warn("[registerEmptyPush] {},{},{}", subDataInfoId, dataCenter, subscriber); - } - if (subscriber.hasPushed()) { - return; - } - processPush(true, datum, Collections.singletonList(subscriber)); + if (subscriber.hasPushed()) { + return; } + processPush(true, datum, Collections.singletonList(subscriber)); + } - private final class RegisterTask implements Runnable { - final Subscriber subscriber; + private final class RegisterTask implements Runnable { + final Subscriber subscriber; - RegisterTask(Subscriber subscriber) { - this.subscriber = subscriber; - } + RegisterTask(Subscriber subscriber) { + this.subscriber = subscriber; + } - @Override - public void run() { - final String dataCenter = sessionServerConfig.getSessionServerDataCenter(); - try { - if (subscriber.hasPushed()) { - return; - } - doExecuteOnSubscriber(dataCenter, subscriber); - } catch (Throwable e) { - LOGGER.error("failed to do register Task, dataCenter={}, {}", dataCenter, - subscriber, e); - } + @Override + public void run() { + final String dataCenter = sessionServerConfig.getSessionServerDataCenter(); + try { + if (subscriber.hasPushed()) { + return; } + doExecuteOnSubscriber(dataCenter, subscriber); + } catch (Throwable e) { + LOGGER.error("failed to do register Task, dataCenter={}, {}", dataCenter, subscriber, e); + } } + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushDataGenerator.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushDataGenerator.java index 65c9dd13f..5f5b4654a 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushDataGenerator.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushDataGenerator.java @@ -24,38 +24,39 @@ import com.alipay.sofa.registry.server.session.converter.pb.ReceivedDataConvertor; import com.alipay.sofa.registry.server.session.predicate.ZonePredicate; import com.google.common.collect.Lists; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Map; import java.util.function.Predicate; +import org.springframework.beans.factory.annotation.Autowired; public class PushDataGenerator { - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - public Object createPushData(SubDatum datum, Map subscriberMap) { - SubscriberUtils.getAndAssertHasSameScope(subscriberMap.values()); - final Subscriber subscriber = subscriberMap.values().iterator().next(); - BaseInfo.ClientVersion clientVersion = subscriber.getClientVersion(); - // only supported 4.x - if (BaseInfo.ClientVersion.StoreData != clientVersion) { - throw new IllegalArgumentException("unsupported clientVersion:" + clientVersion); - } - String dataId = datum.getDataId(); - String clientCell = sessionServerConfig.getClientCell(subscriber.getCell()); - Predicate zonePredicate = ZonePredicate.zonePredicate(dataId, clientCell, - subscriber.getScope(), sessionServerConfig); + public Object createPushData(SubDatum datum, Map subscriberMap) { + SubscriberUtils.getAndAssertHasSameScope(subscriberMap.values()); + final Subscriber subscriber = subscriberMap.values().iterator().next(); + BaseInfo.ClientVersion clientVersion = subscriber.getClientVersion(); + // only supported 4.x + if (BaseInfo.ClientVersion.StoreData != clientVersion) { + throw new IllegalArgumentException("unsupported clientVersion:" + clientVersion); + } + String dataId = datum.getDataId(); + String clientCell = sessionServerConfig.getClientCell(subscriber.getCell()); + Predicate zonePredicate = + ZonePredicate.zonePredicate(dataId, clientCell, subscriber.getScope(), sessionServerConfig); - ReceivedData receivedData = ReceivedDataConverter.getReceivedDataMulti(datum, - subscriber.getScope(), Lists.newArrayList(subscriberMap.keySet()), clientCell, + ReceivedData receivedData = + ReceivedDataConverter.getReceivedDataMulti( + datum, + subscriber.getScope(), + Lists.newArrayList(subscriberMap.keySet()), + clientCell, zonePredicate); - receivedData.setVersion(datum.getVersion()); - final Byte serializerIndex = subscriber.getSourceAddress().getSerializerIndex(); - if (serializerIndex != null && URL.PROTOBUF == serializerIndex.byteValue()) { - return ReceivedDataConvertor.convert2Pb(receivedData); - } - return receivedData; + receivedData.setVersion(datum.getVersion()); + final Byte serializerIndex = subscriber.getSourceAddress().getSerializerIndex(); + if (serializerIndex != null && URL.PROTOBUF == serializerIndex.byteValue()) { + return ReceivedDataConvertor.convert2Pb(receivedData); } - + return receivedData; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushMetrics.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushMetrics.java index 15c7fdbd5..3f1472522 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushMetrics.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushMetrics.java @@ -19,62 +19,89 @@ import io.prometheus.client.Counter; public final class PushMetrics { - private PushMetrics() { - } + private PushMetrics() {} - static final class Fetch { - static final Counter CHANGE_TASK_COUNTER = Counter.build() - .namespace("session").subsystem("fetch") - .name("change_task_total").help("change task").register(); + static final class Fetch { + static final Counter CHANGE_TASK_COUNTER = + Counter.build() + .namespace("session") + .subsystem("fetch") + .name("change_task_total") + .help("change task") + .register(); - static final Counter CHANGE_TASK_EXEC_COUNTER = Counter.build() - .namespace("session").subsystem("fetch") - .name("change_task_exec_total").help("change task exec") - .register(); - static final Counter REGISTER_TASK_COUNTER = Counter.build() - .namespace("session").subsystem("fetch") - .name("register_task_total").help("register task").register(); - static final Counter PUSH_EMPTY_COUNTER = Counter.build() - .namespace("session").subsystem("fetch") - .name("empty_task_total").help("empty task").register(); - static final Counter PUSH_TEMP_COUNTER = Counter.build() - .namespace("session").subsystem("fetch") - .name("temp_task_total").help("temp task").register(); + static final Counter CHANGE_TASK_EXEC_COUNTER = + Counter.build() + .namespace("session") + .subsystem("fetch") + .name("change_task_exec_total") + .help("change task exec") + .register(); + static final Counter REGISTER_TASK_COUNTER = + Counter.build() + .namespace("session") + .subsystem("fetch") + .name("register_task_total") + .help("register task") + .register(); + static final Counter PUSH_EMPTY_COUNTER = + Counter.build() + .namespace("session") + .subsystem("fetch") + .name("empty_task_total") + .help("empty task") + .register(); + static final Counter PUSH_TEMP_COUNTER = + Counter.build() + .namespace("session") + .subsystem("fetch") + .name("temp_task_total") + .help("temp task") + .register(); - private static final Counter CACHE_COUNTER = Counter.build() - .namespace("session").subsystem("fetch").name("cache_total") - .help(" cache").labelNames("hit").register(); + private static final Counter CACHE_COUNTER = + Counter.build() + .namespace("session") + .subsystem("fetch") + .name("cache_total") + .help(" cache") + .labelNames("hit") + .register(); - static final Counter.Child CACHE_HIT_COUNTER = CACHE_COUNTER - .labels("Y"); - static final Counter.Child CACHE_MISS_COUNTER = CACHE_COUNTER - .labels("N"); - } + static final Counter.Child CACHE_HIT_COUNTER = CACHE_COUNTER.labels("Y"); + static final Counter.Child CACHE_MISS_COUNTER = CACHE_COUNTER.labels("N"); + } - static final class Push { - private static final Counter PENDING_COUNTER = Counter.build() - .namespace("session").subsystem("push").name("pending_total") - .help("pending fetch").labelNames("type").register(); - static final Counter.Child PENDING_REPLACE_COUNTER = PENDING_COUNTER - .labels("replace"); - static final Counter.Child PENDING_NEW_COUNTER = PENDING_COUNTER - .labels("new"); - static final Counter.Child PENDING_SKIP_COUNTER = PENDING_COUNTER - .labels("skip"); - - static final Counter COMMIT_COUNTER = Counter.build() - .namespace("session").subsystem("push") - .name("fire_commit_total").help("commit task").register(); - private static final Counter PUSH_CLIENT_COUNTER = Counter.build() - .namespace("session").subsystem("push") - .name("push_client_total").help("push client task") - .labelNames("type").register(); - static final Counter.Child PUSH_CLIENT_PUSHING_COUNTER = PUSH_CLIENT_COUNTER - .labels("I"); - static final Counter.Child PUSH_CLIENT_SUCCESS_COUNTER = PUSH_CLIENT_COUNTER - .labels("Y"); - static final Counter.Child PUSH_CLIENT_FAIL_COUNTER = PUSH_CLIENT_COUNTER - .labels("N"); - } + static final class Push { + private static final Counter PENDING_COUNTER = + Counter.build() + .namespace("session") + .subsystem("push") + .name("pending_total") + .help("pending fetch") + .labelNames("type") + .register(); + static final Counter.Child PENDING_REPLACE_COUNTER = PENDING_COUNTER.labels("replace"); + static final Counter.Child PENDING_NEW_COUNTER = PENDING_COUNTER.labels("new"); + static final Counter.Child PENDING_SKIP_COUNTER = PENDING_COUNTER.labels("skip"); + static final Counter COMMIT_COUNTER = + Counter.build() + .namespace("session") + .subsystem("push") + .name("fire_commit_total") + .help("commit task") + .register(); + private static final Counter PUSH_CLIENT_COUNTER = + Counter.build() + .namespace("session") + .subsystem("push") + .name("push_client_total") + .help("push client task") + .labelNames("type") + .register(); + static final Counter.Child PUSH_CLIENT_PUSHING_COUNTER = PUSH_CLIENT_COUNTER.labels("I"); + static final Counter.Child PUSH_CLIENT_SUCCESS_COUNTER = PUSH_CLIENT_COUNTER.labels("Y"); + static final Counter.Child PUSH_CLIENT_FAIL_COUNTER = PUSH_CLIENT_COUNTER.labels("N"); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushProcessor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushProcessor.java index 3955ad778..d1a899155 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushProcessor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushProcessor.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.session.push; +import static com.alipay.sofa.registry.server.session.push.PushMetrics.Push.*; + import com.alipay.remoting.rpc.exception.InvokeTimeoutException; import com.alipay.sofa.registry.common.model.SubscriberUtils; import com.alipay.sofa.registry.common.model.store.BaseInfo; @@ -36,492 +38,551 @@ import com.alipay.sofa.registry.util.WakeUpLoopRunnable; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.net.InetSocketAddress; import java.util.*; import java.util.concurrent.Executor; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; - -import static com.alipay.sofa.registry.server.session.push.PushMetrics.Push.*; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; public class PushProcessor { - private static final Logger LOGGER = LoggerFactory - .getLogger(PushProcessor.class); + private static final Logger LOGGER = LoggerFactory.getLogger(PushProcessor.class); - private KeyedThreadPoolExecutor pushExecutor; - private final Map pendingTasks = Maps.newConcurrentMap(); - private final Lock pendingLock = new ReentrantLock(); + private KeyedThreadPoolExecutor pushExecutor; + private final Map pendingTasks = Maps.newConcurrentMap(); + private final Lock pendingLock = new ReentrantLock(); - private final Map pushingTasks = Maps.newConcurrentMap(); + private final Map pushingTasks = Maps.newConcurrentMap(); - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Autowired - private PushDataGenerator pushDataGenerator; + @Autowired private PushDataGenerator pushDataGenerator; - @Autowired - private ClientNodeService clientNodeService; + @Autowired private ClientNodeService clientNodeService; - private final WatchDog watchDog = new WatchDog(); + private final WatchDog watchDog = new WatchDog(); - private final ThreadPoolExecutor pushCallbackExecutor = MetricsableThreadPoolExecutor - .newExecutor( - "PushCallbackExecutor", - 2, 1000, - new CallRunHandler()); + private final ThreadPoolExecutor pushCallbackExecutor = + MetricsableThreadPoolExecutor.newExecutor( + "PushCallbackExecutor", 2, 1000, new CallRunHandler()); - @PostConstruct - public void init() { - pushExecutor = new KeyedThreadPoolExecutor("PushExecutor", + @PostConstruct + public void init() { + pushExecutor = + new KeyedThreadPoolExecutor( + "PushExecutor", sessionServerConfig.getPushTaskExecutorPoolSize(), sessionServerConfig.getPushTaskExecutorQueueSize()); - ConcurrentUtils.createDaemonThread("PushWatchDog", watchDog).start(); + ConcurrentUtils.createDaemonThread("PushWatchDog", watchDog).start(); + } + + private boolean firePush(PushTask pushTask) { + PendingTaskKey key = pushTask.pendingKeyOf(); + if (pendingTasks.putIfAbsent(key, pushTask) == null) { + // fast path + PENDING_NEW_COUNTER.inc(); + return true; } - - private boolean firePush(PushTask pushTask) { - PendingTaskKey key = pushTask.pendingKeyOf(); - if (pendingTasks.putIfAbsent(key, pushTask) == null) { - // fast path - PENDING_NEW_COUNTER.inc(); - return true; - } - boolean skip = false; - PushTask prev = null; - pendingLock.lock(); - try { - prev = pendingTasks.get(key); - if (prev == null) { - pendingTasks.put(key, pushTask); - PENDING_NEW_COUNTER.inc(); - } else if (pushTask.afterThan(prev)) { - // update the expireTimestamp as prev's, avoid the push block by the continues fire - pushTask.expireTimestamp = prev.expireTimestamp; - pendingTasks.put(key, pushTask); - PENDING_REPLACE_COUNTER.inc(); - } else { - skip = true; - } - } finally { - pendingLock.unlock(); - } - if (!skip) { - if (pushTask.noDelay) { - watchDog.wakeup(); - } - return true; - } else { - PENDING_SKIP_COUNTER.inc(); - LOGGER.info("[SkipPending] key={}, prev={}, {}, ver={}, now={}, ver={}", key, - prev.taskID, prev.pushingTaskKey, prev.datum.getVersion(), pushTask.taskID, - pushTask.datum.getVersion()); - return false; - } + boolean skip = false; + PushTask prev = null; + pendingLock.lock(); + try { + prev = pendingTasks.get(key); + if (prev == null) { + pendingTasks.put(key, pushTask); + PENDING_NEW_COUNTER.inc(); + } else if (pushTask.afterThan(prev)) { + // update the expireTimestamp as prev's, avoid the push block by the continues fire + pushTask.expireTimestamp = prev.expireTimestamp; + pendingTasks.put(key, pushTask); + PENDING_REPLACE_COUNTER.inc(); + } else { + skip = true; + } + } finally { + pendingLock.unlock(); } - - protected List createPushTask(boolean noDelay, InetSocketAddress addr, - Map subscriberMap, SubDatum datum) { - PushTask pushTask = new PushTask(noDelay, addr, subscriberMap, datum); - // set expireTimestamp, wait to merge to debouncing - pushTask.expireAfter(sessionServerConfig.getPushDataTaskDebouncingMillis()); - return Collections.singletonList(pushTask); + if (!skip) { + if (pushTask.noDelay) { + watchDog.wakeup(); + } + return true; + } else { + PENDING_SKIP_COUNTER.inc(); + LOGGER.info( + "[SkipPending] key={}, prev={}, {}, ver={}, now={}, ver={}", + key, + prev.taskID, + prev.pushingTaskKey, + prev.datum.getVersion(), + pushTask.taskID, + pushTask.datum.getVersion()); + return false; } - - void firePush(boolean noDelay, InetSocketAddress addr, Map subscriberMap, - SubDatum datum) { - List fires = createPushTask(noDelay, addr, subscriberMap, datum); - for (PushTask task : fires) { - boolean fire = firePush(task); - LOGGER.info("fire push={}, {}", fire, task); - } + } + + protected List createPushTask( + boolean noDelay, + InetSocketAddress addr, + Map subscriberMap, + SubDatum datum) { + PushTask pushTask = new PushTask(noDelay, addr, subscriberMap, datum); + // set expireTimestamp, wait to merge to debouncing + pushTask.expireAfter(sessionServerConfig.getPushDataTaskDebouncingMillis()); + return Collections.singletonList(pushTask); + } + + void firePush( + boolean noDelay, + InetSocketAddress addr, + Map subscriberMap, + SubDatum datum) { + List fires = createPushTask(noDelay, addr, subscriberMap, datum); + for (PushTask task : fires) { + boolean fire = firePush(task); + LOGGER.info("fire push={}, {}", fire, task); } - - private boolean commitTask(PushTask task) { - try { - // keyed by pushingKey: client.addr && dataInfoId - pushExecutor.execute(task.pushingTaskKey, task); - COMMIT_COUNTER.inc(); - return true; - } catch (Throwable e) { - LOGGER.error("failed to exec push task {},{}", task.taskID, task.pushingTaskKey, e); - return false; - } + } + + private boolean commitTask(PushTask task) { + try { + // keyed by pushingKey: client.addr && dataInfoId + pushExecutor.execute(task.pushingTaskKey, task); + COMMIT_COUNTER.inc(); + return true; + } catch (Throwable e) { + LOGGER.error("failed to exec push task {},{}", task.taskID, task.pushingTaskKey, e); + return false; } - - private final class WatchDog extends WakeUpLoopRunnable { - - @Override - public void runUnthrowable() { - List pending = transferAndMerge(); - if (sessionServerConfig.isStopPushSwitch()) { - return; - } - if (pending.isEmpty()) { - return; - } - LOGGER.info("process push tasks {}", pending.size()); - for (PushTask task : pending) { - commitTask(task); - } - } - - @Override - public int getWaitingMillis() { - return 100; - } + } + + private final class WatchDog extends WakeUpLoopRunnable { + + @Override + public void runUnthrowable() { + List pending = transferAndMerge(); + if (sessionServerConfig.isStopPushSwitch()) { + return; + } + if (pending.isEmpty()) { + return; + } + LOGGER.info("process push tasks {}", pending.size()); + for (PushTask task : pending) { + commitTask(task); + } } - private List transferAndMerge() { - List pending = Lists.newArrayList(); - final long now = System.currentTimeMillis(); - pendingLock.lock(); - try { - final Iterator> it = pendingTasks.entrySet() - .iterator(); - while (it.hasNext()) { - Map.Entry e = it.next(); - PushTask task = e.getValue(); - if (task.noDelay || task.expireTimestamp <= now) { - pending.add(task); - it.remove(); - } - } - } finally { - pendingLock.unlock(); - } - return pending; + @Override + public int getWaitingMillis() { + return 100; + } + } + + private List transferAndMerge() { + List pending = Lists.newArrayList(); + final long now = System.currentTimeMillis(); + pendingLock.lock(); + try { + final Iterator> it = pendingTasks.entrySet().iterator(); + while (it.hasNext()) { + Map.Entry e = it.next(); + PushTask task = e.getValue(); + if (task.noDelay || task.expireTimestamp <= now) { + pending.add(task); + it.remove(); + } + } + } finally { + pendingLock.unlock(); + } + return pending; + } + + private boolean checkPushing(PushTask task, PushingTaskKey pushingTaskKey) { + // check the pushing task + final PushTask prev = pushingTasks.get(pushingTaskKey); + if (prev == null) { + return true; + } + final long now = System.currentTimeMillis(); + final long span = now - prev.pushTimestamp; + if (span > sessionServerConfig.getClientNodeExchangeTimeoutMillis() * 2) { + // force to remove the prev task + final boolean cleaned = pushingTasks.remove(pushingTaskKey) != null; + LOGGER.warn( + "[prevPushTooLong] {}, clean={}, prev={}, now={}", + pushingTaskKey, + cleaned, + prev.taskID, + task.taskID); + if (cleaned) { + prev.trace.finishPush(PushTrace.PushStatus.Timeout, now).print(); + } + return true; + } + // task after the prev, but prev.pushclient not callback, retry + retry(task, "waiting"); + return false; + } + + private boolean retry(PushTask task, String reason) { + task.retryCount++; + final int retry = task.retryCount; + if (retry <= sessionServerConfig.getPushTaskRetryTimes()) { + final int backoffMillis = getRetryBackoffTime(retry); + task.expireAfter(backoffMillis); + if (firePush(task)) { + LOGGER.info( + "add retry for {}, {}, {}, retry={}, backoff={}", + reason, + task.taskID, + task.pushingTaskKey, + retry, + backoffMillis); + return true; + } + } + LOGGER.info( + "skip retry for {}, {}, {}, retry={}", reason, task.taskID, task.pushingTaskKey, retry); + return false; + } + + // check push empty, some group maybe could not tolerate push empty + protected boolean interruptOnPushEmpty( + SubDatum datum, boolean noDelay, Subscriber sub, InetSocketAddress addr) { + return false; + } + + class PushTask implements Runnable { + final TraceID taskID; + final long createTimestamp = System.currentTimeMillis(); + volatile long expireTimestamp; + volatile long pushTimestamp; + + final boolean noDelay; + final String dataCenter; + final SubDatum datum; + final InetSocketAddress addr; + final Map subscriberMap; + final Subscriber subscriber; + int retryCount; + + final PushingTaskKey pushingTaskKey; + final PushTrace trace; + + PushTask( + boolean noDelay, + InetSocketAddress addr, + Map subscriberMap, + SubDatum datum) { + this.taskID = TraceID.newTraceID(); + this.noDelay = noDelay; + this.dataCenter = datum.getDataCenter(); + this.datum = datum; + this.addr = addr; + this.subscriberMap = subscriberMap; + this.subscriber = subscriberMap.values().iterator().next(); + this.trace = PushTrace.trace(datum, addr, subscriber.getAppName(), noDelay); + this.pushingTaskKey = + new PushingTaskKey( + subscriber.getDataInfoId(), + addr, + subscriber.getScope(), + subscriber.getClientVersion()); } - private boolean checkPushing(PushTask task, PushingTaskKey pushingTaskKey) { - // check the pushing task - final PushTask prev = pushingTasks.get(pushingTaskKey); - if (prev == null) { - return true; - } - final long now = System.currentTimeMillis(); - final long span = now - prev.pushTimestamp; - if (span > sessionServerConfig.getClientNodeExchangeTimeoutMillis() * 2) { - // force to remove the prev task - final boolean cleaned = pushingTasks.remove(pushingTaskKey) != null; - LOGGER.warn("[prevPushTooLong] {}, clean={}, prev={}, now={}", pushingTaskKey, cleaned, - prev.taskID, task.taskID); - if (cleaned) { - prev.trace.finishPush(PushTrace.PushStatus.Timeout, now).print(); - } - return true; - } - // task after the prev, but prev.pushclient not callback, retry - retry(task, "waiting"); - return false; - } - - private boolean retry(PushTask task, String reason) { - task.retryCount++; - final int retry = task.retryCount; - if (retry <= sessionServerConfig.getPushTaskRetryTimes()) { - final int backoffMillis = getRetryBackoffTime(retry); - task.expireAfter(backoffMillis); - if (firePush(task)) { - LOGGER.info("add retry for {}, {}, {}, retry={}, backoff={}", reason, task.taskID, - task.pushingTaskKey, retry, backoffMillis); - return true; - } - } - LOGGER.info("skip retry for {}, {}, {}, retry={}", reason, task.taskID, - task.pushingTaskKey, retry); - return false; - } - - // check push empty, some group maybe could not tolerate push empty - protected boolean interruptOnPushEmpty(SubDatum datum, boolean noDelay, Subscriber sub, - InetSocketAddress addr) { - return false; - } - - class PushTask implements Runnable { - final TraceID taskID; - final long createTimestamp = System.currentTimeMillis(); - volatile long expireTimestamp; - volatile long pushTimestamp; - - final boolean noDelay; - final String dataCenter; - final SubDatum datum; - final InetSocketAddress addr; - final Map subscriberMap; - final Subscriber subscriber; - int retryCount; - - final PushingTaskKey pushingTaskKey; - final PushTrace trace; - - PushTask(boolean noDelay, InetSocketAddress addr, Map subscriberMap, - SubDatum datum) { - this.taskID = TraceID.newTraceID(); - this.noDelay = noDelay; - this.dataCenter = datum.getDataCenter(); - this.datum = datum; - this.addr = addr; - this.subscriberMap = subscriberMap; - this.subscriber = subscriberMap.values().iterator().next(); - this.trace = PushTrace.trace(datum, addr, subscriber.getAppName(), noDelay); - this.pushingTaskKey = new PushingTaskKey(subscriber.getDataInfoId(), addr, - subscriber.getScope(), subscriber.getClientVersion()); - } - - protected Object createPushData() { - return pushDataGenerator.createPushData(datum, subscriberMap); - } - - void expireAfter(long intervalMs) { - this.expireTimestamp = System.currentTimeMillis() + intervalMs; - } - - boolean afterThan(PushTask t) { - return datum.getVersion() > t.datum.getVersion(); - } - - void updatePushTimestamp() { - this.pushTimestamp = System.currentTimeMillis(); - } - - @Override - public void run() { - if (sessionServerConfig.isStopPushSwitch()) { - return; - } - - try { - if (!checkPushing(this, pushingTaskKey)) { - return; - } - if (interruptOnPushEmpty(datum, noDelay, subscriber, addr)) { - return; - } - Object data = createPushData(); - updatePushTimestamp(); - trace.startPush( - SubscriberUtils.getMaxPushedVersion(dataCenter, subscriberMap.values()), - this.pushTimestamp); - pushingTasks.put(pushingTaskKey, this); - clientNodeService.pushWithCallback(data, subscriber.getSourceAddress(), - new PushClientCallback(this, pushingTaskKey)); - PUSH_CLIENT_PUSHING_COUNTER.inc(); - LOGGER.info("{}, pushing {}", taskID, pushingTaskKey); - } catch (RequestChannelClosedException e) { - // try to delete self - trace.finishPush(PushTrace.PushStatus.Fail, System.currentTimeMillis()).print(); - boolean cleaned = pushingTasks.remove(pushingTaskKey) != null; - LOGGER.error("{}, failed to pushing {}, cleaned={}, {}", taskID, pushingTaskKey, - cleaned, e.getMessage()); - } catch (Throwable e) { - trace.finishPush(PushTrace.PushStatus.Fail, System.currentTimeMillis()).print(); - // try to delete self - boolean cleaned = pushingTasks.remove(pushingTaskKey) != null; - LOGGER.error("{}, failed to pushing {}, cleaned={}", taskID, pushingTaskKey, - cleaned, e); - - } - } - - PendingTaskKey pendingKeyOf() { - return new PendingTaskKey(dataCenter, addr, subscriber.getDataInfoId(), - subscriberMap.keySet()); - } + protected Object createPushData() { + return pushDataGenerator.createPushData(datum, subscriberMap); + } - @Override - public String toString() { - StringBuilder sb = new StringBuilder(512); - sb.append("PushTask{").append(subscriber.getDataInfoId()).append(",ID=").append(taskID) - .append(",createT=").append(createTimestamp).append(",expireT=") - .append(expireTimestamp).append(",DC=").append(dataCenter).append(",ver=") - .append(datum.getVersion()).append(",addr=").append(addr).append(",scope=") - .append(subscriber.getScope()).append(",subIds=").append(subscriberMap.keySet()) - .append(",subCtx=").append(subscriber.printPushContext()).append(",retry=") - .append(retryCount); - return sb.toString(); - } + void expireAfter(long intervalMs) { + this.expireTimestamp = System.currentTimeMillis() + intervalMs; } - private final class PushClientCallback implements CallbackHandler { - final PushTask pushTask; - final PushingTaskKey pushingTaskKey; - long finishedTimestamp; + boolean afterThan(PushTask t) { + return datum.getVersion() > t.datum.getVersion(); + } - PushClientCallback(PushTask pushTask, PushingTaskKey pushingTaskKey) { - this.pushTask = pushTask; - this.pushingTaskKey = pushingTaskKey; - } + void updatePushTimestamp() { + this.pushTimestamp = System.currentTimeMillis(); + } - @Override - public void onCallback(Channel channel, Object message) { - this.finishedTimestamp = System.currentTimeMillis(); - PUSH_CLIENT_SUCCESS_COUNTER.inc(); - boolean cleaned = false; - try { - for (Subscriber subscriber : pushTask.subscriberMap.values()) { - if (!subscriber.checkAndUpdateVersion(pushTask.dataCenter, - pushTask.datum.getVersion())) { - LOGGER.warn("PushY, but failed to updateVersion, {}, {}", pushTask.taskID, - pushTask.pushingTaskKey); - } - } - } catch (Throwable e) { - LOGGER.error("error push.onCallback, {}, {}", pushTask.taskID, - pushTask.pushingTaskKey, e); - } finally { - // TODO should use remove(k, exceptV). but in some case, - // after removed=true, the value aslo in the map - cleaned = pushingTasks.remove(pushingTaskKey, pushTask); - } - this.pushTask.trace.finishPush(PushTrace.PushStatus.OK, this.finishedTimestamp).print(); - LOGGER.info("PushY, clean record={}, span={}/{}, {}, {}", cleaned, pushSpanMillis(), - totalSpanMillis(), pushTask.taskID, pushTask.pushingTaskKey); - } + @Override + public void run() { + if (sessionServerConfig.isStopPushSwitch()) { + return; + } + + try { + if (!checkPushing(this, pushingTaskKey)) { + return; + } + if (interruptOnPushEmpty(datum, noDelay, subscriber, addr)) { + return; + } + Object data = createPushData(); + updatePushTimestamp(); + trace.startPush( + SubscriberUtils.getMaxPushedVersion(dataCenter, subscriberMap.values()), + this.pushTimestamp); + pushingTasks.put(pushingTaskKey, this); + clientNodeService.pushWithCallback( + data, subscriber.getSourceAddress(), new PushClientCallback(this, pushingTaskKey)); + PUSH_CLIENT_PUSHING_COUNTER.inc(); + LOGGER.info("{}, pushing {}", taskID, pushingTaskKey); + } catch (RequestChannelClosedException e) { + // try to delete self + trace.finishPush(PushTrace.PushStatus.Fail, System.currentTimeMillis()).print(); + boolean cleaned = pushingTasks.remove(pushingTaskKey) != null; + LOGGER.error( + "{}, failed to pushing {}, cleaned={}, {}", + taskID, + pushingTaskKey, + cleaned, + e.getMessage()); + } catch (Throwable e) { + trace.finishPush(PushTrace.PushStatus.Fail, System.currentTimeMillis()).print(); + // try to delete self + boolean cleaned = pushingTasks.remove(pushingTaskKey) != null; + LOGGER.error("{}, failed to pushing {}, cleaned={}", taskID, pushingTaskKey, cleaned, e); + } + } - @Override - public void onException(Channel channel, Throwable exception) { - this.finishedTimestamp = System.currentTimeMillis(); - PUSH_CLIENT_FAIL_COUNTER.inc(); - boolean cleaned = false; - try { - // TODO should use remove(k, exceptV). but in some case, - // after removed=true, the value aslo in the map - cleaned = pushingTasks.remove(pushingTaskKey, pushTask); - if (channel.isConnected()) { - retry(pushTask, "callbackErr"); - } else { - LOGGER.warn("PushN, channel closed, {}, {}", pushTask.taskID, pushingTaskKey); - } - } catch (Throwable e) { - LOGGER.error("error push.onException, {}, {}", pushTask.taskID, pushingTaskKey, e); - } - if (exception instanceof InvokeTimeoutException) { - if (cleaned) { - this.pushTask.trace.finishPush(PushTrace.PushStatus.Timeout, - this.finishedTimestamp).print(); - } - LOGGER.error("PushN, timeout, clean record={}, span={}/{}, {}, {}", cleaned, - pushSpanMillis(), totalSpanMillis(), pushTask.taskID, pushingTaskKey); - } else { - if (cleaned) { - this.pushTask.trace.finishPush(PushTrace.PushStatus.Fail, - this.finishedTimestamp).print(); - } - LOGGER - .error("PushN, clean record={}, span={}/{}, {}, {}", cleaned, pushSpanMillis(), - totalSpanMillis(), pushTask.taskID, pushingTaskKey, exception); - } - } + PendingTaskKey pendingKeyOf() { + return new PendingTaskKey( + dataCenter, addr, subscriber.getDataInfoId(), subscriberMap.keySet()); + } - private long pushSpanMillis() { - return finishedTimestamp - pushTask.pushTimestamp; - } + @Override + public String toString() { + StringBuilder sb = new StringBuilder(512); + sb.append("PushTask{") + .append(subscriber.getDataInfoId()) + .append(",ID=") + .append(taskID) + .append(",createT=") + .append(createTimestamp) + .append(",expireT=") + .append(expireTimestamp) + .append(",DC=") + .append(dataCenter) + .append(",ver=") + .append(datum.getVersion()) + .append(",addr=") + .append(addr) + .append(",scope=") + .append(subscriber.getScope()) + .append(",subIds=") + .append(subscriberMap.keySet()) + .append(",subCtx=") + .append(subscriber.printPushContext()) + .append(",retry=") + .append(retryCount); + return sb.toString(); + } + } - private long totalSpanMillis() { - return finishedTimestamp - pushTask.createTimestamp; - } + private final class PushClientCallback implements CallbackHandler { + final PushTask pushTask; + final PushingTaskKey pushingTaskKey; + long finishedTimestamp; - @Override - public Executor getExecutor() { - return pushCallbackExecutor; - } + PushClientCallback(PushTask pushTask, PushingTaskKey pushingTaskKey) { + this.pushTask = pushTask; + this.pushingTaskKey = pushingTaskKey; } - private static final class PendingTaskKey { - final String dataCenter; - final String dataInfoId; - final InetSocketAddress addr; - final Set subscriberIds; + @Override + public void onCallback(Channel channel, Object message) { + this.finishedTimestamp = System.currentTimeMillis(); + PUSH_CLIENT_SUCCESS_COUNTER.inc(); + boolean cleaned = false; + try { + for (Subscriber subscriber : pushTask.subscriberMap.values()) { + if (!subscriber.checkAndUpdateVersion(pushTask.dataCenter, pushTask.datum.getVersion())) { + LOGGER.warn( + "PushY, but failed to updateVersion, {}, {}", + pushTask.taskID, + pushTask.pushingTaskKey); + } + } + } catch (Throwable e) { + LOGGER.error("error push.onCallback, {}, {}", pushTask.taskID, pushTask.pushingTaskKey, e); + } finally { + // TODO should use remove(k, exceptV). but in some case, + // after removed=true, the value aslo in the map + cleaned = pushingTasks.remove(pushingTaskKey, pushTask); + } + this.pushTask.trace.finishPush(PushTrace.PushStatus.OK, this.finishedTimestamp).print(); + LOGGER.info( + "PushY, clean record={}, span={}/{}, {}, {}", + cleaned, + pushSpanMillis(), + totalSpanMillis(), + pushTask.taskID, + pushTask.pushingTaskKey); + } - PendingTaskKey(String dataCenter, InetSocketAddress addr, String dataInfoId, - Set subscriberIds) { - this.dataCenter = dataCenter; - this.dataInfoId = dataInfoId; - this.addr = addr; - this.subscriberIds = subscriberIds; - } + @Override + public void onException(Channel channel, Throwable exception) { + this.finishedTimestamp = System.currentTimeMillis(); + PUSH_CLIENT_FAIL_COUNTER.inc(); + boolean cleaned = false; + try { + // TODO should use remove(k, exceptV). but in some case, + // after removed=true, the value aslo in the map + cleaned = pushingTasks.remove(pushingTaskKey, pushTask); + if (channel.isConnected()) { + retry(pushTask, "callbackErr"); + } else { + LOGGER.warn("PushN, channel closed, {}, {}", pushTask.taskID, pushingTaskKey); + } + } catch (Throwable e) { + LOGGER.error("error push.onException, {}, {}", pushTask.taskID, pushingTaskKey, e); + } + if (exception instanceof InvokeTimeoutException) { + if (cleaned) { + this.pushTask + .trace + .finishPush(PushTrace.PushStatus.Timeout, this.finishedTimestamp) + .print(); + } + LOGGER.error( + "PushN, timeout, clean record={}, span={}/{}, {}, {}", + cleaned, + pushSpanMillis(), + totalSpanMillis(), + pushTask.taskID, + pushingTaskKey); + } else { + if (cleaned) { + this.pushTask.trace.finishPush(PushTrace.PushStatus.Fail, this.finishedTimestamp).print(); + } + LOGGER.error( + "PushN, clean record={}, span={}/{}, {}, {}", + cleaned, + pushSpanMillis(), + totalSpanMillis(), + pushTask.taskID, + pushingTaskKey, + exception); + } + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - PendingTaskKey pendingTaskKey = (PendingTaskKey) o; - return Objects.equals(addr, pendingTaskKey.addr) - && Objects.equals(dataInfoId, pendingTaskKey.dataInfoId) - && Objects.equals(dataCenter, pendingTaskKey.dataCenter) - && Objects.equals(subscriberIds, pendingTaskKey.subscriberIds); - } + private long pushSpanMillis() { + return finishedTimestamp - pushTask.pushTimestamp; + } - @Override - public int hashCode() { - return Objects.hash(dataCenter, addr, dataInfoId, subscriberIds); - } + private long totalSpanMillis() { + return finishedTimestamp - pushTask.createTimestamp; + } - @Override - public String toString() { - return "PendingKey{" + dataInfoId + ',' + dataCenter + ',' + addr + ", subscriberIds=" - + subscriberIds + '}'; - } + @Override + public Executor getExecutor() { + return pushCallbackExecutor; + } + } + + private static final class PendingTaskKey { + final String dataCenter; + final String dataInfoId; + final InetSocketAddress addr; + final Set subscriberIds; + + PendingTaskKey( + String dataCenter, InetSocketAddress addr, String dataInfoId, Set subscriberIds) { + this.dataCenter = dataCenter; + this.dataInfoId = dataInfoId; + this.addr = addr; + this.subscriberIds = subscriberIds; } - private static final class PushingTaskKey { - final InetSocketAddress addr; - final String dataInfoId; - final ScopeEnum scopeEnum; - final BaseInfo.ClientVersion clientVersion; + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PendingTaskKey pendingTaskKey = (PendingTaskKey) o; + return Objects.equals(addr, pendingTaskKey.addr) + && Objects.equals(dataInfoId, pendingTaskKey.dataInfoId) + && Objects.equals(dataCenter, pendingTaskKey.dataCenter) + && Objects.equals(subscriberIds, pendingTaskKey.subscriberIds); + } - PushingTaskKey(String dataInfoId, InetSocketAddress addr, ScopeEnum scopeEnum, - BaseInfo.ClientVersion clientVersion) { - this.dataInfoId = dataInfoId; - this.addr = addr; - this.scopeEnum = scopeEnum; - this.clientVersion = clientVersion; - } + @Override + public int hashCode() { + return Objects.hash(dataCenter, addr, dataInfoId, subscriberIds); + } - @Override - public boolean equals(Object o) { - if (this == o) - return true; - if (o == null || getClass() != o.getClass()) - return false; - PushingTaskKey that = (PushingTaskKey) o; - return Objects.equals(addr, that.addr) && Objects.equals(dataInfoId, that.dataInfoId) - && scopeEnum == that.scopeEnum && clientVersion == that.clientVersion; - } + @Override + public String toString() { + return "PendingKey{" + + dataInfoId + + ',' + + dataCenter + + ',' + + addr + + ", subscriberIds=" + + subscriberIds + + '}'; + } + } + + private static final class PushingTaskKey { + final InetSocketAddress addr; + final String dataInfoId; + final ScopeEnum scopeEnum; + final BaseInfo.ClientVersion clientVersion; + + PushingTaskKey( + String dataInfoId, + InetSocketAddress addr, + ScopeEnum scopeEnum, + BaseInfo.ClientVersion clientVersion) { + this.dataInfoId = dataInfoId; + this.addr = addr; + this.scopeEnum = scopeEnum; + this.clientVersion = clientVersion; + } - @Override - public int hashCode() { - return Objects.hash(addr, dataInfoId, scopeEnum, clientVersion); - } + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + PushingTaskKey that = (PushingTaskKey) o; + return Objects.equals(addr, that.addr) + && Objects.equals(dataInfoId, that.dataInfoId) + && scopeEnum == that.scopeEnum + && clientVersion == that.clientVersion; + } - @Override - public String toString() { - return "PushingKey{" + dataInfoId + ',' + scopeEnum + ',' + addr + '}'; - } + @Override + public int hashCode() { + return Objects.hash(addr, dataInfoId, scopeEnum, clientVersion); } - private static final class CallRunHandler extends ThreadPoolExecutor.CallerRunsPolicy { - public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { - super.rejectedExecution(r, e); - LOGGER.warn("push callback busy"); - } + @Override + public String toString() { + return "PushingKey{" + dataInfoId + ',' + scopeEnum + ',' + addr + '}'; } + } - private int getRetryBackoffTime(int retry) { - final int initialSleepTime = sessionServerConfig.getPushDataTaskRetryFirstDelayMillis(); - if (retry == 0) { - return initialSleepTime; - } - int increment = sessionServerConfig.getPushDataTaskRetryIncrementDelayMillis(); - int result = initialSleepTime + (increment * (retry - 1)); - return result >= 0L ? result : 0; + private static final class CallRunHandler extends ThreadPoolExecutor.CallerRunsPolicy { + public void rejectedExecution(Runnable r, ThreadPoolExecutor e) { + super.rejectedExecution(r, e); + LOGGER.warn("push callback busy"); } + } + private int getRetryBackoffTime(int retry) { + final int initialSleepTime = sessionServerConfig.getPushDataTaskRetryFirstDelayMillis(); + if (retry == 0) { + return initialSleepTime; + } + int increment = sessionServerConfig.getPushDataTaskRetryIncrementDelayMillis(); + int result = initialSleepTime + (increment * (retry - 1)); + return result >= 0L ? result : 0; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushTrace.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushTrace.java index ec82ba7ca..22ba0a28d 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushTrace.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/push/PushTrace.java @@ -24,125 +24,141 @@ import com.alipay.sofa.registry.util.DatumVersionUtil; import com.google.common.collect.Lists; import com.google.common.primitives.Longs; - import java.net.InetSocketAddress; import java.util.Collections; import java.util.Comparator; import java.util.List; public final class PushTrace { - private static final Logger LOGGER = LoggerFactory.getLogger("PUSH-TRACE"); - - private final SubDatum datum; - private final long modifyTimestamp; - private final long pushCommitTimestamp = System.currentTimeMillis(); - - private long subscriberPushedVersion; - private final String subApp; - private final InetSocketAddress subAddress; - private final boolean noDelay; - - private long pushStartTimestamp; - - private PushStatus status; - private long pushFinishTimestamp; - - // push.finish - datum.modify - private long datumTotalDelayMillis; - // commit - datum.modify - private long datumPushCommitSpanMillis; - // push.start - fetch.finish - private long datumPushStartSpanMillis; - // push.finish - push.start - private long datumPushFinishSpanMillis; - - // pub after last push - private int newPublisherNum; - // push.finish - firstPub.registerTimestamp - private long firstPubPushDelayMillis; - // push.finish - lastPub.registerTimestamp - private long lastPubPushDelayMillis; - - private PushTrace(SubDatum datum, InetSocketAddress address, String subApp, boolean noDelay) { - this.datum = datum; - this.modifyTimestamp = datum.getVersion() <= ValueConstants.DEFAULT_NO_DATUM_VERSION ? System - .currentTimeMillis() : DatumVersionUtil.getRealTimestamp(datum.getVersion()); - this.subAddress = address; - this.subApp = subApp; - this.noDelay = noDelay; - } - - public static PushTrace trace(SubDatum datum, InetSocketAddress address, String subApp, - boolean noDelay) { - return new PushTrace(datum, address, subApp, noDelay); - } - - public PushTrace startPush(long subscriberPushedVersion, long startPushTimestamp) { - this.subscriberPushedVersion = subscriberPushedVersion; - this.pushStartTimestamp = startPushTimestamp; - return this; - } - - public PushTrace finishPush(PushStatus status, long finishPushTimestamp) { - this.status = status; - this.pushFinishTimestamp = finishPushTimestamp; - return this; - } - - public void print() { - calc(); - LOGGER - .info( - "{},{},{},{},{},noDelay={},pubNum={},pubBytes={},pubNew={},delay={},{},{},{},firstPubDelay={},lastPubDelay={},addr={}", - status, datum.getDataInfoId(), datum.getVersion(), subApp, datum.getDataCenter(), - noDelay, datum.getPublishers().size(), datum.getDataBoxBytes(), newPublisherNum, - datumTotalDelayMillis, datumPushCommitSpanMillis, datumPushStartSpanMillis, - datumPushFinishSpanMillis, firstPubPushDelayMillis, lastPubPushDelayMillis, - subAddress); - } - - private void calc() { - // try find the earliest and the latest publisher after the subPushedVersion - // that means the modify after last push, but this could not handle the publisher.remove - this.datumTotalDelayMillis = pushFinishTimestamp - modifyTimestamp; - this.datumPushCommitSpanMillis = pushCommitTimestamp - modifyTimestamp; - this.datumPushStartSpanMillis = pushStartTimestamp - pushCommitTimestamp; - this.datumPushFinishSpanMillis = pushFinishTimestamp - pushStartTimestamp; - - final List publishers = datum.getPublishers(); - final long lastPushTimestamp = subscriberPushedVersion <= ValueConstants.DEFAULT_NO_DATUM_VERSION ? 0 + private static final Logger LOGGER = LoggerFactory.getLogger("PUSH-TRACE"); + + private final SubDatum datum; + private final long modifyTimestamp; + private final long pushCommitTimestamp = System.currentTimeMillis(); + + private long subscriberPushedVersion; + private final String subApp; + private final InetSocketAddress subAddress; + private final boolean noDelay; + + private long pushStartTimestamp; + + private PushStatus status; + private long pushFinishTimestamp; + + // push.finish - datum.modify + private long datumTotalDelayMillis; + // commit - datum.modify + private long datumPushCommitSpanMillis; + // push.start - fetch.finish + private long datumPushStartSpanMillis; + // push.finish - push.start + private long datumPushFinishSpanMillis; + + // pub after last push + private int newPublisherNum; + // push.finish - firstPub.registerTimestamp + private long firstPubPushDelayMillis; + // push.finish - lastPub.registerTimestamp + private long lastPubPushDelayMillis; + + private PushTrace(SubDatum datum, InetSocketAddress address, String subApp, boolean noDelay) { + this.datum = datum; + this.modifyTimestamp = + datum.getVersion() <= ValueConstants.DEFAULT_NO_DATUM_VERSION + ? System.currentTimeMillis() + : DatumVersionUtil.getRealTimestamp(datum.getVersion()); + this.subAddress = address; + this.subApp = subApp; + this.noDelay = noDelay; + } + + public static PushTrace trace( + SubDatum datum, InetSocketAddress address, String subApp, boolean noDelay) { + return new PushTrace(datum, address, subApp, noDelay); + } + + public PushTrace startPush(long subscriberPushedVersion, long startPushTimestamp) { + this.subscriberPushedVersion = subscriberPushedVersion; + this.pushStartTimestamp = startPushTimestamp; + return this; + } + + public PushTrace finishPush(PushStatus status, long finishPushTimestamp) { + this.status = status; + this.pushFinishTimestamp = finishPushTimestamp; + return this; + } + + public void print() { + calc(); + LOGGER.info( + "{},{},{},{},{},noDelay={},pubNum={},pubBytes={},pubNew={},delay={},{},{},{},firstPubDelay={},lastPubDelay={},addr={}", + status, + datum.getDataInfoId(), + datum.getVersion(), + subApp, + datum.getDataCenter(), + noDelay, + datum.getPublishers().size(), + datum.getDataBoxBytes(), + newPublisherNum, + datumTotalDelayMillis, + datumPushCommitSpanMillis, + datumPushStartSpanMillis, + datumPushFinishSpanMillis, + firstPubPushDelayMillis, + lastPubPushDelayMillis, + subAddress); + } + + private void calc() { + // try find the earliest and the latest publisher after the subPushedVersion + // that means the modify after last push, but this could not handle the publisher.remove + this.datumTotalDelayMillis = pushFinishTimestamp - modifyTimestamp; + this.datumPushCommitSpanMillis = pushCommitTimestamp - modifyTimestamp; + this.datumPushStartSpanMillis = pushStartTimestamp - pushCommitTimestamp; + this.datumPushFinishSpanMillis = pushFinishTimestamp - pushStartTimestamp; + + final List publishers = datum.getPublishers(); + final long lastPushTimestamp = + subscriberPushedVersion <= ValueConstants.DEFAULT_NO_DATUM_VERSION + ? 0 : DatumVersionUtil.getRealTimestamp(subscriberPushedVersion); - final List news = findNewPublishers(publishers, lastPushTimestamp); - final SubPublisher first = news.isEmpty() ? null : news.get(0); - final SubPublisher last = news.isEmpty() ? null : news.get(news.size() - 1); - this.newPublisherNum = news.size(); - this.firstPubPushDelayMillis = first == null ? 0 : pushFinishTimestamp - - first.getRegisterTimestamp(); - this.lastPubPushDelayMillis = last == null ? 0 : pushFinishTimestamp - - last.getRegisterTimestamp(); + final List news = findNewPublishers(publishers, lastPushTimestamp); + final SubPublisher first = news.isEmpty() ? null : news.get(0); + final SubPublisher last = news.isEmpty() ? null : news.get(news.size() - 1); + this.newPublisherNum = news.size(); + this.firstPubPushDelayMillis = + first == null ? 0 : pushFinishTimestamp - first.getRegisterTimestamp(); + this.lastPubPushDelayMillis = + last == null ? 0 : pushFinishTimestamp - last.getRegisterTimestamp(); + } + + enum PushStatus { + OK, + Fail, + Timeout, + } + + private List findNewPublishers( + List publishers, long minRegisterTimestamp) { + if (publishers.isEmpty()) { + return Collections.emptyList(); } - - enum PushStatus { - OK, Fail, Timeout, + List news = Lists.newArrayList(); + for (SubPublisher p : publishers) { + if (p.getRegisterTimestamp() > minRegisterTimestamp) { + news.add(p); + } } - - private List findNewPublishers(List publishers, - long minRegisterTimestamp) { - if (publishers.isEmpty()) { - return Collections.emptyList(); - } - List news = Lists.newArrayList(); - for (SubPublisher p : publishers) { - if (p.getRegisterTimestamp() > minRegisterTimestamp) { - news.add(p); - } - } - news.sort(new Comparator() { - @Override - public int compare(SubPublisher o1, SubPublisher o2) { - return Longs.compare(o1.getRegisterTimestamp(), o2.getRegisterTimestamp()); - } + news.sort( + new Comparator() { + @Override + public int compare(SubPublisher o1, SubPublisher o2) { + return Longs.compare(o1.getRegisterTimestamp(), o2.getRegisterTimestamp()); + } }); - return news; - } + return news; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/registry/Registry.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/registry/Registry.java index 408e930da..20d1861af 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/registry/Registry.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/registry/Registry.java @@ -16,57 +16,54 @@ */ package com.alipay.sofa.registry.server.session.registry; -import java.util.List; - import com.alipay.sofa.registry.common.model.ConnectId; import com.alipay.sofa.registry.common.model.store.StoreData; +import java.util.List; /** - * * @author shangyu.wh * @version $Id: SessionRegistry.java, v 0.1 2017-11-27 19:49 shangyu.wh Exp $ */ public interface Registry { - /** - * register new publisher or subscriber data - * - * @param data - */ - void register(StoreData data); + /** + * register new publisher or subscriber data + * + * @param data + */ + void register(StoreData data); - /** - * cancel publisher or subscriber data by client ip address and port(ip:port),one ip address has more than one processId - * when disconnection between client node and session node,disconnect event fire remove all pub and sub info on session and data node - * this function always use in Console manage Client node list,input ip list must transform to connectId through connect manage - * - * @param connectIds - */ - void cancel(List connectIds); + /** + * cancel publisher or subscriber data by client ip address and port(ip:port),one ip address has + * more than one processId when disconnection between client node and session node,disconnect + * event fire remove all pub and sub info on session and data node this function always use in + * Console manage Client node list,input ip list must transform to connectId through connect + * manage + * + * @param connectIds + */ + void cancel(List connectIds); - /** - * remove publisher or subscriber data by client ip address and port(ip:port) - * this function always use in rest api Console manage ,the run mode is standard - * remove subscriber data will push empty datum to some one who has dataInfoId begin with pushEmptyDataDataIdPrefixes config - * - * @param connectIds - */ - void remove(List connectIds); + /** + * remove publisher or subscriber data by client ip address and port(ip:port) this function always + * use in rest api Console manage ,the run mode is standard remove subscriber data will push empty + * datum to some one who has dataInfoId begin with pushEmptyDataDataIdPrefixes config + * + * @param connectIds + */ + void remove(List connectIds); - /** - * message mode com.alipay.sofa.registry.client.provider for client node to unregister single subscriber or publisher data - * - * @param data - */ - void unRegister(StoreData data); + /** + * message mode com.alipay.sofa.registry.client.provider for client node to unregister single + * subscriber or publisher data + * + * @param data + */ + void unRegister(StoreData data); - /** - * for fetchChangData first invoke - */ - void fetchChangDataProcess(); + /** for fetchChangData first invoke */ + void fetchChangDataProcess(); - /** - * for scheduler clean no connect client - */ - void cleanClientConnect(); -} \ No newline at end of file + /** for scheduler clean no connect client */ + void cleanClientConnect(); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/registry/SessionRegistry.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/registry/SessionRegistry.java index 93e13cfba..ed8b77cd8 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/registry/SessionRegistry.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/registry/SessionRegistry.java @@ -48,14 +48,13 @@ import com.alipay.sofa.registry.util.WakeUpLoopRunnable; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.apache.commons.lang.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.CollectionUtils; - -import javax.annotation.PostConstruct; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; +import javax.annotation.PostConstruct; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; /** * @author shangyu.wh @@ -63,396 +62,384 @@ */ public class SessionRegistry implements Registry { - private static final Logger LOGGER = LoggerFactory - .getLogger(SessionRegistry.class); - - protected static final Logger SCAN_VER_LOGGER = LoggerFactory.getLogger("SCAN-VER"); + private static final Logger LOGGER = LoggerFactory.getLogger(SessionRegistry.class); - /** - * store subscribers - */ - @Autowired - private Interests sessionInterests; + protected static final Logger SCAN_VER_LOGGER = LoggerFactory.getLogger("SCAN-VER"); - /** - * store watchers - */ - @Autowired - private Watchers sessionWatchers; + /** store subscribers */ + @Autowired private Interests sessionInterests; - /** - * store publishers - */ - @Autowired - private DataStore sessionDataStore; + /** store watchers */ + @Autowired private Watchers sessionWatchers; - /** - * transfer data to DataNode - */ - @Autowired - private DataNodeService dataNodeService; + /** store publishers */ + @Autowired private DataStore sessionDataStore; - /** - * trigger task com.alipay.sofa.registry.server.meta.listener process - */ - @Autowired - private TaskListenerManager taskListenerManager; + /** transfer data to DataNode */ + @Autowired private DataNodeService dataNodeService; - @Autowired - private SessionServerConfig sessionServerConfig; + /** trigger task com.alipay.sofa.registry.server.meta.listener process */ + @Autowired private TaskListenerManager taskListenerManager; - @Autowired - private Exchange boltExchange; + @Autowired private SessionServerConfig sessionServerConfig; - @Autowired - private SessionRegistryStrategy sessionRegistryStrategy; + @Autowired private Exchange boltExchange; - @Autowired - private WrapperInterceptorManager wrapperInterceptorManager; + @Autowired private SessionRegistryStrategy sessionRegistryStrategy; - @Autowired - private DataIdMatchStrategy dataIdMatchStrategy; + @Autowired private WrapperInterceptorManager wrapperInterceptorManager; - @Autowired - private WriteDataAcceptor writeDataAcceptor; + @Autowired private DataIdMatchStrategy dataIdMatchStrategy; - @Autowired - private SlotTableCache slotTableCache; + @Autowired private WriteDataAcceptor writeDataAcceptor; - @Autowired - private FirePushService firePushService; + @Autowired private SlotTableCache slotTableCache; - private final VersionWatchDog versionWatchDog = new VersionWatchDog(); + @Autowired private FirePushService firePushService; - private volatile boolean scanVerEnable = false; + private final VersionWatchDog versionWatchDog = new VersionWatchDog(); - @PostConstruct - public void init() { - ConcurrentUtils.createDaemonThread("SessionVerWatchDog", versionWatchDog).start(); - ConcurrentUtils.createDaemonThread("SessionClientWatchDog", new ClientWatchDog()).start(); - } + private volatile boolean scanVerEnable = false; - @Override - public void register(StoreData storeData) { + @PostConstruct + public void init() { + ConcurrentUtils.createDaemonThread("SessionVerWatchDog", versionWatchDog).start(); + ConcurrentUtils.createDaemonThread("SessionClientWatchDog", new ClientWatchDog()).start(); + } - WrapperInvocation wrapperInvocation = new WrapperInvocation( - new Wrapper() { - @Override - public Boolean call() { + @Override + public void register(StoreData storeData) { - switch (storeData.getDataType()) { - case PUBLISHER: - Publisher publisher = (Publisher) storeData; - publisher.setSessionProcessId(ServerEnv.PROCESS_ID); - sessionDataStore.add(publisher); + WrapperInvocation wrapperInvocation = + new WrapperInvocation( + new Wrapper() { + @Override + public Boolean call() { - // All write operations to DataServer (pub/unPub/clientoff/renew/snapshot) - // are handed over to WriteDataAcceptor - writeDataAcceptor.accept(new PublisherWriteDataRequest(publisher, - WriteDataRequest.WriteDataRequestType.PUBLISHER)); + switch (storeData.getDataType()) { + case PUBLISHER: + Publisher publisher = (Publisher) storeData; + publisher.setSessionProcessId(ServerEnv.PROCESS_ID); + sessionDataStore.add(publisher); - sessionRegistryStrategy.afterPublisherRegister(publisher); - break; - case SUBSCRIBER: - Subscriber subscriber = (Subscriber) storeData; + // All write operations to DataServer (pub/unPub/clientoff/renew/snapshot) + // are handed over to WriteDataAcceptor + writeDataAcceptor.accept( + new PublisherWriteDataRequest( + publisher, WriteDataRequest.WriteDataRequestType.PUBLISHER)); - sessionInterests.add(subscriber); + sessionRegistryStrategy.afterPublisherRegister(publisher); + break; + case SUBSCRIBER: + Subscriber subscriber = (Subscriber) storeData; - sessionRegistryStrategy.afterSubscriberRegister(subscriber); - break; - case WATCHER: - Watcher watcher = (Watcher) storeData; + sessionInterests.add(subscriber); - sessionWatchers.add(watcher); + sessionRegistryStrategy.afterSubscriberRegister(subscriber); + break; + case WATCHER: + Watcher watcher = (Watcher) storeData; - sessionRegistryStrategy.afterWatcherRegister(watcher); - break; - default: - break; - } - return null; - } - - @Override - public Supplier getParameterSupplier() { - return () -> storeData; - } - - }, wrapperInterceptorManager); - - try { - wrapperInvocation.proceed(); - } catch (RequestChannelClosedException e) { - throw e; - } catch (Exception e) { - throw new RuntimeException("Proceed register error!", e); - } + sessionWatchers.add(watcher); + sessionRegistryStrategy.afterWatcherRegister(watcher); + break; + default: + break; + } + return null; + } + + @Override + public Supplier getParameterSupplier() { + return () -> storeData; + } + }, + wrapperInterceptorManager); + + try { + wrapperInvocation.proceed(); + } catch (RequestChannelClosedException e) { + throw e; + } catch (Exception e) { + throw new RuntimeException("Proceed register error!", e); } + } - @Override - public void unRegister(StoreData storeData) { + @Override + public void unRegister(StoreData storeData) { - switch (storeData.getDataType()) { - case PUBLISHER: - Publisher publisher = (Publisher) storeData; - publisher.setSessionProcessId(ServerEnv.PROCESS_ID); + switch (storeData.getDataType()) { + case PUBLISHER: + Publisher publisher = (Publisher) storeData; + publisher.setSessionProcessId(ServerEnv.PROCESS_ID); - sessionDataStore.deleteById(storeData.getId(), publisher.getDataInfoId()); + sessionDataStore.deleteById(storeData.getId(), publisher.getDataInfoId()); - // All write operations to DataServer (pub/unPub/clientoff/renew/snapshot) - // are handed over to WriteDataAcceptor - writeDataAcceptor.accept(new PublisherWriteDataRequest(publisher, - WriteDataRequest.WriteDataRequestType.UN_PUBLISHER)); + // All write operations to DataServer (pub/unPub/clientoff/renew/snapshot) + // are handed over to WriteDataAcceptor + writeDataAcceptor.accept( + new PublisherWriteDataRequest( + publisher, WriteDataRequest.WriteDataRequestType.UN_PUBLISHER)); - sessionRegistryStrategy.afterPublisherUnRegister(publisher); - break; + sessionRegistryStrategy.afterPublisherUnRegister(publisher); + break; - case SUBSCRIBER: - Subscriber subscriber = (Subscriber) storeData; - sessionInterests.deleteById(storeData.getId(), subscriber.getDataInfoId()); - sessionRegistryStrategy.afterSubscriberUnRegister(subscriber); - break; + case SUBSCRIBER: + Subscriber subscriber = (Subscriber) storeData; + sessionInterests.deleteById(storeData.getId(), subscriber.getDataInfoId()); + sessionRegistryStrategy.afterSubscriberUnRegister(subscriber); + break; - case WATCHER: - Watcher watcher = (Watcher) storeData; - - sessionWatchers.deleteById(watcher.getId(), watcher.getDataInfoId()); - - sessionRegistryStrategy.afterWatcherUnRegister(watcher); - break; - default: - break; - } + case WATCHER: + Watcher watcher = (Watcher) storeData; - } + sessionWatchers.deleteById(watcher.getId(), watcher.getDataInfoId()); - @Override - public void cancel(List connectIds) { - //update local firstly, data node send error depend on renew check - for (ConnectId connectId : connectIds) { - List removes = removeFromSession(connectId); - if (!removes.isEmpty()) { - // clientOff to dataNode async - clientOffToDataNode(connectId, removes); - } - } + sessionRegistryStrategy.afterWatcherUnRegister(watcher); + break; + default: + break; } - - private List removeFromSession(ConnectId connectId) { - Map publisherMap = sessionDataStore.deleteByConnectId(connectId); - sessionInterests.deleteByConnectId(connectId); - sessionWatchers.deleteByConnectId(connectId); - return Lists.newArrayList(publisherMap.values()); + } + + @Override + public void cancel(List connectIds) { + // update local firstly, data node send error depend on renew check + for (ConnectId connectId : connectIds) { + List removes = removeFromSession(connectId); + if (!removes.isEmpty()) { + // clientOff to dataNode async + clientOffToDataNode(connectId, removes); + } } + } - private void clientOffToDataNode(ConnectId connectId, List clientOffPublishers) { - writeDataAcceptor.accept(new ClientOffWriteDataRequest(connectId, clientOffPublishers)); - } + private List removeFromSession(ConnectId connectId) { + Map publisherMap = sessionDataStore.deleteByConnectId(connectId); + sessionInterests.deleteByConnectId(connectId); + sessionWatchers.deleteByConnectId(connectId); + return Lists.newArrayList(publisherMap.values()); + } - private final class ClientWatchDog extends LoopRunnable { + private void clientOffToDataNode(ConnectId connectId, List clientOffPublishers) { + writeDataAcceptor.accept(new ClientOffWriteDataRequest(connectId, clientOffPublishers)); + } - @Override - public void runUnthrowable() { - try { - cleanClientConnect(); - } catch (Throwable e) { - LOGGER.error("WatchDog failed to cleanClientConnect", e); - } - } + private final class ClientWatchDog extends LoopRunnable { - @Override - public void waitingUnthrowable() { - ConcurrentUtils.sleepUninterruptibly(1, TimeUnit.SECONDS); - } + @Override + public void runUnthrowable() { + try { + cleanClientConnect(); + } catch (Throwable e) { + LOGGER.error("WatchDog failed to cleanClientConnect", e); + } } - private final class VersionWatchDog extends WakeUpLoopRunnable { - boolean prevStopPushSwitch; - - @Override - public void runUnthrowable() { - try { - final boolean stop = sessionServerConfig.isStopPushSwitch(); - // could not start scan ver at begin - // 1. stopPush.val = false in session.default - // 2. stopPush.val = true in meta - // 3. scanVerEnable=true after session start and config the stopPush.val - if (!stop && scanVerEnable) { - scanVersions(); - triggerSubscriberRegister(); - if (prevStopPushSwitch) { - SCAN_VER_LOGGER.info("[ReSub] resub after stopPushSwitch closed"); - } - } - prevStopPushSwitch = stop; - } catch (Throwable e) { - SCAN_VER_LOGGER.error("WatchDog failed fetch versions", e); - } - } - - @Override - public int getWaitingMillis() { - return sessionServerConfig.getSchedulerScanVersionIntervalMillis(); - } + @Override + public void waitingUnthrowable() { + ConcurrentUtils.sleepUninterruptibly(1, TimeUnit.SECONDS); } + } - private void scanVersions() { - // TODO not support multi cluster - Map interestVersions = sessionInterests - .getInterestVersions(sessionServerConfig.getSessionServerDataCenter()); - Map> interestVersionsGroup = groupBySlot(interestVersions); - for (Map.Entry> group : interestVersionsGroup.entrySet()) { - final int slotId = group.getKey(); - try { - fetchChangDataProcess(sessionServerConfig.getSessionServerDataCenter(), slotId, - group.getValue()); - } catch (Throwable e) { - SCAN_VER_LOGGER.error("failed to fetch versions slotId={}, size={}", slotId, group - .getValue().size(), e); - } - } - } + private final class VersionWatchDog extends WakeUpLoopRunnable { + boolean prevStopPushSwitch; - private void triggerSubscriberRegister() { - Collection subscribers = sessionInterests.getInterestsNeverPushed(); - if (!subscribers.isEmpty()) { - SCAN_VER_LOGGER.info("find never pushed subscribers:{}", subscribers.size()); - for (Subscriber subscriber : subscribers) { - try { - firePushService.fireOnRegister(subscriber); - } catch (Throwable e) { - SCAN_VER_LOGGER.error("failed to register subscriber, {}", subscriber, e); - } - } + @Override + public void runUnthrowable() { + try { + final boolean stop = sessionServerConfig.isStopPushSwitch(); + // could not start scan ver at begin + // 1. stopPush.val = false in session.default + // 2. stopPush.val = true in meta + // 3. scanVerEnable=true after session start and config the stopPush.val + if (!stop && scanVerEnable) { + scanVersions(); + triggerSubscriberRegister(); + if (prevStopPushSwitch) { + SCAN_VER_LOGGER.info("[ReSub] resub after stopPushSwitch closed"); + } } + prevStopPushSwitch = stop; + } catch (Throwable e) { + SCAN_VER_LOGGER.error("WatchDog failed fetch versions", e); + } } @Override - public void fetchChangDataProcess() { - scanVerEnable = true; - versionWatchDog.wakeup(); + public int getWaitingMillis() { + return sessionServerConfig.getSchedulerScanVersionIntervalMillis(); } - - private Map> groupBySlot(Map interestVersions) { - if (CollectionUtils.isEmpty(interestVersions)) { - return Collections.emptyMap(); - } - TreeMap> ret = Maps.newTreeMap(); - for (Map.Entry interestVersion : interestVersions.entrySet()) { - final String dataInfoId = interestVersion.getKey(); - Map map = ret.computeIfAbsent(slotTableCache.slotOf(dataInfoId), k -> Maps.newHashMapWithExpectedSize(128)); - map.put(dataInfoId, interestVersion.getValue()); - } - return ret; + } + + private void scanVersions() { + // TODO not support multi cluster + Map interestVersions = + sessionInterests.getInterestVersions(sessionServerConfig.getSessionServerDataCenter()); + Map> interestVersionsGroup = groupBySlot(interestVersions); + for (Map.Entry> group : interestVersionsGroup.entrySet()) { + final int slotId = group.getKey(); + try { + fetchChangDataProcess( + sessionServerConfig.getSessionServerDataCenter(), slotId, group.getValue()); + } catch (Throwable e) { + SCAN_VER_LOGGER.error( + "failed to fetch versions slotId={}, size={}", slotId, group.getValue().size(), e); + } } + } - private void fetchChangDataProcess(String dataCenter, int slotId, - Map interestVersions) { - final String leader = slotTableCache.getLeader(slotId); - if (StringUtils.isBlank(leader)) { - SCAN_VER_LOGGER.warn("slot not assigned, {}", slotId); - return; - } - - Map dataVersions = dataNodeService.fetchDataVersion( - dataCenter, slotId, interestVersions); - - SCAN_VER_LOGGER.info("[fetchSlotVer]{},{},{},interests={},gets={}", slotId, dataCenter, - leader, interestVersions.size(), dataVersions.size()); - Map mergedVersions = new HashMap<>(interestVersions); - mergedVersions.putAll(dataVersions); - for (Map.Entry version : mergedVersions.entrySet()) { - final String dataInfoId = version.getKey(); - final long verVal = version.getValue().getValue(); - if (sessionInterests.checkInterestVersion(dataCenter, dataInfoId, verVal).interested) { - firePushService.fireOnChange(dataCenter, dataInfoId, verVal); - SCAN_VER_LOGGER.info("[fetchSlotVerNotify]{},{},{},{}", slotId, dataInfoId, - dataCenter, verVal); - } + private void triggerSubscriberRegister() { + Collection subscribers = sessionInterests.getInterestsNeverPushed(); + if (!subscribers.isEmpty()) { + SCAN_VER_LOGGER.info("find never pushed subscribers:{}", subscribers.size()); + for (Subscriber subscriber : subscribers) { + try { + firePushService.fireOnRegister(subscriber); + } catch (Throwable e) { + SCAN_VER_LOGGER.error("failed to register subscriber, {}", subscriber, e); } + } } - - public void remove(List connectIds) { - List connectIdsAll = new ArrayList<>(); - connectIds.forEach(connectId -> { - Map pubMap = getSessionDataStore().queryByConnectId(connectId); - boolean pubExisted = pubMap != null && !pubMap.isEmpty(); - - Map subMap = getSessionInterests().queryByConnectId(connectId); - boolean subExisted = false; - if (subMap != null && !subMap.isEmpty()) { - subExisted = true; - - subMap.forEach((registerId, sub) -> { - if (isFireSubscriberPushEmptyTask(sub.getDataId())) { - fireSubscriberPushEmptyTask(sub); - } - }); - } - - if (pubExisted || subExisted) { - connectIdsAll.add(connectId); - } - }); - cancel(connectIdsAll); - } - - protected boolean isFireSubscriberPushEmptyTask(String dataId) { - return dataIdMatchStrategy.match(dataId, () -> sessionServerConfig.getBlacklistSubDataIdRegex()); + } + + @Override + public void fetchChangDataProcess() { + scanVerEnable = true; + versionWatchDog.wakeup(); + } + + private Map> groupBySlot( + Map interestVersions) { + if (CollectionUtils.isEmpty(interestVersions)) { + return Collections.emptyMap(); } - - private void fireSubscriberPushEmptyTask(Subscriber subscriber) { - firePushService.fireOnPushEmpty(subscriber); + TreeMap> ret = Maps.newTreeMap(); + for (Map.Entry interestVersion : interestVersions.entrySet()) { + final String dataInfoId = interestVersion.getKey(); + Map map = + ret.computeIfAbsent( + slotTableCache.slotOf(dataInfoId), k -> Maps.newHashMapWithExpectedSize(128)); + map.put(dataInfoId, interestVersion.getValue()); } - - public void cleanClientConnect() { - Set connectIndexes = new HashSet<>(); - connectIndexes.addAll(sessionDataStore.getConnectIds()); - connectIndexes.addAll(sessionInterests.getConnectIds()); - connectIndexes.addAll(sessionWatchers.getConnectIds()); - - Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort()); - - List connectIds = new ArrayList<>(); - for (ConnectId connectId : connectIndexes) { - Channel channel = sessionServer.getChannel(new URL(connectId.getClientHostAddress(), - connectId.getClientPort())); - if (channel == null) { - connectIds.add(connectId); - LOGGER.warn("Client connect has not existed!it must be remove!connectId:{}", - connectId); - } - } - if (!connectIds.isEmpty()) { - cancel(connectIds); - } + return ret; + } + + private void fetchChangDataProcess( + String dataCenter, int slotId, Map interestVersions) { + final String leader = slotTableCache.getLeader(slotId); + if (StringUtils.isBlank(leader)) { + SCAN_VER_LOGGER.warn("slot not assigned, {}", slotId); + return; } - /** - * Getter method for property sessionInterests. - * - * @return property value of sessionInterests - */ - protected Interests getSessionInterests() { - return sessionInterests; + Map dataVersions = + dataNodeService.fetchDataVersion(dataCenter, slotId, interestVersions); + + SCAN_VER_LOGGER.info( + "[fetchSlotVer]{},{},{},interests={},gets={}", + slotId, + dataCenter, + leader, + interestVersions.size(), + dataVersions.size()); + Map mergedVersions = new HashMap<>(interestVersions); + mergedVersions.putAll(dataVersions); + for (Map.Entry version : mergedVersions.entrySet()) { + final String dataInfoId = version.getKey(); + final long verVal = version.getValue().getValue(); + if (sessionInterests.checkInterestVersion(dataCenter, dataInfoId, verVal).interested) { + firePushService.fireOnChange(dataCenter, dataInfoId, verVal); + SCAN_VER_LOGGER.info( + "[fetchSlotVerNotify]{},{},{},{}", slotId, dataInfoId, dataCenter, verVal); + } } + } + + public void remove(List connectIds) { + List connectIdsAll = new ArrayList<>(); + connectIds.forEach( + connectId -> { + Map pubMap = getSessionDataStore().queryByConnectId(connectId); + boolean pubExisted = pubMap != null && !pubMap.isEmpty(); + + Map subMap = getSessionInterests().queryByConnectId(connectId); + boolean subExisted = false; + if (subMap != null && !subMap.isEmpty()) { + subExisted = true; + + subMap.forEach( + (registerId, sub) -> { + if (isFireSubscriberPushEmptyTask(sub.getDataId())) { + fireSubscriberPushEmptyTask(sub); + } + }); + } - /** - * Getter method for property sessionDataStore. - * - * @return property value of sessionDataStore - */ - protected DataStore getSessionDataStore() { - return sessionDataStore; + if (pubExisted || subExisted) { + connectIdsAll.add(connectId); + } + }); + cancel(connectIdsAll); + } + + protected boolean isFireSubscriberPushEmptyTask(String dataId) { + return dataIdMatchStrategy.match( + dataId, () -> sessionServerConfig.getBlacklistSubDataIdRegex()); + } + + private void fireSubscriberPushEmptyTask(Subscriber subscriber) { + firePushService.fireOnPushEmpty(subscriber); + } + + public void cleanClientConnect() { + Set connectIndexes = new HashSet<>(); + connectIndexes.addAll(sessionDataStore.getConnectIds()); + connectIndexes.addAll(sessionInterests.getConnectIds()); + connectIndexes.addAll(sessionWatchers.getConnectIds()); + + Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort()); + + List connectIds = new ArrayList<>(); + for (ConnectId connectId : connectIndexes) { + Channel channel = + sessionServer.getChannel( + new URL(connectId.getClientHostAddress(), connectId.getClientPort())); + if (channel == null) { + connectIds.add(connectId); + LOGGER.warn("Client connect has not existed!it must be remove!connectId:{}", connectId); + } } - - /** - * Getter method for property taskListenerManager. - * - * @return property value of taskListenerManager - */ - protected TaskListenerManager getTaskListenerManager() { - return taskListenerManager; + if (!connectIds.isEmpty()) { + cancel(connectIds); } + } + + /** + * Getter method for property sessionInterests. + * + * @return property value of sessionInterests + */ + protected Interests getSessionInterests() { + return sessionInterests; + } + + /** + * Getter method for property sessionDataStore. + * + * @return property value of sessionDataStore + */ + protected DataStore getSessionDataStore() { + return sessionDataStore; + } + + /** + * Getter method for property taskListenerManager. + * + * @return property value of taskListenerManager + */ + protected TaskListenerManager getTaskListenerManager() { + return taskListenerManager; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/ClientNodeExchanger.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/ClientNodeExchanger.java index 2a34e3397..6e7d49b4f 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/ClientNodeExchanger.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/ClientNodeExchanger.java @@ -21,22 +21,20 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: ClientNodeExchanger.java, v 0.1 2017-12-12 12:13 shangyu.wh Exp $ */ public class ClientNodeExchanger extends ServerSideExchanger { - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Override - public int getRpcTimeoutMillis() { - return sessionServerConfig.getClientNodeExchangeTimeoutMillis(); - } + @Override + public int getRpcTimeoutMillis() { + return sessionServerConfig.getClientNodeExchangeTimeoutMillis(); + } - @Override - public int getServerPort() { - return sessionServerConfig.getServerPort(); - } -} \ No newline at end of file + @Override + public int getServerPort() { + return sessionServerConfig.getServerPort(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/DataNodeExchanger.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/DataNodeExchanger.java index a2bb0e453..837def88d 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/DataNodeExchanger.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/DataNodeExchanger.java @@ -27,80 +27,75 @@ import com.alipay.sofa.registry.remoting.exchange.message.Response; import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig; import com.alipay.sofa.registry.server.shared.remoting.ClientSideExchanger; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.Resource; import java.util.Collection; import java.util.Set; +import javax.annotation.Resource; +import org.springframework.beans.factory.annotation.Autowired; /** * The type Data node exchanger. + * * @author shangyu.wh * @version $Id : DataNodeExchanger.java, v 0.1 2017-12-01 11:51 shangyu.wh Exp $ */ public class DataNodeExchanger extends ClientSideExchanger { - private static final Logger LOGGER = LoggerFactory - .getLogger(DataNodeExchanger.class); - private static final Logger EXCHANGE_LOGGER = LoggerFactory - .getLogger("SESSION-EXCHANGE"); + private static final Logger LOGGER = LoggerFactory.getLogger(DataNodeExchanger.class); + private static final Logger EXCHANGE_LOGGER = LoggerFactory.getLogger("SESSION-EXCHANGE"); - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Resource(name = "dataClientHandlers") - private Collection dataClientHandlers; + @Resource(name = "dataClientHandlers") + private Collection dataClientHandlers; - public DataNodeExchanger() { - super(Exchange.DATA_SERVER_TYPE); - } - - /** - * @see DataNodeExchanger#request(Request) - */ - @Override - public Response request(Request request) throws RequestException { - URL url = request.getRequestUrl(); - EXCHANGE_LOGGER - .info("DataNode Exchanger request={}, url={}", request.getRequestBody(), url); + public DataNodeExchanger() { + super(Exchange.DATA_SERVER_TYPE); + } - try { - return super.request(request); - } catch (RequestException e) { - LOGGER.error(String.format("Error when request DataNode! Request url=%s, request=%s", - url, request.getRequestBody(), e)); - throw e; - } - } + /** @see DataNodeExchanger#request(Request) */ + @Override + public Response request(Request request) throws RequestException { + URL url = request.getRequestUrl(); + EXCHANGE_LOGGER.info("DataNode Exchanger request={}, url={}", request.getRequestBody(), url); - @Override - public Client connectServer() { - Set ips = serverIps; - int count = tryConnectAllServer(ips); - if (count != ips.size()) { - throw new RuntimeException("failed to connect all dataServers: " + ips); - } - return getClient(); + try { + return super.request(request); + } catch (RequestException e) { + LOGGER.error( + String.format( + "Error when request DataNode! Request url=%s, request=%s", + url, request.getRequestBody(), e)); + throw e; } + } - @Override - protected Collection getClientHandlers() { - return dataClientHandlers; + @Override + public Client connectServer() { + Set ips = serverIps; + int count = tryConnectAllServer(ips); + if (count != ips.size()) { + throw new RuntimeException("failed to connect all dataServers: " + ips); } + return getClient(); + } - @Override - public int getRpcTimeoutMillis() { - return sessionServerConfig.getDataNodeExchangeTimeoutMillis(); - } + @Override + protected Collection getClientHandlers() { + return dataClientHandlers; + } - @Override - public int getServerPort() { - return sessionServerConfig.getDataServerPort(); - } + @Override + public int getRpcTimeoutMillis() { + return sessionServerConfig.getDataNodeExchangeTimeoutMillis(); + } - @Override - public int getConnNum() { - return sessionServerConfig.getDataClientConnNum(); - } + @Override + public int getServerPort() { + return sessionServerConfig.getDataServerPort(); + } -} \ No newline at end of file + @Override + public int getConnNum() { + return sessionServerConfig.getDataClientConnNum(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/CancelAddressRequestHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/CancelAddressRequestHandler.java index f1b0ebeb0..504b1f9b5 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/CancelAddressRequestHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/CancelAddressRequestHandler.java @@ -26,39 +26,36 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: CancelHandler.java, v 0.1 2017-11-30 15:29 shangyu.wh Exp $ */ public class CancelAddressRequestHandler extends AbstractServerHandler { - @Autowired - private Registry sessionRegistry; - - @Override - public Class interest() { - return CancelAddressRequest.class; - } - - @Override - protected NodeType getConnectNodeType() { - return NodeType.CLIENT; - } - - @Override - public void checkParam(CancelAddressRequest request) throws RuntimeException { - ParaCheckUtil.checkNotEmpty(request.getConnectIds(), "request.connectIds"); - } - - @Override - public Object doHandle(Channel channel, CancelAddressRequest request) { - sessionRegistry.cancel(request.getConnectIds()); - return Result.success(); - } - - @Override - public Object buildFailedResponse(String msg) { - return Result.failed(msg); - } - -} \ No newline at end of file + @Autowired private Registry sessionRegistry; + + @Override + public Class interest() { + return CancelAddressRequest.class; + } + + @Override + protected NodeType getConnectNodeType() { + return NodeType.CLIENT; + } + + @Override + public void checkParam(CancelAddressRequest request) throws RuntimeException { + ParaCheckUtil.checkNotEmpty(request.getConnectIds(), "request.connectIds"); + } + + @Override + public Object doHandle(Channel channel, CancelAddressRequest request) { + sessionRegistry.cancel(request.getConnectIds()); + return Result.success(); + } + + @Override + public Object buildFailedResponse(String msg) { + return Result.failed(msg); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ClientNodeConnectionHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ClientNodeConnectionHandler.java index f1832b4f6..f7e16c1d4 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ClientNodeConnectionHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ClientNodeConnectionHandler.java @@ -22,39 +22,39 @@ import com.alipay.sofa.registry.server.session.registry.Registry; import com.alipay.sofa.registry.server.session.scheduler.ExecutorManager; import com.alipay.sofa.registry.server.shared.remoting.ListenServerChannelHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Collections; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: ServerConnectionLisener.java, v 0.1 2017-11-30 15:04 shangyu.wh Exp $ */ public class ClientNodeConnectionHandler extends ListenServerChannelHandler { - @Autowired - private Registry sessionRegistry; - - @Autowired - private ExecutorManager executorManager; - - @Override - public void disconnected(Channel channel) { - super.disconnected(channel); - fireCancelClient(channel); - } - - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.CLIENT; - } - - private void fireCancelClient(Channel channel) { - //avoid block connect ConnectionEventExecutor thread pool - executorManager.getConnectClientExecutor().execute(() -> { - ConnectId connectId = ConnectId.of(channel.getRemoteAddress(), channel.getLocalAddress()); - sessionRegistry.cancel(Collections.singletonList(connectId)); - }); - } -} \ No newline at end of file + @Autowired private Registry sessionRegistry; + + @Autowired private ExecutorManager executorManager; + + @Override + public void disconnected(Channel channel) { + super.disconnected(channel); + fireCancelClient(channel); + } + + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.CLIENT; + } + + private void fireCancelClient(Channel channel) { + // avoid block connect ConnectionEventExecutor thread pool + executorManager + .getConnectClientExecutor() + .execute( + () -> { + ConnectId connectId = + ConnectId.of(channel.getRemoteAddress(), channel.getLocalAddress()); + sessionRegistry.cancel(Collections.singletonList(connectId)); + }); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ConfigureLoadbalanceHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ConfigureLoadbalanceHandler.java index 9b14c34b1..4fe53a7e9 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ConfigureLoadbalanceHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ConfigureLoadbalanceHandler.java @@ -28,29 +28,29 @@ * @author xiangxu * @version : ConfigureLoadbalanceHandler.java, v 0.1 2020年05月29日 11:51 上午 xiangxu Exp $ */ -public class ConfigureLoadbalanceHandler extends AbstractClientHandler { +public class ConfigureLoadbalanceHandler + extends AbstractClientHandler { - @Autowired - private ConnectionsService connectionsService; + @Autowired private ConnectionsService connectionsService; - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.META; - } + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.META; + } - @Override - public Class interest() { - return ConfigureLoadbalanceRequest.class; - } + @Override + public Class interest() { + return ConfigureLoadbalanceRequest.class; + } - @Override - public void checkParam(ConfigureLoadbalanceRequest request) throws RuntimeException { - ParaCheckUtil.checkNonNegative(request.getMaxConnections(), "request.maxConnections"); - } + @Override + public void checkParam(ConfigureLoadbalanceRequest request) throws RuntimeException { + ParaCheckUtil.checkNonNegative(request.getMaxConnections(), "request.maxConnections"); + } - @Override - public Object doHandle(Channel channel, ConfigureLoadbalanceRequest request) { - connectionsService.setMaxConnections(request.getMaxConnections()); - return null; - } -} \ No newline at end of file + @Override + public Object doHandle(Channel channel, ConfigureLoadbalanceRequest request) { + connectionsService.setMaxConnections(request.getMaxConnections()); + return null; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataChangeRequestHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataChangeRequestHandler.java index 6a218c30e..5c6c8beb7 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataChangeRequestHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataChangeRequestHandler.java @@ -27,10 +27,9 @@ import com.alipay.sofa.registry.server.session.scheduler.ExecutorManager; import com.alipay.sofa.registry.server.session.store.Interests; import com.alipay.sofa.registry.server.shared.remoting.AbstractClientHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Map; import java.util.concurrent.Executor; +import org.springframework.beans.factory.annotation.Autowired; /** * @author kezhu.wukz @@ -39,58 +38,51 @@ */ public class DataChangeRequestHandler extends AbstractClientHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(DataChangeRequestHandler.class); - /** - * store subscribers - */ - @Autowired - private Interests sessionInterests; + private static final Logger LOGGER = LoggerFactory.getLogger(DataChangeRequestHandler.class); + /** store subscribers */ + @Autowired private Interests sessionInterests; - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Autowired - private ExecutorManager executorManager; + @Autowired private ExecutorManager executorManager; - @Autowired - private FirePushService firePushService; + @Autowired private FirePushService firePushService; - @Override - protected NodeType getConnectNodeType() { - return NodeType.DATA; - } + @Override + protected NodeType getConnectNodeType() { + return NodeType.DATA; + } - @Override - public Executor getExecutor() { - return executorManager.getDataChangeRequestExecutor(); - } + @Override + public Executor getExecutor() { + return executorManager.getDataChangeRequestExecutor(); + } - @Override - public Object doHandle(Channel channel, DataChangeRequest dataChangeRequest) { - if (sessionServerConfig.isStopPushSwitch()) { - return null; - } - final String dataCenter = dataChangeRequest.getDataCenter(); - for (Map.Entry e : dataChangeRequest.getDataInfoIds().entrySet()) { - final String dataInfoId = e.getKey(); - final DatumVersion version = e.getValue(); - Interests.InterestVersionCheck check = sessionInterests.checkInterestVersion( - dataCenter, dataInfoId, version.getValue()); - if (!check.interested) { - if (check != Interests.InterestVersionCheck.NoSub) { - // log exclude NoSub - LOGGER.info("[SkipChange]{},{}, ver={}, {}", dataInfoId, dataCenter, version, - check); - } - continue; - } - firePushService.fireOnChange(dataCenter, dataInfoId, version.getValue()); + @Override + public Object doHandle(Channel channel, DataChangeRequest dataChangeRequest) { + if (sessionServerConfig.isStopPushSwitch()) { + return null; + } + final String dataCenter = dataChangeRequest.getDataCenter(); + for (Map.Entry e : dataChangeRequest.getDataInfoIds().entrySet()) { + final String dataInfoId = e.getKey(); + final DatumVersion version = e.getValue(); + Interests.InterestVersionCheck check = + sessionInterests.checkInterestVersion(dataCenter, dataInfoId, version.getValue()); + if (!check.interested) { + if (check != Interests.InterestVersionCheck.NoSub) { + // log exclude NoSub + LOGGER.info("[SkipChange]{},{}, ver={}, {}", dataInfoId, dataCenter, version, check); } - return null; + continue; + } + firePushService.fireOnChange(dataCenter, dataInfoId, version.getValue()); } + return null; + } - @Override - public Class interest() { - return DataChangeRequest.class; - } -} \ No newline at end of file + @Override + public Class interest() { + return DataChangeRequest.class; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataPushRequestHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataPushRequestHandler.java index 63b3fd267..e2cd3b6d8 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataPushRequestHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataPushRequestHandler.java @@ -34,29 +34,28 @@ */ public class DataPushRequestHandler extends AbstractClientHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(DataPushRequestHandler.class); + private static final Logger LOGGER = LoggerFactory.getLogger(DataPushRequestHandler.class); - @Autowired - private FirePushService firePushService; + @Autowired private FirePushService firePushService; - @Override - protected NodeType getConnectNodeType() { - return NodeType.DATA; - } + @Override + protected NodeType getConnectNodeType() { + return NodeType.DATA; + } - @Override - public Object doHandle(Channel channel, DataPushRequest request) { - try { - firePushService.fireOnDatum(DatumUtils.of(request.getDatum())); - } catch (Throwable e) { - LOGGER.error("DataPush Request error!", e); - throw new RuntimeException("DataPush Request error!", e); - } - return null; + @Override + public Object doHandle(Channel channel, DataPushRequest request) { + try { + firePushService.fireOnDatum(DatumUtils.of(request.getDatum())); + } catch (Throwable e) { + LOGGER.error("DataPush Request error!", e); + throw new RuntimeException("DataPush Request error!", e); } + return null; + } - @Override - public Class interest() { - return DataPushRequest.class; - } -} \ No newline at end of file + @Override + public Class interest() { + return DataPushRequest.class; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataSlotDiffDigestRequestHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataSlotDiffDigestRequestHandler.java index 1e50a8793..236579ed1 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataSlotDiffDigestRequestHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataSlotDiffDigestRequestHandler.java @@ -31,67 +31,65 @@ import com.alipay.sofa.registry.server.session.store.DataStore; import com.alipay.sofa.registry.server.shared.env.ServerEnv; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Map; import java.util.concurrent.Executor; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-06 15:41 yuzhi.lyz Exp $ */ -public class DataSlotDiffDigestRequestHandler extends - AbstractServerHandler { - private static final Logger LOGGER = LoggerFactory - .getLogger(DataSlotDiffDigestRequestHandler.class); +public class DataSlotDiffDigestRequestHandler + extends AbstractServerHandler { + private static final Logger LOGGER = + LoggerFactory.getLogger(DataSlotDiffDigestRequestHandler.class); - @Autowired - private ExecutorManager executorManager; + @Autowired private ExecutorManager executorManager; - @Autowired - private DataStore sessionDataStore; + @Autowired private DataStore sessionDataStore; - @Autowired - private SlotTableCache slotTableCache; + @Autowired private SlotTableCache slotTableCache; - @Override - public Object doHandle(Channel channel, DataSlotDiffDigestRequest request) { - try { - DataSlotDiffDigestResult result = calcDiffResult(request.getSlotId(), - request.getDatumDigest(), - sessionDataStore.getDataInfoIdPublishers(request.getSlotId())); - result.setSlotTableEpoch(slotTableCache.getEpoch()); - result.setSessionProcessId(ServerEnv.PROCESS_ID); - return new GenericResponse().fillSucceed(result); - } catch (Throwable e) { - LOGGER.error("DiffSync dataInfoIds Request error for slot {}", request.getSlotId(), e); - throw new RuntimeException("DiffSync Request error!", e); - } + @Override + public Object doHandle(Channel channel, DataSlotDiffDigestRequest request) { + try { + DataSlotDiffDigestResult result = + calcDiffResult( + request.getSlotId(), + request.getDatumDigest(), + sessionDataStore.getDataInfoIdPublishers(request.getSlotId())); + result.setSlotTableEpoch(slotTableCache.getEpoch()); + result.setSessionProcessId(ServerEnv.PROCESS_ID); + return new GenericResponse().fillSucceed(result); + } catch (Throwable e) { + LOGGER.error("DiffSync dataInfoIds Request error for slot {}", request.getSlotId(), e); + throw new RuntimeException("DiffSync Request error!", e); } + } - private DataSlotDiffDigestResult calcDiffResult(int targetSlot, - Map digestMap, - Map> existingPublishers) { + private DataSlotDiffDigestResult calcDiffResult( + int targetSlot, + Map digestMap, + Map> existingPublishers) { - DataSlotDiffDigestResult result = DataSlotDiffUtils.diffDigestPublishers(digestMap, - existingPublishers); - DataSlotDiffUtils.logDiffResult(result, targetSlot); - return result; - } + DataSlotDiffDigestResult result = + DataSlotDiffUtils.diffDigestPublishers(digestMap, existingPublishers); + DataSlotDiffUtils.logDiffResult(result, targetSlot); + return result; + } - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.DATA; - } + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.DATA; + } - @Override - public Executor getExecutor() { - return executorManager.getDataSlotSyncRequestExecutor(); - } + @Override + public Executor getExecutor() { + return executorManager.getDataSlotSyncRequestExecutor(); + } - @Override - public Class interest() { - return DataSlotDiffDigestRequest.class; - } + @Override + public Class interest() { + return DataSlotDiffDigestRequest.class; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataSlotDiffPublisherRequestHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataSlotDiffPublisherRequestHandler.java index 648aec7be..64f7dad4c 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataSlotDiffPublisherRequestHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/DataSlotDiffPublisherRequestHandler.java @@ -32,71 +32,70 @@ import com.alipay.sofa.registry.server.session.store.DataStore; import com.alipay.sofa.registry.server.shared.env.ServerEnv; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.List; import java.util.Map; import java.util.concurrent.Executor; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-06 15:41 yuzhi.lyz Exp $ */ -public class DataSlotDiffPublisherRequestHandler extends - AbstractServerHandler { +public class DataSlotDiffPublisherRequestHandler + extends AbstractServerHandler { - private static final Logger LOGGER = LoggerFactory - .getLogger(DataSlotDiffPublisherRequestHandler.class); + private static final Logger LOGGER = + LoggerFactory.getLogger(DataSlotDiffPublisherRequestHandler.class); - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Autowired - private ExecutorManager executorManager; + @Autowired private ExecutorManager executorManager; - @Autowired - private DataStore sessionDataStore; + @Autowired private DataStore sessionDataStore; - @Autowired - private SlotTableCache slotTableCache; + @Autowired private SlotTableCache slotTableCache; - @Override - public Object doHandle(Channel channel, DataSlotDiffPublisherRequest request) { - try { - final int slotId = request.getSlotId(); - DataSlotDiffPublisherResult result = calcDiffResult(slotId, - request.getDatumSummaries(), sessionDataStore.getDataInfoIdPublishers(slotId)); - result.setSlotTableEpoch(slotTableCache.getEpoch()); - result.setSessionProcessId(ServerEnv.PROCESS_ID); - return new GenericResponse().fillSucceed(result); - } catch (Throwable e) { - LOGGER.error("DiffSync publisher Request error for slot {}", request.getSlotId(), e); - throw new RuntimeException("DiffSync Request error!", e); - } + @Override + public Object doHandle(Channel channel, DataSlotDiffPublisherRequest request) { + try { + final int slotId = request.getSlotId(); + DataSlotDiffPublisherResult result = + calcDiffResult( + slotId, + request.getDatumSummaries(), + sessionDataStore.getDataInfoIdPublishers(slotId)); + result.setSlotTableEpoch(slotTableCache.getEpoch()); + result.setSessionProcessId(ServerEnv.PROCESS_ID); + return new GenericResponse().fillSucceed(result); + } catch (Throwable e) { + LOGGER.error("DiffSync publisher Request error for slot {}", request.getSlotId(), e); + throw new RuntimeException("DiffSync Request error!", e); } + } - private DataSlotDiffPublisherResult calcDiffResult(int targetSlot, - List datumSummaries, - Map> existingPublishers) { - DataSlotDiffPublisherResult result = DataSlotDiffUtils.diffPublishersResult(datumSummaries, - existingPublishers, sessionServerConfig.getSlotSyncPublisherMaxNum()); - DataSlotDiffUtils.logDiffResult(result, targetSlot); - return result; - } + private DataSlotDiffPublisherResult calcDiffResult( + int targetSlot, + List datumSummaries, + Map> existingPublishers) { + DataSlotDiffPublisherResult result = + DataSlotDiffUtils.diffPublishersResult( + datumSummaries, existingPublishers, sessionServerConfig.getSlotSyncPublisherMaxNum()); + DataSlotDiffUtils.logDiffResult(result, targetSlot); + return result; + } - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.DATA; - } + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.DATA; + } - @Override - public Executor getExecutor() { - return executorManager.getDataSlotSyncRequestExecutor(); - } + @Override + public Executor getExecutor() { + return executorManager.getDataSlotSyncRequestExecutor(); + } - @Override - public Class interest() { - return DataSlotDiffPublisherRequest.class; - } + @Override + public Class interest() { + return DataSlotDiffPublisherRequest.class; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/GetRevisionPbHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/GetRevisionPbHandler.java index 7ce07a60f..338486e6b 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/GetRevisionPbHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/GetRevisionPbHandler.java @@ -23,34 +23,31 @@ import com.alipay.sofa.registry.remoting.Channel; import com.alipay.sofa.registry.server.session.strategy.AppRevisionHandlerStrategy; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author xiaojian.xj * @version $Id: GetRevisionPbHandler.java, v 0.1 2021年02月04日 21:55 xiaojian.xj Exp $ */ public class GetRevisionPbHandler extends AbstractServerHandler { - @Autowired - private AppRevisionHandlerStrategy appRevisionHandlerStrategy; + @Autowired private AppRevisionHandlerStrategy appRevisionHandlerStrategy; - @Override - protected NodeType getConnectNodeType() { - return Node.NodeType.CLIENT; - } + @Override + protected NodeType getConnectNodeType() { + return Node.NodeType.CLIENT; + } - @Override - public Object doHandle(Channel channel, GetRevisionsRequest request) { - List revisions = request.getRevisionsList().subList(0, request.getRevisionsCount()); - GetRevisionsResponse response = appRevisionHandlerStrategy.queryRevision(revisions); - return response; - } + @Override + public Object doHandle(Channel channel, GetRevisionsRequest request) { + List revisions = request.getRevisionsList().subList(0, request.getRevisionsCount()); + GetRevisionsResponse response = appRevisionHandlerStrategy.queryRevision(revisions); + return response; + } - @Override - public Class interest() { - return GetRevisionsRequest.class; - } -} \ No newline at end of file + @Override + public Class interest() { + return GetRevisionsRequest.class; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/LoadbalanceMetricsHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/LoadbalanceMetricsHandler.java index 802419cbf..cd5b7d627 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/LoadbalanceMetricsHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/LoadbalanceMetricsHandler.java @@ -30,23 +30,22 @@ */ public class LoadbalanceMetricsHandler extends AbstractClientHandler { - @Autowired - private ConnectionsService connectionsService; + @Autowired private ConnectionsService connectionsService; - @Override - protected NodeType getConnectNodeType() { - return NodeType.META; - } + @Override + protected NodeType getConnectNodeType() { + return NodeType.META; + } - @Override - public Object doHandle(Channel channel, Object request) { - LoadbalanceMetrics m = new LoadbalanceMetrics(); - m.setConnectionCount(connectionsService.getConnections().size()); - return m; - } + @Override + public Object doHandle(Channel channel, Object request) { + LoadbalanceMetrics m = new LoadbalanceMetrics(); + m.setConnectionCount(connectionsService.getConnections().size()); + return m; + } - @Override - public Class interest() { - return GetLoadbalanceMetricsRequest.class; - } -} \ No newline at end of file + @Override + public Class interest() { + return GetLoadbalanceMetricsRequest.class; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetaNodeConnectionHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetaNodeConnectionHandler.java index 06f55119f..c2cc970ec 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetaNodeConnectionHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetaNodeConnectionHandler.java @@ -20,13 +20,12 @@ import com.alipay.sofa.registry.server.shared.remoting.ListenClientChannelHandler; /** - * * @author shangyu.wh * @version $Id: ClientConnectionHandler.java, v 0.1 2017-12-08 20:17 shangyu.wh Exp $ */ public class MetaNodeConnectionHandler extends ListenClientChannelHandler { - @Override - protected NodeType getConnectNodeType() { - return NodeType.META; - } -} \ No newline at end of file + @Override + protected NodeType getConnectNodeType() { + return NodeType.META; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetaRevisionHeartbeatPbHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetaRevisionHeartbeatPbHandler.java index 06f792775..183eb2674 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetaRevisionHeartbeatPbHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetaRevisionHeartbeatPbHandler.java @@ -24,40 +24,37 @@ import com.alipay.sofa.registry.server.session.strategy.AppRevisionHandlerStrategy; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; import com.alipay.sofa.registry.util.ParaCheckUtil; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author xiaojian.xj * @version $Id: MetaRevisionHeartbeatPbHandler.java, v 0.1 2021年02月04日 22:49 xiaojian.xj Exp $ */ public class MetaRevisionHeartbeatPbHandler extends AbstractServerHandler { - @Autowired - private AppRevisionHandlerStrategy appRevisionHandlerStrategy; - - @Override - protected NodeType getConnectNodeType() { - return Node.NodeType.CLIENT; - } - - @Override - public void checkParam(MetaHeartbeatRequest request) throws RuntimeException { - ParaCheckUtil.checkNotNull(request, "metaHeartbeatRequest"); - ParaCheckUtil.checkNotEmpty(request.getRevisionsList(), "metaHeartbeatRequest revisions"); - } - - @Override - public Object doHandle(Channel channel, MetaHeartbeatRequest request) { - List revisions = request.getRevisionsList().subList(0, request.getRevisionsCount()); - MetaHeartbeatResponse response = appRevisionHandlerStrategy.heartbeat(revisions); - return response; - } - - @Override - public Class interest() { - return MetaHeartbeatRequest.class; - } -} \ No newline at end of file + @Autowired private AppRevisionHandlerStrategy appRevisionHandlerStrategy; + + @Override + protected NodeType getConnectNodeType() { + return Node.NodeType.CLIENT; + } + + @Override + public void checkParam(MetaHeartbeatRequest request) throws RuntimeException { + ParaCheckUtil.checkNotNull(request, "metaHeartbeatRequest"); + ParaCheckUtil.checkNotEmpty(request.getRevisionsList(), "metaHeartbeatRequest revisions"); + } + + @Override + public Object doHandle(Channel channel, MetaHeartbeatRequest request) { + List revisions = request.getRevisionsList().subList(0, request.getRevisionsCount()); + MetaHeartbeatResponse response = appRevisionHandlerStrategy.heartbeat(revisions); + return response; + } + + @Override + public Class interest() { + return MetaHeartbeatRequest.class; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetadataRegisterPbHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetadataRegisterPbHandler.java index fd0c6ad96..4144c7f4a 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetadataRegisterPbHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/MetadataRegisterPbHandler.java @@ -29,30 +29,28 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author xiaojian.xj * @version $Id: MetadataRegisterPbHandler.java, v 0.1 2021年02月04日 17:13 xiaojian.xj Exp $ */ public class MetadataRegisterPbHandler extends AbstractServerHandler { - @Autowired - private AppRevisionHandlerStrategy appRevisionHandlerStrategy; + @Autowired private AppRevisionHandlerStrategy appRevisionHandlerStrategy; - @Override - protected NodeType getConnectNodeType() { - return Node.NodeType.CLIENT; - } + @Override + protected NodeType getConnectNodeType() { + return Node.NodeType.CLIENT; + } - @Override - public Object doHandle(Channel channel, MetaRegister request) { - RegisterResponse registerResponse = new RegisterResponse(); - AppRevision appRevision = AppRevisionConvertor.convert2Java(request); - appRevisionHandlerStrategy.handleAppRevisionRegister(appRevision, registerResponse); - return RegisterResponseConvertor.convert2Pb(registerResponse); - } + @Override + public Object doHandle(Channel channel, MetaRegister request) { + RegisterResponse registerResponse = new RegisterResponse(); + AppRevision appRevision = AppRevisionConvertor.convert2Java(request); + appRevisionHandlerStrategy.handleAppRevisionRegister(appRevision, registerResponse); + return RegisterResponseConvertor.convert2Pb(registerResponse); + } - @Override - public Class interest() { - return MetaRegister.class; - } -} \ No newline at end of file + @Override + public Class interest() { + return MetaRegister.class; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/NotifyProvideDataChangeHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/NotifyProvideDataChangeHandler.java index 40f17dd48..ef2ef6dbf 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/NotifyProvideDataChangeHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/NotifyProvideDataChangeHandler.java @@ -30,65 +30,58 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: DataChangeRequestHandler.java, v 0.1 2017-12-12 15:09 shangyu.wh Exp $ */ public class NotifyProvideDataChangeHandler extends AbstractClientHandler { - private static final Logger LOGGER = LoggerFactory - .getLogger(NotifyProvideDataChangeHandler.class); - - private static final Logger TASK_LOGGER = LoggerFactory.getLogger( - NotifyProvideDataChangeHandler.class, "[Task]"); - /** - * store watchers - */ - @Autowired - private Watchers sessionWatchers; + private static final Logger LOGGER = + LoggerFactory.getLogger(NotifyProvideDataChangeHandler.class); - /** - * trigger task com.alipay.sofa.registry.server.meta.listener process - */ - @Autowired - private TaskListenerManager taskListenerManager; + private static final Logger TASK_LOGGER = + LoggerFactory.getLogger(NotifyProvideDataChangeHandler.class, "[Task]"); + /** store watchers */ + @Autowired private Watchers sessionWatchers; - @Override - protected NodeType getConnectNodeType() { - return NodeType.META; - } + /** trigger task com.alipay.sofa.registry.server.meta.listener process */ + @Autowired private TaskListenerManager taskListenerManager; - @Override - public Object doHandle(Channel channel, ProvideDataChangeEvent provideDataChangeEvent) { - final String notifyDataInfoId = provideDataChangeEvent.getDataInfoId(); - if (!ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID.equals(notifyDataInfoId) - && !ValueConstants.BLACK_LIST_DATA_ID.equals(notifyDataInfoId) - && !ValueConstants.DATA_DATUM_SYNC_SESSION_INTERVAL_SEC.equals(notifyDataInfoId) - && !ValueConstants.DATA_SESSION_LEASE_SEC.equals(notifyDataInfoId)) { - boolean result = sessionWatchers.checkWatcherVersions( - provideDataChangeEvent.getDataInfoId(), provideDataChangeEvent.getVersion()); - if (!result) { - LOGGER - .info( - "Request message dataInfo {}, version {} not be interested or lower than current version!", - provideDataChangeEvent.getDataInfoId(), provideDataChangeEvent.getVersion()); - return null; - } + @Override + protected NodeType getConnectNodeType() { + return NodeType.META; + } - } - fireDataChangeFetchTask(provideDataChangeEvent); + @Override + public Object doHandle(Channel channel, ProvideDataChangeEvent provideDataChangeEvent) { + final String notifyDataInfoId = provideDataChangeEvent.getDataInfoId(); + if (!ValueConstants.STOP_PUSH_DATA_SWITCH_DATA_ID.equals(notifyDataInfoId) + && !ValueConstants.BLACK_LIST_DATA_ID.equals(notifyDataInfoId) + && !ValueConstants.DATA_DATUM_SYNC_SESSION_INTERVAL_SEC.equals(notifyDataInfoId) + && !ValueConstants.DATA_SESSION_LEASE_SEC.equals(notifyDataInfoId)) { + boolean result = + sessionWatchers.checkWatcherVersions( + provideDataChangeEvent.getDataInfoId(), provideDataChangeEvent.getVersion()); + if (!result) { + LOGGER.info( + "Request message dataInfo {}, version {} not be interested or lower than current version!", + provideDataChangeEvent.getDataInfoId(), + provideDataChangeEvent.getVersion()); return null; + } } + fireDataChangeFetchTask(provideDataChangeEvent); + return null; + } - private void fireDataChangeFetchTask(ProvideDataChangeEvent provideDataChangeEvent) { - TaskEvent taskEvent = new TaskEvent(provideDataChangeEvent, - TaskType.PROVIDE_DATA_CHANGE_FETCH_TASK); - TASK_LOGGER.info("send " + taskEvent.getTaskType() + " taskEvent:{}", taskEvent); - taskListenerManager.sendTaskEvent(taskEvent); - } + private void fireDataChangeFetchTask(ProvideDataChangeEvent provideDataChangeEvent) { + TaskEvent taskEvent = + new TaskEvent(provideDataChangeEvent, TaskType.PROVIDE_DATA_CHANGE_FETCH_TASK); + TASK_LOGGER.info("send " + taskEvent.getTaskType() + " taskEvent:{}", taskEvent); + taskListenerManager.sendTaskEvent(taskEvent); + } - @Override - public Class interest() { - return ProvideDataChangeEvent.class; - } -} \ No newline at end of file + @Override + public Class interest() { + return ProvideDataChangeEvent.class; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/PublisherHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/PublisherHandler.java index 6ce8deb5b..b6f10151b 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/PublisherHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/PublisherHandler.java @@ -23,9 +23,8 @@ import com.alipay.sofa.registry.server.session.scheduler.ExecutorManager; import com.alipay.sofa.registry.server.session.strategy.PublisherHandlerStrategy; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.concurrent.Executor; +import org.springframework.beans.factory.annotation.Autowired; /** * TODO @@ -35,36 +34,34 @@ */ public class PublisherHandler extends AbstractServerHandler { - @Autowired - private ExecutorManager executorManager; + @Autowired private ExecutorManager executorManager; - @Autowired - private PublisherHandlerStrategy publisherHandlerStrategy; + @Autowired private PublisherHandlerStrategy publisherHandlerStrategy; - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.CLIENT; - } + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.CLIENT; + } - @Override - public Object doHandle(Channel channel, PublisherRegister publisherRegister) { - RegisterResponse result = new RegisterResponse(); - publisherHandlerStrategy.handlePublisherRegister(channel, publisherRegister, result); - return result; - } + @Override + public Object doHandle(Channel channel, PublisherRegister publisherRegister) { + RegisterResponse result = new RegisterResponse(); + publisherHandlerStrategy.handlePublisherRegister(channel, publisherRegister, result); + return result; + } - @Override - protected void logRequest(Channel channel, PublisherRegister request) { - // not log - } + @Override + protected void logRequest(Channel channel, PublisherRegister request) { + // not log + } - @Override - public Class interest() { - return PublisherRegister.class; - } + @Override + public Class interest() { + return PublisherRegister.class; + } - @Override - public Executor getExecutor() { - return executorManager.getAccessDataExecutor(); - } -} \ No newline at end of file + @Override + public Executor getExecutor() { + return executorManager.getAccessDataExecutor(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/PublisherPbHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/PublisherPbHandler.java index 0ef4209e4..d9be33763 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/PublisherPbHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/PublisherPbHandler.java @@ -25,9 +25,8 @@ import com.alipay.sofa.registry.server.session.converter.pb.PublisherRegisterConvertor; import com.alipay.sofa.registry.server.session.converter.pb.RegisterResponseConvertor; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.concurrent.Executor; +import org.springframework.beans.factory.annotation.Autowired; /** * TODO @@ -37,52 +36,51 @@ */ public class PublisherPbHandler extends AbstractServerHandler { - @Autowired - private PublisherHandler publisherHandler; - - @Override - protected Node.NodeType getConnectNodeType() { - return publisherHandler.getConnectNodeType(); - } + @Autowired private PublisherHandler publisherHandler; - /** - * Reply object. - * - * @param channel the channel - * @param message the message - * @return the object - * @throws RemotingException the remoting exception - */ - @Override - public Object doHandle(Channel channel, PublisherRegisterPb message) { - RegisterResponsePb.Builder builder = RegisterResponsePb.newBuilder(); + @Override + protected Node.NodeType getConnectNodeType() { + return publisherHandler.getConnectNodeType(); + } - Object response = publisherHandler.doHandle(channel, - PublisherRegisterConvertor.convert2Java(message)); - if (!(response instanceof RegisterResponse)) { - return builder.setSuccess(false).setMessage("Unknown response type").build(); - } + /** + * Reply object. + * + * @param channel the channel + * @param message the message + * @return the object + * @throws RemotingException the remoting exception + */ + @Override + public Object doHandle(Channel channel, PublisherRegisterPb message) { + RegisterResponsePb.Builder builder = RegisterResponsePb.newBuilder(); - return RegisterResponseConvertor.convert2Pb((RegisterResponse) response); + Object response = + publisherHandler.doHandle(channel, PublisherRegisterConvertor.convert2Java(message)); + if (!(response instanceof RegisterResponse)) { + return builder.setSuccess(false).setMessage("Unknown response type").build(); } - @Override - protected void logRequest(Channel channel, PublisherRegisterPb request) { - // not log - } + return RegisterResponseConvertor.convert2Pb((RegisterResponse) response); + } - /** - * Interest class. - * - * @return the class - */ - @Override - public Class interest() { - return PublisherRegisterPb.class; - } + @Override + protected void logRequest(Channel channel, PublisherRegisterPb request) { + // not log + } - @Override - public Executor getExecutor() { - return publisherHandler.getExecutor(); - } + /** + * Interest class. + * + * @return the class + */ + @Override + public Class interest() { + return PublisherRegisterPb.class; + } + + @Override + public Executor getExecutor() { + return publisherHandler.getExecutor(); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ServiceAppMappingPbHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ServiceAppMappingPbHandler.java index f23c32c36..f4923ee04 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ServiceAppMappingPbHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/ServiceAppMappingPbHandler.java @@ -23,35 +23,32 @@ import com.alipay.sofa.registry.remoting.Channel; import com.alipay.sofa.registry.server.session.strategy.AppRevisionHandlerStrategy; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; -import org.springframework.beans.factory.annotation.Autowired; import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author xiaojian.xj * @version $Id: ServiceAppMappingPbHandler.java, v 0.1 2021年02月04日 20:18 xiaojian.xj Exp $ */ public class ServiceAppMappingPbHandler extends AbstractServerHandler { - @Autowired - private AppRevisionHandlerStrategy appRevisionHandlerStrategy; + @Autowired private AppRevisionHandlerStrategy appRevisionHandlerStrategy; - @Override - protected NodeType getConnectNodeType() { - return Node.NodeType.CLIENT; - } + @Override + protected NodeType getConnectNodeType() { + return Node.NodeType.CLIENT; + } - @Override - public Object doHandle(Channel channel, ServiceAppMappingRequest request) { + @Override + public Object doHandle(Channel channel, ServiceAppMappingRequest request) { - List services = request.getServiceIdsList() - .subList(0, request.getServiceIdsCount()); - ServiceAppMappingResponse response = appRevisionHandlerStrategy.queryApps(services); - return response; - } + List services = request.getServiceIdsList().subList(0, request.getServiceIdsCount()); + ServiceAppMappingResponse response = appRevisionHandlerStrategy.queryApps(services); + return response; + } - @Override - public Class interest() { - return ServiceAppMappingRequest.class; - } -} \ No newline at end of file + @Override + public Class interest() { + return ServiceAppMappingRequest.class; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SubscriberHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SubscriberHandler.java index 77ac17ac2..717009bfc 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SubscriberHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SubscriberHandler.java @@ -23,47 +23,43 @@ import com.alipay.sofa.registry.server.session.scheduler.ExecutorManager; import com.alipay.sofa.registry.server.session.strategy.SubscriberHandlerStrategy; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.concurrent.Executor; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: SubscriberHandler.java, v 0.1 2017-11-30 15:01 shangyu.wh Exp $ */ public class SubscriberHandler extends AbstractServerHandler { - @Autowired - private ExecutorManager executorManager; + @Autowired private ExecutorManager executorManager; - @Autowired - private SubscriberHandlerStrategy subscriberHandlerStrategy; + @Autowired private SubscriberHandlerStrategy subscriberHandlerStrategy; - @Override - public Object doHandle(Channel channel, SubscriberRegister subscriberRegister) { - RegisterResponse registerResponse = new RegisterResponse(); - subscriberHandlerStrategy.handleSubscriberRegister(channel, subscriberRegister, - registerResponse); - return registerResponse; - } + @Override + public Object doHandle(Channel channel, SubscriberRegister subscriberRegister) { + RegisterResponse registerResponse = new RegisterResponse(); + subscriberHandlerStrategy.handleSubscriberRegister( + channel, subscriberRegister, registerResponse); + return registerResponse; + } - @Override - protected void logRequest(Channel channel, SubscriberRegister request) { - // not log - } + @Override + protected void logRequest(Channel channel, SubscriberRegister request) { + // not log + } - @Override - public Class interest() { - return SubscriberRegister.class; - } + @Override + public Class interest() { + return SubscriberRegister.class; + } - @Override - public Executor getExecutor() { - return executorManager.getAccessDataExecutor(); - } + @Override + public Executor getExecutor() { + return executorManager.getAccessDataExecutor(); + } - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.CLIENT; - } -} \ No newline at end of file + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.CLIENT; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SubscriberPbHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SubscriberPbHandler.java index f295144e7..478ceaf7b 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SubscriberPbHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SubscriberPbHandler.java @@ -28,9 +28,8 @@ import com.alipay.sofa.registry.server.session.converter.pb.RegisterResponseConvertor; import com.alipay.sofa.registry.server.session.converter.pb.SubscriberRegisterConvertor; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.concurrent.Executor; +import org.springframework.beans.factory.annotation.Autowired; /** * @author zhuoyu.sjw @@ -38,66 +37,65 @@ */ public class SubscriberPbHandler extends AbstractServerHandler { - @Autowired - private SubscriberHandler subscriberHandler; + @Autowired private SubscriberHandler subscriberHandler; - @Override - protected Node.NodeType getConnectNodeType() { - return subscriberHandler.getConnectNodeType(); - } - - /** - * Reply object. - * - * @param channel the channel - * @param message the message - * @return the object - * @throws RemotingException the remoting exception - */ - @Override - public Object doHandle(Channel channel, SubscriberRegisterPb message) { - RegisterResponsePb.Builder builder = RegisterResponsePb.newBuilder(); + @Override + protected Node.NodeType getConnectNodeType() { + return subscriberHandler.getConnectNodeType(); + } - if (channel instanceof BoltChannel) { - BoltChannel boltChannel = (BoltChannel) channel; - InvokeContext invokeContext = boltChannel.getBizContext().getInvokeContext(); + /** + * Reply object. + * + * @param channel the channel + * @param message the message + * @return the object + * @throws RemotingException the remoting exception + */ + @Override + public Object doHandle(Channel channel, SubscriberRegisterPb message) { + RegisterResponsePb.Builder builder = RegisterResponsePb.newBuilder(); - if (null != invokeContext) { - // set client custom codec for request command if not null - Object clientCustomCodec = invokeContext.get(InvokeContext.BOLT_CUSTOM_SERIALIZER); - if (null == clientCustomCodec) { - invokeContext.put(InvokeContext.BOLT_CUSTOM_SERIALIZER, - ProtobufSerializer.PROTOCOL_PROTOBUF); - } - } - } + if (channel instanceof BoltChannel) { + BoltChannel boltChannel = (BoltChannel) channel; + InvokeContext invokeContext = boltChannel.getBizContext().getInvokeContext(); - Object response = subscriberHandler.doHandle(channel, - SubscriberRegisterConvertor.convert2Java(message)); - if (!(response instanceof RegisterResponse)) { - return builder.setSuccess(false).setMessage("Unknown response type").build(); + if (null != invokeContext) { + // set client custom codec for request command if not null + Object clientCustomCodec = invokeContext.get(InvokeContext.BOLT_CUSTOM_SERIALIZER); + if (null == clientCustomCodec) { + invokeContext.put( + InvokeContext.BOLT_CUSTOM_SERIALIZER, ProtobufSerializer.PROTOCOL_PROTOBUF); } - - return RegisterResponseConvertor.convert2Pb((RegisterResponse) response); + } } - @Override - protected void logRequest(Channel channel, SubscriberRegisterPb request) { - // not log + Object response = + subscriberHandler.doHandle(channel, SubscriberRegisterConvertor.convert2Java(message)); + if (!(response instanceof RegisterResponse)) { + return builder.setSuccess(false).setMessage("Unknown response type").build(); } - /** - * Interest class. - * - * @return the class - */ - @Override - public Class interest() { - return SubscriberRegisterPb.class; - } + return RegisterResponseConvertor.convert2Pb((RegisterResponse) response); + } - @Override - public Executor getExecutor() { - return subscriberHandler.getExecutor(); - } + @Override + protected void logRequest(Channel channel, SubscriberRegisterPb request) { + // not log + } + + /** + * Interest class. + * + * @return the class + */ + @Override + public Class interest() { + return SubscriberRegisterPb.class; + } + + @Override + public Executor getExecutor() { + return subscriberHandler.getExecutor(); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SyncConfigHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SyncConfigHandler.java index 5825d59ab..21bd956f5 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SyncConfigHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SyncConfigHandler.java @@ -25,34 +25,32 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author zhuoyu.sjw * @version $Id: SyncConfigHandler.java, v 0.1 2018-03-14 23:15 zhuoyu.sjw Exp $$ */ public class SyncConfigHandler extends AbstractServerHandler { - @Autowired - private SyncConfigHandlerStrategy syncConfigHandlerStrategy; + @Autowired private SyncConfigHandlerStrategy syncConfigHandlerStrategy; - @Override - public InvokeType getInvokeType() { - return InvokeType.SYNC; - } + @Override + public InvokeType getInvokeType() { + return InvokeType.SYNC; + } - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.CLIENT; - } + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.CLIENT; + } - @Override - public Object doHandle(Channel channel, Object request) { - SyncConfigResponse response = new SyncConfigResponse(); - response.setSuccess(true); - syncConfigHandlerStrategy.handleSyncConfigResponse(response); - return response; - } + @Override + public Object doHandle(Channel channel, Object request) { + SyncConfigResponse response = new SyncConfigResponse(); + response.setSuccess(true); + syncConfigHandlerStrategy.handleSyncConfigResponse(response); + return response; + } - @Override - public Class interest() { - return SyncConfigRequest.class; - } + @Override + public Class interest() { + return SyncConfigRequest.class; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SyncConfigPbHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SyncConfigPbHandler.java index dce50e5df..eb85cb140 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SyncConfigPbHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/SyncConfigPbHandler.java @@ -26,60 +26,61 @@ import com.alipay.sofa.registry.server.session.converter.pb.SyncConfigRequestConvertor; import com.alipay.sofa.registry.server.session.converter.pb.SyncConfigResponseConvertor; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.concurrent.Executor; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author zhuoyu.sjw * @version $Id: SyncConfigPbHandler.java, v 0.1 2018-04-02 17:13 zhuoyu.sjw Exp $$ */ public class SyncConfigPbHandler extends AbstractServerHandler { - @Autowired - private SyncConfigHandler syncConfigHandler; + @Autowired private SyncConfigHandler syncConfigHandler; - @Override - protected Node.NodeType getConnectNodeType() { - return syncConfigHandler.getConnectNodeType(); - } + @Override + protected Node.NodeType getConnectNodeType() { + return syncConfigHandler.getConnectNodeType(); + } - /** - * Reply object. - * - * @param channel the channel - * @param message the message - * @return the object - * @throws RemotingException the remoting exception - */ - @Override - public Object doHandle(Channel channel, SyncConfigRequestPb message) { - SyncConfigResponsePb.Builder builder = SyncConfigResponsePb.newBuilder(); + /** + * Reply object. + * + * @param channel the channel + * @param message the message + * @return the object + * @throws RemotingException the remoting exception + */ + @Override + public Object doHandle(Channel channel, SyncConfigRequestPb message) { + SyncConfigResponsePb.Builder builder = SyncConfigResponsePb.newBuilder(); - Object response = syncConfigHandler.doHandle(channel, - SyncConfigRequestConvertor.convert2Java(message)); - if (!(response instanceof SyncConfigResponse)) { - return builder.setResult( - ResultPb.newBuilder().setSuccess(false) - .setMessage("Unknown sync config response type").build()).build(); - } - - return SyncConfigResponseConvertor.convert2Pb((SyncConfigResponse) response); + Object response = + syncConfigHandler.doHandle(channel, SyncConfigRequestConvertor.convert2Java(message)); + if (!(response instanceof SyncConfigResponse)) { + return builder + .setResult( + ResultPb.newBuilder() + .setSuccess(false) + .setMessage("Unknown sync config response type") + .build()) + .build(); } - /** - * Interest class. - * - * @return the class - */ - @Override - public Class interest() { - return SyncConfigRequestPb.class; - } + return SyncConfigResponseConvertor.convert2Pb((SyncConfigResponse) response); + } - @Override - public Executor getExecutor() { - return syncConfigHandler.getExecutor(); - } + /** + * Interest class. + * + * @return the class + */ + @Override + public Class interest() { + return SyncConfigRequestPb.class; + } + + @Override + public Executor getExecutor() { + return syncConfigHandler.getExecutor(); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/WatcherHandler.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/WatcherHandler.java index ecfebd6b4..bf3411b70 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/WatcherHandler.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/remoting/handler/WatcherHandler.java @@ -23,43 +23,38 @@ import com.alipay.sofa.registry.server.session.scheduler.ExecutorManager; import com.alipay.sofa.registry.server.session.strategy.WatcherHandlerStrategy; import com.alipay.sofa.registry.server.shared.remoting.AbstractServerHandler; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.concurrent.Executor; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: SubscriberHandler.java, v 0.1 2017-11-30 15:01 shangyu.wh Exp $ */ public class WatcherHandler extends AbstractServerHandler { - @Autowired - private ExecutorManager executorManager; - - @Autowired - private WatcherHandlerStrategy watcherHandlerStrategy; - - @Override - public Object doHandle(Channel channel, ConfiguratorRegister message) { - RegisterResponse result = new RegisterResponse(); - ConfiguratorRegister configuratorRegister = (ConfiguratorRegister) message; - watcherHandlerStrategy.handleConfiguratorRegister(channel, configuratorRegister, result); - return result; - } - - @Override - public Class interest() { - return ConfiguratorRegister.class; - } - - @Override - public Executor getExecutor() { - return executorManager.getAccessDataExecutor(); - } - - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.CLIENT; - } - -} \ No newline at end of file + @Autowired private ExecutorManager executorManager; + + @Autowired private WatcherHandlerStrategy watcherHandlerStrategy; + + @Override + public Object doHandle(Channel channel, ConfiguratorRegister message) { + RegisterResponse result = new RegisterResponse(); + ConfiguratorRegister configuratorRegister = (ConfiguratorRegister) message; + watcherHandlerStrategy.handleConfiguratorRegister(channel, configuratorRegister, result); + return result; + } + + @Override + public Class interest() { + return ConfiguratorRegister.class; + } + + @Override + public Executor getExecutor() { + return executorManager.getAccessDataExecutor(); + } + + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.CLIENT; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/ClientsOpenResource.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/ClientsOpenResource.java index 1d600c631..8e4ccce94 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/ClientsOpenResource.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/ClientsOpenResource.java @@ -20,18 +20,18 @@ import com.alipay.sofa.registry.common.model.ConnectId; import com.alipay.sofa.registry.common.model.sessionserver.CancelAddressRequest; import com.alipay.sofa.registry.server.session.registry.Registry; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.CollectionUtils; - +import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; /** * The type Clients open resource. + * * @author zhuoyu.sjw * @version $Id : ClientsResource.java, v 0.1 2018-04-11 19:04 zhuoyu.sjw Exp $$ */ @@ -40,29 +40,28 @@ @Produces(MediaType.APPLICATION_JSON) public class ClientsOpenResource { - @Autowired - private Registry sessionRegistry; - - /** - * Client off common response. - * - * @param request the request - * @return the common response - */ - @POST - @Path("/off") - public CommonResponse clientOff(CancelAddressRequest request) { + @Autowired private Registry sessionRegistry; - if (null == request) { - return CommonResponse.buildFailedResponse("Request can not be null."); - } + /** + * Client off common response. + * + * @param request the request + * @return the common response + */ + @POST + @Path("/off") + public CommonResponse clientOff(CancelAddressRequest request) { - if (CollectionUtils.isEmpty(request.getConnectIds())) { - return CommonResponse.buildFailedResponse("ConnectIds can not be null."); - } + if (null == request) { + return CommonResponse.buildFailedResponse("Request can not be null."); + } - final List connectIds = request.getConnectIds(); - sessionRegistry.cancel(connectIds); - return CommonResponse.buildSuccessResponse(); + if (CollectionUtils.isEmpty(request.getConnectIds())) { + return CommonResponse.buildFailedResponse("ConnectIds can not be null."); } + + final List connectIds = request.getConnectIds(); + sessionRegistry.cancel(connectIds); + return CommonResponse.buildSuccessResponse(); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/ConnectionsResource.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/ConnectionsResource.java index f0a7cb00e..27043c216 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/ConnectionsResource.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/ConnectionsResource.java @@ -17,35 +17,33 @@ package com.alipay.sofa.registry.server.session.resource; import com.alipay.sofa.registry.server.session.connections.ConnectionsService; -import org.springframework.beans.factory.annotation.Autowired; - +import java.util.List; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; -import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; @Path("connections") public class ConnectionsResource { - @Autowired - private ConnectionsService connectionsService; + @Autowired private ConnectionsService connectionsService; - @POST - @Path("setMax") - @Produces(MediaType.APPLICATION_JSON) - public Response setMax(@FormParam("connections") int connections) { - ResponseBuilder build = Response.status(Response.Status.OK); - connectionsService.setMaxConnections(connections); - return build.build(); - } + @POST + @Path("setMax") + @Produces(MediaType.APPLICATION_JSON) + public Response setMax(@FormParam("connections") int connections) { + ResponseBuilder build = Response.status(Response.Status.OK); + connectionsService.setMaxConnections(connections); + return build.build(); + } - @GET - @Path("query") - @Produces(MediaType.APPLICATION_JSON) - public Response query() { - ResponseBuilder builder = Response.status(Response.Status.OK); - List connectionsSet = connectionsService.getConnections(); - builder.entity(connectionsSet.toArray()); - return builder.build(); - } + @GET + @Path("query") + @Produces(MediaType.APPLICATION_JSON) + public Response query() { + ResponseBuilder builder = Response.status(Response.Status.OK); + List connectionsSet = connectionsService.getConnections(); + builder.entity(connectionsSet.toArray()); + return builder.build(); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/HealthResource.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/HealthResource.java index 42ee256c1..ba790bccb 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/HealthResource.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/HealthResource.java @@ -16,6 +16,12 @@ */ package com.alipay.sofa.registry.server.session.resource; +import com.alipay.sofa.registry.common.model.CommonResponse; +import com.alipay.sofa.registry.metrics.ReporterUtils; +import com.alipay.sofa.registry.server.session.bootstrap.SessionServerBootstrap; +import com.alipay.sofa.registry.util.Bool; +import com.codahale.metrics.Gauge; +import com.codahale.metrics.MetricRegistry; import javax.annotation.PostConstruct; import javax.ws.rs.GET; import javax.ws.rs.Path; @@ -24,79 +30,70 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.ResponseBuilder; import javax.ws.rs.core.Response.Status; - -import com.alipay.sofa.registry.util.Bool; import org.springframework.beans.factory.annotation.Autowired; -import com.alipay.sofa.registry.common.model.CommonResponse; -import com.alipay.sofa.registry.metrics.ReporterUtils; -import com.alipay.sofa.registry.server.session.bootstrap.SessionServerBootstrap; -import com.codahale.metrics.Gauge; -import com.codahale.metrics.MetricRegistry; - /** - * * @author shangyu.wh * @version $Id: PushSwitchResource.java, v 0.1 2018-10-29 16:51 shangyu.wh Exp $ */ @Path("health") public class HealthResource { - @Autowired - private SessionServerBootstrap sessionServerBootstrap; - - @PostConstruct - public void init() { - MetricRegistry metrics = new MetricRegistry(); - metrics.register("healthCheck", (Gauge) () -> getHealthCheckResult()); - ReporterUtils.startSlf4jReporter(60, metrics); + @Autowired private SessionServerBootstrap sessionServerBootstrap; + + @PostConstruct + public void init() { + MetricRegistry metrics = new MetricRegistry(); + metrics.register("healthCheck", (Gauge) () -> getHealthCheckResult()); + ReporterUtils.startSlf4jReporter(60, metrics); + } + + @GET + @Path("check") + @Produces(MediaType.APPLICATION_JSON) + public Response checkHealth() { + ResponseBuilder builder = Response.status(Response.Status.OK); + CommonResponse response = getHealthCheckResult(); + builder.entity(response); + if (!response.isSuccess()) { + builder.status(Status.INTERNAL_SERVER_ERROR); } - @GET - @Path("check") - @Produces(MediaType.APPLICATION_JSON) - public Response checkHealth() { - ResponseBuilder builder = Response.status(Response.Status.OK); - CommonResponse response = getHealthCheckResult(); - builder.entity(response); - if (!response.isSuccess()) { - builder.status(Status.INTERNAL_SERVER_ERROR); - } - - return builder.build(); - } + return builder.build(); + } - protected StringBuilder getStatus(Bool result) { - StringBuilder sb = new StringBuilder("SessionServerBoot "); - boolean start = false; + protected StringBuilder getStatus(Bool result) { + StringBuilder sb = new StringBuilder("SessionServerBoot "); + boolean start = false; - start = sessionServerBootstrap.getMetaStart(); - sb.append(", MetaServerStart:").append(start); + start = sessionServerBootstrap.getMetaStart(); + sb.append(", MetaServerStart:").append(start); - start = sessionServerBootstrap.getSchedulerStart(); - sb.append(", SchedulerStart:").append(start); + start = sessionServerBootstrap.getSchedulerStart(); + sb.append(", SchedulerStart:").append(start); - start = sessionServerBootstrap.getHttpStart(); - sb.append(", HttpServerStart:").append(start); + start = sessionServerBootstrap.getHttpStart(); + sb.append(", HttpServerStart:").append(start); - start = sessionServerBootstrap.getServerStart(); - sb.append(", SessionServerStart:").append(start); + start = sessionServerBootstrap.getServerStart(); + sb.append(", SessionServerStart:").append(start); - start = sessionServerBootstrap.getServerForSessionSyncStart(); - sb.append(", ServerForSessionSyncStart:").append(start); + start = sessionServerBootstrap.getServerForSessionSyncStart(); + sb.append(", ServerForSessionSyncStart:").append(start); - start = sessionServerBootstrap.getDataStart(); - sb.append(", ConnectDataServer:").append(start); + start = sessionServerBootstrap.getDataStart(); + sb.append(", ConnectDataServer:").append(start); - result.setBool(start); - return sb; - } + result.setBool(start); + return sb; + } - private CommonResponse getHealthCheckResult() { - Bool ret = Bool.newFalse(); - String desc = getStatus(ret).toString(); + private CommonResponse getHealthCheckResult() { + Bool ret = Bool.newFalse(); + String desc = getStatus(ret).toString(); - return ret.isTrue() ? CommonResponse.buildSuccessResponse(desc) : CommonResponse - .buildFailedResponse(desc); - } -} \ No newline at end of file + return ret.isTrue() + ? CommonResponse.buildSuccessResponse(desc) + : CommonResponse.buildFailedResponse(desc); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/SessionDigestResource.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/SessionDigestResource.java index 15573ab32..f9aa86d6f 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/SessionDigestResource.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/SessionDigestResource.java @@ -16,14 +16,28 @@ */ package com.alipay.sofa.registry.server.session.resource; +import static com.alipay.sofa.registry.common.model.constants.ValueConstants.CONNECT_ID_SPLIT; + import com.alipay.sofa.registry.common.model.ConnectId; +import com.alipay.sofa.registry.common.model.store.Publisher; +import com.alipay.sofa.registry.common.model.store.StoreData; +import com.alipay.sofa.registry.common.model.store.Subscriber; +import com.alipay.sofa.registry.common.model.store.Watcher; +import com.alipay.sofa.registry.metrics.ReporterUtils; +import com.alipay.sofa.registry.net.NetUtil; +import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig; +import com.alipay.sofa.registry.server.session.store.DataStore; +import com.alipay.sofa.registry.server.session.store.Interests; +import com.alipay.sofa.registry.server.session.store.Watchers; +import com.alipay.sofa.registry.server.shared.meta.MetaServerService; +import com.codahale.metrics.Gauge; +import com.codahale.metrics.MetricRegistry; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; - import javax.annotation.PostConstruct; import javax.ws.rs.GET; import javax.ws.rs.POST; @@ -32,259 +46,235 @@ import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; - -import com.alipay.sofa.registry.net.NetUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; -import com.alipay.sofa.registry.common.model.store.Publisher; -import com.alipay.sofa.registry.common.model.store.StoreData; -import com.alipay.sofa.registry.common.model.store.Subscriber; -import com.alipay.sofa.registry.common.model.store.Watcher; -import com.alipay.sofa.registry.metrics.ReporterUtils; -import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig; -import com.alipay.sofa.registry.server.session.store.DataStore; -import com.alipay.sofa.registry.server.session.store.Interests; -import com.alipay.sofa.registry.server.session.store.Watchers; -import com.alipay.sofa.registry.server.shared.meta.MetaServerService; -import com.codahale.metrics.Gauge; -import com.codahale.metrics.MetricRegistry; -import static com.alipay.sofa.registry.common.model.constants.ValueConstants.CONNECT_ID_SPLIT; - /** - * * @author shangyu.wh * @version $Id: SessionOpenResource.java, v 0.1 2018-03-21 11:06 shangyu.wh Exp $ */ @Path("digest") public class SessionDigestResource { - /** - * store subscribers - */ - @Autowired - private Interests sessionInterests; + /** store subscribers */ + @Autowired private Interests sessionInterests; - /** - * store watchers - */ - @Autowired - private Watchers sessionWatchers; + /** store watchers */ + @Autowired private Watchers sessionWatchers; - /** - * store publishers - */ - @Autowired - private DataStore sessionDataStore; + /** store publishers */ + @Autowired private DataStore sessionDataStore; - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - private static final String LOCAL_ADDRESS = NetUtil.getLocalAddress().getHostAddress(); + private static final String LOCAL_ADDRESS = NetUtil.getLocalAddress().getHostAddress(); - @Autowired - private MetaServerService mataNodeService; + @Autowired private MetaServerService mataNodeService; - private final static String SUB = "SUB"; + private static final String SUB = "SUB"; - private final static String PUB = "PUB"; + private static final String PUB = "PUB"; - private final static String WAT = "WAT"; + private static final String WAT = "WAT"; - private final static String SESSION = "SESSION"; + private static final String SESSION = "SESSION"; - private final static String DATA = "DATA"; + private static final String DATA = "DATA"; - private final static String META = "META"; + private static final String META = "META"; - @PostConstruct - public void init() { - MetricRegistry metrics = new MetricRegistry(); - metrics.register("pushSwitch", (Gauge) () -> getPushSwitch()); - ReporterUtils.startSlf4jReporter(60, metrics); - } + @PostConstruct + public void init() { + MetricRegistry metrics = new MetricRegistry(); + metrics.register("pushSwitch", (Gauge) () -> getPushSwitch()); + ReporterUtils.startSlf4jReporter(60, metrics); + } - @GET - @Path("{type}/data/query") - @Produces(MediaType.APPLICATION_JSON) - public Map> getSessionDataByDataInfoId(@QueryParam("dataInfoId") String dataInfoId, - @PathParam("type") String type) { - Map> serverList = new HashMap<>(); - if (dataInfoId != null) { - Collection publishers = sessionDataStore.getDatas(dataInfoId); - Collection subscribers = sessionInterests.getDatas(dataInfoId); - Collection watchers = sessionWatchers.getDatas(dataInfoId); - fillServerList(type, serverList, publishers, subscribers, watchers); - } + @GET + @Path("{type}/data/query") + @Produces(MediaType.APPLICATION_JSON) + public Map> getSessionDataByDataInfoId( + @QueryParam("dataInfoId") String dataInfoId, @PathParam("type") String type) { + Map> serverList = new HashMap<>(); + if (dataInfoId != null) { + Collection publishers = sessionDataStore.getDatas(dataInfoId); + Collection subscribers = sessionInterests.getDatas(dataInfoId); + Collection watchers = sessionWatchers.getDatas(dataInfoId); + fillServerList(type, serverList, publishers, subscribers, watchers); + } - return serverList; + return serverList; + } + + @POST + @Path("{type}/connect/query") + @Produces(MediaType.APPLICATION_JSON) + public Map> getSessionDataByConnectId( + List queryConnectIds, final @PathParam("type") String type) { + List connectIds = new ArrayList<>(queryConnectIds.size()); + for (String queryConnectId : queryConnectIds) { + String connectId = queryConnectId; + if (!queryConnectId.contains(CONNECT_ID_SPLIT)) { + connectId = + connectId + + CONNECT_ID_SPLIT + + LOCAL_ADDRESS + + ":" + + sessionServerConfig.getServerPort(); + } + connectIds.add(ConnectId.parse(connectId)); } - @POST - @Path("{type}/connect/query") - @Produces(MediaType.APPLICATION_JSON) - public Map> getSessionDataByConnectId(List queryConnectIds, - final @PathParam("type") String type) { - List connectIds = new ArrayList<>(queryConnectIds.size()); - for (String queryConnectId : queryConnectIds) { - String connectId = queryConnectId; - if (!queryConnectId.contains(CONNECT_ID_SPLIT)) { - connectId = connectId + CONNECT_ID_SPLIT + LOCAL_ADDRESS + ":" - + sessionServerConfig.getServerPort(); - } - connectIds.add(ConnectId.parse(connectId)); - } - - Map> serverList = new HashMap<>(); - - if (connectIds != null) { - connectIds.forEach(connectId -> { - Map pubMap = sessionDataStore.queryByConnectId(connectId); - Map subMap = sessionInterests.queryByConnectId(connectId); - Map watcherMap = sessionWatchers.queryByConnectId(connectId); - - Collection publishers = pubMap != null && !pubMap.isEmpty() - ? pubMap.values() - : new ArrayList<>(); - Collection subscribers = subMap != null && !subMap.isEmpty() - ? subMap.values() - : new ArrayList<>(); - Collection watchers = watcherMap != null && !watcherMap.isEmpty() + Map> serverList = new HashMap<>(); + + if (connectIds != null) { + connectIds.forEach( + connectId -> { + Map pubMap = sessionDataStore.queryByConnectId(connectId); + Map subMap = sessionInterests.queryByConnectId(connectId); + Map watcherMap = sessionWatchers.queryByConnectId(connectId); + + Collection publishers = + pubMap != null && !pubMap.isEmpty() ? pubMap.values() : new ArrayList<>(); + Collection subscribers = + subMap != null && !subMap.isEmpty() ? subMap.values() : new ArrayList<>(); + Collection watchers = + watcherMap != null && !watcherMap.isEmpty() ? watcherMap.values() : new ArrayList<>(); - fillServerList(type, serverList, publishers, subscribers, watchers); - }); - } - - return serverList; - } - - @GET - @Path("/data/count") - @Produces(MediaType.APPLICATION_JSON) - public String getSessionDataCount() { - long countSub = sessionInterests.count(); - long countPub = sessionDataStore.count(); - long countSubW = sessionWatchers.count(); - - return String.format("Subscriber count: %s, Publisher count: %s, Watcher count: %s", - countSub, countPub, countSubW); - } - - /** - * return true mean push switch on - */ - @GET - @Path("pushSwitch") - @Produces(MediaType.APPLICATION_JSON) - public Map getPushSwitch() { - Map resultMap = new HashMap<>(1); - resultMap.put("pushSwitch", !sessionServerConfig.isStopPushSwitch() ? "open" : "closed"); - return resultMap; - } - - @GET - @Path("getDataInfoIdList") - @Produces(MediaType.APPLICATION_JSON) - public Collection getDataInfoIdList() { - Collection ret = new HashSet<>(); - ret.addAll(sessionInterests.getDataInfoIds()); - ret.addAll(sessionDataStore.getDataInfoIds()); - return ret; - } - - @GET - @Path("checkSumDataInfoIdList") - @Produces(MediaType.APPLICATION_JSON) - public int checkSumDataInfoIdList() { - return getDataInfoIdList().hashCode(); + fillServerList(type, serverList, publishers, subscribers, watchers); + }); } - private void fillServerList(String type, - Map> serverList, - Collection publishers, - Collection subscribers, Collection watchers) { - if (type != null && !type.isEmpty()) { - String inputType = type.toUpperCase(); - - switch (inputType) { - case PUB: - if (!CollectionUtils.isEmpty(publishers)) { - serverList.put(PUB, publishers); - } - break; - case SUB: - if (!CollectionUtils.isEmpty(subscribers)) { - serverList.put(SUB, subscribers); - } - break; - case WAT: - if (!CollectionUtils.isEmpty(watchers)) { - serverList.put(WAT, watchers); - } - break; - default: - if (!CollectionUtils.isEmpty(publishers)) { - serverList.put(PUB, publishers); - } - if (!CollectionUtils.isEmpty(subscribers)) { - serverList.put(SUB, subscribers); - } - if (!CollectionUtils.isEmpty(watchers)) { - serverList.put(WAT, watchers); - } - break; - } - - } else { - if (publishers != null) { - serverList.put(PUB, publishers); - } - if (subscribers != null) { - serverList.put(SUB, subscribers); - } - if (watchers != null) { - serverList.put(WAT, watchers); - } - } + return serverList; + } + + @GET + @Path("/data/count") + @Produces(MediaType.APPLICATION_JSON) + public String getSessionDataCount() { + long countSub = sessionInterests.count(); + long countPub = sessionDataStore.count(); + long countSubW = sessionWatchers.count(); + + return String.format( + "Subscriber count: %s, Publisher count: %s, Watcher count: %s", + countSub, countPub, countSubW); + } + + /** return true mean push switch on */ + @GET + @Path("pushSwitch") + @Produces(MediaType.APPLICATION_JSON) + public Map getPushSwitch() { + Map resultMap = new HashMap<>(1); + resultMap.put("pushSwitch", !sessionServerConfig.isStopPushSwitch() ? "open" : "closed"); + return resultMap; + } + + @GET + @Path("getDataInfoIdList") + @Produces(MediaType.APPLICATION_JSON) + public Collection getDataInfoIdList() { + Collection ret = new HashSet<>(); + ret.addAll(sessionInterests.getDataInfoIds()); + ret.addAll(sessionDataStore.getDataInfoIds()); + return ret; + } + + @GET + @Path("checkSumDataInfoIdList") + @Produces(MediaType.APPLICATION_JSON) + public int checkSumDataInfoIdList() { + return getDataInfoIdList().hashCode(); + } + + private void fillServerList( + String type, + Map> serverList, + Collection publishers, + Collection subscribers, + Collection watchers) { + if (type != null && !type.isEmpty()) { + String inputType = type.toUpperCase(); + + switch (inputType) { + case PUB: + if (!CollectionUtils.isEmpty(publishers)) { + serverList.put(PUB, publishers); + } + break; + case SUB: + if (!CollectionUtils.isEmpty(subscribers)) { + serverList.put(SUB, subscribers); + } + break; + case WAT: + if (!CollectionUtils.isEmpty(watchers)) { + serverList.put(WAT, watchers); + } + break; + default: + if (!CollectionUtils.isEmpty(publishers)) { + serverList.put(PUB, publishers); + } + if (!CollectionUtils.isEmpty(subscribers)) { + serverList.put(SUB, subscribers); + } + if (!CollectionUtils.isEmpty(watchers)) { + serverList.put(WAT, watchers); + } + break; + } + + } else { + if (publishers != null) { + serverList.put(PUB, publishers); + } + if (subscribers != null) { + serverList.put(SUB, subscribers); + } + if (watchers != null) { + serverList.put(WAT, watchers); + } } - - @GET - @Path("{type}/serverList/query") - @Produces(MediaType.APPLICATION_JSON) - public List getServerListAll(@PathParam("type") String type) { - List serverList = new ArrayList<>(); - if (type != null && !type.isEmpty()) { - String inputType = type.toUpperCase(); - - switch (inputType) { - case SESSION: - serverList = getSessionServerList(); - break; - case DATA: - serverList = getDataServerList(); - break; - case META: - serverList = getMetaServerList(); - break; - default: - serverList = new ArrayList<>(); - break; - } - - } - return serverList; + } + + @GET + @Path("{type}/serverList/query") + @Produces(MediaType.APPLICATION_JSON) + public List getServerListAll(@PathParam("type") String type) { + List serverList = new ArrayList<>(); + if (type != null && !type.isEmpty()) { + String inputType = type.toUpperCase(); + + switch (inputType) { + case SESSION: + serverList = getSessionServerList(); + break; + case DATA: + serverList = getDataServerList(); + break; + case META: + serverList = getMetaServerList(); + break; + default: + serverList = new ArrayList<>(); + break; + } } + return serverList; + } - public List getSessionServerList() { - return mataNodeService.getSessionServerList(sessionServerConfig.getSessionServerRegion()); - } + public List getSessionServerList() { + return mataNodeService.getSessionServerList(sessionServerConfig.getSessionServerRegion()); + } - public List getDataServerList() { - return new ArrayList<>(mataNodeService.getDataServerList()); - } + public List getDataServerList() { + return new ArrayList<>(mataNodeService.getDataServerList()); + } - public List getMetaServerList() { - return new ArrayList<>(mataNodeService.getMetaServerList()); - } -} \ No newline at end of file + public List getMetaServerList() { + return new ArrayList<>(mataNodeService.getMetaServerList()); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/SessionOpenResource.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/SessionOpenResource.java index 0c403c354..ea9141c69 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/SessionOpenResource.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/resource/SessionOpenResource.java @@ -22,13 +22,12 @@ import com.alipay.sofa.registry.server.shared.meta.MetaServerService; import com.alipay.sofa.registry.util.ParaCheckUtil; import com.google.common.base.Joiner; -import org.apache.commons.lang.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.ws.rs.*; -import javax.ws.rs.core.MediaType; import java.util.List; import java.util.stream.Collectors; +import javax.ws.rs.*; +import javax.ws.rs.core.MediaType; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; /** * @author shangyu.wh @@ -37,68 +36,66 @@ @Path("api/servers") public class SessionOpenResource { - @Autowired - private SessionServerConfig sessionServerConfig; - - @Autowired - private MetaServerService metaNodeService; + @Autowired private SessionServerConfig sessionServerConfig; - @Autowired - private SlotTableCache slotTableCache; + @Autowired private MetaServerService metaNodeService; - @GET - @Path("query.json") - @Produces(MediaType.APPLICATION_JSON) - public List getSessionServerListJson(@QueryParam("zone") String zone) { - if (StringUtils.isBlank(zone)) { - zone = sessionServerConfig.getSessionServerRegion(); - } + @Autowired private SlotTableCache slotTableCache; - if (StringUtils.isNotBlank(zone)) { - zone = zone.toUpperCase(); - } - return getSessionServers(zone); + @GET + @Path("query.json") + @Produces(MediaType.APPLICATION_JSON) + public List getSessionServerListJson(@QueryParam("zone") String zone) { + if (StringUtils.isBlank(zone)) { + zone = sessionServerConfig.getSessionServerRegion(); } - @GET - @Path("query") - @Produces(MediaType.TEXT_PLAIN) - public String getSessionServerList(@QueryParam("zone") String zone) { - return Joiner.on(";").join(getSessionServerListJson(zone)); + if (StringUtils.isNotBlank(zone)) { + zone = zone.toUpperCase(); } + return getSessionServers(zone); + } - @GET - @Path("alive") - public String checkAlive() { - return "OK"; - } + @GET + @Path("query") + @Produces(MediaType.TEXT_PLAIN) + public String getSessionServerList(@QueryParam("zone") String zone) { + return Joiner.on(";").join(getSessionServerListJson(zone)); + } - /** - * Get server list for current data center - * - * @return - */ - @GET - @Path("dataCenter") - @Produces(MediaType.APPLICATION_JSON) - public List getCurrentDataCenterServerList() { - return getSessionServers(null); - } + @GET + @Path("alive") + public String checkAlive() { + return "OK"; + } - private List getSessionServers(String zone) { - List serverList = metaNodeService.getSessionServerList(zone); + /** + * Get server list for current data center + * + * @return + */ + @GET + @Path("dataCenter") + @Produces(MediaType.APPLICATION_JSON) + public List getCurrentDataCenterServerList() { + return getSessionServers(null); + } - serverList = serverList.stream() - .map(server -> server + ":" + sessionServerConfig.getServerPort()) - .collect(Collectors.toList()); - return serverList; - } + private List getSessionServers(String zone) { + List serverList = metaNodeService.getSessionServerList(zone); - @GET - @Path("slot") - @Produces(MediaType.APPLICATION_JSON) - public Slot getSlot(@QueryParam("dataInfoId") String dataInfoId) { - ParaCheckUtil.checkNotBlank(dataInfoId, "dataInfoId"); - return slotTableCache.getSlot(dataInfoId); - } -} \ No newline at end of file + serverList = + serverList.stream() + .map(server -> server + ":" + sessionServerConfig.getServerPort()) + .collect(Collectors.toList()); + return serverList; + } + + @GET + @Path("slot") + @Produces(MediaType.APPLICATION_JSON) + public Slot getSlot(@QueryParam("dataInfoId") String dataInfoId) { + ParaCheckUtil.checkNotBlank(dataInfoId, "dataInfoId"); + return slotTableCache.getSlot(dataInfoId); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/ExecutorManager.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/ExecutorManager.java index 0f812cc29..0e872ee0a 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/ExecutorManager.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/ExecutorManager.java @@ -23,131 +23,153 @@ import com.alipay.sofa.registry.server.shared.meta.MetaServerService; import com.alipay.sofa.registry.task.MetricsableThreadPoolExecutor; import com.alipay.sofa.registry.util.NamedThreadFactory; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.HashMap; import java.util.Map; import java.util.concurrent.*; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version $Id: ExecutorManager.java, v 0.1 2017-11-28 14:41 shangyu.wh Exp $ */ public class ExecutorManager { - private static final Logger LOGGER = LoggerFactory - .getLogger(ExecutorManager.class); - - private final ScheduledThreadPoolExecutor scheduler; - - private final ThreadPoolExecutor accessDataExecutor; - private final ThreadPoolExecutor dataChangeRequestExecutor; - private final ThreadPoolExecutor dataSlotSyncRequestExecutor; - private final ThreadPoolExecutor connectClientExecutor; - - @Autowired - protected MetaServerService metaServerService; - - @Autowired - protected AppRevisionHeartbeatRegistry appRevisionHeartbeatRegistry; - - private Map reportExecutors = new HashMap<>(); - - private static final String ACCESS_DATA_EXECUTOR = "AccessDataExecutor"; - - private static final String DATA_CHANGE_REQUEST_EXECUTOR = "DataChangeRequestExecutor"; - - private static final String DATA_SLOT_MIGRATE_REQUEST_EXECUTOR = "DataSlotMigrateRequestExecutor"; - - private static final String CONNECT_CLIENT_EXECUTOR = "ConnectClientExecutor"; - - public ExecutorManager(SessionServerConfig sessionServerConfig) { - scheduler = new ScheduledThreadPoolExecutor(sessionServerConfig.getSessionSchedulerPoolSize(), - new NamedThreadFactory("SessionScheduler")); - - accessDataExecutor = reportExecutors.computeIfAbsent(ACCESS_DATA_EXECUTOR, - k -> new MetricsableThreadPoolExecutor(ACCESS_DATA_EXECUTOR, - sessionServerConfig.getAccessDataExecutorMinPoolSize(), - sessionServerConfig.getAccessDataExecutorMaxPoolSize(), - sessionServerConfig.getAccessDataExecutorKeepAliveTime(), TimeUnit.SECONDS, - new ArrayBlockingQueue<>(sessionServerConfig.getAccessDataExecutorQueueSize()), - new NamedThreadFactory("AccessExecutor", true), (r, executor) -> { - String msg = String - .format("Task(%s) %s rejected from %s, just ignore it to let client timeout.", r.getClass(), - r, executor); - LOGGER.error(msg); - })); - - dataChangeRequestExecutor = reportExecutors.computeIfAbsent(DATA_CHANGE_REQUEST_EXECUTOR, - k -> new MetricsableThreadPoolExecutor(DATA_CHANGE_REQUEST_EXECUTOR, - sessionServerConfig.getDataChangeExecutorMinPoolSize(), - sessionServerConfig.getDataChangeExecutorMaxPoolSize(), - sessionServerConfig.getDataChangeExecutorKeepAliveTime(), TimeUnit.SECONDS, - new ArrayBlockingQueue<>(sessionServerConfig.getDataChangeExecutorQueueSize()), - new NamedThreadFactory("DataChangeExecutor", true))); - - dataSlotSyncRequestExecutor = reportExecutors.computeIfAbsent(DATA_SLOT_MIGRATE_REQUEST_EXECUTOR, - k -> new MetricsableThreadPoolExecutor(DATA_SLOT_MIGRATE_REQUEST_EXECUTOR, - sessionServerConfig.getSlotSyncWorkerSize(), - sessionServerConfig.getSlotSyncWorkerSize(), - 60, TimeUnit.SECONDS, - new ArrayBlockingQueue<>(sessionServerConfig.getSlotSyncMaxBufferSize()), - new NamedThreadFactory("SlotSyncExecutor", true))); - - connectClientExecutor = reportExecutors.computeIfAbsent(CONNECT_CLIENT_EXECUTOR, - k -> new MetricsableThreadPoolExecutor(CONNECT_CLIENT_EXECUTOR, - sessionServerConfig.getConnectClientExecutorMinPoolSize(), - sessionServerConfig.getConnectClientExecutorMaxPoolSize(), 60L, TimeUnit.SECONDS, - new LinkedBlockingQueue(sessionServerConfig.getConnectClientExecutorQueueSize()), - new NamedThreadFactory("DisconnectCliExecutor", true))); + private static final Logger LOGGER = LoggerFactory.getLogger(ExecutorManager.class); + + private final ScheduledThreadPoolExecutor scheduler; + + private final ThreadPoolExecutor accessDataExecutor; + private final ThreadPoolExecutor dataChangeRequestExecutor; + private final ThreadPoolExecutor dataSlotSyncRequestExecutor; + private final ThreadPoolExecutor connectClientExecutor; + + @Autowired protected MetaServerService metaServerService; + + @Autowired protected AppRevisionHeartbeatRegistry appRevisionHeartbeatRegistry; + + private Map reportExecutors = new HashMap<>(); + + private static final String ACCESS_DATA_EXECUTOR = "AccessDataExecutor"; + + private static final String DATA_CHANGE_REQUEST_EXECUTOR = "DataChangeRequestExecutor"; + + private static final String DATA_SLOT_MIGRATE_REQUEST_EXECUTOR = "DataSlotMigrateRequestExecutor"; + + private static final String CONNECT_CLIENT_EXECUTOR = "ConnectClientExecutor"; + + public ExecutorManager(SessionServerConfig sessionServerConfig) { + scheduler = + new ScheduledThreadPoolExecutor( + sessionServerConfig.getSessionSchedulerPoolSize(), + new NamedThreadFactory("SessionScheduler")); + + accessDataExecutor = + reportExecutors.computeIfAbsent( + ACCESS_DATA_EXECUTOR, + k -> + new MetricsableThreadPoolExecutor( + ACCESS_DATA_EXECUTOR, + sessionServerConfig.getAccessDataExecutorMinPoolSize(), + sessionServerConfig.getAccessDataExecutorMaxPoolSize(), + sessionServerConfig.getAccessDataExecutorKeepAliveTime(), + TimeUnit.SECONDS, + new ArrayBlockingQueue<>(sessionServerConfig.getAccessDataExecutorQueueSize()), + new NamedThreadFactory("AccessExecutor", true), + (r, executor) -> { + String msg = + String.format( + "Task(%s) %s rejected from %s, just ignore it to let client timeout.", + r.getClass(), r, executor); + LOGGER.error(msg); + })); + + dataChangeRequestExecutor = + reportExecutors.computeIfAbsent( + DATA_CHANGE_REQUEST_EXECUTOR, + k -> + new MetricsableThreadPoolExecutor( + DATA_CHANGE_REQUEST_EXECUTOR, + sessionServerConfig.getDataChangeExecutorMinPoolSize(), + sessionServerConfig.getDataChangeExecutorMaxPoolSize(), + sessionServerConfig.getDataChangeExecutorKeepAliveTime(), + TimeUnit.SECONDS, + new ArrayBlockingQueue<>(sessionServerConfig.getDataChangeExecutorQueueSize()), + new NamedThreadFactory("DataChangeExecutor", true))); + + dataSlotSyncRequestExecutor = + reportExecutors.computeIfAbsent( + DATA_SLOT_MIGRATE_REQUEST_EXECUTOR, + k -> + new MetricsableThreadPoolExecutor( + DATA_SLOT_MIGRATE_REQUEST_EXECUTOR, + sessionServerConfig.getSlotSyncWorkerSize(), + sessionServerConfig.getSlotSyncWorkerSize(), + 60, + TimeUnit.SECONDS, + new ArrayBlockingQueue<>(sessionServerConfig.getSlotSyncMaxBufferSize()), + new NamedThreadFactory("SlotSyncExecutor", true))); + + connectClientExecutor = + reportExecutors.computeIfAbsent( + CONNECT_CLIENT_EXECUTOR, + k -> + new MetricsableThreadPoolExecutor( + CONNECT_CLIENT_EXECUTOR, + sessionServerConfig.getConnectClientExecutorMinPoolSize(), + sessionServerConfig.getConnectClientExecutorMaxPoolSize(), + 60L, + TimeUnit.SECONDS, + new LinkedBlockingQueue( + sessionServerConfig.getConnectClientExecutorQueueSize()), + new NamedThreadFactory("DisconnectCliExecutor", true))); + } + + public void startScheduler() { + scheduler.scheduleWithFixedDelay( + () -> appRevisionHeartbeatRegistry.doRevisionHeartbeat(), 10, 10, TimeUnit.MINUTES); + scheduler.scheduleWithFixedDelay( + () -> appRevisionHeartbeatRegistry.doRevisionGc(), 60, 60, TimeUnit.SECONDS); + } + + public void stopScheduler() { + if (scheduler != null && !scheduler.isShutdown()) { + scheduler.shutdown(); } - public void startScheduler() { - scheduler.scheduleWithFixedDelay(() -> appRevisionHeartbeatRegistry.doRevisionHeartbeat(), 10, 10, TimeUnit.MINUTES); - scheduler.scheduleWithFixedDelay(() -> appRevisionHeartbeatRegistry.doRevisionGc(), 60, 60, TimeUnit.SECONDS); + if (accessDataExecutor != null && !accessDataExecutor.isShutdown()) { + accessDataExecutor.shutdown(); } - public void stopScheduler() { - if (scheduler != null && !scheduler.isShutdown()) { - scheduler.shutdown(); - } - - if (accessDataExecutor != null && !accessDataExecutor.isShutdown()) { - accessDataExecutor.shutdown(); - } - - if (dataChangeRequestExecutor != null && !dataChangeRequestExecutor.isShutdown()) { - dataChangeRequestExecutor.shutdown(); - } - - if (dataSlotSyncRequestExecutor != null && !dataSlotSyncRequestExecutor.isShutdown()) { - dataSlotSyncRequestExecutor.shutdown(); - } - - if (connectClientExecutor != null && !connectClientExecutor.isShutdown()) { - connectClientExecutor.shutdown(); - } + if (dataChangeRequestExecutor != null && !dataChangeRequestExecutor.isShutdown()) { + dataChangeRequestExecutor.shutdown(); } - public Map getReportExecutors() { - return reportExecutors; + if (dataSlotSyncRequestExecutor != null && !dataSlotSyncRequestExecutor.isShutdown()) { + dataSlotSyncRequestExecutor.shutdown(); } - public ThreadPoolExecutor getAccessDataExecutor() { - return accessDataExecutor; + if (connectClientExecutor != null && !connectClientExecutor.isShutdown()) { + connectClientExecutor.shutdown(); } + } - public ThreadPoolExecutor getDataChangeRequestExecutor() { - return dataChangeRequestExecutor; - } + public Map getReportExecutors() { + return reportExecutors; + } - public ThreadPoolExecutor getDataSlotSyncRequestExecutor() { - return dataSlotSyncRequestExecutor; - } + public ThreadPoolExecutor getAccessDataExecutor() { + return accessDataExecutor; + } - public ThreadPoolExecutor getConnectClientExecutor() { - return connectClientExecutor; - } + public ThreadPoolExecutor getDataChangeRequestExecutor() { + return dataChangeRequestExecutor; + } + + public ThreadPoolExecutor getDataSlotSyncRequestExecutor() { + return dataSlotSyncRequestExecutor; + } -} \ No newline at end of file + public ThreadPoolExecutor getConnectClientExecutor() { + return connectClientExecutor; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/AbstractSessionTask.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/AbstractSessionTask.java index ae41f743e..a0d6c5c1b 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/AbstractSessionTask.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/AbstractSessionTask.java @@ -16,59 +16,56 @@ */ package com.alipay.sofa.registry.server.session.scheduler.task; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicInteger; - import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.task.Retryable; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicInteger; /** - * * @author shangyu.wh * @author kezhu.wukz * @version $Id: AbstractSessionTask.java, v 0.1 2018-01-15 14:35 shangyu.wh Exp $ */ public abstract class AbstractSessionTask implements SessionTask, Retryable { - private final static Logger LOGGER = LoggerFactory.getLogger(AbstractSessionTask.class, - "[Task]"); + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSessionTask.class, "[Task]"); - protected volatile String taskId; + protected volatile String taskId; - private AtomicInteger execCount = new AtomicInteger(1); + private AtomicInteger execCount = new AtomicInteger(1); - @Override - public synchronized String getTaskId() { - if (taskId == null) { - taskId = UUID.randomUUID().toString(); - } - - return taskId; + @Override + public synchronized String getTaskId() { + if (taskId == null) { + taskId = UUID.randomUUID().toString(); } - protected synchronized void setTaskId(String taskId) { - this.taskId = taskId; - } + return taskId; + } + + protected synchronized void setTaskId(String taskId) { + this.taskId = taskId; + } - protected boolean checkRetryTimes(int configTimes) { - if (configTimes > 0) { - if (execCount.incrementAndGet() > configTimes) { - LOGGER.info(" info:{} retry times more than {}", this, configTimes); - return false; - } else { - return true; - } - } + protected boolean checkRetryTimes(int configTimes) { + if (configTimes > 0) { + if (execCount.incrementAndGet() > configTimes) { + LOGGER.info(" info:{} retry times more than {}", this, configTimes); return false; + } else { + return true; + } } + return false; + } - protected int getExecCount() { - return execCount.get(); - } + protected int getExecCount() { + return execCount.get(); + } - @Override - public long getExpiryTime() { - return -1; - } -} \ No newline at end of file + @Override + public long getExpiryTime() { + return -1; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/Constant.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/Constant.java index f4f974917..32a03c392 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/Constant.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/Constant.java @@ -17,15 +17,14 @@ package com.alipay.sofa.registry.server.session.scheduler.task; /** - * * @author shangyu.wh * @version $Id: Constant.java, v 0.1 2018-08-17 17:07 shangyu.wh Exp $ */ public class Constant { - public final static String PUSH_CLIENT_SUBSCRIBERS = "PUSH_CLIENT_SUBSCRIBERS"; + public static final String PUSH_CLIENT_SUBSCRIBERS = "PUSH_CLIENT_SUBSCRIBERS"; - public final static String PUSH_CLIENT_DATUM = "PUSH_CLIENT_DATUM"; + public static final String PUSH_CLIENT_DATUM = "PUSH_CLIENT_DATUM"; - public final static String PUSH_CLIENT_URL = "PUSH_CLIENT_URL"; -} \ No newline at end of file + public static final String PUSH_CLIENT_URL = "PUSH_CLIENT_URL"; +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/ProvideDataChangeFetchTask.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/ProvideDataChangeFetchTask.java index 3292ac1ec..1ee3700aa 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/ProvideDataChangeFetchTask.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/ProvideDataChangeFetchTask.java @@ -37,7 +37,6 @@ import com.alipay.sofa.registry.task.listener.TaskEvent; import com.alipay.sofa.registry.task.listener.TaskEvent.TaskType; import com.alipay.sofa.registry.task.listener.TaskListenerManager; - import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -45,135 +44,141 @@ import java.util.concurrent.ConcurrentHashMap; /** - * * @author shangyu.wh * @version $Id: SubscriberRegisterFetchTask.java, v 0.1 2017-12-07 16:23 shangyu.wh Exp $ */ public class ProvideDataChangeFetchTask extends AbstractSessionTask { - private static final Logger TASK_LOGGER = LoggerFactory.getLogger( - ProvideDataChangeFetchTask.class, "[Task]"); - - private static final Logger LOGGER = LoggerFactory - .getLogger(ProvideDataChangeFetchTask.class); - - private final SessionServerConfig sessionServerConfig; - /** - * trigger push client process - */ - private final TaskListenerManager taskListenerManager; - /** - * Meta Node service - */ - private final MetaServerService metaServerService; - - private final Watchers sessionWatchers; - - private final Exchange boltExchange; - - private ProvideDataChangeEvent provideDataChangeEvent; - - private ProvideDataProcessor provideDataProcessorManager; - - public ProvideDataChangeFetchTask(SessionServerConfig sessionServerConfig, - TaskListenerManager taskListenerManager, - MetaServerService metaServerService, - Watchers sessionWatchers, Exchange boltExchange, - ProvideDataProcessor provideDataProcessorManager) { - this.sessionServerConfig = sessionServerConfig; - this.taskListenerManager = taskListenerManager; - this.metaServerService = metaServerService; - this.sessionWatchers = sessionWatchers; - this.boltExchange = boltExchange; - this.provideDataProcessorManager = provideDataProcessorManager; + private static final Logger TASK_LOGGER = + LoggerFactory.getLogger(ProvideDataChangeFetchTask.class, "[Task]"); + + private static final Logger LOGGER = LoggerFactory.getLogger(ProvideDataChangeFetchTask.class); + + private final SessionServerConfig sessionServerConfig; + /** trigger push client process */ + private final TaskListenerManager taskListenerManager; + /** Meta Node service */ + private final MetaServerService metaServerService; + + private final Watchers sessionWatchers; + + private final Exchange boltExchange; + + private ProvideDataChangeEvent provideDataChangeEvent; + + private ProvideDataProcessor provideDataProcessorManager; + + public ProvideDataChangeFetchTask( + SessionServerConfig sessionServerConfig, + TaskListenerManager taskListenerManager, + MetaServerService metaServerService, + Watchers sessionWatchers, + Exchange boltExchange, + ProvideDataProcessor provideDataProcessorManager) { + this.sessionServerConfig = sessionServerConfig; + this.taskListenerManager = taskListenerManager; + this.metaServerService = metaServerService; + this.sessionWatchers = sessionWatchers; + this.boltExchange = boltExchange; + this.provideDataProcessorManager = provideDataProcessorManager; + } + + @Override + public void setTaskEvent(TaskEvent taskEvent) { + // taskId create from event + if (taskEvent.getTaskId() != null) { + setTaskId(taskEvent.getTaskId()); } - @Override - public void setTaskEvent(TaskEvent taskEvent) { - //taskId create from event - if (taskEvent.getTaskId() != null) { - setTaskId(taskEvent.getTaskId()); - } + Object obj = taskEvent.getEventObj(); - Object obj = taskEvent.getEventObj(); - - if (!(obj instanceof ProvideDataChangeEvent)) { - throw new IllegalArgumentException("Input task event object error!"); - } - - this.provideDataChangeEvent = (ProvideDataChangeEvent) obj; + if (!(obj instanceof ProvideDataChangeEvent)) { + throw new IllegalArgumentException("Input task event object error!"); } - @Override - public void execute() { + this.provideDataChangeEvent = (ProvideDataChangeEvent) obj; + } - ProvideData provideData = null; - String dataInfoId = provideDataChangeEvent.getDataInfoId(); - if (provideDataChangeEvent.getDataOperator() != DataOperator.REMOVE) { - provideData = metaServerService.fetchData(dataInfoId); + @Override + public void execute() { - if (provideData == null) { - LOGGER.warn("Notify provider data Change request {} fetch no provider data!", provideDataChangeEvent); - return; - } - provideDataProcessorManager.changeDataProcess(provideData); + ProvideData provideData = null; + String dataInfoId = provideDataChangeEvent.getDataInfoId(); + if (provideDataChangeEvent.getDataOperator() != DataOperator.REMOVE) { + provideData = metaServerService.fetchData(dataInfoId); - } - DataInfo dataInfo = DataInfo.valueOf(dataInfoId); - - Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort()); - if (sessionServer != null) { - for (Channel channel : sessionServer.getChannels()) { - - //filter all connect client has watcher registerId - ConnectId connectId = ConnectId.of(channel.getRemoteAddress(), channel.getLocalAddress()); - Map map = getCache(connectId); - List registerIds = new ArrayList<>(); - map.forEach((registerId, watchers) -> { - if (watchers != null && watchers.getDataInfoId().equals(dataInfoId)) { - registerIds.add(registerId); - } - }); - if (!registerIds.isEmpty()) { - ReceivedConfigData receivedConfigData; - if (provideDataChangeEvent.getDataOperator() == DataOperator.REMOVE) { - receivedConfigData = ReceivedDataConverter - .getReceivedConfigData(null, dataInfo, provideDataChangeEvent.getVersion()); - } else { - receivedConfigData = ReceivedDataConverter - .getReceivedConfigData(provideData.getProvideData(), dataInfo, - provideData.getVersion()); - } - receivedConfigData.setConfiguratorRegistIds(registerIds); - firePushTask(receivedConfigData, new URL(channel.getRemoteAddress())); - } - } - } + if (provideData == null) { + LOGGER.warn( + "Notify provider data Change request {} fetch no provider data!", + provideDataChangeEvent); + return; + } + provideDataProcessorManager.changeDataProcess(provideData); } - - private void firePushTask(ReceivedConfigData receivedConfigData, URL clientUrl) { - - Map parameter = new HashMap<>(); - parameter.put(receivedConfigData, clientUrl); - TaskEvent taskEvent = new TaskEvent(parameter, TaskType.RECEIVED_DATA_CONFIG_PUSH_TASK); - TASK_LOGGER.info("send " + taskEvent.getTaskType() + " taskEvent:{}", taskEvent); - taskListenerManager.sendTaskEvent(taskEvent); - } - - private Map getCache(ConnectId connectId) { - Map map = sessionWatchers.queryByConnectId(connectId); - return map == null ? new ConcurrentHashMap<>() : map; - } - - @Override - public boolean checkRetryTimes() { - return checkRetryTimes(sessionServerConfig.getSubscriberRegisterFetchRetryTimes()); - } - - @Override - public String toString() { - return "PROVIDE_DATA_CHANGE_FETCH_TASK{" + "taskId='" + getTaskId() + '\'' - + ", notifyProvideDataChange=" + provideDataChangeEvent + ", retryTimes='" - + sessionServerConfig.getSubscriberRegisterFetchRetryTimes() + '\'' + '}'; + DataInfo dataInfo = DataInfo.valueOf(dataInfoId); + + Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort()); + if (sessionServer != null) { + for (Channel channel : sessionServer.getChannels()) { + + // filter all connect client has watcher registerId + ConnectId connectId = ConnectId.of(channel.getRemoteAddress(), channel.getLocalAddress()); + Map map = getCache(connectId); + List registerIds = new ArrayList<>(); + map.forEach( + (registerId, watchers) -> { + if (watchers != null && watchers.getDataInfoId().equals(dataInfoId)) { + registerIds.add(registerId); + } + }); + if (!registerIds.isEmpty()) { + ReceivedConfigData receivedConfigData; + if (provideDataChangeEvent.getDataOperator() == DataOperator.REMOVE) { + receivedConfigData = + ReceivedDataConverter.getReceivedConfigData( + null, dataInfo, provideDataChangeEvent.getVersion()); + } else { + receivedConfigData = + ReceivedDataConverter.getReceivedConfigData( + provideData.getProvideData(), dataInfo, provideData.getVersion()); + } + receivedConfigData.setConfiguratorRegistIds(registerIds); + firePushTask(receivedConfigData, new URL(channel.getRemoteAddress())); + } + } } -} \ No newline at end of file + } + + private void firePushTask(ReceivedConfigData receivedConfigData, URL clientUrl) { + + Map parameter = new HashMap<>(); + parameter.put(receivedConfigData, clientUrl); + TaskEvent taskEvent = new TaskEvent(parameter, TaskType.RECEIVED_DATA_CONFIG_PUSH_TASK); + TASK_LOGGER.info("send " + taskEvent.getTaskType() + " taskEvent:{}", taskEvent); + taskListenerManager.sendTaskEvent(taskEvent); + } + + private Map getCache(ConnectId connectId) { + Map map = sessionWatchers.queryByConnectId(connectId); + return map == null ? new ConcurrentHashMap<>() : map; + } + + @Override + public boolean checkRetryTimes() { + return checkRetryTimes(sessionServerConfig.getSubscriberRegisterFetchRetryTimes()); + } + + @Override + public String toString() { + return "PROVIDE_DATA_CHANGE_FETCH_TASK{" + + "taskId='" + + getTaskId() + + '\'' + + ", notifyProvideDataChange=" + + provideDataChangeEvent + + ", retryTimes='" + + sessionServerConfig.getSubscriberRegisterFetchRetryTimes() + + '\'' + + '}'; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/ReceivedConfigDataPushTask.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/ReceivedConfigDataPushTask.java index 964ee86be..c3a28937e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/ReceivedConfigDataPushTask.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/ReceivedConfigDataPushTask.java @@ -26,119 +26,133 @@ import com.alipay.sofa.registry.server.session.node.service.ClientNodeService; import com.alipay.sofa.registry.server.session.strategy.ReceivedConfigDataPushTaskStrategy; import com.alipay.sofa.registry.task.listener.TaskEvent; - import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.Executor; /** - * * @author shangyu.wh * @version $Id: SubscriberRegisterPushTask.java, v 0.1 2017-12-11 20:57 shangyu.wh Exp $ */ public class ReceivedConfigDataPushTask extends AbstractSessionTask { - private static final Logger LOGGER = LoggerFactory.getLogger( - ReceivedConfigDataPushTask.class, - "[Task]"); - - private final SessionServerConfig sessionServerConfig; - private final ClientNodeService clientNodeService; - private ReceivedConfigData receivedConfigData; - private URL url; - private ReceivedConfigDataPushTaskStrategy receivedConfigDataPushTaskStrategy; - - public ReceivedConfigDataPushTask(SessionServerConfig sessionServerConfig, - ClientNodeService clientNodeService, - ReceivedConfigDataPushTaskStrategy receivedConfigDataPushTaskStrategy) { - this.sessionServerConfig = sessionServerConfig; - this.clientNodeService = clientNodeService; - this.receivedConfigDataPushTaskStrategy = receivedConfigDataPushTaskStrategy; + private static final Logger LOGGER = + LoggerFactory.getLogger(ReceivedConfigDataPushTask.class, "[Task]"); + + private final SessionServerConfig sessionServerConfig; + private final ClientNodeService clientNodeService; + private ReceivedConfigData receivedConfigData; + private URL url; + private ReceivedConfigDataPushTaskStrategy receivedConfigDataPushTaskStrategy; + + public ReceivedConfigDataPushTask( + SessionServerConfig sessionServerConfig, + ClientNodeService clientNodeService, + ReceivedConfigDataPushTaskStrategy receivedConfigDataPushTaskStrategy) { + this.sessionServerConfig = sessionServerConfig; + this.clientNodeService = clientNodeService; + this.receivedConfigDataPushTaskStrategy = receivedConfigDataPushTaskStrategy; + } + + @Override + public void execute() { + + if (sessionServerConfig.isStopPushSwitch()) { + LOGGER.info( + "Stop Push receivedConfigData with switch on! dataId: {},group: {},Instance: {}, url: {}", + receivedConfigData.getDataId(), + receivedConfigData.getGroup(), + receivedConfigData.getInstanceId(), + url); + return; } - @Override - public void execute() { - - if (sessionServerConfig.isStopPushSwitch()) { - LOGGER - .info( - "Stop Push receivedConfigData with switch on! dataId: {},group: {},Instance: {}, url: {}", - receivedConfigData.getDataId(), receivedConfigData.getGroup(), - receivedConfigData.getInstanceId(), url); - return; - } - - CallbackHandler callbackHandler = new CallbackHandler() { - @Override - public void onCallback(Channel channel, Object message) { - LOGGER.info( - "Push receivedConfigData success! dataId: {},group: {},Instance: {}, url: {}", - receivedConfigData.getDataId(), receivedConfigData.getGroup(), - receivedConfigData.getInstanceId(), url); - } - - @Override - public void onException(Channel channel, Throwable exception) { - LOGGER.error( - "Push receivedConfigData error! dataId: {},group: {},Instance: {}, url: {}", - receivedConfigData.getDataId(), receivedConfigData.getGroup(), - receivedConfigData.getInstanceId(), url); - } - - @Override - public Executor getExecutor() { - return null; - } + CallbackHandler callbackHandler = + new CallbackHandler() { + @Override + public void onCallback(Channel channel, Object message) { + LOGGER.info( + "Push receivedConfigData success! dataId: {},group: {},Instance: {}, url: {}", + receivedConfigData.getDataId(), + receivedConfigData.getGroup(), + receivedConfigData.getInstanceId(), + url); + } + + @Override + public void onException(Channel channel, Throwable exception) { + LOGGER.error( + "Push receivedConfigData error! dataId: {},group: {},Instance: {}, url: {}", + receivedConfigData.getDataId(), + receivedConfigData.getGroup(), + receivedConfigData.getInstanceId(), + url); + } + + @Override + public Executor getExecutor() { + return null; + } }; - clientNodeService.pushWithCallback( - receivedConfigDataPushTaskStrategy.convert2PushData(receivedConfigData, url), url, - callbackHandler); - } - - @Override - public long getExpiryTime() { - //TODO CONFIG - return -1; - } + clientNodeService.pushWithCallback( + receivedConfigDataPushTaskStrategy.convert2PushData(receivedConfigData, url), + url, + callbackHandler); + } - @Override - public void setTaskEvent(TaskEvent taskEvent) { + @Override + public long getExpiryTime() { + // TODO CONFIG + return -1; + } - //taskId create from event - if (taskEvent.getTaskId() != null) { - setTaskId(taskEvent.getTaskId()); - } + @Override + public void setTaskEvent(TaskEvent taskEvent) { - Object obj = taskEvent.getEventObj(); - - if (obj instanceof Map) { + // taskId create from event + if (taskEvent.getTaskId() != null) { + setTaskId(taskEvent.getTaskId()); + } - Map parameter = (Map) obj; + Object obj = taskEvent.getEventObj(); - if (parameter.size() == 1) { + if (obj instanceof Map) { - Entry entry = (parameter.entrySet()).iterator().next(); - ReceivedConfigData receivedData = entry.getKey(); - URL url = entry.getValue(); + Map parameter = (Map) obj; - this.receivedConfigData = receivedData; - this.url = url; - } else { - throw new IllegalArgumentException("Input task event object error!"); - } - } - } + if (parameter.size() == 1) { - @Override - public String toString() { - return "RECEIVED_DATA_CONFIG_PUSH_TASK{" + "taskId='" + getTaskId() + '\'' - + ", receivedConfigData=" + receivedConfigData + ", url=" + url + ", retry='" - + sessionServerConfig.getPushTaskRetryTimes() + '\'' + '}'; - } + Entry entry = (parameter.entrySet()).iterator().next(); + ReceivedConfigData receivedData = entry.getKey(); + URL url = entry.getValue(); - @Override - public boolean checkRetryTimes() { - return checkRetryTimes(sessionServerConfig.getPushTaskRetryTimes()); + this.receivedConfigData = receivedData; + this.url = url; + } else { + throw new IllegalArgumentException("Input task event object error!"); + } } -} \ No newline at end of file + } + + @Override + public String toString() { + return "RECEIVED_DATA_CONFIG_PUSH_TASK{" + + "taskId='" + + getTaskId() + + '\'' + + ", receivedConfigData=" + + receivedConfigData + + ", url=" + + url + + ", retry='" + + sessionServerConfig.getPushTaskRetryTimes() + + '\'' + + '}'; + } + + @Override + public boolean checkRetryTimes() { + return checkRetryTimes(sessionServerConfig.getPushTaskRetryTimes()); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/SessionTask.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/SessionTask.java index 02433c4f3..a8569a445 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/SessionTask.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/SessionTask.java @@ -19,10 +19,7 @@ import com.alipay.sofa.registry.task.Task; /** - * * @author shangyu.wh * @version $Id: SessionTask.java, v 0.1 2017-12-07 20:57 shangyu.wh Exp $ */ -public interface SessionTask extends Task { - -} \ No newline at end of file +public interface SessionTask extends Task {} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/WatcherRegisterFetchTask.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/WatcherRegisterFetchTask.java index 522905fe9..e1adaee46 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/WatcherRegisterFetchTask.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/task/WatcherRegisterFetchTask.java @@ -30,122 +30,125 @@ import com.alipay.sofa.registry.task.listener.TaskEvent; import com.alipay.sofa.registry.task.listener.TaskEvent.TaskType; import com.alipay.sofa.registry.task.listener.TaskListenerManager; - import java.util.*; /** - * * @author shangyu.wh * @version $Id: SubscriberRegisterFetchTask.java, v 0.1 2017-12-07 16:23 shangyu.wh Exp $ */ public class WatcherRegisterFetchTask extends AbstractSessionTask { - private static final Logger taskLogger = LoggerFactory.getLogger( - WatcherRegisterFetchTask.class, "[Task]"); - - private final SessionServerConfig sessionServerConfig; - /** - * trigger push client process - */ - private final TaskListenerManager taskListenerManager; - /** - * Meta Node service - */ - private final MetaServerService metaServerService; - - private Watcher watcher; - - private static final int TRY_COUNT = 3; - - public WatcherRegisterFetchTask(SessionServerConfig sessionServerConfig, - TaskListenerManager taskListenerManager, - MetaServerService metaServerService) { - this.sessionServerConfig = sessionServerConfig; - this.taskListenerManager = taskListenerManager; - this.metaServerService = metaServerService; - } + private static final Logger taskLogger = + LoggerFactory.getLogger(WatcherRegisterFetchTask.class, "[Task]"); - @Override - public void setTaskEvent(TaskEvent taskEvent) { + private final SessionServerConfig sessionServerConfig; + /** trigger push client process */ + private final TaskListenerManager taskListenerManager; + /** Meta Node service */ + private final MetaServerService metaServerService; - //taskId create from event - if (taskEvent.getTaskId() != null) { - setTaskId(taskEvent.getTaskId()); - } + private Watcher watcher; - Object obj = taskEvent.getEventObj(); + private static final int TRY_COUNT = 3; - if (!(obj instanceof Watcher)) { - throw new IllegalArgumentException("Input task event object error!"); - } + public WatcherRegisterFetchTask( + SessionServerConfig sessionServerConfig, + TaskListenerManager taskListenerManager, + MetaServerService metaServerService) { + this.sessionServerConfig = sessionServerConfig; + this.taskListenerManager = taskListenerManager; + this.metaServerService = metaServerService; + } - this.watcher = (Watcher) obj; + @Override + public void setTaskEvent(TaskEvent taskEvent) { + + // taskId create from event + if (taskEvent.getTaskId() != null) { + setTaskId(taskEvent.getTaskId()); } - @Override - public void execute() { - - if (watcher == null) { - throw new IllegalArgumentException("watcher can not be null!"); - } - - List subscriberRegisterIdList = Collections.singletonList(watcher.getRegisterId()); - - boolean isOldVersion = !ClientVersion.StoreData.equals(watcher.getClientVersion()); - - ProvideData provideData = null; - - for (int tryCount = 0; tryCount < TRY_COUNT; tryCount++) { - try { - provideData = metaServerService.fetchData(watcher.getDataInfoId()); - break; - } catch (Exception e) { - randomDelay(3000); - } - } - - if (provideData == null) { - taskLogger.error("Fetch provider data error,set null value return.dataInfoId={}", - watcher.getDataId()); - provideData = new ProvideData(null, watcher.getDataInfoId(), null); - } - - if (!isOldVersion) { - DataInfo dataInfo = DataInfo.valueOf(provideData.getDataInfoId()); - ReceivedConfigData receivedConfigData = ReceivedDataConverter.getReceivedConfigData( - provideData.getProvideData(), dataInfo, provideData.getVersion()); - receivedConfigData.setConfiguratorRegistIds(subscriberRegisterIdList); - firePushTask(receivedConfigData); - } + Object obj = taskEvent.getEventObj(); + + if (!(obj instanceof Watcher)) { + throw new IllegalArgumentException("Input task event object error!"); } - private void firePushTask(ReceivedConfigData receivedConfigData) { - Map parameter = new HashMap<>(); - parameter.put(receivedConfigData, watcher.getSourceAddress()); - TaskEvent taskEvent = new TaskEvent(parameter, TaskType.RECEIVED_DATA_CONFIG_PUSH_TASK); - taskLogger.info("send " + taskEvent.getTaskType() + " taskEvent:{}", taskEvent); - taskListenerManager.sendTaskEvent(taskEvent); + this.watcher = (Watcher) obj; + } + + @Override + public void execute() { + + if (watcher == null) { + throw new IllegalArgumentException("watcher can not be null!"); } - @Override - public boolean checkRetryTimes() { - return checkRetryTimes(sessionServerConfig.getSubscriberRegisterFetchRetryTimes()); + List subscriberRegisterIdList = Collections.singletonList(watcher.getRegisterId()); + + boolean isOldVersion = !ClientVersion.StoreData.equals(watcher.getClientVersion()); + + ProvideData provideData = null; + + for (int tryCount = 0; tryCount < TRY_COUNT; tryCount++) { + try { + provideData = metaServerService.fetchData(watcher.getDataInfoId()); + break; + } catch (Exception e) { + randomDelay(3000); + } } - private void randomDelay(int max) { - Random random = new Random(); - int randomNum = random.nextInt(max); - try { - Thread.sleep(randomNum); - } catch (InterruptedException e) { - taskLogger.error("[TimeUtil] random delay error", e); - } + if (provideData == null) { + taskLogger.error( + "Fetch provider data error,set null value return.dataInfoId={}", watcher.getDataId()); + provideData = new ProvideData(null, watcher.getDataInfoId(), null); } - @Override - public String toString() { - return "WATCHER_REGISTER_FETCH_TASK{" + "taskId='" + getTaskId() + '\'' + ", watcher=" - + watcher + ", retryTimes='" - + sessionServerConfig.getSubscriberRegisterFetchRetryTimes() + '\'' + '}'; + if (!isOldVersion) { + DataInfo dataInfo = DataInfo.valueOf(provideData.getDataInfoId()); + ReceivedConfigData receivedConfigData = + ReceivedDataConverter.getReceivedConfigData( + provideData.getProvideData(), dataInfo, provideData.getVersion()); + receivedConfigData.setConfiguratorRegistIds(subscriberRegisterIdList); + firePushTask(receivedConfigData); + } + } + + private void firePushTask(ReceivedConfigData receivedConfigData) { + Map parameter = new HashMap<>(); + parameter.put(receivedConfigData, watcher.getSourceAddress()); + TaskEvent taskEvent = new TaskEvent(parameter, TaskType.RECEIVED_DATA_CONFIG_PUSH_TASK); + taskLogger.info("send " + taskEvent.getTaskType() + " taskEvent:{}", taskEvent); + taskListenerManager.sendTaskEvent(taskEvent); + } + + @Override + public boolean checkRetryTimes() { + return checkRetryTimes(sessionServerConfig.getSubscriberRegisterFetchRetryTimes()); + } + + private void randomDelay(int max) { + Random random = new Random(); + int randomNum = random.nextInt(max); + try { + Thread.sleep(randomNum); + } catch (InterruptedException e) { + taskLogger.error("[TimeUtil] random delay error", e); } -} \ No newline at end of file + } + + @Override + public String toString() { + return "WATCHER_REGISTER_FETCH_TASK{" + + "taskId='" + + getTaskId() + + '\'' + + ", watcher=" + + watcher + + ", retryTimes='" + + sessionServerConfig.getSubscriberRegisterFetchRetryTimes() + + '\'' + + '}'; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/CacheCountTask.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/CacheCountTask.java index f73c66eeb..7628403bc 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/CacheCountTask.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/CacheCountTask.java @@ -28,111 +28,105 @@ import com.alipay.sofa.registry.server.session.store.Watchers; import com.alipay.sofa.registry.util.ConcurrentUtils; import com.alipay.sofa.registry.util.NamedThreadFactory; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; /** * @author qian.lqlq * @version $Id: CacheDigestTask.java, v 0.1 2018-04-27 17:40 qian.lqlq Exp $ */ public class CacheCountTask { - private static final Logger LOGGER = LoggerFactory.getLogger(CacheCountTask.class, - "[CacheCountTask]"); - private static final Logger COUNT_LOGGER = LoggerFactory.getLogger("CACHE-COUNT"); - - @Autowired - private DataStore sessionDataStore; - - @Autowired - private Interests sessionInterests; - - @Autowired - private Watchers sessionWatchers; - - @Autowired - private SessionServerConfig sessionServerConfig; + private static final Logger LOGGER = + LoggerFactory.getLogger(CacheCountTask.class, "[CacheCountTask]"); + private static final Logger COUNT_LOGGER = LoggerFactory.getLogger("CACHE-COUNT"); - @PostConstruct - public void init() { - final int intervalSec = sessionServerConfig.getCacheCountIntervalSecs(); - if (intervalSec <= 0) { - LOGGER.info("cache count off with intervalSecs={}", intervalSec); - return; - } - ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1, - new NamedThreadFactory("CacheCountTask")); - executor.scheduleWithFixedDelay(() -> { - try { - syncCount(); - } catch (Throwable t) { - LOGGER.error("cache count error", t); - } - }, intervalSec, intervalSec, TimeUnit.SECONDS); - } - - public void syncCount() { - List pubs = sessionDataStore.getDataList(); - List subs = sessionInterests.getDataList(); - List wats = sessionWatchers.getDataList(); - - Map> pubGroupCounts = DataUtils - .countGroupByInstanceIdGroup(pubs); - printInstanceIdGroupCount("[PubGroup]", pubGroupCounts); - - Map> subGroupCounts = DataUtils - .countGroupByInstanceIdGroup(subs); - printInstanceIdGroupCount("[SubGroup]", subGroupCounts); + @Autowired private DataStore sessionDataStore; - Map> watGroupCounts = DataUtils - .countGroupByInstanceIdGroup(wats); - printInstanceIdGroupCount("[WatGroup]", watGroupCounts); + @Autowired private Interests sessionInterests; - Map>> pubCounts = DataUtils - .countGroupByInstanceIdGroupApp(pubs); - printInstanceIdGroupAppCount("[Pub]", pubCounts); + @Autowired private Watchers sessionWatchers; - Map>> subCounts = DataUtils - .countGroupByInstanceIdGroupApp(subs); - printInstanceIdGroupAppCount("[Sub]", subCounts); - - Map>> watCounts = DataUtils - .countGroupByInstanceIdGroupApp(wats); - printInstanceIdGroupAppCount("[Wat]", watCounts); + @Autowired private SessionServerConfig sessionServerConfig; + @PostConstruct + public void init() { + final int intervalSec = sessionServerConfig.getCacheCountIntervalSecs(); + if (intervalSec <= 0) { + LOGGER.info("cache count off with intervalSecs={}", intervalSec); + return; } - - private static void printInstanceIdGroupAppCount(String prefix, - Map>> counts) { - for (Entry>> count : counts.entrySet()) { - final String instanceId = count.getKey(); - for (Entry> groupCounts : count.getValue().entrySet()) { - final String group = groupCounts.getKey(); - for (Entry apps : groupCounts.getValue().entrySet()) { - final String app = apps.getKey(); - COUNT_LOGGER.info("{}{},{},{},{}", prefix, instanceId, group, app, - apps.getValue()); - } - ConcurrentUtils.sleepUninterruptibly(100, TimeUnit.MILLISECONDS); - } + ScheduledExecutorService executor = + new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("CacheCountTask")); + executor.scheduleWithFixedDelay( + () -> { + try { + syncCount(); + } catch (Throwable t) { + LOGGER.error("cache count error", t); + } + }, + intervalSec, + intervalSec, + TimeUnit.SECONDS); + } + + public void syncCount() { + List pubs = sessionDataStore.getDataList(); + List subs = sessionInterests.getDataList(); + List wats = sessionWatchers.getDataList(); + + Map> pubGroupCounts = DataUtils.countGroupByInstanceIdGroup(pubs); + printInstanceIdGroupCount("[PubGroup]", pubGroupCounts); + + Map> subGroupCounts = DataUtils.countGroupByInstanceIdGroup(subs); + printInstanceIdGroupCount("[SubGroup]", subGroupCounts); + + Map> watGroupCounts = DataUtils.countGroupByInstanceIdGroup(wats); + printInstanceIdGroupCount("[WatGroup]", watGroupCounts); + + Map>> pubCounts = + DataUtils.countGroupByInstanceIdGroupApp(pubs); + printInstanceIdGroupAppCount("[Pub]", pubCounts); + + Map>> subCounts = + DataUtils.countGroupByInstanceIdGroupApp(subs); + printInstanceIdGroupAppCount("[Sub]", subCounts); + + Map>> watCounts = + DataUtils.countGroupByInstanceIdGroupApp(wats); + printInstanceIdGroupAppCount("[Wat]", watCounts); + } + + private static void printInstanceIdGroupAppCount( + String prefix, Map>> counts) { + for (Entry>> count : counts.entrySet()) { + final String instanceId = count.getKey(); + for (Entry> groupCounts : count.getValue().entrySet()) { + final String group = groupCounts.getKey(); + for (Entry apps : groupCounts.getValue().entrySet()) { + final String app = apps.getKey(); + COUNT_LOGGER.info("{}{},{},{},{}", prefix, instanceId, group, app, apps.getValue()); } + ConcurrentUtils.sleepUninterruptibly(100, TimeUnit.MILLISECONDS); + } } - - private static void printInstanceIdGroupCount(String prefix, - Map> counts) { - for (Entry> count : counts.entrySet()) { - final String instanceId = count.getKey(); - Map groupCounts = count.getValue(); - for (Entry groups : groupCounts.entrySet()) { - final String group = groups.getKey(); - COUNT_LOGGER.info("{}{},{},{}", prefix, instanceId, group, groups.getValue()); - } - } + } + + private static void printInstanceIdGroupCount( + String prefix, Map> counts) { + for (Entry> count : counts.entrySet()) { + final String instanceId = count.getKey(); + Map groupCounts = count.getValue(); + for (Entry groups : groupCounts.entrySet()) { + final String group = groups.getKey(); + COUNT_LOGGER.info("{}{},{},{}", prefix, instanceId, group, groups.getValue()); + } } -} \ No newline at end of file + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/SessionCacheDigestTask.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/SessionCacheDigestTask.java index 740751b7b..16b01297c 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/SessionCacheDigestTask.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/SessionCacheDigestTask.java @@ -26,13 +26,12 @@ import com.alipay.sofa.registry.server.session.store.DataStore; import com.alipay.sofa.registry.server.session.store.Interests; import com.alipay.sofa.registry.util.ConcurrentUtils; -import org.apache.commons.lang.time.DateUtils; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.util.*; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import org.apache.commons.lang.time.DateUtils; +import org.springframework.beans.factory.annotation.Autowired; /** * @author xiaojian.xj @@ -40,74 +39,77 @@ */ public class SessionCacheDigestTask { - private static final Logger LOGGER = LoggerFactory.getLogger("CACHE-DIGEST"); + private static final Logger LOGGER = LoggerFactory.getLogger("CACHE-DIGEST"); - @Autowired - private DataStore sessionDataStore; + @Autowired private DataStore sessionDataStore; - @Autowired - private Interests sessionInterests; + @Autowired private Interests sessionInterests; - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @PostConstruct - public void init() { - final int intervalMinutes = sessionServerConfig.getCacheDigestIntervalMinutes(); - if (intervalMinutes <= 0) { - LOGGER.info("cache digest off with intervalMinutes={}", intervalMinutes); - return; - } - Date firstDate = new Date(); - firstDate = DateUtils.round(firstDate, Calendar.MINUTE); - firstDate.setMinutes(firstDate.getMinutes() / intervalMinutes * intervalMinutes - + intervalMinutes); - Timer timer = new Timer("CacheDigestTask", true); - TimerTask task = new TimerTask() { - @Override - public void run() { - dump(); - } - }; - timer.scheduleAtFixedRate(task, firstDate, intervalMinutes * 60 * 1000); + @PostConstruct + public void init() { + final int intervalMinutes = sessionServerConfig.getCacheDigestIntervalMinutes(); + if (intervalMinutes <= 0) { + LOGGER.info("cache digest off with intervalMinutes={}", intervalMinutes); + return; } + Date firstDate = new Date(); + firstDate = DateUtils.round(firstDate, Calendar.MINUTE); + firstDate.setMinutes( + firstDate.getMinutes() / intervalMinutes * intervalMinutes + intervalMinutes); + Timer timer = new Timer("CacheDigestTask", true); + TimerTask task = + new TimerTask() { + @Override + public void run() { + dump(); + } + }; + timer.scheduleAtFixedRate(task, firstDate, intervalMinutes * 60 * 1000); + } - private void dump() { - try { - Collection storeDataInfoIds = sessionDataStore.getDataInfoIds(); - Collection interestDataInfoIds = sessionInterests.getDataInfoIds(); - Set dataInfoIds = new HashSet<>(storeDataInfoIds.size() + interestDataInfoIds.size()); + private void dump() { + try { + Collection storeDataInfoIds = sessionDataStore.getDataInfoIds(); + Collection interestDataInfoIds = sessionInterests.getDataInfoIds(); + Set dataInfoIds = new HashSet<>(storeDataInfoIds.size() + interestDataInfoIds.size()); - dataInfoIds.addAll(storeDataInfoIds); - dataInfoIds.addAll(interestDataInfoIds); + dataInfoIds.addAll(storeDataInfoIds); + dataInfoIds.addAll(interestDataInfoIds); - dataInfoIds.stream().forEach(dataInfoId -> { + dataInfoIds.stream() + .forEach( + dataInfoId -> { Collection publishers = sessionDataStore.getDatas(dataInfoId); Collection subscribers = sessionInterests.getDatas(dataInfoId); - LOGGER.info("[dataInfo] {}; {}; {}; {}; [{}]; [{}]", - sessionServerConfig.getSessionServerDataCenter(), dataInfoId, - publishers.size(), subscribers.size(), - logPubOrSub(publishers), logPubOrSub(subscribers)); + LOGGER.info( + "[dataInfo] {}; {}; {}; {}; [{}]; [{}]", + sessionServerConfig.getSessionServerDataCenter(), + dataInfoId, + publishers.size(), + subscribers.size(), + logPubOrSub(publishers), + logPubOrSub(subscribers)); // avoid io is too busy ConcurrentUtils.sleepUninterruptibly(2, TimeUnit.MILLISECONDS); - }); - - } catch (Throwable t) { - LOGGER.error("[CacheDigestTask] cache digest error", t); - } + }); + } catch (Throwable t) { + LOGGER.error("[CacheDigestTask] cache digest error", t); } + } - private String logPubOrSub(Collection infos) { + private String logPubOrSub(Collection infos) { - return Optional.ofNullable(infos).orElse(new ArrayList<>()).stream() - .filter(info -> info != null).map(info -> logUrl(info.getSourceAddress())) - .collect(Collectors.joining(",")); - } - - private String logUrl(URL url) { - return url == null ? "null" : url.getAddressString(); - } + return Optional.ofNullable(infos).orElse(new ArrayList<>()).stream() + .filter(info -> info != null) + .map(info -> logUrl(info.getSourceAddress())) + .collect(Collectors.joining(",")); + } -} \ No newline at end of file + private String logUrl(URL url) { + return url == null ? "null" : url.getAddressString(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/SyncClientsHeartbeatTask.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/SyncClientsHeartbeatTask.java index e9c91c541..9688424f7 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/SyncClientsHeartbeatTask.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/scheduler/timertask/SyncClientsHeartbeatTask.java @@ -31,148 +31,146 @@ import com.alipay.sofa.registry.task.batcher.TaskDispatchers; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.scheduling.annotation.Scheduled; - import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ThreadPoolExecutor; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; /** * The type Sync clients heartbeat task. + * * @author zhuoyu.sjw * @version $Id : SyncClientsHeartbeatTask.java, v 0.1 2018-03-31 16:07 zhuoyu.sjw Exp $$ */ public class SyncClientsHeartbeatTask { - private static final Logger CONSOLE_COUNT_LOGGER = LoggerFactory.getLogger("SESSION-CONSOLE", - "[Count]"); - - private static final Logger PRO_LOGGER = LoggerFactory.getLogger( - "SESSION-PROFILE-DIGEST", "[TaskExecute]"); - - private static final Logger EXE_LOGGER = LoggerFactory.getLogger( - "SESSION-PROFILE-DIGEST", - "[ExecutorMetrics]"); - - public static final String SYMBOLIC1 = " ├─ "; - public static final String SYMBOLIC2 = " └─ "; - - @Autowired - private Exchange boltExchange; - - @Autowired - private SessionServerConfig sessionServerConfig; - - /** - * store subscribers - */ - @Autowired - private Interests sessionInterests; - - /** - * store watchers - */ - @Autowired - private Watchers sessionWatchers; - - /** - * store publishers - */ - @Autowired - private DataStore sessionDataStore; - - @Autowired - private ExecutorManager executorManager; - - @Scheduled(initialDelayString = "${session.server.syncHeartbeat.fixedDelay}", fixedDelayString = "${session.server.syncHeartbeat.fixedDelay}") - public void syncCount() { - long countSub = sessionInterests.count(); - long countPub = sessionDataStore.count(); - long countSubW = sessionWatchers.count(); - - int channelCount = 0; - Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort()); - if (sessionServer != null) { - channelCount = sessionServer.getChannelCount(); - } - - CONSOLE_COUNT_LOGGER.info( - "Subscriber count: {}, Publisher count: {}, Watcher count: {}, Connection count: {}", - countSub, countPub, countSubW, channelCount); - } + private static final Logger CONSOLE_COUNT_LOGGER = + LoggerFactory.getLogger("SESSION-CONSOLE", "[Count]"); - @Scheduled(initialDelayString = "${session.server.printTask.fixedDelay}", fixedDelayString = "${session.server.printTask.fixedDelay}") - public void printTaskExecute() { + private static final Logger PRO_LOGGER = + LoggerFactory.getLogger("SESSION-PROFILE-DIGEST", "[TaskExecute]"); - Map taskDispatcherMap = TaskDispatchers.getTaskDispatcherMap(); - if (taskDispatcherMap != null) { + private static final Logger EXE_LOGGER = + LoggerFactory.getLogger("SESSION-PROFILE-DIGEST", "[ExecutorMetrics]"); - StringBuilder sb = new StringBuilder(); - logInfo(sb, taskDispatcherMap, "TaskDispatcher"); - PRO_LOGGER.info(sb.toString()); - } + public static final String SYMBOLIC1 = " ├─ "; + public static final String SYMBOLIC2 = " └─ "; - } + @Autowired private Exchange boltExchange; - protected void logInfo(StringBuilder sb0, Map taskDispatcherMap, - String info) { - sb0.append("\n").append(info).append(" >>>>>>>"); - StringBuilder sb = new StringBuilder(); - for (Iterator> i = taskDispatcherMap.entrySet().iterator(); i - .hasNext();) { - Entry entry = i.next(); - AcceptorExecutor acceptorExecutor = entry.getValue().getAcceptorExecutor(); - String outterTreeSymbol = SYMBOLIC1; - if (!i.hasNext()) { - outterTreeSymbol = SYMBOLIC2; - } - sb.append(outterTreeSymbol).append(entry.getKey()); - sb.append(", AcceptedTasks:").append(acceptorExecutor.getAcceptedTasks()); - sb.append(", ReplayedTasks:").append(acceptorExecutor.getReplayedTasks()); - sb.append(", QueueOverflows:").append(acceptorExecutor.getQueueOverflows()); - sb.append(" ,PendingTaskSize:").append(acceptorExecutor.getPendingTaskSize()); - sb.append(", ExpiredTasks:").append(acceptorExecutor.getExpiredTasks()); - sb.append(", OverriddenTasks:").append(acceptorExecutor.getOverriddenTasks()); - sb.append(", MaxBuffer:").append(acceptorExecutor.getMaxBufferSize()).append("\n"); - } - sb0.append("\n").append(sb); - } + @Autowired private SessionServerConfig sessionServerConfig; - @Scheduled(initialDelayString = "${session.server.printTask.fixedDelay}", fixedDelayString = "${session.server.printTask.fixedDelay}") - public void printExecutorTaskExecute() { + /** store subscribers */ + @Autowired private Interests sessionInterests; - Map reportExecutors = executorManager.getReportExecutors(); - if (reportExecutors != null) { + /** store watchers */ + @Autowired private Watchers sessionWatchers; - StringBuilder sb = new StringBuilder(); - logInfoExecutor(sb, reportExecutors, "ExecutorMetrics"); - EXE_LOGGER.info(sb.toString()); - } + /** store publishers */ + @Autowired private DataStore sessionDataStore; + @Autowired private ExecutorManager executorManager; + + @Scheduled( + initialDelayString = "${session.server.syncHeartbeat.fixedDelay}", + fixedDelayString = "${session.server.syncHeartbeat.fixedDelay}") + public void syncCount() { + long countSub = sessionInterests.count(); + long countPub = sessionDataStore.count(); + long countSubW = sessionWatchers.count(); + + int channelCount = 0; + Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort()); + if (sessionServer != null) { + channelCount = sessionServer.getChannelCount(); + } + + CONSOLE_COUNT_LOGGER.info( + "Subscriber count: {}, Publisher count: {}, Watcher count: {}, Connection count: {}", + countSub, + countPub, + countSubW, + channelCount); + } + + @Scheduled( + initialDelayString = "${session.server.printTask.fixedDelay}", + fixedDelayString = "${session.server.printTask.fixedDelay}") + public void printTaskExecute() { + + Map taskDispatcherMap = TaskDispatchers.getTaskDispatcherMap(); + if (taskDispatcherMap != null) { + + StringBuilder sb = new StringBuilder(); + logInfo(sb, taskDispatcherMap, "TaskDispatcher"); + PRO_LOGGER.info(sb.toString()); } + } + + protected void logInfo( + StringBuilder sb0, Map taskDispatcherMap, String info) { + sb0.append("\n").append(info).append(" >>>>>>>"); + StringBuilder sb = new StringBuilder(); + for (Iterator> i = taskDispatcherMap.entrySet().iterator(); + i.hasNext(); ) { + Entry entry = i.next(); + AcceptorExecutor acceptorExecutor = entry.getValue().getAcceptorExecutor(); + String outterTreeSymbol = SYMBOLIC1; + if (!i.hasNext()) { + outterTreeSymbol = SYMBOLIC2; + } + sb.append(outterTreeSymbol).append(entry.getKey()); + sb.append(", AcceptedTasks:").append(acceptorExecutor.getAcceptedTasks()); + sb.append(", ReplayedTasks:").append(acceptorExecutor.getReplayedTasks()); + sb.append(", QueueOverflows:").append(acceptorExecutor.getQueueOverflows()); + sb.append(" ,PendingTaskSize:").append(acceptorExecutor.getPendingTaskSize()); + sb.append(", ExpiredTasks:").append(acceptorExecutor.getExpiredTasks()); + sb.append(", OverriddenTasks:").append(acceptorExecutor.getOverriddenTasks()); + sb.append(", MaxBuffer:").append(acceptorExecutor.getMaxBufferSize()).append("\n"); + } + sb0.append("\n").append(sb); + } + + @Scheduled( + initialDelayString = "${session.server.printTask.fixedDelay}", + fixedDelayString = "${session.server.printTask.fixedDelay}") + public void printExecutorTaskExecute() { - protected void logInfoExecutor(StringBuilder sb0, Map reportExecutors, String info) { - sb0.append("\n").append(info).append(" >>>>>>>"); - StringBuilder sb = new StringBuilder(); - for (Iterator> i = reportExecutors.entrySet().iterator(); i.hasNext(); ) { - Entry entry = i.next(); - String executorName = entry.getKey(); - - MetricRegistry metricRegistry = TaskMetrics.getInstance().getMetricRegistry(); - Map map = metricRegistry.getGauges((name, value) -> name.startsWith(executorName)); - - String outterTreeSymbol = SYMBOLIC1; - if (!i.hasNext()) { - outterTreeSymbol = SYMBOLIC2; - } - sb.append(outterTreeSymbol).append(executorName); - map.forEach((key, gauge) -> { - String name = key.substring(executorName.length() + 1); - sb.append(", ").append(name).append(":").append(gauge.getValue()); - }); - sb.append("\n"); - } - sb0.append("\n").append(sb); + Map reportExecutors = executorManager.getReportExecutors(); + if (reportExecutors != null) { + + StringBuilder sb = new StringBuilder(); + logInfoExecutor(sb, reportExecutors, "ExecutorMetrics"); + EXE_LOGGER.info(sb.toString()); + } + } + + protected void logInfoExecutor( + StringBuilder sb0, Map reportExecutors, String info) { + sb0.append("\n").append(info).append(" >>>>>>>"); + StringBuilder sb = new StringBuilder(); + for (Iterator> i = reportExecutors.entrySet().iterator(); + i.hasNext(); ) { + Entry entry = i.next(); + String executorName = entry.getKey(); + + MetricRegistry metricRegistry = TaskMetrics.getInstance().getMetricRegistry(); + Map map = + metricRegistry.getGauges((name, value) -> name.startsWith(executorName)); + + String outterTreeSymbol = SYMBOLIC1; + if (!i.hasNext()) { + outterTreeSymbol = SYMBOLIC2; + } + sb.append(outterTreeSymbol).append(executorName); + map.forEach( + (key, gauge) -> { + String name = key.substring(executorName.length() + 1); + sb.append(", ").append(name).append(":").append(gauge.getValue()); + }); + sb.append("\n"); } + sb0.append("\n").append(sb); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/slot/SlotTableCache.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/slot/SlotTableCache.java index d596a7523..778d917a6 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/slot/SlotTableCache.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/slot/SlotTableCache.java @@ -20,26 +20,25 @@ import com.alipay.sofa.registry.common.model.slot.SlotTable; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-06 16:21 yuzhi.lyz Exp $ */ public interface SlotTableCache { - int slotOf(String dataInfoId); + int slotOf(String dataInfoId); - Slot getSlot(String dataInfoId); + Slot getSlot(String dataInfoId); - Slot getSlot(int slotId); + Slot getSlot(int slotId); - String getLeader(String dataInfoId); + String getLeader(String dataInfoId); - String getLeader(int slotId); + String getLeader(int slotId); - long getEpoch(); + long getEpoch(); - boolean updateSlotTable(SlotTable slotTable); + boolean updateSlotTable(SlotTable slotTable); - int slotNum(); + int slotNum(); - SlotTable currentSlotTable(); + SlotTable currentSlotTable(); } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/slot/SlotTableCacheImpl.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/slot/SlotTableCacheImpl.java index bb51c3d63..74bdfd628 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/slot/SlotTableCacheImpl.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/slot/SlotTableCacheImpl.java @@ -27,100 +27,101 @@ import com.alipay.sofa.registry.server.shared.slot.DiskSlotTableRecorder; import com.alipay.sofa.registry.server.shared.slot.SlotTableRecorder; import com.google.common.collect.Lists; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.util.List; +import javax.annotation.PostConstruct; import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; /** * @author yuzhi.lyz * @version v 0.1 2020-11-11 10:07 yuzhi.lyz Exp $ */ public final class SlotTableCacheImpl implements SlotTableCache { - private static final Logger LOGGER = LoggerFactory - .getLogger(SlotTableCacheImpl.class); - - private final SlotFunction slotFunction = SlotFunctionRegistry.getFunc(); - private volatile SlotTable slotTable = SlotTable.INIT; - - @Autowired - private SlotGenericResource slotGenericResource; - - private List recorders; - - @PostConstruct - public void init() { - recorders = Lists.newArrayList(slotGenericResource, new DiskSlotTableRecorder()); - } - - @Override - public int slotOf(String dataInfoId) { - return slotFunction.slotOf(dataInfoId); - } - - @Override - public Slot getSlot(String dataInfoId) { - int slotId = slotOf(dataInfoId); - return slotTable.getSlot(slotId); + private static final Logger LOGGER = LoggerFactory.getLogger(SlotTableCacheImpl.class); + + private final SlotFunction slotFunction = SlotFunctionRegistry.getFunc(); + private volatile SlotTable slotTable = SlotTable.INIT; + + @Autowired private SlotGenericResource slotGenericResource; + + private List recorders; + + @PostConstruct + public void init() { + recorders = Lists.newArrayList(slotGenericResource, new DiskSlotTableRecorder()); + } + + @Override + public int slotOf(String dataInfoId) { + return slotFunction.slotOf(dataInfoId); + } + + @Override + public Slot getSlot(String dataInfoId) { + int slotId = slotOf(dataInfoId); + return slotTable.getSlot(slotId); + } + + @Override + public Slot getSlot(int slotId) { + return slotTable.getSlot(slotId); + } + + @Override + public String getLeader(String dataInfoId) { + final Slot slot = getSlot(dataInfoId); + return slot == null ? null : slot.getLeader(); + } + + @Override + public String getLeader(int slotId) { + final Slot slot = slotTable.getSlot(slotId); + return slot == null ? null : slot.getLeader(); + } + + @Override + public long getEpoch() { + return slotTable.getEpoch(); + } + + @Override + public synchronized boolean updateSlotTable(SlotTable slotTable) { + final long curEpoch = this.slotTable.getEpoch(); + if (curEpoch >= slotTable.getEpoch()) { + LOGGER.info("skip update, current={}, update={}", curEpoch, slotTable.getEpoch()); + return false; } - - @Override - public Slot getSlot(int slotId) { - return slotTable.getSlot(slotId); - } - - @Override - public String getLeader(String dataInfoId) { - final Slot slot = getSlot(dataInfoId); - return slot == null ? null : slot.getLeader(); - } - - @Override - public String getLeader(int slotId) { - final Slot slot = slotTable.getSlot(slotId); - return slot == null ? null : slot.getLeader(); - } - - @Override - public long getEpoch() { - return slotTable.getEpoch(); + recordSlotTable(slotTable); + this.slotTable = slotTable; + for (Slot slot : this.slotTable.getSlots()) { + if (StringUtils.isBlank(slot.getLeader())) { + LOGGER.error("[NoLeader] {}", slot); + } } - - @Override - public synchronized boolean updateSlotTable(SlotTable slotTable) { - final long curEpoch = this.slotTable.getEpoch(); - if (curEpoch >= slotTable.getEpoch()) { - LOGGER.info("skip update, current={}, update={}", curEpoch, slotTable.getEpoch()); - return false; - } - recordSlotTable(slotTable); - this.slotTable = slotTable; - for (Slot slot : this.slotTable.getSlots()) { - if (StringUtils.isBlank(slot.getLeader())) { - LOGGER.error("[NoLeader] {}", slot); - } - } - LOGGER.info("updating slot table, expect={}, current={}, {}", slotTable.getEpoch(), - curEpoch, this.slotTable); - return true; - } - - private void recordSlotTable(SlotTable slotTable) { - recorders.forEach(recorder -> { - if(recorder != null) { - recorder.record(slotTable); - } + LOGGER.info( + "updating slot table, expect={}, current={}, {}", + slotTable.getEpoch(), + curEpoch, + this.slotTable); + return true; + } + + private void recordSlotTable(SlotTable slotTable) { + recorders.forEach( + recorder -> { + if (recorder != null) { + recorder.record(slotTable); + } }); - } + } - @Override - public int slotNum() { - return SlotConfig.SLOT_NUM; - } + @Override + public int slotNum() { + return SlotConfig.SLOT_NUM; + } - @Override - public SlotTable currentSlotTable() { - return new SlotTable(slotTable.getEpoch(), slotTable.getSlots()); - } + @Override + public SlotTable currentSlotTable() { + return new SlotTable(slotTable.getEpoch(), slotTable.getSlots()); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/AbstractDataManager.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/AbstractDataManager.java index 1a071a1e5..afc2b130c 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/AbstractDataManager.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/AbstractDataManager.java @@ -23,147 +23,145 @@ import com.alipay.sofa.registry.util.ParaCheckUtil; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.apache.commons.collections.MapUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.CollectionUtils; - import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.stream.Collectors; +import org.apache.commons.collections.MapUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-18 17:18 yuzhi.lyz Exp $ */ -public abstract class AbstractDataManager implements - DataManager { - private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); - protected final Lock read = readWriteLock - .readLock(); - protected final Lock write = readWriteLock - .writeLock(); - - protected final ConcurrentHashMap> stores = new ConcurrentHashMap<>(); - protected final Logger logger; - - @Autowired - protected SessionServerConfig sessionServerConfig; - - AbstractDataManager(Logger logger) { - this.logger = logger; +public abstract class AbstractDataManager + implements DataManager { + private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); + protected final Lock read = readWriteLock.readLock(); + protected final Lock write = readWriteLock.writeLock(); + + protected final ConcurrentHashMap> stores = + new ConcurrentHashMap<>(); + protected final Logger logger; + + @Autowired protected SessionServerConfig sessionServerConfig; + + AbstractDataManager(Logger logger) { + this.logger = logger; + } + + protected T addData(T data) { + Map dataMap = + stores.computeIfAbsent(data.getDataInfoId(), k -> Maps.newConcurrentMap()); + + T existing = dataMap.put(data.getRegisterId(), data); + return existing; + } + + @Override + public boolean deleteById(String registerId, String dataInfoId) { + Map dataMap = stores.get(dataInfoId); + if (CollectionUtils.isEmpty(dataMap)) { + logger.warn("Delete but not registered, {}", dataInfoId); + return false; } + T dataToDelete = dataMap.remove(registerId); - protected T addData(T data) { - Map dataMap = stores.computeIfAbsent(data.getDataInfoId(), - k -> Maps.newConcurrentMap()); - - T existing = dataMap.put(data.getRegisterId(), data); - return existing; + if (dataToDelete == null) { + logger.warn("Delete but not registered, {}, {}", dataInfoId, registerId); } - - @Override - public boolean deleteById(String registerId, String dataInfoId) { - Map dataMap = stores.get(dataInfoId); - if (CollectionUtils.isEmpty(dataMap)) { - logger.warn("Delete but not registered, {}", dataInfoId); - return false; + return dataToDelete != null; + } + + @Override + public Map deleteByConnectId(ConnectId connectId) { + Map ret = Maps.newHashMap(); + + for (Map map : stores.values()) { + // copy a map for iterate + for (Map.Entry e : Maps.newHashMap(map).entrySet()) { + final T data = e.getValue(); + if (connectId.equals(data.connectId())) { + // may be the value has removed by anther thread + if (map.remove(e.getKey(), data)) { + ret.put(e.getKey(), data); + } } - T dataToDelete = dataMap.remove(registerId); - - if (dataToDelete == null) { - logger.warn("Delete but not registered, {}, {}", dataInfoId, registerId); - } - return dataToDelete != null; - } - - @Override - public Map deleteByConnectId(ConnectId connectId) { - Map ret = Maps.newHashMap(); - - for (Map map : stores.values()) { - // copy a map for iterate - for (Map.Entry e : Maps.newHashMap(map).entrySet()) { - final T data = e.getValue(); - if (connectId.equals(data.connectId())) { - // may be the value has removed by anther thread - if (map.remove(e.getKey(), data)) { - ret.put(e.getKey(), data); - } - } - } - } - return ret; + } } - - @Override - public Collection getDatas(String dataInfoId) { - ParaCheckUtil.checkNotBlank(dataInfoId, "dataInfoId"); - Map dataMap = stores.get(dataInfoId); - if (MapUtils.isEmpty(dataMap)) { - return Collections.emptyList(); - } - return Lists.newArrayList(dataMap.values()); - } - - @Override - public Map> getDatas() { - return StoreHelpers.copyMap((Map) stores); + return ret; + } + + @Override + public Collection getDatas(String dataInfoId) { + ParaCheckUtil.checkNotBlank(dataInfoId, "dataInfoId"); + Map dataMap = stores.get(dataInfoId); + if (MapUtils.isEmpty(dataMap)) { + return Collections.emptyList(); } - - @Override - public List getDataList() { - List ret = new ArrayList<>(512); - for (Map store : stores.values()) { - ret.addAll(store.values()); - } - return ret; - } - - @Override - public Map queryByConnectId(ConnectId connectId) { - return StoreHelpers.getByConnectId(connectId, stores); - } - - @Override - public T queryById(String registerId, String dataInfoId) { - final Map datas = stores.get(dataInfoId); - return datas == null ? null : datas.get(registerId); - } - - @Override - public long count() { - return StoreHelpers.count(stores); - } - - @Override - public Set getConnectIds() { - return StoreHelpers.collectConnectIds(stores); - } - - @Override - public Set collectProcessIds() { - return StoreHelpers.collectProcessIds(stores); - } - - @Override - public Collection getDataInfoIds() { - return stores.entrySet().stream().filter(e -> !(e.getValue().isEmpty())).map(e -> e.getKey()) - .collect(Collectors.toSet()); - } - - public SessionServerConfig getSessionServerConfig() { - return sessionServerConfig; - } - - /** - * Setter method for property sessionServerConfig. - * - * @param sessionServerConfig value to be assigned to property sessionServerConfig - */ - public void setSessionServerConfig(SessionServerConfig sessionServerConfig) { - this.sessionServerConfig = sessionServerConfig; + return Lists.newArrayList(dataMap.values()); + } + + @Override + public Map> getDatas() { + return StoreHelpers.copyMap((Map) stores); + } + + @Override + public List getDataList() { + List ret = new ArrayList<>(512); + for (Map store : stores.values()) { + ret.addAll(store.values()); } + return ret; + } + + @Override + public Map queryByConnectId(ConnectId connectId) { + return StoreHelpers.getByConnectId(connectId, stores); + } + + @Override + public T queryById(String registerId, String dataInfoId) { + final Map datas = stores.get(dataInfoId); + return datas == null ? null : datas.get(registerId); + } + + @Override + public long count() { + return StoreHelpers.count(stores); + } + + @Override + public Set getConnectIds() { + return StoreHelpers.collectConnectIds(stores); + } + + @Override + public Set collectProcessIds() { + return StoreHelpers.collectProcessIds(stores); + } + + @Override + public Collection getDataInfoIds() { + return stores.entrySet().stream() + .filter(e -> !(e.getValue().isEmpty())) + .map(e -> e.getKey()) + .collect(Collectors.toSet()); + } + + public SessionServerConfig getSessionServerConfig() { + return sessionServerConfig; + } + + /** + * Setter method for property sessionServerConfig. + * + * @param sessionServerConfig value to be assigned to property sessionServerConfig + */ + public void setSessionServerConfig(SessionServerConfig sessionServerConfig) { + this.sessionServerConfig = sessionServerConfig; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/DataManager.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/DataManager.java index 628661b8f..5afc8ed66 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/DataManager.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/DataManager.java @@ -17,7 +17,6 @@ package com.alipay.sofa.registry.server.session.store; import com.alipay.sofa.registry.common.model.ConnectId; - import java.util.Collection; import java.util.List; import java.util.Map; @@ -26,66 +25,64 @@ /** * Session Data store manager,according base data function * - * Session Data struct + *

Session Data struct * - * - DataInfo ID - * | - * - Publisher List - * | - * - Subscriber List + *

- DataInfo ID | - Publisher List | - Subscriber List * * @author shangyu.wh * @version $Id: DataManager.java, v 0.1 2017-11-30 17:57 shangyu.wh Exp $ */ public interface DataManager { - /** - * new publisher and subscriber data add - * - * @param data - */ - boolean add(DATA data); + /** + * new publisher and subscriber data add + * + * @param data + */ + boolean add(DATA data); - /** - * query data by client node connectId - * - * @param connectId - * @return - */ - Map queryByConnectId(ConnectId connectId); + /** + * query data by client node connectId + * + * @param connectId + * @return + */ + Map queryByConnectId(ConnectId connectId); - /** - * remove data by client node connectId - * - * @param connectId - */ - Map deleteByConnectId(ConnectId connectId); + /** + * remove data by client node connectId + * + * @param connectId + */ + Map deleteByConnectId(ConnectId connectId); - DATA queryById(ID registerId, DATAINFOID dataInfoId); + DATA queryById(ID registerId, DATAINFOID dataInfoId); - /** - * remove single data by register id - * @param registerId - * @param dataInfoId - * @return - */ - boolean deleteById(ID registerId, DATAINFOID dataInfoId); + /** + * remove single data by register id + * + * @param registerId + * @param dataInfoId + * @return + */ + boolean deleteById(ID registerId, DATAINFOID dataInfoId); - /** - * count pub and sub number - * @return - */ - long count(); + /** + * count pub and sub number + * + * @return + */ + long count(); - Set getConnectIds(); + Set getConnectIds(); - Collection getDatas(DATAINFOID dataInfoId); + Collection getDatas(DATAINFOID dataInfoId); - List getDataList(); + List getDataList(); - Map> getDatas(); + Map> getDatas(); - Set collectProcessIds(); + Set collectProcessIds(); - Collection getDataInfoIds(); -} \ No newline at end of file + Collection getDataInfoIds(); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/DataStore.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/DataStore.java index 364730330..5236cefde 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/DataStore.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/DataStore.java @@ -17,15 +17,14 @@ package com.alipay.sofa.registry.server.session.store; import com.alipay.sofa.registry.common.model.store.Publisher; - import java.util.Map; /** - * * @author shangyu.wh * @version $Id: DataStore.java, v 0.1 2017-12-01 18:13 shangyu.wh Exp $ */ public interface DataStore extends DataManager { - Map> getDataInfoIdPublishers(int slotId); -} \ No newline at end of file + Map> getDataInfoIdPublishers( + int slotId); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/Interests.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/Interests.java index bb355a464..9909c3616 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/Interests.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/Interests.java @@ -18,7 +18,6 @@ import com.alipay.sofa.registry.common.model.dataserver.DatumVersion; import com.alipay.sofa.registry.common.model.store.Subscriber; - import java.util.Collection; import java.util.Map; @@ -28,31 +27,33 @@ */ public interface Interests extends DataManager { - /** - * check subscribers interest dataInfoId version,very dataCenter dataInfoId version different - * if return false - * else check return bigger version - * - * @param dataCenter - * @param datumDataInfoId - * @param version - * @return - */ - InterestVersionCheck checkInterestVersion(String dataCenter, String datumDataInfoId, - long version); - - Collection getInterests(String datumDataInfoId); - - Map getInterestVersions(String dataCenter); - - Collection getInterestsNeverPushed(); - - enum InterestVersionCheck { - NoSub(false), Obsolete(false), Interested(true), ; - public final boolean interested; - - private InterestVersionCheck(boolean Interested) { - this.interested = Interested; - } + /** + * check subscribers interest dataInfoId version,very dataCenter dataInfoId version different if + * return false else check return bigger version + * + * @param dataCenter + * @param datumDataInfoId + * @param version + * @return + */ + InterestVersionCheck checkInterestVersion( + String dataCenter, String datumDataInfoId, long version); + + Collection getInterests(String datumDataInfoId); + + Map getInterestVersions(String dataCenter); + + Collection getInterestsNeverPushed(); + + enum InterestVersionCheck { + NoSub(false), + Obsolete(false), + Interested(true), + ; + public final boolean interested; + + private InterestVersionCheck(boolean Interested) { + this.interested = Interested; } -} \ No newline at end of file + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionDataStore.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionDataStore.java index 16dfba3d6..03b179a98 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionDataStore.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionDataStore.java @@ -22,7 +22,6 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.util.ParaCheckUtil; import com.google.common.collect.Maps; - import java.util.Map; /** @@ -31,49 +30,51 @@ */ public class SessionDataStore extends AbstractDataManager implements DataStore { - private static final Logger LOGGER = LoggerFactory.getLogger(SessionDataStore.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SessionDataStore.class); - public SessionDataStore() { - super(LOGGER); - } + public SessionDataStore() { + super(LOGGER); + } - @Override - public boolean add(Publisher publisher) { - ParaCheckUtil.checkNotNull(publisher.getVersion(), "publisher.version"); - ParaCheckUtil.checkNotNull(publisher.getRegisterTimestamp(), "publisher.registerTimestamp"); + @Override + public boolean add(Publisher publisher) { + ParaCheckUtil.checkNotNull(publisher.getVersion(), "publisher.version"); + ParaCheckUtil.checkNotNull(publisher.getRegisterTimestamp(), "publisher.registerTimestamp"); - PublisherUtils.internPublisher(publisher); - Map publishers = stores.computeIfAbsent(publisher.getDataInfoId(), k -> Maps - .newConcurrentMap()); + PublisherUtils.internPublisher(publisher); + Map publishers = + stores.computeIfAbsent(publisher.getDataInfoId(), k -> Maps.newConcurrentMap()); - boolean toAdd = true; - Publisher existingPublisher = null; - write.lock(); - try { - existingPublisher = publishers.get(publisher.getRegisterId()); - if (existingPublisher != null) { - if (!existingPublisher.registerVersion().orderThan(publisher.registerVersion())) { - toAdd = false; - } - } - if (toAdd) { - publishers.put(publisher.getRegisterId(), publisher); - } - } finally { - write.unlock(); - } - // log without lock - if (existingPublisher != null && !toAdd) { - LOGGER.warn("conflict publisher {}, {}, exist={}, input={}", - publisher.getDataInfoId(), publisher.getRegisterId(), - existingPublisher.registerVersion(), publisher.registerVersion()); + boolean toAdd = true; + Publisher existingPublisher = null; + write.lock(); + try { + existingPublisher = publishers.get(publisher.getRegisterId()); + if (existingPublisher != null) { + if (!existingPublisher.registerVersion().orderThan(publisher.registerVersion())) { + toAdd = false; } - return toAdd; - + } + if (toAdd) { + publishers.put(publisher.getRegisterId(), publisher); + } + } finally { + write.unlock(); } - - @Override - public Map> getDataInfoIdPublishers(int slotId) { - throw new UnsupportedOperationException(); + // log without lock + if (existingPublisher != null && !toAdd) { + LOGGER.warn( + "conflict publisher {}, {}, exist={}, input={}", + publisher.getDataInfoId(), + publisher.getRegisterId(), + existingPublisher.registerVersion(), + publisher.registerVersion()); } -} \ No newline at end of file + return toAdd; + } + + @Override + public Map> getDataInfoIdPublishers(int slotId) { + throw new UnsupportedOperationException(); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionInterests.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionInterests.java index 6c6e91a18..a5d5a16e2 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionInterests.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionInterests.java @@ -23,12 +23,11 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.util.ParaCheckUtil; import com.google.common.collect.Maps; -import org.springframework.util.CollectionUtils; - import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; +import org.springframework.util.CollectionUtils; /** * @author shangyu.wh @@ -36,89 +35,93 @@ */ public class SessionInterests extends AbstractDataManager implements Interests { - private static final Logger LOGGER = LoggerFactory.getLogger(SessionInterests.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SessionInterests.class); - public SessionInterests() { - super(LOGGER); - } + public SessionInterests() { + super(LOGGER); + } - @Override - public boolean add(Subscriber subscriber) { - ParaCheckUtil.checkNotNull(subscriber.getScope(), "subscriber.scope"); - ParaCheckUtil.checkNotNull(subscriber.getClientVersion(), "subscriber.clientVersion"); + @Override + public boolean add(Subscriber subscriber) { + ParaCheckUtil.checkNotNull(subscriber.getScope(), "subscriber.scope"); + ParaCheckUtil.checkNotNull(subscriber.getClientVersion(), "subscriber.clientVersion"); - Subscriber.internSubscriber(subscriber); + Subscriber.internSubscriber(subscriber); - Subscriber existingSubscriber = addData(subscriber); + Subscriber existingSubscriber = addData(subscriber); - if (existingSubscriber != null) { - LOGGER.warn("dups subscriber, {}, {}, exist={}/{}, input={}/{}", - existingSubscriber.getDataInfoId(), existingSubscriber.getRegisterId(), - // not use get registerVersion, avoid the subscriber.version is null - existingSubscriber.getVersion(), existingSubscriber.getRegisterTimestamp(), - subscriber.getVersion(), existingSubscriber.getRegisterTimestamp()); - } - return true; + if (existingSubscriber != null) { + LOGGER.warn( + "dups subscriber, {}, {}, exist={}/{}, input={}/{}", + existingSubscriber.getDataInfoId(), + existingSubscriber.getRegisterId(), + // not use get registerVersion, avoid the subscriber.version is null + existingSubscriber.getVersion(), + existingSubscriber.getRegisterTimestamp(), + subscriber.getVersion(), + existingSubscriber.getRegisterTimestamp()); } + return true; + } - @Override - public InterestVersionCheck checkInterestVersion(String dataCenter, String datumDataInfoId, - long version) { - Collection subscribers = getInterests(datumDataInfoId); - if (CollectionUtils.isEmpty(subscribers)) { - return InterestVersionCheck.NoSub; - } - for (Subscriber subscriber : subscribers) { - if (subscriber.checkVersion(dataCenter, version)) { - return InterestVersionCheck.Interested; - } - } - return InterestVersionCheck.Obsolete; + @Override + public InterestVersionCheck checkInterestVersion( + String dataCenter, String datumDataInfoId, long version) { + Collection subscribers = getInterests(datumDataInfoId); + if (CollectionUtils.isEmpty(subscribers)) { + return InterestVersionCheck.NoSub; } - - @Override - public Collection getInterests(String datumDataInfoId) { - return getDatas(datumDataInfoId); + for (Subscriber subscriber : subscribers) { + if (subscriber.checkVersion(dataCenter, version)) { + return InterestVersionCheck.Interested; + } } + return InterestVersionCheck.Obsolete; + } - @Override - public Map getInterestVersions(String dataCenter) { - final Map ret = Maps.newHashMapWithExpectedSize(stores.size()); - final String localDataCenter = sessionServerConfig.getSessionServerDataCenter(); - final boolean isLocalDataCenter = localDataCenter.equals(dataCenter); - for (Map.Entry> e : stores.entrySet()) { - Map subs = e.getValue(); - if (subs.isEmpty()) { - continue; - } - final String dataInfoId = e.getKey(); - long maxVersion = 0; - for (Subscriber sub : subs.values()) { - // not global sub and not local dataCenter, not interest the other dataCenter's pub - if (sub.getScope() != ScopeEnum.global && !isLocalDataCenter) { - continue; - } - final long pushVersion = sub.getPushVersion(dataCenter); - if (maxVersion < pushVersion) { - maxVersion = pushVersion; - } - } - ret.put(dataInfoId, new DatumVersion(maxVersion)); - } + @Override + public Collection getInterests(String datumDataInfoId) { + return getDatas(datumDataInfoId); + } - return ret; + @Override + public Map getInterestVersions(String dataCenter) { + final Map ret = Maps.newHashMapWithExpectedSize(stores.size()); + final String localDataCenter = sessionServerConfig.getSessionServerDataCenter(); + final boolean isLocalDataCenter = localDataCenter.equals(dataCenter); + for (Map.Entry> e : stores.entrySet()) { + Map subs = e.getValue(); + if (subs.isEmpty()) { + continue; + } + final String dataInfoId = e.getKey(); + long maxVersion = 0; + for (Subscriber sub : subs.values()) { + // not global sub and not local dataCenter, not interest the other dataCenter's pub + if (sub.getScope() != ScopeEnum.global && !isLocalDataCenter) { + continue; + } + final long pushVersion = sub.getPushVersion(dataCenter); + if (maxVersion < pushVersion) { + maxVersion = pushVersion; + } + } + ret.put(dataInfoId, new DatumVersion(maxVersion)); } - @Override - public Collection getInterestsNeverPushed() { - List subscribers = new ArrayList<>(512); - for (Map e : stores.values()) { - for (Subscriber subscriber : e.values()) { - if (!subscriber.hasPushed()) { - subscribers.add(subscriber); - } - } + return ret; + } + + @Override + public Collection getInterestsNeverPushed() { + List subscribers = new ArrayList<>(512); + for (Map e : stores.values()) { + for (Subscriber subscriber : e.values()) { + if (!subscriber.hasPushed()) { + subscribers.add(subscriber); } - return subscribers; + } } -} \ No newline at end of file + return subscribers; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionWatchers.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionWatchers.java index 2312cbf62..0e5f213c4 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionWatchers.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SessionWatchers.java @@ -20,56 +20,58 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.util.VersionsMapUtils; -import org.apache.commons.collections.MapUtils; - import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.apache.commons.collections.MapUtils; /** * @author shangyu.wh * @version $Id: SessionWatchers.java, v 0.1 2018-04-17 19:00 shangyu.wh Exp $ */ public class SessionWatchers extends AbstractDataManager implements Watchers { - private static final Logger LOGGER = LoggerFactory.getLogger(SessionWatchers.class); + private static final Logger LOGGER = LoggerFactory.getLogger(SessionWatchers.class); - public SessionWatchers() { - super(LOGGER); - } + public SessionWatchers() { + super(LOGGER); + } - /** - * store watcher dataInfo version - */ - private ConcurrentHashMap watcherVersions = new ConcurrentHashMap<>(); + /** store watcher dataInfo version */ + private ConcurrentHashMap watcherVersions = + new ConcurrentHashMap<>(); - @Override - public boolean add(Watcher watcher) { - Watcher.internWatcher(watcher); + @Override + public boolean add(Watcher watcher) { + Watcher.internWatcher(watcher); - Watcher existingWatcher = addData(watcher); - if (existingWatcher != null) { - LOGGER.warn("dups watcher, {}, {}, exist={}/{}, input={}/{}", - existingWatcher.getDataInfoId(), existingWatcher.getRegisterId(), - // not use get registerVersion, avoid the subscriber.version is null - existingWatcher.getVersion(), existingWatcher.getRegisterTimestamp(), - watcher.getVersion(), watcher.getRegisterTimestamp()); - } - return true; + Watcher existingWatcher = addData(watcher); + if (existingWatcher != null) { + LOGGER.warn( + "dups watcher, {}, {}, exist={}/{}, input={}/{}", + existingWatcher.getDataInfoId(), + existingWatcher.getRegisterId(), + // not use get registerVersion, avoid the subscriber.version is null + existingWatcher.getVersion(), + existingWatcher.getRegisterTimestamp(), + watcher.getVersion(), + watcher.getRegisterTimestamp()); } + return true; + } - @Override - public boolean checkWatcherVersions(String dataInfoId, Long version) { - read.lock(); - try { - Map watcherMap = stores.get(dataInfoId); - if (MapUtils.isEmpty(watcherMap)) { - LOGGER.info("There are not Watcher Existed! Who are interest with dataInfoId {} !", - dataInfoId); - return false; - } + @Override + public boolean checkWatcherVersions(String dataInfoId, Long version) { + read.lock(); + try { + Map watcherMap = stores.get(dataInfoId); + if (MapUtils.isEmpty(watcherMap)) { + LOGGER.info( + "There are not Watcher Existed! Who are interest with dataInfoId {} !", dataInfoId); + return false; + } - return VersionsMapUtils.checkAndUpdateVersions(watcherVersions, dataInfoId, version); - } finally { - read.unlock(); - } + return VersionsMapUtils.checkAndUpdateVersions(watcherVersions, dataInfoId, version); + } finally { + read.unlock(); } -} \ No newline at end of file + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SlotSessionDataStore.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SlotSessionDataStore.java index e3256b383..5b48d541e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SlotSessionDataStore.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/SlotSessionDataStore.java @@ -20,132 +20,139 @@ import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.server.session.slot.SlotTableCache; import com.google.common.collect.Maps; +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; import org.glassfish.jersey.internal.guava.Sets; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.CollectionUtils; -import java.util.*; -import java.util.concurrent.ConcurrentHashMap; - /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-06 16:24 yuzhi.lyz Exp $ */ public class SlotSessionDataStore implements DataStore { - @Autowired - private SlotTableCache slotTableCache; - - private final Map slot2DataStores = new ConcurrentHashMap<>(); - - private DataStore getOrCreateDataStore(String dataInfoId) { - int slotId = slotTableCache.slotOf(dataInfoId); - return slot2DataStores.computeIfAbsent(slotId, k -> new SessionDataStore()); - } - - @Override - public Collection getDatas(String dataInfoId) { - DataStore ds = getOrCreateDataStore(dataInfoId); - return ds.getDatas(dataInfoId); - } - - @Override - public List getDataList() { - List ret = new ArrayList<>(2048); - slot2DataStores.values().forEach(ds -> { - ret.addAll(ds.getDataList()); - }); - return ret; - } - - @Override - public Publisher queryById(String registerId, String dataInfoId) { - DataStore ds = getOrCreateDataStore(dataInfoId); - return ds.queryById(registerId, dataInfoId); - } - - @Override - public Collection getDataInfoIds() { - Set set = new HashSet<>(128); - slot2DataStores.values().forEach(ds -> { - set.addAll(ds.getDataInfoIds()); - }); - return set; + @Autowired private SlotTableCache slotTableCache; + + private final Map slot2DataStores = new ConcurrentHashMap<>(); + + private DataStore getOrCreateDataStore(String dataInfoId) { + int slotId = slotTableCache.slotOf(dataInfoId); + return slot2DataStores.computeIfAbsent(slotId, k -> new SessionDataStore()); + } + + @Override + public Collection getDatas(String dataInfoId) { + DataStore ds = getOrCreateDataStore(dataInfoId); + return ds.getDatas(dataInfoId); + } + + @Override + public List getDataList() { + List ret = new ArrayList<>(2048); + slot2DataStores + .values() + .forEach( + ds -> { + ret.addAll(ds.getDataList()); + }); + return ret; + } + + @Override + public Publisher queryById(String registerId, String dataInfoId) { + DataStore ds = getOrCreateDataStore(dataInfoId); + return ds.queryById(registerId, dataInfoId); + } + + @Override + public Collection getDataInfoIds() { + Set set = new HashSet<>(128); + slot2DataStores + .values() + .forEach( + ds -> { + set.addAll(ds.getDataInfoIds()); + }); + return set; + } + + @Override + public Set getConnectIds() { + Set ret = Sets.newHashSet(); + slot2DataStores.values().forEach(d -> ret.addAll(d.getConnectIds())); + return ret; + } + + @Override + public Set collectProcessIds() { + Set ret = Sets.newHashSet(); + slot2DataStores.values().forEach(d -> ret.addAll(d.collectProcessIds())); + return ret; + } + + @Override + public Map> getDatas() { + Map> ret = new HashMap<>(512); + for (DataStore ds : slot2DataStores.values()) { + Map> m = ds.getDatas(); + for (Map.Entry> e : m.entrySet()) { + Map publisherMap = + ret.computeIfAbsent(e.getKey(), k -> new HashMap<>(128)); + publisherMap.putAll(e.getValue()); + } } - - @Override - public Set getConnectIds() { - Set ret = Sets.newHashSet(); - slot2DataStores.values().forEach(d -> ret.addAll(d.getConnectIds())); - return ret; - } - - @Override - public Set collectProcessIds() { - Set ret = Sets.newHashSet(); - slot2DataStores.values().forEach(d -> ret.addAll(d.collectProcessIds())); - return ret; - } - - @Override - public Map> getDatas() { - Map> ret = new HashMap<>(512); - for (DataStore ds : slot2DataStores.values()) { - Map> m = ds.getDatas(); - for (Map.Entry> e : m.entrySet()) { - Map publisherMap = ret.computeIfAbsent(e.getKey(), k -> new HashMap<>(128)); - publisherMap.putAll(e.getValue()); - } - } - return ret; - } - - @Override - public Map> getDataInfoIdPublishers(int slotId) { - DataStore ds = slot2DataStores.computeIfAbsent(slotId, k -> new SessionDataStore()); - return ds.getDatas(); - } - - @Override - public boolean add(Publisher publisher) { - DataStore ds = getOrCreateDataStore(publisher.getDataInfoId()); - return ds.add(publisher); - } - - @Override - public boolean deleteById(String registerId, String dataInfoId) { - DataStore ds = getOrCreateDataStore(dataInfoId); - return ds.deleteById(registerId, dataInfoId); - } - - @Override - public Map queryByConnectId(ConnectId connectId) { - Map ret = new HashMap<>(128); - slot2DataStores.values().forEach(ds -> { - Map m = ds.queryByConnectId(connectId); - if (!CollectionUtils.isEmpty(m)) { + return ret; + } + + @Override + public Map> getDataInfoIdPublishers(int slotId) { + DataStore ds = slot2DataStores.computeIfAbsent(slotId, k -> new SessionDataStore()); + return ds.getDatas(); + } + + @Override + public boolean add(Publisher publisher) { + DataStore ds = getOrCreateDataStore(publisher.getDataInfoId()); + return ds.add(publisher); + } + + @Override + public boolean deleteById(String registerId, String dataInfoId) { + DataStore ds = getOrCreateDataStore(dataInfoId); + return ds.deleteById(registerId, dataInfoId); + } + + @Override + public Map queryByConnectId(ConnectId connectId) { + Map ret = new HashMap<>(128); + slot2DataStores + .values() + .forEach( + ds -> { + Map m = ds.queryByConnectId(connectId); + if (!CollectionUtils.isEmpty(m)) { ret.putAll(m); - } - }); - return ret; - } - - @Override - public Map deleteByConnectId(ConnectId connectId) { - Map ret = Maps.newHashMap(); - for (DataStore ds : slot2DataStores.values()) { - ret.putAll(ds.deleteByConnectId(connectId)); - } - return ret; + } + }); + return ret; + } + + @Override + public Map deleteByConnectId(ConnectId connectId) { + Map ret = Maps.newHashMap(); + for (DataStore ds : slot2DataStores.values()) { + ret.putAll(ds.deleteByConnectId(connectId)); } - - @Override - public long count() { - long count = 0; - for (DataStore ds : slot2DataStores.values()) { - count += ds.count(); - } - return count; + return ret; + } + + @Override + public long count() { + long count = 0; + for (DataStore ds : slot2DataStores.values()) { + count += ds.count(); } + return count; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/StoreHelpers.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/StoreHelpers.java index 5fb6ed6d4..600869e72 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/StoreHelpers.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/StoreHelpers.java @@ -20,74 +20,77 @@ import com.alipay.sofa.registry.common.model.store.BaseInfo; import com.google.common.collect.Maps; import com.google.common.collect.Sets; - import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-18 16:42 yuzhi.lyz Exp $ */ public final class StoreHelpers { - private StoreHelpers() { - } + private StoreHelpers() {} - public static Set collectConnectId(Map map) { - Set sets = Sets.newHashSet(); - map.values().forEach(r -> sets.add(r.connectId())); - return sets; - } + public static Set collectConnectId(Map map) { + Set sets = Sets.newHashSet(); + map.values().forEach(r -> sets.add(r.connectId())); + return sets; + } - public static Set collectConnectIds(Map> maps) { - Set sets = Sets.newHashSet(); - maps.values().forEach(m -> sets.addAll(collectConnectId(m))); - return sets; - } + public static Set collectConnectIds( + Map> maps) { + Set sets = Sets.newHashSet(); + maps.values().forEach(m -> sets.addAll(collectConnectId(m))); + return sets; + } - public static long count(Map> maps) { - long count = 0; - for (Map map : maps.values()) { - count += map.size(); - } - return count; + public static long count(Map> maps) { + long count = 0; + for (Map map : maps.values()) { + count += map.size(); } + return count; + } - public static Map getByConnectId(ConnectId connectId, - Map> maps) { - Map retMap = Maps.newHashMap(); - maps.values().forEach(m -> { - m.values().forEach(r -> { - if (connectId.equals(r.connectId())) { - retMap.put(r.getRegisterId(), r); - } + public static Map getByConnectId( + ConnectId connectId, Map> maps) { + Map retMap = Maps.newHashMap(); + maps.values() + .forEach( + m -> { + m.values() + .forEach( + r -> { + if (connectId.equals(r.connectId())) { + retMap.put(r.getRegisterId(), r); + } + }); }); - }); - return retMap; - } + return retMap; + } - public static Set collectProcessIds(Map> maps) { - HashSet processIds = Sets.newHashSet(); - for (Map map : maps.values()) { - for (T t : map.values()) { - if (t.getProcessId() != null) { - processIds.add(t.getProcessId()); - } - } + public static Set collectProcessIds( + Map> maps) { + HashSet processIds = Sets.newHashSet(); + for (Map map : maps.values()) { + for (T t : map.values()) { + if (t.getProcessId() != null) { + processIds.add(t.getProcessId()); } - return processIds; + } } + return processIds; + } - public static Map copyMap(Map m) { - Map ret = new HashMap<>(m.size()); - for (Map.Entry e : m.entrySet()) { - if (!e.getValue().isEmpty()) { - ret.put(e.getKey(), new HashMap<>(e.getValue())); - } - } - return ret; + public static Map copyMap(Map m) { + Map ret = new HashMap<>(m.size()); + for (Map.Entry e : m.entrySet()) { + if (!e.getValue().isEmpty()) { + ret.put(e.getKey(), new HashMap<>(e.getValue())); + } } + return ret; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/Watchers.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/Watchers.java index d4423e35a..6a65097d5 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/Watchers.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/store/Watchers.java @@ -19,21 +19,17 @@ import com.alipay.sofa.registry.common.model.store.Watcher; /** - * * @author shangyu.wh * @version $Id: SessionInterests.java, v 0.1 2017-11-30 15:53 shangyu.wh Exp $ */ public interface Watchers extends DataManager { - /** - * check watchers interest dataInfoId version - * if not exist add - * else check and update bigger one - * - * @param dataInfoId - * @param version - * @return - */ - boolean checkWatcherVersions(String dataInfoId, Long version); - -} \ No newline at end of file + /** + * check watchers interest dataInfoId version if not exist add else check and update bigger one + * + * @param dataInfoId + * @param version + * @return + */ + boolean checkWatcherVersions(String dataInfoId, Long version); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/AppRevisionHandlerStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/AppRevisionHandlerStrategy.java index 3dee979f6..f6f4172c3 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/AppRevisionHandlerStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/AppRevisionHandlerStrategy.java @@ -25,31 +25,35 @@ public interface AppRevisionHandlerStrategy { - /** - * appRevision register - * @param appRevision - * @param response - */ - void handleAppRevisionRegister(AppRevision appRevision, RegisterResponse response); + /** + * appRevision register + * + * @param appRevision + * @param response + */ + void handleAppRevisionRegister(AppRevision appRevision, RegisterResponse response); - /** - * query apps by services - * @param services - * @return - */ - ServiceAppMappingResponse queryApps(List services); + /** + * query apps by services + * + * @param services + * @return + */ + ServiceAppMappingResponse queryApps(List services); - /** - * query appRevision - * @param revisions - * @return - */ - GetRevisionsResponse queryRevision(List revisions); + /** + * query appRevision + * + * @param revisions + * @return + */ + GetRevisionsResponse queryRevision(List revisions); - /** - * revision heartbeat - * @param revisions - * @return - */ - MetaHeartbeatResponse heartbeat(List revisions); + /** + * revision heartbeat + * + * @param revisions + * @return + */ + MetaHeartbeatResponse heartbeat(List revisions); } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/DefaultAppRevisionHandlerStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/DefaultAppRevisionHandlerStrategy.java index 00c7246f8..cb373ded2 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/DefaultAppRevisionHandlerStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/DefaultAppRevisionHandlerStrategy.java @@ -29,113 +29,108 @@ import com.alipay.sofa.registry.server.session.converter.pb.AppRevisionConvertor; import com.alipay.sofa.registry.server.session.metadata.AppRevisionCacheRegistry; import com.alipay.sofa.registry.server.session.metadata.AppRevisionHeartbeatRegistry; -import org.apache.commons.lang.StringUtils; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.ArrayList; import java.util.List; import java.util.Optional; +import org.apache.commons.lang.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; public class DefaultAppRevisionHandlerStrategy implements AppRevisionHandlerStrategy { - private static final Logger LOG = LoggerFactory - .getLogger(DefaultAppRevisionHandlerStrategy.class); + private static final Logger LOG = + LoggerFactory.getLogger(DefaultAppRevisionHandlerStrategy.class); - @Autowired - private AppRevisionCacheRegistry appRevisionCacheService; + @Autowired private AppRevisionCacheRegistry appRevisionCacheService; - @Autowired - private AppRevisionHeartbeatRegistry appRevisionHeartbeatRegistry; + @Autowired private AppRevisionHeartbeatRegistry appRevisionHeartbeatRegistry; - @Override - public void handleAppRevisionRegister(AppRevision appRevision, RegisterResponse response) { - try { - validate(appRevision); - appRevisionCacheService.register(appRevision); - response.setSuccess(true); - response.setMessage("app revision register success!"); - } catch (Throwable e) { - response.setSuccess(false); - response.setMessage("app revision register failed!"); - LOG.error("app revision register error.", e); - } + @Override + public void handleAppRevisionRegister(AppRevision appRevision, RegisterResponse response) { + try { + validate(appRevision); + appRevisionCacheService.register(appRevision); + response.setSuccess(true); + response.setMessage("app revision register success!"); + } catch (Throwable e) { + response.setSuccess(false); + response.setMessage("app revision register failed!"); + LOG.error("app revision register error.", e); } + } - @Override - public ServiceAppMappingResponse queryApps(List services) { - ServiceAppMappingResponse.Builder builder = ServiceAppMappingResponse.newBuilder(); + @Override + public ServiceAppMappingResponse queryApps(List services) { + ServiceAppMappingResponse.Builder builder = ServiceAppMappingResponse.newBuilder(); - int statusCode = ValueConstants.METADATA_STATUS_PROCESS_SUCCESS; - try { - for (String service : Optional.ofNullable(services).orElse(new ArrayList<>())) { - InterfaceMapping appNames = appRevisionCacheService.getAppNames(service); - AppList.Builder build = AppList.newBuilder().addAllApps(appNames.getApps()); - build.setVersion(appNames.getNanosVersion()); - builder.putServiceAppMapping(service, build.build()); - } - } catch (Throwable e) { - statusCode = ValueConstants.METADATA_STATUS_PROCESS_ERROR; - builder.setMessage(String - .format("query apps by services error. service: %s.", services)); - LOG.error(String.format("query apps by services error. service: %s", services), e); - - } - builder.setStatusCode(statusCode); - return builder.build(); + int statusCode = ValueConstants.METADATA_STATUS_PROCESS_SUCCESS; + try { + for (String service : Optional.ofNullable(services).orElse(new ArrayList<>())) { + InterfaceMapping appNames = appRevisionCacheService.getAppNames(service); + AppList.Builder build = AppList.newBuilder().addAllApps(appNames.getApps()); + build.setVersion(appNames.getNanosVersion()); + builder.putServiceAppMapping(service, build.build()); + } + } catch (Throwable e) { + statusCode = ValueConstants.METADATA_STATUS_PROCESS_ERROR; + builder.setMessage(String.format("query apps by services error. service: %s.", services)); + LOG.error(String.format("query apps by services error. service: %s", services), e); } + builder.setStatusCode(statusCode); + return builder.build(); + } - @Override - public GetRevisionsResponse queryRevision(List revisions) { - GetRevisionsResponse.Builder builder = GetRevisionsResponse.newBuilder(); - int statusCode = ValueConstants.METADATA_STATUS_PROCESS_SUCCESS; - try { - for (String revision : Optional.ofNullable(revisions).orElse(new ArrayList<>())) { - AppRevision appRevision = appRevisionCacheService.getRevision(revision); - if (appRevision == null) { - statusCode = ValueConstants.METADATA_STATUS_DATA_NOT_FOUND; - builder.setMessage(String.format("query revision: %s fail.", revision)); - LOG.error("query revision {} fail", revision); - } - builder.putRevisions(revision, AppRevisionConvertor.convert2Pb(appRevision)); - } - } catch (Throwable e) { - statusCode = ValueConstants.METADATA_STATUS_PROCESS_ERROR; - builder.setMessage(String.format("query revisions: %s error.", revisions)); - LOG.error("query revision {} error", revisions, e); + @Override + public GetRevisionsResponse queryRevision(List revisions) { + GetRevisionsResponse.Builder builder = GetRevisionsResponse.newBuilder(); + int statusCode = ValueConstants.METADATA_STATUS_PROCESS_SUCCESS; + try { + for (String revision : Optional.ofNullable(revisions).orElse(new ArrayList<>())) { + AppRevision appRevision = appRevisionCacheService.getRevision(revision); + if (appRevision == null) { + statusCode = ValueConstants.METADATA_STATUS_DATA_NOT_FOUND; + builder.setMessage(String.format("query revision: %s fail.", revision)); + LOG.error("query revision {} fail", revision); } - builder.setStatusCode(statusCode); - return builder.build(); + builder.putRevisions(revision, AppRevisionConvertor.convert2Pb(appRevision)); + } + } catch (Throwable e) { + statusCode = ValueConstants.METADATA_STATUS_PROCESS_ERROR; + builder.setMessage(String.format("query revisions: %s error.", revisions)); + LOG.error("query revision {} error", revisions, e); } + builder.setStatusCode(statusCode); + return builder.build(); + } - @Override - public MetaHeartbeatResponse heartbeat(List revisions) { + @Override + public MetaHeartbeatResponse heartbeat(List revisions) { - MetaHeartbeatResponse.Builder builder = MetaHeartbeatResponse.newBuilder(); - int statusCode = ValueConstants.METADATA_STATUS_PROCESS_SUCCESS; - try { - for (String revision : Optional.ofNullable(revisions).orElse(new ArrayList<>())) { - AppRevision appRevision = appRevisionHeartbeatRegistry.heartbeat(revision); - if (appRevision == null) { - statusCode = ValueConstants.METADATA_STATUS_DATA_NOT_FOUND; - builder.setMessage(String.format("revision: %s heartbeat fail.", revision)); - LOG.error("revision heartbeat {} fail", revision); - } - } - } catch (Throwable e) { - statusCode = ValueConstants.METADATA_STATUS_PROCESS_ERROR; - builder.setMessage(String.format("revisions: %s heartbeat error.", revisions)); - LOG.error("revision heartbeat {} error", revisions, e); + MetaHeartbeatResponse.Builder builder = MetaHeartbeatResponse.newBuilder(); + int statusCode = ValueConstants.METADATA_STATUS_PROCESS_SUCCESS; + try { + for (String revision : Optional.ofNullable(revisions).orElse(new ArrayList<>())) { + AppRevision appRevision = appRevisionHeartbeatRegistry.heartbeat(revision); + if (appRevision == null) { + statusCode = ValueConstants.METADATA_STATUS_DATA_NOT_FOUND; + builder.setMessage(String.format("revision: %s heartbeat fail.", revision)); + LOG.error("revision heartbeat {} fail", revision); } - builder.setStatusCode(statusCode); - return builder.build(); + } + } catch (Throwable e) { + statusCode = ValueConstants.METADATA_STATUS_PROCESS_ERROR; + builder.setMessage(String.format("revisions: %s heartbeat error.", revisions)); + LOG.error("revision heartbeat {} error", revisions, e); } + builder.setStatusCode(statusCode); + return builder.build(); + } - private void validate(AppRevision appRevision) { - if (StringUtils.isBlank(appRevision.getAppName())) { - throw new IllegalArgumentException("register appName is empty"); - } - if (StringUtils.isBlank(appRevision.getRevision())) { - throw new IllegalArgumentException("register revision is empty"); - } + private void validate(AppRevision appRevision) { + if (StringUtils.isBlank(appRevision.getAppName())) { + throw new IllegalArgumentException("register appName is empty"); + } + if (StringUtils.isBlank(appRevision.getRevision())) { + throw new IllegalArgumentException("register revision is empty"); } -} \ No newline at end of file + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/PublisherHandlerStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/PublisherHandlerStrategy.java index ce0325b45..88821cd9a 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/PublisherHandlerStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/PublisherHandlerStrategy.java @@ -25,7 +25,6 @@ * @since 2019/2/15 */ public interface PublisherHandlerStrategy { - void handlePublisherRegister(Channel channel, - PublisherRegister publisherRegister, - RegisterResponse registerResponse); + void handlePublisherRegister( + Channel channel, PublisherRegister publisherRegister, RegisterResponse registerResponse); } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/ReceivedConfigDataPushTaskStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/ReceivedConfigDataPushTaskStrategy.java index bd0cf0640..24cfc3cd7 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/ReceivedConfigDataPushTaskStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/ReceivedConfigDataPushTaskStrategy.java @@ -24,5 +24,5 @@ * @since 2019/1/4 */ public interface ReceivedConfigDataPushTaskStrategy { - Object convert2PushData(ReceivedConfigData receivedConfigData, URL url); + Object convert2PushData(ReceivedConfigData receivedConfigData, URL url); } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SessionRegistryStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SessionRegistryStrategy.java index 268256c6e..2ab2cc1e3 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SessionRegistryStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SessionRegistryStrategy.java @@ -26,15 +26,15 @@ */ public interface SessionRegistryStrategy { - void afterPublisherRegister(Publisher publisher); + void afterPublisherRegister(Publisher publisher); - void afterSubscriberRegister(Subscriber subscriber); + void afterSubscriberRegister(Subscriber subscriber); - void afterWatcherRegister(Watcher watcher); + void afterWatcherRegister(Watcher watcher); - void afterPublisherUnRegister(Publisher publisher); + void afterPublisherUnRegister(Publisher publisher); - void afterSubscriberUnRegister(Subscriber subscriber); + void afterSubscriberUnRegister(Subscriber subscriber); - void afterWatcherUnRegister(Watcher watcher); + void afterWatcherUnRegister(Watcher watcher); } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SubscriberHandlerStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SubscriberHandlerStrategy.java index d3a219368..35c0bcd07 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SubscriberHandlerStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SubscriberHandlerStrategy.java @@ -25,7 +25,6 @@ * @since 2019/2/15 */ public interface SubscriberHandlerStrategy { - void handleSubscriberRegister(Channel channel, - SubscriberRegister subscriberRegister, - RegisterResponse registerResponse); + void handleSubscriberRegister( + Channel channel, SubscriberRegister subscriberRegister, RegisterResponse registerResponse); } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SyncConfigHandlerStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SyncConfigHandlerStrategy.java index 7c96acf7a..d8862f4e7 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SyncConfigHandlerStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/SyncConfigHandlerStrategy.java @@ -23,5 +23,5 @@ * @since 2019/2/15 */ public interface SyncConfigHandlerStrategy { - void handleSyncConfigResponse(SyncConfigResponse syncConfigResponse); + void handleSyncConfigResponse(SyncConfigResponse syncConfigResponse); } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/WatcherHandlerStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/WatcherHandlerStrategy.java index fca03a1af..23d99a243 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/WatcherHandlerStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/WatcherHandlerStrategy.java @@ -25,7 +25,8 @@ * @since 2019/2/15 */ public interface WatcherHandlerStrategy { - void handleConfiguratorRegister(Channel channel, - ConfiguratorRegister configuratorRegister, - RegisterResponse registerResponse); + void handleConfiguratorRegister( + Channel channel, + ConfiguratorRegister configuratorRegister, + RegisterResponse registerResponse); } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultPublisherHandlerStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultPublisherHandlerStrategy.java index ca701ec25..7cf8ac999 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultPublisherHandlerStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultPublisherHandlerStrategy.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.session.strategy.impl; +import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; + import com.alipay.sofa.registry.common.model.constants.ValueConstants; import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.common.model.store.URL; @@ -31,78 +33,88 @@ import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; -import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; - /** * @author xuanbei * @since 2019/2/15 */ public class DefaultPublisherHandlerStrategy implements PublisherHandlerStrategy { - private static final Logger PUB_LOGGER = LoggerFactory.getLogger("PUB-RECEIVE"); - @Autowired - private Registry sessionRegistry; + private static final Logger PUB_LOGGER = LoggerFactory.getLogger("PUB-RECEIVE"); + @Autowired private Registry sessionRegistry; - @Override - public void handlePublisherRegister(Channel channel, PublisherRegister publisherRegister, - RegisterResponse registerResponse) { - Publisher publisher = null; - try { - String ip = channel.getRemoteAddress().getAddress().getHostAddress(); - int port = channel.getRemoteAddress().getPort(); - publisherRegister.setIp(ip); - publisherRegister.setPort(port); + @Override + public void handlePublisherRegister( + Channel channel, PublisherRegister publisherRegister, RegisterResponse registerResponse) { + Publisher publisher = null; + try { + String ip = channel.getRemoteAddress().getAddress().getHostAddress(); + int port = channel.getRemoteAddress().getPort(); + publisherRegister.setIp(ip); + publisherRegister.setPort(port); - if (StringUtils.isBlank(publisherRegister.getZone())) { - publisherRegister.setZone(ValueConstants.DEFAULT_ZONE); - } + if (StringUtils.isBlank(publisherRegister.getZone())) { + publisherRegister.setZone(ValueConstants.DEFAULT_ZONE); + } - if (StringUtils.isBlank(publisherRegister.getInstanceId())) { - publisherRegister.setInstanceId(DEFAULT_INSTANCE_ID); - } + if (StringUtils.isBlank(publisherRegister.getInstanceId())) { + publisherRegister.setInstanceId(DEFAULT_INSTANCE_ID); + } - publisher = PublisherConverter.convert(publisherRegister); - publisher.setProcessId(ip + ":" + port); + publisher = PublisherConverter.convert(publisherRegister); + publisher.setProcessId(ip + ":" + port); - handle(publisher, channel, publisherRegister, registerResponse); - } catch (Throwable e) { - handleError(publisherRegister, publisher, registerResponse, e); - } + handle(publisher, channel, publisherRegister, registerResponse); + } catch (Throwable e) { + handleError(publisherRegister, publisher, registerResponse, e); } + } - protected void handle(Publisher publisher, Channel channel, - PublisherRegister publisherRegister, RegisterResponse registerResponse) { - publisher.setSourceAddress(new URL(channel.getRemoteAddress())); - publisher.setTargetAddress(new URL(channel.getLocalAddress())); - final String eventType = publisherRegister.getEventType(); - if (EventTypeConstants.REGISTER.equals(eventType)) { - sessionRegistry.register(publisher); - } else if (EventTypeConstants.UNREGISTER.equals(eventType)) { - sessionRegistry.unRegister(publisher); - } else { - RegisterLogs.REGISTER_LOGGER.warn("unsupported publisher.eventType:{}", eventType); - } - registerResponse.setSuccess(true); - registerResponse.setVersion(publisher.getVersion()); - registerResponse.setRegistId(publisherRegister.getRegistId()); - registerResponse.setMessage("Publisher register success!"); - log(true, publisherRegister, publisher); + protected void handle( + Publisher publisher, + Channel channel, + PublisherRegister publisherRegister, + RegisterResponse registerResponse) { + publisher.setSourceAddress(new URL(channel.getRemoteAddress())); + publisher.setTargetAddress(new URL(channel.getLocalAddress())); + final String eventType = publisherRegister.getEventType(); + if (EventTypeConstants.REGISTER.equals(eventType)) { + sessionRegistry.register(publisher); + } else if (EventTypeConstants.UNREGISTER.equals(eventType)) { + sessionRegistry.unRegister(publisher); + } else { + RegisterLogs.REGISTER_LOGGER.warn("unsupported publisher.eventType:{}", eventType); } + registerResponse.setSuccess(true); + registerResponse.setVersion(publisher.getVersion()); + registerResponse.setRegistId(publisherRegister.getRegistId()); + registerResponse.setMessage("Publisher register success!"); + log(true, publisherRegister, publisher); + } - private void log(boolean success, PublisherRegister publisherRegister, Publisher publisher) { - //[Y|N],[R|U|N],app,zone,dataInfoId,registerId,version,registerTimestamp,clientVersion,clientIp,clientPort - PUB_LOGGER.info("{},{},{},{},{},{},{},{},{},{},{},{},{}", success ? 'Y' : 'N', - EventTypeConstants.getEventTypeFlag(publisherRegister.getEventType()), - publisherRegister.getAppName(), publisherRegister.getZone(), publisherRegister - .getDataId(), publisherRegister.getGroup(), publisherRegister.getInstanceId(), - publisherRegister.getRegistId(), publisherRegister.getVersion(), publisher == null ? "" - : publisher.getRegisterTimestamp(), - publisher == null ? "" : publisher.getClientVersion(), publisherRegister.getIp(), - publisherRegister.getPort()); - } + private void log(boolean success, PublisherRegister publisherRegister, Publisher publisher) { + // [Y|N],[R|U|N],app,zone,dataInfoId,registerId,version,registerTimestamp,clientVersion,clientIp,clientPort + PUB_LOGGER.info( + "{},{},{},{},{},{},{},{},{},{},{},{},{}", + success ? 'Y' : 'N', + EventTypeConstants.getEventTypeFlag(publisherRegister.getEventType()), + publisherRegister.getAppName(), + publisherRegister.getZone(), + publisherRegister.getDataId(), + publisherRegister.getGroup(), + publisherRegister.getInstanceId(), + publisherRegister.getRegistId(), + publisherRegister.getVersion(), + publisher == null ? "" : publisher.getRegisterTimestamp(), + publisher == null ? "" : publisher.getClientVersion(), + publisherRegister.getIp(), + publisherRegister.getPort()); + } - protected void handleError(PublisherRegister publisherRegister, Publisher publisher, - RegisterResponse registerResponse, Throwable e) { - log(false, publisherRegister, publisher); - RegisterLogs.logError(publisherRegister, "Publisher", registerResponse, e); - } + protected void handleError( + PublisherRegister publisherRegister, + Publisher publisher, + RegisterResponse registerResponse, + Throwable e) { + log(false, publisherRegister, publisher); + RegisterLogs.logError(publisherRegister, "Publisher", registerResponse, e); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultReceivedConfigDataPushTaskStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultReceivedConfigDataPushTaskStrategy.java index e37219ac8..1c191021e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultReceivedConfigDataPushTaskStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultReceivedConfigDataPushTaskStrategy.java @@ -25,13 +25,13 @@ * @author xuanbei * @since 2019/1/4 */ -public class DefaultReceivedConfigDataPushTaskStrategy implements - ReceivedConfigDataPushTaskStrategy { - @Override - public Object convert2PushData(ReceivedConfigData receivedConfigData, URL url) { - if (url.getSerializerIndex() != null && URL.PROTOBUF == url.getSerializerIndex()) { - return ReceivedDataConvertor.convert2Pb(receivedConfigData); - } - return receivedConfigData; +public class DefaultReceivedConfigDataPushTaskStrategy + implements ReceivedConfigDataPushTaskStrategy { + @Override + public Object convert2PushData(ReceivedConfigData receivedConfigData, URL url) { + if (url.getSerializerIndex() != null && URL.PROTOBUF == url.getSerializerIndex()) { + return ReceivedDataConvertor.convert2Pb(receivedConfigData); } + return receivedConfigData; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSessionRegistryStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSessionRegistryStrategy.java index 289434ce6..be9a4056e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSessionRegistryStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSessionRegistryStrategy.java @@ -16,18 +16,17 @@ */ package com.alipay.sofa.registry.server.session.strategy.impl; -import com.alipay.sofa.registry.server.session.push.FirePushService; -import org.springframework.beans.factory.annotation.Autowired; - import com.alipay.sofa.registry.common.model.store.Publisher; import com.alipay.sofa.registry.common.model.store.Subscriber; import com.alipay.sofa.registry.common.model.store.Watcher; import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig; +import com.alipay.sofa.registry.server.session.push.FirePushService; import com.alipay.sofa.registry.server.session.strategy.SessionRegistryStrategy; import com.alipay.sofa.registry.task.listener.TaskEvent; import com.alipay.sofa.registry.task.listener.TaskListenerManager; +import org.springframework.beans.factory.annotation.Autowired; /** * @author kezhu.wukz @@ -35,57 +34,44 @@ * @since 2019/2/15 */ public class DefaultSessionRegistryStrategy implements SessionRegistryStrategy { - private static final Logger taskLogger = LoggerFactory.getLogger( - DefaultSessionRegistryStrategy.class, "[Task]"); + private static final Logger taskLogger = + LoggerFactory.getLogger(DefaultSessionRegistryStrategy.class, "[Task]"); - /** - * trigger task com.alipay.sofa.registry.server.meta.listener process - */ - @Autowired - private TaskListenerManager taskListenerManager; + /** trigger task com.alipay.sofa.registry.server.meta.listener process */ + @Autowired private TaskListenerManager taskListenerManager; - @Autowired - private FirePushService firePushService; + @Autowired private FirePushService firePushService; - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Override - public void afterPublisherRegister(Publisher publisher) { + @Override + public void afterPublisherRegister(Publisher publisher) {} + @Override + public void afterSubscriberRegister(Subscriber subscriber) { + if (!sessionServerConfig.isStopPushSwitch()) { + firePushService.fireOnRegister(subscriber); } + } - @Override - public void afterSubscriberRegister(Subscriber subscriber) { - if (!sessionServerConfig.isStopPushSwitch()) { - firePushService.fireOnRegister(subscriber); - } - } + @Override + public void afterWatcherRegister(Watcher watcher) { + fireWatcherRegisterFetchTask(watcher); + } - @Override - public void afterWatcherRegister(Watcher watcher) { - fireWatcherRegisterFetchTask(watcher); - } + @Override + public void afterPublisherUnRegister(Publisher publisher) {} - @Override - public void afterPublisherUnRegister(Publisher publisher) { + @Override + public void afterSubscriberUnRegister(Subscriber subscriber) {} - } + @Override + public void afterWatcherUnRegister(Watcher watcher) {} - @Override - public void afterSubscriberUnRegister(Subscriber subscriber) { - - } - - @Override - public void afterWatcherUnRegister(Watcher watcher) { - - } - - private void fireWatcherRegisterFetchTask(Watcher watcher) { - //trigger fetch data for watcher,and push to client node - TaskEvent taskEvent = new TaskEvent(watcher, TaskEvent.TaskType.WATCHER_REGISTER_FETCH_TASK); - taskLogger.info("send " + taskEvent.getTaskType() + " taskEvent:{}", taskEvent); - taskListenerManager.sendTaskEvent(taskEvent); - } + private void fireWatcherRegisterFetchTask(Watcher watcher) { + // trigger fetch data for watcher,and push to client node + TaskEvent taskEvent = new TaskEvent(watcher, TaskEvent.TaskType.WATCHER_REGISTER_FETCH_TASK); + taskLogger.info("send " + taskEvent.getTaskType() + " taskEvent:{}", taskEvent); + taskListenerManager.sendTaskEvent(taskEvent); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSubscriberHandlerStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSubscriberHandlerStrategy.java index 99d3b84a5..b16be7c47 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSubscriberHandlerStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSubscriberHandlerStrategy.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.session.strategy.impl; +import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; + import com.alipay.sofa.registry.common.model.constants.ValueConstants; import com.alipay.sofa.registry.common.model.store.Subscriber; import com.alipay.sofa.registry.common.model.store.URL; @@ -32,81 +34,91 @@ import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; -import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; - /** * @author xuanbei * @since 2019/2/15 */ public class DefaultSubscriberHandlerStrategy implements SubscriberHandlerStrategy { - private static final Logger SUB_LOGGER = LoggerFactory.getLogger("SUB-RECEIVE"); + private static final Logger SUB_LOGGER = LoggerFactory.getLogger("SUB-RECEIVE"); - @Autowired - private Registry sessionRegistry; + @Autowired private Registry sessionRegistry; - @Override - public void handleSubscriberRegister(Channel channel, SubscriberRegister subscriberRegister, - RegisterResponse registerResponse) { - Subscriber subscriber = null; - try { - String ip = channel.getRemoteAddress().getAddress().getHostAddress(); - int port = channel.getRemoteAddress().getPort(); - subscriberRegister.setIp(ip); - subscriberRegister.setPort(port); + @Override + public void handleSubscriberRegister( + Channel channel, SubscriberRegister subscriberRegister, RegisterResponse registerResponse) { + Subscriber subscriber = null; + try { + String ip = channel.getRemoteAddress().getAddress().getHostAddress(); + int port = channel.getRemoteAddress().getPort(); + subscriberRegister.setIp(ip); + subscriberRegister.setPort(port); - if (StringUtils.isBlank(subscriberRegister.getZone())) { - subscriberRegister.setZone(ValueConstants.DEFAULT_ZONE); - } + if (StringUtils.isBlank(subscriberRegister.getZone())) { + subscriberRegister.setZone(ValueConstants.DEFAULT_ZONE); + } - if (StringUtils.isBlank(subscriberRegister.getInstanceId())) { - subscriberRegister.setInstanceId(DEFAULT_INSTANCE_ID); - } + if (StringUtils.isBlank(subscriberRegister.getInstanceId())) { + subscriberRegister.setInstanceId(DEFAULT_INSTANCE_ID); + } - subscriber = SubscriberConverter.convert(subscriberRegister); - subscriber.setProcessId(ip + ":" + port); + subscriber = SubscriberConverter.convert(subscriberRegister); + subscriber.setProcessId(ip + ":" + port); - handle(subscriber, channel, subscriberRegister, registerResponse); - } catch (Throwable e) { - handleError(subscriberRegister, subscriber, registerResponse, e); - } + handle(subscriber, channel, subscriberRegister, registerResponse); + } catch (Throwable e) { + handleError(subscriberRegister, subscriber, registerResponse, e); } + } - protected void handle(Subscriber subscriber, Channel channel, - SubscriberRegister subscriberRegister, RegisterResponse registerResponse) { - subscriber.setSourceAddress(new URL(channel.getRemoteAddress(), BoltChannelUtil - .getBoltCustomSerializer(channel))); - subscriber.setTargetAddress(new URL(channel.getLocalAddress())); + protected void handle( + Subscriber subscriber, + Channel channel, + SubscriberRegister subscriberRegister, + RegisterResponse registerResponse) { + subscriber.setSourceAddress( + new URL(channel.getRemoteAddress(), BoltChannelUtil.getBoltCustomSerializer(channel))); + subscriber.setTargetAddress(new URL(channel.getLocalAddress())); - final String eventType = subscriberRegister.getEventType(); - if (EventTypeConstants.REGISTER.equals(eventType)) { - sessionRegistry.register(subscriber); - } else if (EventTypeConstants.UNREGISTER.equals(eventType)) { - sessionRegistry.unRegister(subscriber); - } else { - RegisterLogs.REGISTER_LOGGER.warn("unsupported subscriber.eventType:{}", eventType); - } - registerResponse.setVersion(subscriberRegister.getVersion()); - registerResponse.setRegistId(subscriberRegister.getRegistId()); - registerResponse.setSuccess(true); - registerResponse.setMessage("Subscriber register success!"); - log(true, subscriberRegister, subscriber); + final String eventType = subscriberRegister.getEventType(); + if (EventTypeConstants.REGISTER.equals(eventType)) { + sessionRegistry.register(subscriber); + } else if (EventTypeConstants.UNREGISTER.equals(eventType)) { + sessionRegistry.unRegister(subscriber); + } else { + RegisterLogs.REGISTER_LOGGER.warn("unsupported subscriber.eventType:{}", eventType); } + registerResponse.setVersion(subscriberRegister.getVersion()); + registerResponse.setRegistId(subscriberRegister.getRegistId()); + registerResponse.setSuccess(true); + registerResponse.setMessage("Subscriber register success!"); + log(true, subscriberRegister, subscriber); + } - private void log(boolean success, SubscriberRegister subscriberRegister, Subscriber subscriber) { - //[Y|N],[R|U|N],app,zone,dataInfoId,registerId,scope,elementType,clientVersion,clientIp,clientPort - SUB_LOGGER.info("{},{},{},{},{},{},{},{},{},{},{},{},{}", success ? 'Y' : 'N', - EventTypeConstants.getEventTypeFlag(subscriberRegister.getEventType()), - subscriberRegister.getAppName(), subscriberRegister.getZone(), - subscriberRegister.getDataId(), subscriberRegister.getGroup(), - subscriberRegister.getInstanceId(), subscriberRegister.getRegistId(), - subscriberRegister.getScope(), subscriber == null ? "" : subscriber.getElementType(), - subscriber == null ? "" : subscriber.getClientVersion(), subscriberRegister.getIp(), - subscriberRegister.getPort()); - } + private void log(boolean success, SubscriberRegister subscriberRegister, Subscriber subscriber) { + // [Y|N],[R|U|N],app,zone,dataInfoId,registerId,scope,elementType,clientVersion,clientIp,clientPort + SUB_LOGGER.info( + "{},{},{},{},{},{},{},{},{},{},{},{},{}", + success ? 'Y' : 'N', + EventTypeConstants.getEventTypeFlag(subscriberRegister.getEventType()), + subscriberRegister.getAppName(), + subscriberRegister.getZone(), + subscriberRegister.getDataId(), + subscriberRegister.getGroup(), + subscriberRegister.getInstanceId(), + subscriberRegister.getRegistId(), + subscriberRegister.getScope(), + subscriber == null ? "" : subscriber.getElementType(), + subscriber == null ? "" : subscriber.getClientVersion(), + subscriberRegister.getIp(), + subscriberRegister.getPort()); + } - protected void handleError(SubscriberRegister subscriberRegister, Subscriber subscriber, - RegisterResponse registerResponse, Throwable e) { - log(false, subscriberRegister, subscriber); - RegisterLogs.logError(subscriberRegister, "Subscriber", registerResponse, e); - } + protected void handleError( + SubscriberRegister subscriberRegister, + Subscriber subscriber, + RegisterResponse registerResponse, + Throwable e) { + log(false, subscriberRegister, subscriber); + RegisterLogs.logError(subscriberRegister, "Subscriber", registerResponse, e); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSyncConfigHandlerStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSyncConfigHandlerStrategy.java index bac43a754..3ec23189c 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSyncConfigHandlerStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultSyncConfigHandlerStrategy.java @@ -19,7 +19,6 @@ import com.alipay.sofa.registry.common.model.constants.ValueConstants; import com.alipay.sofa.registry.core.model.SyncConfigResponse; import com.alipay.sofa.registry.server.session.strategy.SyncConfigHandlerStrategy; - import java.util.ArrayList; import java.util.List; @@ -28,10 +27,10 @@ * @since 2019/2/15 */ public class DefaultSyncConfigHandlerStrategy implements SyncConfigHandlerStrategy { - @Override - public void handleSyncConfigResponse(SyncConfigResponse syncConfigResponse) { - List list = new ArrayList<>(); - list.add(ValueConstants.DEFAULT_DATA_CENTER); - syncConfigResponse.setAvailableSegments(list); - } + @Override + public void handleSyncConfigResponse(SyncConfigResponse syncConfigResponse) { + List list = new ArrayList<>(); + list.add(ValueConstants.DEFAULT_DATA_CENTER); + syncConfigResponse.setAvailableSegments(list); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultWatcherHandlerStrategy.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultWatcherHandlerStrategy.java index 74a1a4070..b1c78360d 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultWatcherHandlerStrategy.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/DefaultWatcherHandlerStrategy.java @@ -16,6 +16,8 @@ */ package com.alipay.sofa.registry.server.session.strategy.impl; +import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; + import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.common.model.store.Watcher; import com.alipay.sofa.registry.core.constants.EventTypeConstants; @@ -31,76 +33,86 @@ import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; -import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; - /** * @author xuanbei * @since 2019/2/15 */ public class DefaultWatcherHandlerStrategy implements WatcherHandlerStrategy { - private static final Logger WATCH_LOGGER = LoggerFactory.getLogger("WATCH-RECEIVE"); + private static final Logger WATCH_LOGGER = LoggerFactory.getLogger("WATCH-RECEIVE"); - @Autowired - private Registry sessionRegistry; + @Autowired private Registry sessionRegistry; - @Override - public void handleConfiguratorRegister(Channel channel, - ConfiguratorRegister configuratorRegister, - RegisterResponse registerResponse) { - Watcher watcher = null; - try { - configuratorRegister.setIp(channel.getRemoteAddress().getAddress().getHostAddress()); - configuratorRegister.setPort(channel.getRemoteAddress().getPort()); + @Override + public void handleConfiguratorRegister( + Channel channel, + ConfiguratorRegister configuratorRegister, + RegisterResponse registerResponse) { + Watcher watcher = null; + try { + configuratorRegister.setIp(channel.getRemoteAddress().getAddress().getHostAddress()); + configuratorRegister.setPort(channel.getRemoteAddress().getPort()); - if (StringUtils.isBlank(configuratorRegister.getInstanceId())) { - configuratorRegister.setInstanceId(DEFAULT_INSTANCE_ID); - } + if (StringUtils.isBlank(configuratorRegister.getInstanceId())) { + configuratorRegister.setInstanceId(DEFAULT_INSTANCE_ID); + } - watcher = SubscriberConverter.convert(configuratorRegister); - watcher.setProcessId(channel.getRemoteAddress().getHostName() + ":" - + channel.getRemoteAddress().getPort()); + watcher = SubscriberConverter.convert(configuratorRegister); + watcher.setProcessId( + channel.getRemoteAddress().getHostName() + ":" + channel.getRemoteAddress().getPort()); - handle(watcher, channel, configuratorRegister, registerResponse); - } catch (Throwable e) { - handleError(configuratorRegister, watcher, registerResponse, e); - } + handle(watcher, channel, configuratorRegister, registerResponse); + } catch (Throwable e) { + handleError(configuratorRegister, watcher, registerResponse, e); } + } - protected void handle(Watcher watcher, Channel channel, ConfiguratorRegister register, - RegisterResponse registerResponse) { - watcher.setSourceAddress(new URL(channel.getRemoteAddress(), BoltChannelUtil - .getBoltCustomSerializer(channel))); - watcher.setTargetAddress(new URL(channel.getLocalAddress())); + protected void handle( + Watcher watcher, + Channel channel, + ConfiguratorRegister register, + RegisterResponse registerResponse) { + watcher.setSourceAddress( + new URL(channel.getRemoteAddress(), BoltChannelUtil.getBoltCustomSerializer(channel))); + watcher.setTargetAddress(new URL(channel.getLocalAddress())); - final String eventType = register.getEventType(); - if (EventTypeConstants.REGISTER.equals(eventType)) { - sessionRegistry.register(watcher); - } else if (EventTypeConstants.UNREGISTER.equals(eventType)) { - sessionRegistry.unRegister(watcher); - } else { - RegisterLogs.REGISTER_LOGGER.warn("unsupported watch.eventType:{}", eventType); - } - registerResponse.setVersion(register.getVersion()); - registerResponse.setRegistId(register.getRegistId()); - registerResponse.setSuccess(true); - registerResponse.setMessage("ConfiguratorRegister register success!"); - log(true, register, watcher); + final String eventType = register.getEventType(); + if (EventTypeConstants.REGISTER.equals(eventType)) { + sessionRegistry.register(watcher); + } else if (EventTypeConstants.UNREGISTER.equals(eventType)) { + sessionRegistry.unRegister(watcher); + } else { + RegisterLogs.REGISTER_LOGGER.warn("unsupported watch.eventType:{}", eventType); } + registerResponse.setVersion(register.getVersion()); + registerResponse.setRegistId(register.getRegistId()); + registerResponse.setSuccess(true); + registerResponse.setMessage("ConfiguratorRegister register success!"); + log(true, register, watcher); + } - private void log(boolean success, ConfiguratorRegister register, Watcher watcher) { - //[Y|N],[R|U|N],app,zone,dataInfoId,registerId,clientVersion,clientIp,clientPort - WATCH_LOGGER - .info("{},{},{},{},{},{},{},{},{},{},{}", success ? 'Y' : 'N', - EventTypeConstants.getEventTypeFlag(register.getEventType()), - register.getAppName(), register.getZone(), register.getDataId(), - register.getGroup(), register.getInstanceId(), register.getRegistId(), - watcher == null ? "" : watcher.getClientVersion(), register.getIp(), - register.getPort()); - } + private void log(boolean success, ConfiguratorRegister register, Watcher watcher) { + // [Y|N],[R|U|N],app,zone,dataInfoId,registerId,clientVersion,clientIp,clientPort + WATCH_LOGGER.info( + "{},{},{},{},{},{},{},{},{},{},{}", + success ? 'Y' : 'N', + EventTypeConstants.getEventTypeFlag(register.getEventType()), + register.getAppName(), + register.getZone(), + register.getDataId(), + register.getGroup(), + register.getInstanceId(), + register.getRegistId(), + watcher == null ? "" : watcher.getClientVersion(), + register.getIp(), + register.getPort()); + } - protected void handleError(ConfiguratorRegister register, Watcher watcher, - RegisterResponse registerResponse, Throwable e) { - log(false, register, watcher); - RegisterLogs.logError(register, "Watcher", registerResponse, e); - } + protected void handleError( + ConfiguratorRegister register, + Watcher watcher, + RegisterResponse registerResponse, + Throwable e) { + log(false, register, watcher); + RegisterLogs.logError(register, "Watcher", registerResponse, e); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/RegisterLogs.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/RegisterLogs.java index 33edca513..6cf63c6a8 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/RegisterLogs.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/strategy/impl/RegisterLogs.java @@ -23,24 +23,19 @@ import com.alipay.sofa.registry.remoting.exchange.RequestChannelClosedException; public final class RegisterLogs { - public static final Logger REGISTER_LOGGER = LoggerFactory - .getLogger("REGISTER"); + public static final Logger REGISTER_LOGGER = LoggerFactory.getLogger("REGISTER"); - private RegisterLogs() { - } - - public static void logError(BaseRegister register, String name, - RegisterResponse registerResponse, Throwable e) { - if (e instanceof RequestChannelClosedException) { - REGISTER_LOGGER.warn("{} register error, Type {}, {}", name, - register.getEventType(), e.getMessage()); - } else { - REGISTER_LOGGER.error("{} register error, Type {}", name, - register.getEventType(), e); - } - registerResponse.setSuccess(false); - registerResponse.setMessage(name + " register failed!Type:" - + register.getEventType()); - } + private RegisterLogs() {} + public static void logError( + BaseRegister register, String name, RegisterResponse registerResponse, Throwable e) { + if (e instanceof RequestChannelClosedException) { + REGISTER_LOGGER.warn( + "{} register error, Type {}, {}", name, register.getEventType(), e.getMessage()); + } else { + REGISTER_LOGGER.error("{} register error, Type {}", name, register.getEventType(), e); + } + registerResponse.setSuccess(false); + registerResponse.setMessage(name + " register failed!Type:" + register.getEventType()); + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/AccessLimitWrapperInterceptor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/AccessLimitWrapperInterceptor.java index 4c6c136a4..630d42a12 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/AccessLimitWrapperInterceptor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/AccessLimitWrapperInterceptor.java @@ -22,32 +22,31 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author shangyu.wh * @version 1.0: AccessLimitWrapperInterceptor.java, v 0.1 2019-08-26 20:29 shangyu.wh Exp $ */ public class AccessLimitWrapperInterceptor implements WrapperInterceptor { - @Autowired - private AccessLimitService accessLimitService; - - @Override - public Boolean invokeCodeWrapper(WrapperInvocation invocation) - throws Exception { + @Autowired private AccessLimitService accessLimitService; - BaseInfo baseInfo = (BaseInfo) invocation.getParameterSupplier().get(); + @Override + public Boolean invokeCodeWrapper(WrapperInvocation invocation) + throws Exception { - if (!accessLimitService.tryAcquire()) { - throw new RuntimeException(String.format( - "Register access limit for session server!dataInfoId=%s,connectId=%s", - baseInfo.getDataInfoId(), baseInfo.getSourceAddress())); - } + BaseInfo baseInfo = (BaseInfo) invocation.getParameterSupplier().get(); - return invocation.proceed(); + if (!accessLimitService.tryAcquire()) { + throw new RuntimeException( + String.format( + "Register access limit for session server!dataInfoId=%s,connectId=%s", + baseInfo.getDataInfoId(), baseInfo.getSourceAddress())); } - @Override - public int getOrder() { - return 0; - } -} \ No newline at end of file + return invocation.proceed(); + } + + @Override + public int getOrder() { + return 0; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/BlacklistWrapperInterceptor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/BlacklistWrapperInterceptor.java index 044865504..1be797230 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/BlacklistWrapperInterceptor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/BlacklistWrapperInterceptor.java @@ -32,41 +32,37 @@ */ public class BlacklistWrapperInterceptor implements WrapperInterceptor { - @Autowired - private FirePushService firePushService; - /** - * blacklist filter - */ - @Autowired - private ProcessFilter processFilter; + @Autowired private FirePushService firePushService; + /** blacklist filter */ + @Autowired private ProcessFilter processFilter; - @Override - public Boolean invokeCodeWrapper(WrapperInvocation invocation) - throws Exception { + @Override + public Boolean invokeCodeWrapper(WrapperInvocation invocation) + throws Exception { - BaseInfo storeData = (BaseInfo) invocation.getParameterSupplier().get(); + BaseInfo storeData = (BaseInfo) invocation.getParameterSupplier().get(); - if (processFilter.match(storeData)) { - if (DataType.PUBLISHER == storeData.getDataType()) { - // match blacklist stop pub. - return true; - } + if (processFilter.match(storeData)) { + if (DataType.PUBLISHER == storeData.getDataType()) { + // match blacklist stop pub. + return true; + } - if (DataType.SUBSCRIBER == storeData.getDataType()) { - fireSubscriberPushEmptyTask((Subscriber) storeData); - return true; - } - } - return invocation.proceed(); + if (DataType.SUBSCRIBER == storeData.getDataType()) { + fireSubscriberPushEmptyTask((Subscriber) storeData); + return true; + } } + return invocation.proceed(); + } - @Override - public int getOrder() { - return 200; - } + @Override + public int getOrder() { + return 200; + } - private void fireSubscriberPushEmptyTask(Subscriber subscriber) { - //trigger empty data push - firePushService.fireOnPushEmpty(subscriber); - } -} \ No newline at end of file + private void fireSubscriberPushEmptyTask(Subscriber subscriber) { + // trigger empty data push + firePushService.fireOnPushEmpty(subscriber); + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/ClientCheckWrapperInterceptor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/ClientCheckWrapperInterceptor.java index bd0797e1f..ae27e482e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/ClientCheckWrapperInterceptor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/ClientCheckWrapperInterceptor.java @@ -33,31 +33,29 @@ */ public class ClientCheckWrapperInterceptor implements WrapperInterceptor { - @Autowired - private SessionServerConfig sessionServerConfig; + @Autowired private SessionServerConfig sessionServerConfig; - @Autowired - private Exchange boltExchange; + @Autowired private Exchange boltExchange; - @Override - public Boolean invokeCodeWrapper(WrapperInvocation invocation) - throws Exception { + @Override + public Boolean invokeCodeWrapper(WrapperInvocation invocation) + throws Exception { - BaseInfo baseInfo = (BaseInfo) invocation.getParameterSupplier().get(); + BaseInfo baseInfo = (BaseInfo) invocation.getParameterSupplier().get(); - Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort()); + Server sessionServer = boltExchange.getServer(sessionServerConfig.getServerPort()); - Channel channel = sessionServer.getChannel(baseInfo.getSourceAddress()); + Channel channel = sessionServer.getChannel(baseInfo.getSourceAddress()); - if (channel == null) { - throw new RequestChannelClosedException(String.format( - "Register address %s channel closed", baseInfo.getSourceAddress())); - } - return invocation.proceed(); + if (channel == null) { + throw new RequestChannelClosedException( + String.format("Register address %s channel closed", baseInfo.getSourceAddress())); } - - @Override - public int getOrder() { - return 100; - } -} \ No newline at end of file + return invocation.proceed(); + } + + @Override + public int getOrder() { + return 100; + } +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/Wrapper.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/Wrapper.java index 19090af52..61240701e 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/Wrapper.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/Wrapper.java @@ -19,13 +19,12 @@ import java.util.function.Supplier; /** - * * @author shangyu.wh * @version 1.0: Wrapper.java, v 0.1 2019-06-18 19:33 shangyu.wh Exp $ */ public interface Wrapper { - R call(); + R call(); - Supplier getParameterSupplier(); -} \ No newline at end of file + Supplier getParameterSupplier(); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInterceptor.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInterceptor.java index f23478ffe..6b8a18168 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInterceptor.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInterceptor.java @@ -17,24 +17,24 @@ package com.alipay.sofa.registry.server.session.wrapper; /** - * * @author shangyu.wh * @version 1.0: WrapperInterceptor.java, v 0.1 2019-06-18 11:45 shangyu.wh Exp $ */ public interface WrapperInterceptor { - /** - * invoke inside function - * - * @param invocation - * @return - * @throws Exception - */ - R invokeCodeWrapper(WrapperInvocation invocation) throws Exception; + /** + * invoke inside function + * + * @param invocation + * @return + * @throws Exception + */ + R invokeCodeWrapper(WrapperInvocation invocation) throws Exception; - /** - * Interceptor order - * @return - */ - int getOrder(); -} \ No newline at end of file + /** + * Interceptor order + * + * @return + */ + int getOrder(); +} diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInterceptorManager.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInterceptorManager.java index 009f6876f..e4860b4ca 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInterceptorManager.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInterceptorManager.java @@ -21,50 +21,53 @@ import java.util.concurrent.CopyOnWriteArrayList; /** - * * @author shangyu.wh * @version 1.0: WrapperInterceptorManager.java, v 0.1 2019-06-18 14:51 shangyu.wh Exp $ */ public class WrapperInterceptorManager { - private List interceptorChain = new CopyOnWriteArrayList<>(); - - public int addInterceptor(WrapperInterceptor item){ - // The index of the search key, if it is contained in the list; otherwise, (-(insertion point) - 1) - final int index = Collections.binarySearch(interceptorChain, item, - (o1, o2) -> { - if (o1 == null && o2 == null) { - return 0; - } else if (o1 == null) { - return 1; - } else if (o2 == null) { - return -1; - } + private List interceptorChain = new CopyOnWriteArrayList<>(); - if (o1.getOrder() < o2.getOrder()) { - return -1; - } else if (o1.getOrder() > o2.getOrder()) { - return 1; - } - return 0; - }); - final int insertAt; - if (index < 0) { - insertAt = -(index + 1); - } else { - insertAt = index + 1; - } + public int addInterceptor(WrapperInterceptor item) { + // The index of the search key, if it is contained in the list; otherwise, (-(insertion point) - + // 1) + final int index = + Collections.binarySearch( + interceptorChain, + item, + (o1, o2) -> { + if (o1 == null && o2 == null) { + return 0; + } else if (o1 == null) { + return 1; + } else if (o2 == null) { + return -1; + } - interceptorChain.add(insertAt, item); - return insertAt; + if (o1.getOrder() < o2.getOrder()) { + return -1; + } else if (o1.getOrder() > o2.getOrder()) { + return 1; + } + return 0; + }); + final int insertAt; + if (index < 0) { + insertAt = -(index + 1); + } else { + insertAt = index + 1; } - /** - * Getter method for property interceptorChain. - * - * @return property value of interceptorChain - */ - public List getInterceptorChain() { - return interceptorChain; - } + interceptorChain.add(insertAt, item); + return insertAt; + } + + /** + * Getter method for property interceptorChain. + * + * @return property value of interceptorChain + */ + public List getInterceptorChain() { + return interceptorChain; + } } diff --git a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInvocation.java b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInvocation.java index 7a736944f..f90aee1f8 100644 --- a/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInvocation.java +++ b/server/server/session/src/main/java/com/alipay/sofa/registry/server/session/wrapper/WrapperInvocation.java @@ -21,39 +21,38 @@ import java.util.function.Supplier; /** - * * @author shangyu.wh * @version 1.0: WrapperInvocation.java, v 0.1 2019-06-18 11:43 shangyu.wh Exp $ */ public class WrapperInvocation { - private final Wrapper target; - - private List interceptorChain; + private final Wrapper target; - private Iterator iterator; + private List interceptorChain; - public WrapperInvocation(Wrapper target, - WrapperInterceptorManager wrapperInterceptorManager) { - this.interceptorChain = wrapperInterceptorManager.getInterceptorChain(); - this.iterator = this.interceptorChain.iterator(); - this.target = target; - } + private Iterator iterator; - public R proceed() throws Exception { - if (iterator.hasNext()) { - WrapperInterceptor interceptor = iterator.next(); - return interceptor.invokeCodeWrapper(this); - } - return target.call(); - } + public WrapperInvocation( + Wrapper target, WrapperInterceptorManager wrapperInterceptorManager) { + this.interceptorChain = wrapperInterceptorManager.getInterceptorChain(); + this.iterator = this.interceptorChain.iterator(); + this.target = target; + } - /** - * Getter method for property ParameterSupplier. - * - * @return property value of ParameterSupplier - */ - public Supplier getParameterSupplier() { - return target.getParameterSupplier(); + public R proceed() throws Exception { + if (iterator.hasNext()) { + WrapperInterceptor interceptor = iterator.next(); + return interceptor.invokeCodeWrapper(this); } -} \ No newline at end of file + return target.call(); + } + + /** + * Getter method for property ParameterSupplier. + * + * @return property value of ParameterSupplier + */ + public Supplier getParameterSupplier() { + return target.getParameterSupplier(); + } +} diff --git a/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/WrapperInvocationTest.java b/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/WrapperInvocationTest.java index f8ad38fa0..16da23e71 100644 --- a/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/WrapperInvocationTest.java +++ b/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/WrapperInvocationTest.java @@ -16,130 +16,133 @@ */ package com.alipay.sofa.registry.server.session; +import static junit.framework.Assert.*; + import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.server.session.wrapper.Wrapper; import com.alipay.sofa.registry.server.session.wrapper.WrapperInterceptor; import com.alipay.sofa.registry.server.session.wrapper.WrapperInterceptorManager; import com.alipay.sofa.registry.server.session.wrapper.WrapperInvocation; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Supplier; - -import static junit.framework.Assert.*; - /** - * * @author shangyu.wh * @version 1.0: WrapperInvocationTest.java, v 0.1 2019-06-18 17:41 shangyu.wh Exp $ */ public class WrapperInvocationTest { - private Logger logger = LoggerFactory.getLogger(getClass()); + private Logger logger = LoggerFactory.getLogger(getClass()); - @Rule - public ExpectedException thrown = ExpectedException.none(); + @Rule public ExpectedException thrown = ExpectedException.none(); - @Test - public void testWrapperInterceptorException() throws Exception { - thrown.expect(IllegalAccessException.class); - thrown.expectMessage("test exception!"); - testAll("EXP"); - } + @Test + public void testWrapperInterceptorException() throws Exception { + thrown.expect(IllegalAccessException.class); + thrown.expectMessage("test exception!"); + testAll("EXP"); + } - @Test - public void testWrapperInterceptorProceed() throws Exception { - assertEquals(testAll("Proceed"), 1); - } + @Test + public void testWrapperInterceptorProceed() throws Exception { + assertEquals(testAll("Proceed"), 1); + } - @Test - public void testWrapperInterceptorAllRun() throws Exception { - assertEquals(testAll("AllRun"), 2); - } + @Test + public void testWrapperInterceptorAllRun() throws Exception { + assertEquals(testAll("AllRun"), 2); + } - private int testAll(String input) throws Exception { + private int testAll(String input) throws Exception { - AtomicInteger ret = new AtomicInteger(0); + AtomicInteger ret = new AtomicInteger(0); - WrapperInterceptorManager wrapperInterceptorManager = new WrapperInterceptorManager(); + WrapperInterceptorManager wrapperInterceptorManager = new WrapperInterceptorManager(); - wrapperInterceptorManager.addInterceptor(new WrapperInterceptor(){ + wrapperInterceptorManager.addInterceptor( + new WrapperInterceptor() { - @Override - public Boolean invokeCodeWrapper(WrapperInvocation invocation) throws Exception { - logger.info("0"); - if("EXP".equals(invocation.getParameterSupplier().get())){ - throw new IllegalAccessException("test exception!"); - } - return invocation.proceed(); + @Override + public Boolean invokeCodeWrapper(WrapperInvocation invocation) + throws Exception { + logger.info("0"); + if ("EXP".equals(invocation.getParameterSupplier().get())) { + throw new IllegalAccessException("test exception!"); } + return invocation.proceed(); + } - @Override - public int getOrder() { - return 0; - } + @Override + public int getOrder() { + return 0; + } }); - wrapperInterceptorManager.addInterceptor(new WrapperInterceptor(){ + wrapperInterceptorManager.addInterceptor( + new WrapperInterceptor() { - @Override - public Boolean invokeCodeWrapper(WrapperInvocation invocation) throws Exception { - logger.info("1"); - if("Proceed".equals(invocation.getParameterSupplier().get())){ - ret.set(1); - return true; - } - return invocation.proceed(); + @Override + public Boolean invokeCodeWrapper(WrapperInvocation invocation) + throws Exception { + logger.info("1"); + if ("Proceed".equals(invocation.getParameterSupplier().get())) { + ret.set(1); + return true; } + return invocation.proceed(); + } - @Override - public int getOrder() { - return 1; - } + @Override + public int getOrder() { + return 1; + } }); - wrapperInterceptorManager.addInterceptor(new WrapperInterceptor(){ + wrapperInterceptorManager.addInterceptor( + new WrapperInterceptor() { - @Override - public Boolean invokeCodeWrapper(WrapperInvocation invocation) throws Exception { - logger.info("2"); - if("test".equals(invocation.getParameterSupplier().get())){ - return true; - } - return invocation.proceed(); + @Override + public Boolean invokeCodeWrapper(WrapperInvocation invocation) + throws Exception { + logger.info("2"); + if ("test".equals(invocation.getParameterSupplier().get())) { + return true; } + return invocation.proceed(); + } - @Override - public int getOrder() { - return 2; - } + @Override + public int getOrder() { + return 2; + } }); - - - WrapperInvocation wrapperInvocation = new WrapperInvocation(new Wrapper() { - @Override - public Boolean call() { - if("AllRun".equals(getParameterSupplier().get())) { - System.out.println("success"); - ret.set(2); - return true; + WrapperInvocation wrapperInvocation = + new WrapperInvocation( + new Wrapper() { + @Override + public Boolean call() { + if ("AllRun".equals(getParameterSupplier().get())) { + System.out.println("success"); + ret.set(2); + return true; } return null; - } - - @Override - public Supplier getParameterSupplier() { - return ()->input; - } + } - }, wrapperInterceptorManager); + @Override + public Supplier getParameterSupplier() { + return () -> input; + } + }, + wrapperInterceptorManager); - wrapperInvocation.proceed(); + wrapperInvocation.proceed(); - return ret.get(); - } -} \ No newline at end of file + return ret.get(); + } +} diff --git a/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/store/BaseTest.java b/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/store/BaseTest.java index e77a07aae..ecd93a1c5 100644 --- a/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/store/BaseTest.java +++ b/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/store/BaseTest.java @@ -19,10 +19,8 @@ import org.springframework.boot.SpringBootConfiguration; /** - * * @author shangyu.wh * @version $Id: BaseTest.java, v 0.1 2017-12-14 21:47 shangyu.wh Exp $ */ @SpringBootConfiguration -public class BaseTest { -} \ No newline at end of file +public class BaseTest {} diff --git a/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/store/DataCacheTest.java b/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/store/DataCacheTest.java index ea2b1a3d6..4fbe55145 100644 --- a/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/store/DataCacheTest.java +++ b/server/server/session/src/test/java/com/alipay/sofa/registry/server/session/store/DataCacheTest.java @@ -28,465 +28,496 @@ import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfigBean; import com.google.common.collect.Lists; import com.google.common.collect.Maps; -import org.junit.Assert; -import org.junit.Test; - import java.net.InetSocketAddress; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; +import org.junit.Assert; +import org.junit.Test; /** * @author shangyu.wh * @version $Id: DataCacheTest.java, v 0.1 2017-12-06 19:42 shangyu.wh Exp $ */ - public class DataCacheTest extends BaseTest { - private AtomicLong version = new AtomicLong(1); + private AtomicLong version = new AtomicLong(1); - private AtomicLong registId = new AtomicLong(1000); + private AtomicLong registId = new AtomicLong(1000); - @Test - public void testGetSub() { - SessionInterests sessionInterests = new SessionInterests(); - sessionInterests.setSessionServerConfig(new SessionServerConfigBean(null)); + @Test + public void testGetSub() { + SessionInterests sessionInterests = new SessionInterests(); + sessionInterests.setSessionServerConfig(new SessionServerConfigBean(null)); - String dataId = "dataid"; - String connectId = "192.168.1.2:9000_127.0.0.1:34567"; + String dataId = "dataid"; + String connectId = "192.168.1.2:9000_127.0.0.1:34567"; - for (int i = 0; i < 100; i++) { - sessionInterests.add(getSub(dataId, ScopeEnum.zone, null, null)); - } - //add other ip - sessionInterests.add(getSub(dataId, ScopeEnum.zone, null, new URL("192.168.1.9", 8000))); + for (int i = 0; i < 100; i++) { + sessionInterests.add(getSub(dataId, ScopeEnum.zone, null, null)); + } + // add other ip + sessionInterests.add(getSub(dataId, ScopeEnum.zone, null, new URL("192.168.1.9", 8000))); - Map> map = getCacheSub( + Map> map = + getCacheSub( DataInfo.toDataInfoId(dataId, "instance2", "rpc"), ScopeEnum.zone, sessionInterests); - Assert.assertTrue(getCacheSub(sessionInterests, connectId)); + Assert.assertTrue(getCacheSub(sessionInterests, connectId)); - sessionInterests.deleteByConnectId(ConnectId.parse(connectId)); + sessionInterests.deleteByConnectId(ConnectId.parse(connectId)); - Map> map2 = getCacheSub( + Map> map2 = + getCacheSub( DataInfo.toDataInfoId(dataId, "instance2", "rpc"), ScopeEnum.zone, sessionInterests); - Assert.assertFalse(getCacheSub(sessionInterests, connectId)); + Assert.assertFalse(getCacheSub(sessionInterests, connectId)); - //map no change - Assert.assertEquals(2, map.size()); - - //get cache change,just remain 192.168.1.9:8000 - Assert.assertEquals(map2.keySet().size(), 1); - Assert.assertEquals(NetUtil.toAddressString(map2.keySet().iterator().next()), - "192.168.1.9:8000"); - } + // map no change + Assert.assertEquals(2, map.size()); - @Test - public void testDeleteSubById() { - SessionInterests sessionInterests = new SessionInterests(); - sessionInterests.setSessionServerConfig(new SessionServerConfigBean(null)); + // get cache change,just remain 192.168.1.9:8000 + Assert.assertEquals(map2.keySet().size(), 1); + Assert.assertEquals( + NetUtil.toAddressString(map2.keySet().iterator().next()), "192.168.1.9:8000"); + } - String dataId = "dataid"; + @Test + public void testDeleteSubById() { + SessionInterests sessionInterests = new SessionInterests(); + sessionInterests.setSessionServerConfig(new SessionServerConfigBean(null)); - for (int i = 0; i < 100; i++) { + String dataId = "dataid"; - sessionInterests.add(getSub(dataId, ScopeEnum.zone, null, null)); - } - //add other ip - sessionInterests.add(getSub(dataId, ScopeEnum.zone, "xxregist123", new URL("192.168.1.9", - 8000))); - //sessionInterests.add(getSub(dataId,ScopeEnum.zone,"xxregist456",new URL("192.168.1.10", 7000))); + for (int i = 0; i < 100; i++) { - Map> map = getCacheSub( + sessionInterests.add(getSub(dataId, ScopeEnum.zone, null, null)); + } + // add other ip + sessionInterests.add( + getSub(dataId, ScopeEnum.zone, "xxregist123", new URL("192.168.1.9", 8000))); + // sessionInterests.add(getSub(dataId,ScopeEnum.zone,"xxregist456",new URL("192.168.1.10", + // 7000))); + + Map> map = + getCacheSub( DataInfo.toDataInfoId(dataId, "instance2", "rpc"), ScopeEnum.zone, sessionInterests); - Assert.assertTrue(getCacheSub(sessionInterests, "192.168.1.9:8000_127.0.0.1:34567")); + Assert.assertTrue(getCacheSub(sessionInterests, "192.168.1.9:8000_127.0.0.1:34567")); - sessionInterests.deleteById("xxregist123", - DataInfo.toDataInfoId(dataId, "instance2", "rpc")); + sessionInterests.deleteById("xxregist123", DataInfo.toDataInfoId(dataId, "instance2", "rpc")); - Map> map2 = getCacheSub( + Map> map2 = + getCacheSub( DataInfo.toDataInfoId(dataId, "instance2", "rpc"), ScopeEnum.zone, sessionInterests); - Assert.assertFalse(getCacheSub(sessionInterests, "192.168.1.9:8000_127.0.0.1:34567")); - //map no change - Assert.assertEquals(2, map.size()); - - //remain 100 - Assert.assertEquals(map2.keySet().size(), 1); + Assert.assertFalse(getCacheSub(sessionInterests, "192.168.1.9:8000_127.0.0.1:34567")); + // map no change + Assert.assertEquals(2, map.size()); - InetSocketAddress address = new InetSocketAddress("192.168.1.2", 9000); - InetSocketAddress addressDel = new InetSocketAddress("192.168.1.9", 8000); - Assert.assertFalse(map2.get(address).isEmpty()); + // remain 100 + Assert.assertEquals(map2.keySet().size(), 1); - Assert.assertTrue(map2.get(addressDel) == null); + InetSocketAddress address = new InetSocketAddress("192.168.1.2", 9000); + InetSocketAddress addressDel = new InetSocketAddress("192.168.1.9", 8000); + Assert.assertFalse(map2.get(address).isEmpty()); - //Assert.assertEquals(NetUtil.toAddressString(map2.keySet().iterator().next()),"192.168.1.2:9000"); - Assert.assertEquals(map2.get(address).size(), 100); - } + Assert.assertTrue(map2.get(addressDel) == null); - @Test - public void testGetPub() { - SessionDataStore sessionDataStore = new SessionDataStore(); + // Assert.assertEquals(NetUtil.toAddressString(map2.keySet().iterator().next()),"192.168.1.2:9000"); + Assert.assertEquals(map2.get(address).size(), 100); + } - String dataId = "dataid"; - String connectId = "192.168.1.2:9000_127.0.0.1:34567"; - for (int i = 0; i < 10; i++) { + @Test + public void testGetPub() { + SessionDataStore sessionDataStore = new SessionDataStore(); - sessionDataStore.add(getPub(dataId, null, null)); - } + String dataId = "dataid"; + String connectId = "192.168.1.2:9000_127.0.0.1:34567"; + for (int i = 0; i < 10; i++) { - Assert.assertTrue(getCachePub(sessionDataStore, connectId)); - sessionDataStore.deleteByConnectId(ConnectId.parse(connectId)); - Assert.assertFalse(getCachePub(sessionDataStore, connectId)); + sessionDataStore.add(getPub(dataId, null, null)); } - @Test - public void testGetPubRefresh() { - SessionDataStore sessionDataStore = new SessionDataStore(); - - String dataId = "dataid"; - String connectId = "192.168.1.2:9000"; - int number = 1000; - List publisherList = Lists.newArrayList(); - for (int i = 0; i < number; i++) { - String connectIdss = "192.111.0.1:" + (8000 + i); - Publisher p = getPub(dataId, null, URL.valueOf(connectIdss)); - sessionDataStore.add(p); - publisherList.add(p); - Assert.assertTrue(getCachePub(sessionDataStore, connectIdss - + ValueConstants.CONNECT_ID_SPLIT - + p.getTargetAddress() - .buildAddressString())); - } - for (Publisher p : publisherList) { - String c = connectId + ValueConstants.CONNECT_ID_SPLIT - + p.getTargetAddress().buildAddressString(); - Assert.assertFalse(getCachePub(sessionDataStore, c)); - } + Assert.assertTrue(getCachePub(sessionDataStore, connectId)); + sessionDataStore.deleteByConnectId(ConnectId.parse(connectId)); + Assert.assertFalse(getCachePub(sessionDataStore, connectId)); + } + + @Test + public void testGetPubRefresh() { + SessionDataStore sessionDataStore = new SessionDataStore(); + + String dataId = "dataid"; + String connectId = "192.168.1.2:9000"; + int number = 1000; + List publisherList = Lists.newArrayList(); + for (int i = 0; i < number; i++) { + String connectIdss = "192.111.0.1:" + (8000 + i); + Publisher p = getPub(dataId, null, URL.valueOf(connectIdss)); + sessionDataStore.add(p); + publisherList.add(p); + Assert.assertTrue( + getCachePub( + sessionDataStore, + connectIdss + + ValueConstants.CONNECT_ID_SPLIT + + p.getTargetAddress().buildAddressString())); } - - @Test - public void testDelPubById() { - SessionDataStore sessionDataStore = new SessionDataStore(); - String dataId = "dataid"; - String connectId = "192.168.1.2:9000_127.0.0.1:34567"; - for (int i = 0; i < 10; i++) { - - sessionDataStore.add(getPub(dataId, null, null)); - } - - sessionDataStore.add(getPub(dataId, "XXXX", new URL("192.168.1.9", 8000))); - - Assert.assertTrue(getCachePub(sessionDataStore, connectId)); - Assert.assertTrue(getCachePub(sessionDataStore, "192.168.1.9:8000_127.0.0.1:34567")); - sessionDataStore.deleteById("XXXX", DataInfo.toDataInfoId(dataId, "instance2", "rpc")); - Assert.assertTrue(getCachePub(sessionDataStore, connectId)); - Assert.assertFalse(getCachePub(sessionDataStore, "192.168.1.9:8000_127.0.0.1:34567")); + for (Publisher p : publisherList) { + String c = + connectId + ValueConstants.CONNECT_ID_SPLIT + p.getTargetAddress().buildAddressString(); + Assert.assertFalse(getCachePub(sessionDataStore, c)); } + } - private boolean getCachePub(SessionDataStore sessionDataStore, String connectId) { - Map map = sessionDataStore.queryByConnectId(ConnectId.parse(connectId)); - return map != null && !map.isEmpty(); - } + @Test + public void testDelPubById() { + SessionDataStore sessionDataStore = new SessionDataStore(); + String dataId = "dataid"; + String connectId = "192.168.1.2:9000_127.0.0.1:34567"; + for (int i = 0; i < 10; i++) { - private boolean getCacheSub(SessionInterests sessionInterests, String connectId) { - Map map = sessionInterests.queryByConnectId(ConnectId.parse(connectId)); - return map != null && !map.isEmpty(); + sessionDataStore.add(getPub(dataId, null, null)); } - private Map> getCacheSub(String dataInfoId, - ScopeEnum scopeEnum, - SessionInterests sessionInterests) { - Collection subscribers = sessionInterests.getDatas(dataInfoId); - Map> ret = Maps.newHashMap(); - Map> scopes = SubscriberUtils.groupByScope(subscribers); - List list = scopes.get(scopeEnum); - ret.putAll(SubscriberUtils.groupBySourceAddress(list)); - return ret; - } - - private Subscriber getSub(String dataId, ScopeEnum scopeEnum, String registerId, URL url) { - - String processid = "4466"; - - Subscriber subscriberRegister = new Subscriber(); - subscriberRegister.setAppName("app"); - subscriberRegister.setCell("My zone"); - subscriberRegister.setClientId("clientid" + version.get()); - subscriberRegister.setDataId(dataId); - subscriberRegister.setGroup("rpc"); - subscriberRegister.setInstanceId("instance2"); - subscriberRegister.setRegisterId(registerId == null ? String.valueOf(registId - .incrementAndGet()) : registerId); - subscriberRegister.setProcessId(processid); - subscriberRegister.setVersion(version.get()); - subscriberRegister.setRegisterTimestamp(System.currentTimeMillis()); - subscriberRegister.setScope(scopeEnum); - subscriberRegister.setClientVersion(BaseInfo.ClientVersion.StoreData); - subscriberRegister.setDataInfoId(DataInfo.toDataInfoId(dataId, "instance2", "rpc")); - - subscriberRegister.setSourceAddress(url == null ? new URL("192.168.1.2", 9000) : url); - subscriberRegister.setTargetAddress(new URL("127.0.0.1", 34567)); - - return subscriberRegister; - } - - private Publisher getPub(String dataId, String registerId, URL url) { - - String processid = "4466"; - - Publisher publisher = new Publisher(); - publisher.setAppName("app"); - publisher.setCell("My zone"); - publisher.setClientId("clientid" + version.get()); - publisher.setDataId(dataId); - publisher.setGroup("rpc"); - publisher.setInstanceId("instance2"); - publisher.setRegisterId(registerId == null ? String.valueOf(registId.incrementAndGet()) - : registerId); - publisher.setProcessId(processid); - publisher.setVersion(version.get()); - publisher.setRegisterTimestamp(System.currentTimeMillis()); - publisher.setDataInfoId(DataInfo.toDataInfoId(dataId, "instance2", "rpc")); - - publisher.setSourceAddress(url == null ? new URL("192.168.1.2", 9000) : url); - publisher.setTargetAddress(new URL("127.0.0.1", 34567)); - - return publisher; - } - - @Test - public void testOverwriteSameConnectIdPublisher() { - - SessionDataStore sessionDataStore = new SessionDataStore(); - - Publisher publisher1 = new Publisher(); - publisher1.setDataInfoId("dataInfoId1"); - publisher1.setDataId("dataId1"); - publisher1.setRegisterId("RegisterId1"); - publisher1.setSourceAddress(new URL("192.168.1.1", 12345)); - publisher1.setTargetAddress(new URL("192.168.1.2", 9600)); - publisher1.setVersion(1L); - publisher1.setRegisterTimestamp(System.currentTimeMillis()); - - Publisher publisher2 = new Publisher(); - publisher2.setDataInfoId("dataInfoId2"); - publisher2.setDataId("dataId2"); - publisher2.setRegisterId("RegisterId2"); - publisher2.setSourceAddress(new URL("192.168.1.1", 12345)); - publisher2.setTargetAddress(new URL("192.168.1.2", 9600)); - publisher2.setVersion(2L); - publisher2.setRegisterTimestamp(System.currentTimeMillis()); - sessionDataStore.add(publisher1); - sessionDataStore.add(publisher2); - - Assert.assertEquals( - sessionDataStore - .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")).size(), 2); - sessionDataStore.add(publisher2); - - Assert.assertEquals( - sessionDataStore - .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")).size(), 2); - - Publisher publisher3 = new Publisher(); - publisher3.setDataInfoId(publisher1.getDataInfoId()); - publisher3.setDataId(publisher1.getDataId()); - publisher3.setRegisterId(publisher1.getRegisterId()); - publisher3.setSourceAddress(new URL("192.168.1.1", 12346)); - publisher3.setTargetAddress(new URL("192.168.1.2", 9600)); - publisher3.setVersion(2L); - publisher3.setRegisterTimestamp(System.currentTimeMillis()); - - Publisher publisher4 = new Publisher(); - publisher4.setDataInfoId(publisher2.getDataInfoId()); - publisher4.setDataId(publisher2.getDataId()); - publisher4.setRegisterId(publisher2.getRegisterId()); - publisher4.setSourceAddress(new URL("192.168.1.1", 12346)); - publisher4.setTargetAddress(new URL("192.168.1.2", 9600)); - publisher4.setVersion(2L); - publisher4.setRegisterTimestamp(System.currentTimeMillis()); - - sessionDataStore.add(publisher3); - sessionDataStore.add(publisher4); - - Assert.assertEquals( - sessionDataStore - .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")).size(), 0); - Assert.assertEquals( - sessionDataStore - .queryByConnectId(ConnectId.parse("192.168.1.1:12346_192.168.1.2:9600")).size(), 2); - - } - - @Test - public void testOverwriteSameConnectIdSubscriber() { - - SessionInterests sessionInterests = new SessionInterests(); - SessionServerConfig config = new SessionServerConfigBean(new CommonConfig()); - config.setStopPushSwitch(false); - sessionInterests.setSessionServerConfig(config); - - Subscriber subscriber1 = new Subscriber(); - subscriber1.setScope(ScopeEnum.dataCenter); - subscriber1.setClientVersion(BaseInfo.ClientVersion.StoreData); - subscriber1.setDataInfoId("dataInfoId1"); - subscriber1.setDataId("dataId1"); - subscriber1.setRegisterId("RegisterId1"); - subscriber1.setSourceAddress(new URL("192.168.1.1", 12345)); - subscriber1.setTargetAddress(new URL("192.168.1.2", 9600)); - - Subscriber subscriber2 = new Subscriber(); - subscriber2.setScope(ScopeEnum.dataCenter); - subscriber2.setClientVersion(BaseInfo.ClientVersion.StoreData); - subscriber2.setDataInfoId("dataInfoId2"); - subscriber2.setDataId("dataId2"); - subscriber2.setRegisterId("RegisterId2"); - subscriber2.setSourceAddress(new URL("192.168.1.1", 12345)); - subscriber2.setTargetAddress(new URL("192.168.1.2", 9600)); - - sessionInterests.add(subscriber1); - sessionInterests.add(subscriber2); - - Assert.assertEquals( - sessionInterests - .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")).size(), 2); - sessionInterests.add(subscriber2); - - Assert.assertEquals( - sessionInterests - .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")).size(), 2); - - Subscriber subscriber3 = new Subscriber(); - subscriber3.setScope(ScopeEnum.dataCenter); - subscriber3.setClientVersion(BaseInfo.ClientVersion.StoreData); - subscriber3.setDataInfoId(subscriber1.getDataInfoId()); - subscriber3.setDataId(subscriber1.getDataId()); - subscriber3.setRegisterId(subscriber1.getRegisterId()); - subscriber3.setSourceAddress(new URL("192.168.1.1", 12346)); - subscriber3.setTargetAddress(new URL("192.168.1.2", 9600)); - - Subscriber subscriber4 = new Subscriber(); - subscriber4.setScope(ScopeEnum.dataCenter); - subscriber4.setClientVersion(BaseInfo.ClientVersion.StoreData); - subscriber4.setDataInfoId(subscriber2.getDataInfoId()); - subscriber4.setDataId(subscriber2.getDataId()); - subscriber4.setRegisterId(subscriber2.getRegisterId()); - subscriber4.setSourceAddress(new URL("192.168.1.1", 12346)); - subscriber4.setTargetAddress(new URL("192.168.1.2", 9600)); - - sessionInterests.add(subscriber3); - sessionInterests.add(subscriber4); - - Assert.assertEquals( - sessionInterests - .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")).size(), 0); - Assert.assertEquals( - sessionInterests - .queryByConnectId(ConnectId.parse("192.168.1.1:12346_192.168.1.2:9600")).size(), 2); - } - - @Test - public void testOverwriteSameConnectIdWatcher() { - - SessionWatchers sessionWatchers = new SessionWatchers(); - - Watcher watcher1 = new Watcher(); - watcher1.setDataInfoId("dataInfoId1"); - watcher1.setDataId("dataId1"); - watcher1.setRegisterId("RegisterId1"); - watcher1.setSourceAddress(new URL("192.168.1.1", 12345)); - watcher1.setTargetAddress(new URL("192.168.1.2", 9600)); - - Watcher watcher2 = new Watcher(); - watcher2.setDataInfoId("dataInfoId2"); - watcher2.setDataId("dataId2"); - watcher2.setRegisterId("RegisterId2"); - watcher2.setSourceAddress(new URL("192.168.1.1", 12345)); - watcher2.setTargetAddress(new URL("192.168.1.2", 9600)); - - sessionWatchers.add(watcher1); - sessionWatchers.add(watcher2); - - Assert.assertEquals( - sessionWatchers.queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) - .size(), 2); - sessionWatchers.add(watcher2); - - Assert.assertEquals( - sessionWatchers.queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) - .size(), 2); - - Watcher watcher3 = new Watcher(); - watcher3.setDataInfoId(watcher1.getDataInfoId()); - watcher3.setDataId(watcher1.getDataId()); - watcher3.setRegisterId(watcher1.getRegisterId()); - watcher3.setSourceAddress(new URL("192.168.1.1", 12346)); - watcher3.setTargetAddress(new URL("192.168.1.2", 9600)); - - Watcher watcher4 = new Watcher(); - watcher4.setDataInfoId(watcher2.getDataInfoId()); - watcher4.setDataId(watcher2.getDataId()); - watcher4.setRegisterId(watcher2.getRegisterId()); - watcher4.setSourceAddress(new URL("192.168.1.1", 12346)); - watcher4.setTargetAddress(new URL("192.168.1.2", 9600)); - - sessionWatchers.add(watcher3); - sessionWatchers.add(watcher4); - - Assert.assertEquals( - sessionWatchers.queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) - .size(), 0); - Assert.assertEquals( - sessionWatchers.queryByConnectId(ConnectId.parse("192.168.1.1:12346_192.168.1.2:9600")) - .size(), 2); - } - - @Test - public void testSubAndClientOffUnorder() { - SessionInterests sessionInterests = new SessionInterests(); - SessionServerConfig config = new SessionServerConfigBean(null); - sessionInterests.setSessionServerConfig(config); - - Subscriber subscriber1 = new Subscriber(); - subscriber1.setScope(ScopeEnum.dataCenter); - subscriber1.setClientVersion(BaseInfo.ClientVersion.StoreData); - subscriber1.setDataInfoId("dataInfoId1"); - subscriber1.setDataId("dataId1"); - subscriber1.setRegisterId("RegisterId1"); - subscriber1.setSourceAddress(new URL("192.168.1.1", 12345)); - subscriber1.setTargetAddress(new URL("192.168.1.2", 9600)); - sessionInterests.add(subscriber1); - - Subscriber subscriber2 = new Subscriber(); - subscriber2.setScope(subscriber1.getScope()); - subscriber2.setClientVersion(subscriber1.getClientVersion()); - subscriber2.setDataInfoId(subscriber1.getDataInfoId()); - subscriber2.setDataId(subscriber1.getDataId()); - subscriber2.setRegisterId(subscriber1.getRegisterId()); - subscriber2.setSourceAddress(new URL("192.168.1.1", 12346)); - subscriber2.setTargetAddress(new URL("192.168.1.2", 9600)); - - sessionInterests.add(subscriber2); - - sessionInterests.deleteByConnectId(ConnectId.parse(subscriber1.getSourceAddress() - .getAddressString() + "_" + subscriber1.getTargetAddress().getAddressString())); - - Assert.assertEquals( - sessionInterests - .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")).isEmpty(), - true); - Assert.assertEquals( - sessionInterests - .queryByConnectId(ConnectId.parse("192.168.1.1:12346_192.168.1.2:9600")).size(), 1); - - Map> addressMap = getCacheSub( - subscriber1.getDataInfoId(), subscriber1.getScope(), sessionInterests); - Assert.assertEquals(addressMap.get(new InetSocketAddress("192.168.1.1", 12345)), null); - Assert.assertEquals(addressMap.get(new InetSocketAddress("192.168.1.1", 12346)).size(), 1); - Assert.assertEquals(sessionInterests.getDatas(subscriber1.getDataInfoId()).size(), 1); - Assert.assertTrue(sessionInterests.getDatas(subscriber1.getDataInfoId()).contains( - subscriber2)); - } -} \ No newline at end of file + sessionDataStore.add(getPub(dataId, "XXXX", new URL("192.168.1.9", 8000))); + + Assert.assertTrue(getCachePub(sessionDataStore, connectId)); + Assert.assertTrue(getCachePub(sessionDataStore, "192.168.1.9:8000_127.0.0.1:34567")); + sessionDataStore.deleteById("XXXX", DataInfo.toDataInfoId(dataId, "instance2", "rpc")); + Assert.assertTrue(getCachePub(sessionDataStore, connectId)); + Assert.assertFalse(getCachePub(sessionDataStore, "192.168.1.9:8000_127.0.0.1:34567")); + } + + private boolean getCachePub(SessionDataStore sessionDataStore, String connectId) { + Map map = sessionDataStore.queryByConnectId(ConnectId.parse(connectId)); + return map != null && !map.isEmpty(); + } + + private boolean getCacheSub(SessionInterests sessionInterests, String connectId) { + Map map = sessionInterests.queryByConnectId(ConnectId.parse(connectId)); + return map != null && !map.isEmpty(); + } + + private Map> getCacheSub( + String dataInfoId, ScopeEnum scopeEnum, SessionInterests sessionInterests) { + Collection subscribers = sessionInterests.getDatas(dataInfoId); + Map> ret = Maps.newHashMap(); + Map> scopes = SubscriberUtils.groupByScope(subscribers); + List list = scopes.get(scopeEnum); + ret.putAll(SubscriberUtils.groupBySourceAddress(list)); + return ret; + } + + private Subscriber getSub(String dataId, ScopeEnum scopeEnum, String registerId, URL url) { + + String processid = "4466"; + + Subscriber subscriberRegister = new Subscriber(); + subscriberRegister.setAppName("app"); + subscriberRegister.setCell("My zone"); + subscriberRegister.setClientId("clientid" + version.get()); + subscriberRegister.setDataId(dataId); + subscriberRegister.setGroup("rpc"); + subscriberRegister.setInstanceId("instance2"); + subscriberRegister.setRegisterId( + registerId == null ? String.valueOf(registId.incrementAndGet()) : registerId); + subscriberRegister.setProcessId(processid); + subscriberRegister.setVersion(version.get()); + subscriberRegister.setRegisterTimestamp(System.currentTimeMillis()); + subscriberRegister.setScope(scopeEnum); + subscriberRegister.setClientVersion(BaseInfo.ClientVersion.StoreData); + subscriberRegister.setDataInfoId(DataInfo.toDataInfoId(dataId, "instance2", "rpc")); + + subscriberRegister.setSourceAddress(url == null ? new URL("192.168.1.2", 9000) : url); + subscriberRegister.setTargetAddress(new URL("127.0.0.1", 34567)); + + return subscriberRegister; + } + + private Publisher getPub(String dataId, String registerId, URL url) { + + String processid = "4466"; + + Publisher publisher = new Publisher(); + publisher.setAppName("app"); + publisher.setCell("My zone"); + publisher.setClientId("clientid" + version.get()); + publisher.setDataId(dataId); + publisher.setGroup("rpc"); + publisher.setInstanceId("instance2"); + publisher.setRegisterId( + registerId == null ? String.valueOf(registId.incrementAndGet()) : registerId); + publisher.setProcessId(processid); + publisher.setVersion(version.get()); + publisher.setRegisterTimestamp(System.currentTimeMillis()); + publisher.setDataInfoId(DataInfo.toDataInfoId(dataId, "instance2", "rpc")); + + publisher.setSourceAddress(url == null ? new URL("192.168.1.2", 9000) : url); + publisher.setTargetAddress(new URL("127.0.0.1", 34567)); + + return publisher; + } + + @Test + public void testOverwriteSameConnectIdPublisher() { + + SessionDataStore sessionDataStore = new SessionDataStore(); + + Publisher publisher1 = new Publisher(); + publisher1.setDataInfoId("dataInfoId1"); + publisher1.setDataId("dataId1"); + publisher1.setRegisterId("RegisterId1"); + publisher1.setSourceAddress(new URL("192.168.1.1", 12345)); + publisher1.setTargetAddress(new URL("192.168.1.2", 9600)); + publisher1.setVersion(1L); + publisher1.setRegisterTimestamp(System.currentTimeMillis()); + + Publisher publisher2 = new Publisher(); + publisher2.setDataInfoId("dataInfoId2"); + publisher2.setDataId("dataId2"); + publisher2.setRegisterId("RegisterId2"); + publisher2.setSourceAddress(new URL("192.168.1.1", 12345)); + publisher2.setTargetAddress(new URL("192.168.1.2", 9600)); + publisher2.setVersion(2L); + publisher2.setRegisterTimestamp(System.currentTimeMillis()); + sessionDataStore.add(publisher1); + sessionDataStore.add(publisher2); + + Assert.assertEquals( + sessionDataStore + .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) + .size(), + 2); + sessionDataStore.add(publisher2); + + Assert.assertEquals( + sessionDataStore + .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) + .size(), + 2); + + Publisher publisher3 = new Publisher(); + publisher3.setDataInfoId(publisher1.getDataInfoId()); + publisher3.setDataId(publisher1.getDataId()); + publisher3.setRegisterId(publisher1.getRegisterId()); + publisher3.setSourceAddress(new URL("192.168.1.1", 12346)); + publisher3.setTargetAddress(new URL("192.168.1.2", 9600)); + publisher3.setVersion(2L); + publisher3.setRegisterTimestamp(System.currentTimeMillis()); + + Publisher publisher4 = new Publisher(); + publisher4.setDataInfoId(publisher2.getDataInfoId()); + publisher4.setDataId(publisher2.getDataId()); + publisher4.setRegisterId(publisher2.getRegisterId()); + publisher4.setSourceAddress(new URL("192.168.1.1", 12346)); + publisher4.setTargetAddress(new URL("192.168.1.2", 9600)); + publisher4.setVersion(2L); + publisher4.setRegisterTimestamp(System.currentTimeMillis()); + + sessionDataStore.add(publisher3); + sessionDataStore.add(publisher4); + + Assert.assertEquals( + sessionDataStore + .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) + .size(), + 0); + Assert.assertEquals( + sessionDataStore + .queryByConnectId(ConnectId.parse("192.168.1.1:12346_192.168.1.2:9600")) + .size(), + 2); + } + + @Test + public void testOverwriteSameConnectIdSubscriber() { + + SessionInterests sessionInterests = new SessionInterests(); + SessionServerConfig config = new SessionServerConfigBean(new CommonConfig()); + config.setStopPushSwitch(false); + sessionInterests.setSessionServerConfig(config); + + Subscriber subscriber1 = new Subscriber(); + subscriber1.setScope(ScopeEnum.dataCenter); + subscriber1.setClientVersion(BaseInfo.ClientVersion.StoreData); + subscriber1.setDataInfoId("dataInfoId1"); + subscriber1.setDataId("dataId1"); + subscriber1.setRegisterId("RegisterId1"); + subscriber1.setSourceAddress(new URL("192.168.1.1", 12345)); + subscriber1.setTargetAddress(new URL("192.168.1.2", 9600)); + + Subscriber subscriber2 = new Subscriber(); + subscriber2.setScope(ScopeEnum.dataCenter); + subscriber2.setClientVersion(BaseInfo.ClientVersion.StoreData); + subscriber2.setDataInfoId("dataInfoId2"); + subscriber2.setDataId("dataId2"); + subscriber2.setRegisterId("RegisterId2"); + subscriber2.setSourceAddress(new URL("192.168.1.1", 12345)); + subscriber2.setTargetAddress(new URL("192.168.1.2", 9600)); + + sessionInterests.add(subscriber1); + sessionInterests.add(subscriber2); + + Assert.assertEquals( + sessionInterests + .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) + .size(), + 2); + sessionInterests.add(subscriber2); + + Assert.assertEquals( + sessionInterests + .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) + .size(), + 2); + + Subscriber subscriber3 = new Subscriber(); + subscriber3.setScope(ScopeEnum.dataCenter); + subscriber3.setClientVersion(BaseInfo.ClientVersion.StoreData); + subscriber3.setDataInfoId(subscriber1.getDataInfoId()); + subscriber3.setDataId(subscriber1.getDataId()); + subscriber3.setRegisterId(subscriber1.getRegisterId()); + subscriber3.setSourceAddress(new URL("192.168.1.1", 12346)); + subscriber3.setTargetAddress(new URL("192.168.1.2", 9600)); + + Subscriber subscriber4 = new Subscriber(); + subscriber4.setScope(ScopeEnum.dataCenter); + subscriber4.setClientVersion(BaseInfo.ClientVersion.StoreData); + subscriber4.setDataInfoId(subscriber2.getDataInfoId()); + subscriber4.setDataId(subscriber2.getDataId()); + subscriber4.setRegisterId(subscriber2.getRegisterId()); + subscriber4.setSourceAddress(new URL("192.168.1.1", 12346)); + subscriber4.setTargetAddress(new URL("192.168.1.2", 9600)); + + sessionInterests.add(subscriber3); + sessionInterests.add(subscriber4); + + Assert.assertEquals( + sessionInterests + .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) + .size(), + 0); + Assert.assertEquals( + sessionInterests + .queryByConnectId(ConnectId.parse("192.168.1.1:12346_192.168.1.2:9600")) + .size(), + 2); + } + + @Test + public void testOverwriteSameConnectIdWatcher() { + + SessionWatchers sessionWatchers = new SessionWatchers(); + + Watcher watcher1 = new Watcher(); + watcher1.setDataInfoId("dataInfoId1"); + watcher1.setDataId("dataId1"); + watcher1.setRegisterId("RegisterId1"); + watcher1.setSourceAddress(new URL("192.168.1.1", 12345)); + watcher1.setTargetAddress(new URL("192.168.1.2", 9600)); + + Watcher watcher2 = new Watcher(); + watcher2.setDataInfoId("dataInfoId2"); + watcher2.setDataId("dataId2"); + watcher2.setRegisterId("RegisterId2"); + watcher2.setSourceAddress(new URL("192.168.1.1", 12345)); + watcher2.setTargetAddress(new URL("192.168.1.2", 9600)); + + sessionWatchers.add(watcher1); + sessionWatchers.add(watcher2); + + Assert.assertEquals( + sessionWatchers + .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) + .size(), + 2); + sessionWatchers.add(watcher2); + + Assert.assertEquals( + sessionWatchers + .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) + .size(), + 2); + + Watcher watcher3 = new Watcher(); + watcher3.setDataInfoId(watcher1.getDataInfoId()); + watcher3.setDataId(watcher1.getDataId()); + watcher3.setRegisterId(watcher1.getRegisterId()); + watcher3.setSourceAddress(new URL("192.168.1.1", 12346)); + watcher3.setTargetAddress(new URL("192.168.1.2", 9600)); + + Watcher watcher4 = new Watcher(); + watcher4.setDataInfoId(watcher2.getDataInfoId()); + watcher4.setDataId(watcher2.getDataId()); + watcher4.setRegisterId(watcher2.getRegisterId()); + watcher4.setSourceAddress(new URL("192.168.1.1", 12346)); + watcher4.setTargetAddress(new URL("192.168.1.2", 9600)); + + sessionWatchers.add(watcher3); + sessionWatchers.add(watcher4); + + Assert.assertEquals( + sessionWatchers + .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) + .size(), + 0); + Assert.assertEquals( + sessionWatchers + .queryByConnectId(ConnectId.parse("192.168.1.1:12346_192.168.1.2:9600")) + .size(), + 2); + } + + @Test + public void testSubAndClientOffUnorder() { + SessionInterests sessionInterests = new SessionInterests(); + SessionServerConfig config = new SessionServerConfigBean(null); + sessionInterests.setSessionServerConfig(config); + + Subscriber subscriber1 = new Subscriber(); + subscriber1.setScope(ScopeEnum.dataCenter); + subscriber1.setClientVersion(BaseInfo.ClientVersion.StoreData); + subscriber1.setDataInfoId("dataInfoId1"); + subscriber1.setDataId("dataId1"); + subscriber1.setRegisterId("RegisterId1"); + subscriber1.setSourceAddress(new URL("192.168.1.1", 12345)); + subscriber1.setTargetAddress(new URL("192.168.1.2", 9600)); + sessionInterests.add(subscriber1); + + Subscriber subscriber2 = new Subscriber(); + subscriber2.setScope(subscriber1.getScope()); + subscriber2.setClientVersion(subscriber1.getClientVersion()); + subscriber2.setDataInfoId(subscriber1.getDataInfoId()); + subscriber2.setDataId(subscriber1.getDataId()); + subscriber2.setRegisterId(subscriber1.getRegisterId()); + subscriber2.setSourceAddress(new URL("192.168.1.1", 12346)); + subscriber2.setTargetAddress(new URL("192.168.1.2", 9600)); + + sessionInterests.add(subscriber2); + + sessionInterests.deleteByConnectId( + ConnectId.parse( + subscriber1.getSourceAddress().getAddressString() + + "_" + + subscriber1.getTargetAddress().getAddressString())); + + Assert.assertEquals( + sessionInterests + .queryByConnectId(ConnectId.parse("192.168.1.1:12345_192.168.1.2:9600")) + .isEmpty(), + true); + Assert.assertEquals( + sessionInterests + .queryByConnectId(ConnectId.parse("192.168.1.1:12346_192.168.1.2:9600")) + .size(), + 1); + + Map> addressMap = + getCacheSub(subscriber1.getDataInfoId(), subscriber1.getScope(), sessionInterests); + Assert.assertEquals(addressMap.get(new InetSocketAddress("192.168.1.1", 12345)), null); + Assert.assertEquals(addressMap.get(new InetSocketAddress("192.168.1.1", 12346)).size(), 1); + Assert.assertEquals(sessionInterests.getDatas(subscriber1.getDataInfoId()).size(), 1); + Assert.assertTrue(sessionInterests.getDatas(subscriber1.getDataInfoId()).contains(subscriber2)); + } +} diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/AbstractComparator.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/AbstractComparator.java index 6600b2f81..e42c13a29 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/AbstractComparator.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/AbstractComparator.java @@ -18,95 +18,93 @@ import com.alipay.sofa.registry.common.model.Triple; import com.alipay.sofa.registry.common.model.Tuple; - import java.util.Collection; import java.util.HashSet; import java.util.Set; /** * @author chen.zhu - *

- * Jan 12, 2021 + *

Jan 12, 2021 */ public class AbstractComparator implements Comparator { - protected Set added = new HashSet<>(); - protected Set removed = new HashSet<>(); - protected Set remainings = new HashSet<>(); - protected Set> modified = new HashSet<>(); - protected volatile int count; - - @Override - public Set getAdded() { - return added; - } - - @Override - public Set getRemoved() { - return removed; + protected Set added = new HashSet<>(); + protected Set removed = new HashSet<>(); + protected Set remainings = new HashSet<>(); + protected Set> modified = new HashSet<>(); + protected volatile int count; + + @Override + public Set getAdded() { + return added; + } + + @Override + public Set getRemoved() { + return removed; + } + + @Override + public Set> getModified() { + return modified; + } + + @Override + public void accept(ComparatorVisitor visitor) { + for (T t : added) { + visitor.visitAdded(t); } - @Override - public Set> getModified() { - return modified; + for (T t : removed) { + visitor.visitRemoved(t); } - @Override - public void accept(ComparatorVisitor visitor) { - for (T t : added) { - visitor.visitAdded(t); - } - - for (T t : removed) { - visitor.visitRemoved(t); - } - - for (Tuple mod : modified) { - visitor.visitModified(mod); - } + for (Tuple mod : modified) { + visitor.visitModified(mod); } + } - @Override - public void acceptAdded(ComparatorVisitor visitor) { - for (T t : added) { - visitor.visitAdded(t); - } + @Override + public void acceptAdded(ComparatorVisitor visitor) { + for (T t : added) { + visitor.visitAdded(t); } + } - @Override - public void acceptRemoved(ComparatorVisitor visitor) { - for (T t : removed) { - visitor.visitRemoved(t); - } + @Override + public void acceptRemoved(ComparatorVisitor visitor) { + for (T t : removed) { + visitor.visitRemoved(t); } + } - @Override - public void acceptRemains(ComparatorVisitor visitor) { - for (T t : remainings) { - visitor.visitRemaining(t); - } + @Override + public void acceptRemains(ComparatorVisitor visitor) { + for (T t : remainings) { + visitor.visitRemaining(t); } + } - @Override - public boolean hasAnyChange() { - return count > 0; - } + @Override + public boolean hasAnyChange() { + return count > 0; + } - @Override - public int totalChange() { - return count; - } + @Override + public int totalChange() { + return count; + } - protected Triple, Set, Set> getDiff(Collection current, - Collection future) { + protected Triple, Set, Set> getDiff( + Collection current, Collection future) { - Set added = new HashSet<>(future); - Set remaining = new HashSet<>(future); - Set deleted = new HashSet<>(current); + Set added = new HashSet<>(future); + Set remaining = new HashSet<>(future); + Set deleted = new HashSet<>(current); - added.removeAll(deleted); - remaining.retainAll(deleted); - deleted.removeAll(future); + added.removeAll(deleted); + remaining.retainAll(deleted); + deleted.removeAll(future); - return new Triple, Set, Set>(added, remaining, deleted); - } + return new Triple, Set, Set>(added, remaining, deleted); + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/Comparator.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/Comparator.java index 6a8a78a14..e3294fadf 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/Comparator.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/Comparator.java @@ -17,31 +17,29 @@ package com.alipay.sofa.registry.server.shared.comparator; import com.alipay.sofa.registry.common.model.Tuple; - import java.util.Set; /** * @author chen.zhu - *

- * Jan 12, 2021 + *

Jan 12, 2021 */ public interface Comparator { - Set getAdded(); + Set getAdded(); - Set getRemoved(); + Set getRemoved(); - Set> getModified(); + Set> getModified(); - void accept(ComparatorVisitor visitor); + void accept(ComparatorVisitor visitor); - void acceptAdded(ComparatorVisitor visitor); + void acceptAdded(ComparatorVisitor visitor); - void acceptRemoved(ComparatorVisitor visitor); + void acceptRemoved(ComparatorVisitor visitor); - void acceptRemains(ComparatorVisitor visitor); + void acceptRemains(ComparatorVisitor visitor); - boolean hasAnyChange(); + boolean hasAnyChange(); - int totalChange(); + int totalChange(); } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/ComparatorVisitor.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/ComparatorVisitor.java index 96be3a82f..7aa8fa291 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/ComparatorVisitor.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/ComparatorVisitor.java @@ -20,16 +20,15 @@ /** * @author chen.zhu - *

- * Jan 12, 2021 + *

Jan 12, 2021 */ public interface ComparatorVisitor { - void visitAdded(T added); + void visitAdded(T added); - void visitModified(Tuple modified); + void visitModified(Tuple modified); - void visitRemoved(T removed); + void visitRemoved(T removed); - void visitRemaining(T remain); + void visitRemaining(T remain); } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/NodeComparator.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/NodeComparator.java index e72c2f5e9..9962569bb 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/NodeComparator.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/comparator/NodeComparator.java @@ -17,38 +17,33 @@ package com.alipay.sofa.registry.server.shared.comparator; import com.alipay.sofa.registry.common.model.Triple; -import com.alipay.sofa.registry.server.shared.comparator.AbstractComparator; - import java.util.Collection; import java.util.Set; /** * @author chen.zhu - *

- * Jan 12, 2021 - * - * String stands for data node ip - * - * as the situation is mainly about rebalance the slot-table - * which, data node is stored just as IP address (String) + *

Jan 12, 2021 + *

String stands for data node ip + *

as the situation is mainly about rebalance the slot-table which, data node is stored just + * as IP address (String) */ public class NodeComparator extends AbstractComparator { - private Collection prev; + private Collection prev; - private Collection current; + private Collection current; - public NodeComparator(Collection prev, Collection current) { - this.prev = prev; - this.current = current; - compare(); - } + public NodeComparator(Collection prev, Collection current) { + this.prev = prev; + this.current = current; + compare(); + } - public void compare() { - Triple, Set, Set> triple = getDiff(prev, current); - this.added = triple.getFirst(); - this.remainings = triple.getMiddle(); - this.removed = triple.getLast(); - this.count = this.added.size() + this.removed.size(); - } + public void compare() { + Triple, Set, Set> triple = getDiff(prev, current); + this.added = triple.getFirst(); + this.remainings = triple.getMiddle(); + this.removed = triple.getLast(); + this.count = this.added.size() + this.removed.size(); + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/config/DefaultSlotTableConfig.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/config/DefaultSlotTableConfig.java index 9f8a9ef04..dd112d5bc 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/config/DefaultSlotTableConfig.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/config/DefaultSlotTableConfig.java @@ -18,26 +18,25 @@ /** * @author chen.zhu - *

- * Dec 15, 2020 + *

Dec 15, 2020 */ public class DefaultSlotTableConfig implements SlotTableConfig { - public static final String SLOT_NUMS = "slot.nums"; + public static final String SLOT_NUMS = "slot.nums"; - public static final String SLOT_REPLICA_NUMS = "slot.replica.nums"; + public static final String SLOT_REPLICA_NUMS = "slot.replica.nums"; - private final int slotNums = Integer.getInteger(SLOT_NUMS, 2); + private final int slotNums = Integer.getInteger(SLOT_NUMS, 2); - private final int slotReplicaNums = Integer.getInteger(SLOT_REPLICA_NUMS, 1); + private final int slotReplicaNums = Integer.getInteger(SLOT_REPLICA_NUMS, 1); - @Override - public int getSlotNums() { - return slotNums; - } + @Override + public int getSlotNums() { + return slotNums; + } - @Override - public int getSlotReplicaNums() { - return slotReplicaNums; - } + @Override + public int getSlotReplicaNums() { + return slotReplicaNums; + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/config/SlotTableConfig.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/config/SlotTableConfig.java index f530794f0..5a8f2790b 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/config/SlotTableConfig.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/config/SlotTableConfig.java @@ -18,24 +18,23 @@ /** * @author chen.zhu - *

- * Dec 15, 2020 + *

Dec 15, 2020 */ public interface SlotTableConfig { - /** - * Gets get slot nums. - * - * @return the get total slot nums - */ - int getSlotNums(); + /** + * Gets get slot nums. + * + * @return the get total slot nums + */ + int getSlotNums(); - /** - * Gets get slot replica nums. - * - * @return the get slot replica nums - */ - int getSlotReplicaNums(); + /** + * Gets get slot replica nums. + * + * @return the get slot replica nums + */ + int getSlotReplicaNums(); - SlotTableConfig DEFAULT = new DefaultSlotTableConfig(); + SlotTableConfig DEFAULT = new DefaultSlotTableConfig(); } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/env/ServerEnv.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/env/ServerEnv.java index 81b0b25e1..1af6335bb 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/env/ServerEnv.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/env/ServerEnv.java @@ -18,81 +18,81 @@ import com.alipay.sofa.registry.common.model.ProcessId; import com.alipay.sofa.registry.net.NetUtil; -import org.apache.commons.lang.StringUtils; -import org.glassfish.jersey.internal.guava.Sets; - import java.util.Collection; import java.util.Map; import java.util.Random; import java.util.Set; +import org.apache.commons.lang.StringUtils; +import org.glassfish.jersey.internal.guava.Sets; /** * @author yuzhi.lyz * @version v 0.1 2020-11-28 15:25 yuzhi.lyz Exp $ */ public final class ServerEnv { - private ServerEnv() { - } + private ServerEnv() {} - public static final String IP = NetUtil.getLocalAddress().getHostAddress(); - public static final int PID = getPID(); - public static final ProcessId PROCESS_ID = createProcessId(); - - private static ProcessId createProcessId() { - Random random = new Random(); - return new ProcessId(IP, System.currentTimeMillis(), PID, random.nextInt(1024 * 8)); - } + public static final String IP = NetUtil.getLocalAddress().getHostAddress(); + public static final int PID = getPID(); + public static final ProcessId PROCESS_ID = createProcessId(); - static int getPID() { - String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName(); - if (StringUtils.isBlank(processName)) { - throw new RuntimeException("failed to get processName"); - } + private static ProcessId createProcessId() { + Random random = new Random(); + return new ProcessId(IP, System.currentTimeMillis(), PID, random.nextInt(1024 * 8)); + } - String[] processSplitName = processName.split("@"); - if (processSplitName.length == 0) { - throw new RuntimeException("failed to get processName"); - } - String pid = processSplitName[0]; - return Integer.parseInt(pid); + static int getPID() { + String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName(); + if (StringUtils.isBlank(processName)) { + throw new RuntimeException("failed to get processName"); } - public static boolean isLocalServer(String ip) { - return IP.equals(ip); + String[] processSplitName = processName.split("@"); + if (processSplitName.length == 0) { + throw new RuntimeException("failed to get processName"); } + String pid = processSplitName[0]; + return Integer.parseInt(pid); + } - public static Collection getMetaAddresses(Map> metaMap, - String localDataCenter) { - if (metaMap == null) { - throw new RuntimeException("metaNodes is null"); - } - if (localDataCenter == null) { - throw new RuntimeException("local datacenter is null"); - } - Collection addresses = metaMap.get(localDataCenter); - if (addresses == null || addresses.isEmpty()) { - throw new RuntimeException(String.format("LocalDataCenter(%s) is not in metaNode", - localDataCenter)); - } - return addresses; + public static boolean isLocalServer(String ip) { + return IP.equals(ip); + } + + public static Collection getMetaAddresses( + Map> metaMap, String localDataCenter) { + if (metaMap == null) { + throw new RuntimeException("metaNodes is null"); + } + if (localDataCenter == null) { + throw new RuntimeException("local datacenter is null"); + } + Collection addresses = metaMap.get(localDataCenter); + if (addresses == null || addresses.isEmpty()) { + throw new RuntimeException( + String.format("LocalDataCenter(%s) is not in metaNode", localDataCenter)); } + return addresses; + } - public static Set transferMetaIps(Map> metaMap, String localDataCenter) { - Set metaIps = Sets.newHashSet(); - if (metaMap != null && !metaMap.isEmpty()) { - if (localDataCenter != null && !localDataCenter.isEmpty()) { - Collection metas = metaMap.get(localDataCenter); - if (metas != null && !metas.isEmpty()) { - metas.forEach(domain -> { - String ip = NetUtil.getIPAddressFromDomain(domain); - if (ip == null) { - throw new RuntimeException("Meta convert domain {" + domain + "} error!"); - } - metaIps.add(ip); - }); + public static Set transferMetaIps( + Map> metaMap, String localDataCenter) { + Set metaIps = Sets.newHashSet(); + if (metaMap != null && !metaMap.isEmpty()) { + if (localDataCenter != null && !localDataCenter.isEmpty()) { + Collection metas = metaMap.get(localDataCenter); + if (metas != null && !metas.isEmpty()) { + metas.forEach( + domain -> { + String ip = NetUtil.getIPAddressFromDomain(domain); + if (ip == null) { + throw new RuntimeException("Meta convert domain {" + domain + "} error!"); } - } + metaIps.add(ip); + }); } - return metaIps; + } } + return metaIps; + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/AbstractMetaServerManager.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/AbstractMetaServerManager.java index ab39a656e..37f326d58 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/AbstractMetaServerManager.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/AbstractMetaServerManager.java @@ -37,213 +37,223 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import com.google.common.collect.Sets; -import org.apache.commons.lang.StringUtils; - -import javax.annotation.PostConstruct; -import javax.annotation.Resource; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import org.apache.commons.lang.StringUtils; /** * @author chen.zhu - *

- * Mar 15, 2021 + *

Mar 15, 2021 */ -public abstract class AbstractMetaServerManager extends ClientSideExchanger implements MetaServerManager, Initializable, Startable { +public abstract class AbstractMetaServerManager extends ClientSideExchanger + implements MetaServerManager, Initializable, Startable { - private static final long INIT_META_LEADER_EPOCH = -1L; + private static final long INIT_META_LEADER_EPOCH = -1L; - private static final Logger LOGGER = LoggerFactory.getLogger(AbstractMetaServerManager.class); + private static final Logger LOGGER = LoggerFactory.getLogger(AbstractMetaServerManager.class); - @Resource(name = "metaClientHandlers") - private Collection metaClientHandlers; + @Resource(name = "metaClientHandlers") + private Collection metaClientHandlers; - private final ReadWriteLock lock = new ReentrantReadWriteLock(); + private final ReadWriteLock lock = new ReentrantReadWriteLock(); - private final AtomicInteger metaServerIndex = new AtomicInteger(0); + private final AtomicInteger metaServerIndex = new AtomicInteger(0); - protected volatile List defaultMetaServers; + protected volatile List defaultMetaServers; - protected volatile List runtimeMetaServers; + protected volatile List runtimeMetaServers; - protected volatile String metaLeader; + protected volatile String metaLeader; - protected volatile long metaLeaderEpoch = INIT_META_LEADER_EPOCH; + protected volatile long metaLeaderEpoch = INIT_META_LEADER_EPOCH; - protected AbstractMetaServerManager() { - super(Exchange.META_SERVER_TYPE); - } + protected AbstractMetaServerManager() { + super(Exchange.META_SERVER_TYPE); + } - @PostConstruct - public void postConstruct() { - initialize(); - start(); - } + @PostConstruct + public void postConstruct() { + initialize(); + start(); + } - @Override - public void initialize() { - defaultMetaServers = getConfiguredMetaIp(); - this.runtimeMetaServers = Lists.newArrayList(defaultMetaServers); - } + @Override + public void initialize() { + defaultMetaServers = getConfiguredMetaIp(); + this.runtimeMetaServers = Lists.newArrayList(defaultMetaServers); + } - @Override - public void start() { - this.serverIps = Sets.newHashSet(runtimeMetaServers); - connectServer(); - } + @Override + public void start() { + this.serverIps = Sets.newHashSet(runtimeMetaServers); + connectServer(); + } - @Override - public List getDefaultMetaServerList() { - try { - lock.readLock().lock(); - return Lists.newArrayList(defaultMetaServers); - } finally { - lock.readLock().unlock(); - } + @Override + public List getDefaultMetaServerList() { + try { + lock.readLock().lock(); + return Lists.newArrayList(defaultMetaServers); + } finally { + lock.readLock().unlock(); } + } - @Override - public List getRuntimeMetaServerList() { - try { - lock.readLock().lock(); - return Lists.newArrayList(runtimeMetaServers); - } finally { - lock.readLock().unlock(); - } + @Override + public List getRuntimeMetaServerList() { + try { + lock.readLock().lock(); + return Lists.newArrayList(runtimeMetaServers); + } finally { + lock.readLock().unlock(); } + } - @Override - public String getMetaServerLeader() { - try { - lock.readLock().lock(); - return getLeader(); - } finally { - lock.readLock().unlock(); - } + @Override + public String getMetaServerLeader() { + try { + lock.readLock().lock(); + return getLeader(); + } finally { + lock.readLock().unlock(); } + } - @Override - public void refresh(BaseHeartBeatResponse heartBeatResp) { - String futureLeader = heartBeatResp.getMetaLeader(); - long futureEpoch = heartBeatResp.getMetaLeaderEpoch(); - if (futureEpoch >= metaLeaderEpoch && !StringUtils.isEmpty(futureLeader)) { - lock.writeLock().lock(); - try { - metaLeaderEpoch = futureEpoch; - metaLeader = futureLeader; - } finally { - lock.writeLock().unlock(); - } - } - List metaServers = NodeUtils.transferNodeToIpList(heartBeatResp.getMetaNodes()); - lock.writeLock().lock(); - try { - this.runtimeMetaServers = metaServers; - } finally { - lock.writeLock().unlock(); - } - doRefreshConnections(); + @Override + public void refresh(BaseHeartBeatResponse heartBeatResp) { + String futureLeader = heartBeatResp.getMetaLeader(); + long futureEpoch = heartBeatResp.getMetaLeaderEpoch(); + if (futureEpoch >= metaLeaderEpoch && !StringUtils.isEmpty(futureLeader)) { + lock.writeLock().lock(); + try { + metaLeaderEpoch = futureEpoch; + metaLeader = futureLeader; + } finally { + lock.writeLock().unlock(); + } } + List metaServers = NodeUtils.transferNodeToIpList(heartBeatResp.getMetaNodes()); + lock.writeLock().lock(); + try { + this.runtimeMetaServers = metaServers; + } finally { + lock.writeLock().unlock(); + } + doRefreshConnections(); + } - @VisibleForTesting - protected void doRefreshConnections() { - Set future = Sets.newHashSet(this.runtimeMetaServers); - NodeComparator diff = new NodeComparator(this.serverIps, future); - diff.accept(new ComparatorVisitor() { - @Override - public void visitAdded(String added) { - try { - LOGGER.info("[visitAdded] connect new meta-server: {}", added); - URL url = new URL(added, getServerPort()); - connect(url); - } catch (Throwable th) { - LOGGER.error("[visitAdded]", th); - } + @VisibleForTesting + protected void doRefreshConnections() { + Set future = Sets.newHashSet(this.runtimeMetaServers); + NodeComparator diff = new NodeComparator(this.serverIps, future); + diff.accept( + new ComparatorVisitor() { + @Override + public void visitAdded(String added) { + try { + LOGGER.info("[visitAdded] connect new meta-server: {}", added); + URL url = new URL(added, getServerPort()); + connect(url); + } catch (Throwable th) { + LOGGER.error("[visitAdded]", th); } + } - @Override - public void visitModified(Tuple modified) { - //do nothing - } + @Override + public void visitModified(Tuple modified) { + // do nothing + } - @Override - public void visitRemoved(String removed) { - try { - LOGGER.info("[visitRemoved] close meta-server connection: {}", removed); - boltExchange.getClient(serverType).getChannel(new URL(removed, getServerPort())).close(); - } catch (Throwable th) { - LOGGER.error("[visitRemoved]", th); - } + @Override + public void visitRemoved(String removed) { + try { + LOGGER.info("[visitRemoved] close meta-server connection: {}", removed); + boltExchange + .getClient(serverType) + .getChannel(new URL(removed, getServerPort())) + .close(); + } catch (Throwable th) { + LOGGER.error("[visitRemoved]", th); } + } - @Override - public void visitRemaining(String remain) { - //do nothing - } + @Override + public void visitRemaining(String remain) { + // do nothing + } }); - } + } - @Override - public Response sendRequest(Object requestBody) throws RequestException { - Request request = new Request() { - @Override - public Object getRequestBody() { - return requestBody; - } + @Override + public Response sendRequest(Object requestBody) throws RequestException { + Request request = + new Request() { + @Override + public Object getRequestBody() { + return requestBody; + } - @Override - public URL getRequestUrl() { - return new URL(getLeader(), getServerPort()); - } + @Override + public URL getRequestUrl() { + return new URL(getLeader(), getServerPort()); + } }; - return request(request); - } + return request(request); + } - @Override - public Response request(Request request) throws RequestException { - LOGGER.info("[request] MetaNode Exchanger request={},url={},callbackHandler={}", - request.getRequestBody(), request.getRequestUrl(), request.getCallBackHandler()); - try { - return super.request(request); - } catch (Throwable e) { - //retry - URL url = new URL(getLeader(), getServerPort()); - LOGGER.warn( - "[request] MetaNode Exchanger request send error!It will be retry once!Request url:{}", url); - return super.request(request); - } + @Override + public Response request(Request request) throws RequestException { + LOGGER.info( + "[request] MetaNode Exchanger request={},url={},callbackHandler={}", + request.getRequestBody(), + request.getRequestUrl(), + request.getCallBackHandler()); + try { + return super.request(request); + } catch (Throwable e) { + // retry + URL url = new URL(getLeader(), getServerPort()); + LOGGER.warn( + "[request] MetaNode Exchanger request send error!It will be retry once!Request url:{}", + url); + return super.request(request); } + } - @Override - protected Collection getClientHandlers() { - return metaClientHandlers; - } + @Override + protected Collection getClientHandlers() { + return metaClientHandlers; + } - private String getLeader() { - if (StringUtils.isEmpty(metaLeader) || metaLeaderEpoch == INIT_META_LEADER_EPOCH) { - int index = metaServerIndex.incrementAndGet() % defaultMetaServers.size(); - metaServerIndex.set(index); - return defaultMetaServers.get(index); - } - return metaLeader; + private String getLeader() { + if (StringUtils.isEmpty(metaLeader) || metaLeaderEpoch == INIT_META_LEADER_EPOCH) { + int index = metaServerIndex.incrementAndGet() % defaultMetaServers.size(); + metaServerIndex.set(index); + return defaultMetaServers.get(index); } + return metaLeader; + } - private List getConfiguredMetaIp() { - Set set = Sets.newHashSet(); - Collection metaDomains = getConfiguredMetaServerDomains(); - metaDomains.forEach(domain -> { - String ip = NetUtil.getIPAddressFromDomain(domain); - if (ip == null) { - throw new SofaRegistryRuntimeException("Node config convert domain {" + domain + "} error!"); - } - set.add(ip); + private List getConfiguredMetaIp() { + Set set = Sets.newHashSet(); + Collection metaDomains = getConfiguredMetaServerDomains(); + metaDomains.forEach( + domain -> { + String ip = NetUtil.getIPAddressFromDomain(domain); + if (ip == null) { + throw new SofaRegistryRuntimeException( + "Node config convert domain {" + domain + "} error!"); + } + set.add(ip); }); - return Lists.newArrayList(set); - } + return Lists.newArrayList(set); + } - protected abstract Collection getConfiguredMetaServerDomains(); + protected abstract Collection getConfiguredMetaServerDomains(); } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/AbstractMetaServerService.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/AbstractMetaServerService.java index 01ad06b6a..f57b68eed 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/AbstractMetaServerService.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/AbstractMetaServerService.java @@ -30,191 +30,205 @@ import com.alipay.sofa.registry.util.ConcurrentUtils; import com.alipay.sofa.registry.util.WakeUpLoopRunnable; import com.google.common.collect.Sets; +import java.util.*; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; -import java.util.*; - /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-28 15:21 yuzhi.lyz Exp $ */ -public abstract class AbstractMetaServerService implements - MetaServerService { - protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); +public abstract class AbstractMetaServerService + implements MetaServerService { + protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); - @Autowired - protected MetaServerManager metaServerManager; + @Autowired protected MetaServerManager metaServerManager; - protected volatile State state = State.NULL; + protected volatile State state = State.NULL; - private Renewer renewer; + private Renewer renewer; - @Override - public synchronized void startRenewer(int intervalMs) { - if (renewer != null) { - throw new IllegalStateException("has started renewer"); - } - this.renewer = new Renewer(intervalMs); - ConcurrentUtils.createDaemonThread("meta-renewer", this.renewer).start(); + @Override + public synchronized void startRenewer(int intervalMs) { + if (renewer != null) { + throw new IllegalStateException("has started renewer"); } - - @Override - public boolean handleSlotTableChange(SlotTableChangeEvent event) { - long epoch = event.getSlotTableEpoch(); - long currentEpoch = getCurrentSlotTableEpoch(); - if (currentEpoch >= epoch) { - LOGGER.warn( - "[handleSlotTableChange] slot-table change event epoch: [{}], current epoch: [{}], " - + "won't retrieve again", epoch, currentEpoch); - return false; - } - LOGGER - .info("[handleSlotTableChange] slot table is changed, run heart-beat to retrieve new version"); - if (renewer != null) { - renewer.wakeup(); - } - return true; + this.renewer = new Renewer(intervalMs); + ConcurrentUtils.createDaemonThread("meta-renewer", this.renewer).start(); + } + + @Override + public boolean handleSlotTableChange(SlotTableChangeEvent event) { + long epoch = event.getSlotTableEpoch(); + long currentEpoch = getCurrentSlotTableEpoch(); + if (currentEpoch >= epoch) { + LOGGER.warn( + "[handleSlotTableChange] slot-table change event epoch: [{}], current epoch: [{}], " + + "won't retrieve again", + epoch, + currentEpoch); + return false; } - - private final class Renewer extends WakeUpLoopRunnable { - final int intervalMs; - - Renewer(int intervalMs) { - this.intervalMs = intervalMs; - } - - @Override - public void runUnthrowable() { - try { - renewNode(); - } catch (Throwable e) { - LOGGER.error("failed to renewNode", e); - } - } - - @Override - public int getWaitingMillis() { - return intervalMs; - } + LOGGER.info( + "[handleSlotTableChange] slot table is changed, run heart-beat to retrieve new version"); + if (renewer != null) { + renewer.wakeup(); } + return true; + } - @Override - public void renewNode() { - final String leaderIp = metaServerManager.getMetaServerLeader(); - try { - HeartbeatRequest heartbeatRequest = createRequest(); - GenericResponse resp = (GenericResponse) metaServerManager.sendRequest(heartbeatRequest).getResult(); - if (resp != null && resp.isSuccess()) { - updateState(resp.getData()); - metaServerManager.refresh(resp.getData()); - handleRenewResult(resp.getData()); - } else { - LOGGER.error("[RenewNodeTask] renew data node to metaServer error : {}, {}", - leaderIp, resp); - throw new RuntimeException("[RenewNodeTask] renew data node to metaServer error : " - + leaderIp); - } - } catch (Throwable e) { - LOGGER.error("renew node error from {}", leaderIp, e); - throw new RuntimeException("renew node error! " + e.getMessage(), e); - } - } + private final class Renewer extends WakeUpLoopRunnable { + final int intervalMs; - private void updateState(T response) { - State s = new State(response.getDataCentersFromMetaNodes(), response.getSessionNodesMap(), - response.getSlotTable().getDataServers(), response.getSessionServerEpoch(), response.getMetaLeader(), response.getMetaLeaderEpoch()); - this.state = s; - LOGGER.info("update MetaStat, sessions={}/{}, datas={}, metaLeader: {}, metaLeaderEpoch: {}", - s.sessionServerEpoch, s.sessionNodes.keySet(), s.dataServers, s.metaLeader, s.metaLeaderEpoch); + Renewer(int intervalMs) { + this.intervalMs = intervalMs; } @Override - public ProvideData fetchData(String dataInfoId) { - final String leaderIp = metaServerManager.getMetaServerLeader(); - try { - Response response = metaServerManager.sendRequest(new FetchProvideDataRequest(dataInfoId)); - - Object result = response.getResult(); - if (result instanceof ProvideData) { - return (ProvideData) result; - } else { - LOGGER.error("fetch null provider data from {}", leaderIp); - throw new RuntimeException("metaServerService fetch null provider data!"); - } - } catch (Exception e) { - LOGGER.error("fetch provider data error from {}", leaderIp, e); - throw new RuntimeException("fetch provider data error! " + e.getMessage(), e); - } - - } - - public Map getSessionNodes() { - return state.sessionNodes; + public void runUnthrowable() { + try { + renewNode(); + } catch (Throwable e) { + LOGGER.error("failed to renewNode", e); + } } - public Set getSessionServerList() { - return state.sessionNodes.keySet(); + @Override + public int getWaitingMillis() { + return intervalMs; } - - public Set getDataServerList() { - return state.dataServers; + } + + @Override + public void renewNode() { + final String leaderIp = metaServerManager.getMetaServerLeader(); + try { + HeartbeatRequest heartbeatRequest = createRequest(); + GenericResponse resp = + (GenericResponse) metaServerManager.sendRequest(heartbeatRequest).getResult(); + if (resp != null && resp.isSuccess()) { + updateState(resp.getData()); + metaServerManager.refresh(resp.getData()); + handleRenewResult(resp.getData()); + } else { + LOGGER.error( + "[RenewNodeTask] renew data node to metaServer error : {}, {}", leaderIp, resp); + throw new RuntimeException( + "[RenewNodeTask] renew data node to metaServer error : " + leaderIp); + } + } catch (Throwable e) { + LOGGER.error("renew node error from {}", leaderIp, e); + throw new RuntimeException("renew node error! " + e.getMessage(), e); } - - public Set getMetaServerList() { - return Sets.newHashSet(metaServerManager.getRuntimeMetaServerList()); + } + + private void updateState(T response) { + State s = + new State( + response.getDataCentersFromMetaNodes(), + response.getSessionNodesMap(), + response.getSlotTable().getDataServers(), + response.getSessionServerEpoch(), + response.getMetaLeader(), + response.getMetaLeaderEpoch()); + this.state = s; + LOGGER.info( + "update MetaStat, sessions={}/{}, datas={}, metaLeader: {}, metaLeaderEpoch: {}", + s.sessionServerEpoch, + s.sessionNodes.keySet(), + s.dataServers, + s.metaLeader, + s.metaLeaderEpoch); + } + + @Override + public ProvideData fetchData(String dataInfoId) { + final String leaderIp = metaServerManager.getMetaServerLeader(); + try { + Response response = metaServerManager.sendRequest(new FetchProvideDataRequest(dataInfoId)); + + Object result = response.getResult(); + if (result instanceof ProvideData) { + return (ProvideData) result; + } else { + LOGGER.error("fetch null provider data from {}", leaderIp); + throw new RuntimeException("metaServerService fetch null provider data!"); + } + } catch (Exception e) { + LOGGER.error("fetch provider data error from {}", leaderIp, e); + throw new RuntimeException("fetch provider data error! " + e.getMessage(), e); } - - public List getSessionServerList(String zonename) { - List serverList = new ArrayList<>(); - for (SessionNode sessionNode : getSessionNodes().values()) { - if (StringUtils.isBlank(zonename) || zonename.equals(sessionNode.getRegionId())) { - URL url = sessionNode.getNodeUrl(); - if (url != null) { - serverList.add(url.getIpAddress()); - } - } + } + + public Map getSessionNodes() { + return state.sessionNodes; + } + + public Set getSessionServerList() { + return state.sessionNodes.keySet(); + } + + public Set getDataServerList() { + return state.dataServers; + } + + public Set getMetaServerList() { + return Sets.newHashSet(metaServerManager.getRuntimeMetaServerList()); + } + + public List getSessionServerList(String zonename) { + List serverList = new ArrayList<>(); + for (SessionNode sessionNode : getSessionNodes().values()) { + if (StringUtils.isBlank(zonename) || zonename.equals(sessionNode.getRegionId())) { + URL url = sessionNode.getNodeUrl(); + if (url != null) { + serverList.add(url.getIpAddress()); } - return serverList; + } } - - @Override - public long getSessionServerEpoch() { - return state.sessionServerEpoch; - } - - @Override - public Set getDataCenters() { - return state.dataCenters; + return serverList; + } + + @Override + public long getSessionServerEpoch() { + return state.sessionServerEpoch; + } + + @Override + public Set getDataCenters() { + return state.dataCenters; + } + + protected abstract void handleRenewResult(T result); + + protected abstract HeartbeatRequest createRequest(); + + protected abstract long getCurrentSlotTableEpoch(); + + private static final class State { + static final State NULL = + new State( + Collections.emptySet(), Collections.emptyMap(), Collections.emptySet(), 0, null, -1L); + protected final long sessionServerEpoch; + protected final Map sessionNodes; + protected final Set dataServers; + protected final String metaLeader; + protected final long metaLeaderEpoch; + protected final Set dataCenters; + + State( + Set dataCenters, + Map sessionNodes, + Set dataServers, + long sessionServerEpoch, + String metaLeader, + long metaLeaderEpoch) { + this.sessionServerEpoch = sessionServerEpoch; + this.dataCenters = Collections.unmodifiableSet(new TreeSet<>(dataCenters)); + this.sessionNodes = Collections.unmodifiableMap(sessionNodes); + this.dataServers = Collections.unmodifiableSet(dataServers); + this.metaLeader = metaLeader; + this.metaLeaderEpoch = metaLeaderEpoch; } - - protected abstract void handleRenewResult(T result); - - protected abstract HeartbeatRequest createRequest(); - - protected abstract long getCurrentSlotTableEpoch(); - - private static final class State { - static final State NULL = new State(Collections.emptySet(), Collections.emptyMap(), - Collections.emptySet(), 0, null, -1L); - protected final long sessionServerEpoch; - protected final Map sessionNodes; - protected final Set dataServers; - protected final String metaLeader; - protected final long metaLeaderEpoch; - protected final Set dataCenters; - - State(Set dataCenters, Map sessionNodes, - Set dataServers, long sessionServerEpoch, - String metaLeader, long metaLeaderEpoch) { - this.sessionServerEpoch = sessionServerEpoch; - this.dataCenters = Collections.unmodifiableSet(new TreeSet<>(dataCenters)); - this.sessionNodes = Collections.unmodifiableMap(sessionNodes); - this.dataServers = Collections.unmodifiableSet(dataServers); - this.metaLeader = metaLeader; - this.metaLeaderEpoch = metaLeaderEpoch; - } - } - + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/MetaServerManager.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/MetaServerManager.java index 69fd827db..3ea66e524 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/MetaServerManager.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/MetaServerManager.java @@ -19,23 +19,21 @@ import com.alipay.sofa.registry.common.model.metaserver.inter.heartbeat.BaseHeartBeatResponse; import com.alipay.sofa.registry.remoting.exchange.RequestException; import com.alipay.sofa.registry.remoting.exchange.message.Response; - import java.util.List; /** * @author chen.zhu - *

- * Mar 15, 2021 + *

Mar 15, 2021 */ public interface MetaServerManager { - List getDefaultMetaServerList(); + List getDefaultMetaServerList(); - List getRuntimeMetaServerList(); + List getRuntimeMetaServerList(); - String getMetaServerLeader(); + String getMetaServerLeader(); - void refresh(BaseHeartBeatResponse heartBeatResp); + void refresh(BaseHeartBeatResponse heartBeatResp); - Response sendRequest(Object requestBody) throws RequestException; + Response sendRequest(Object requestBody) throws RequestException; } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/MetaServerService.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/MetaServerService.java index e7c1ebb44..3eddc9e1a 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/MetaServerService.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/meta/MetaServerService.java @@ -18,47 +18,45 @@ import com.alipay.sofa.registry.common.model.metaserver.ProvideData; import com.alipay.sofa.registry.common.model.metaserver.SlotTableChangeEvent; - import java.util.List; import java.util.Set; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-28 15:19 yuzhi.lyz Exp $ */ public interface MetaServerService { - void startRenewer(int intervalMs); + void startRenewer(int intervalMs); - /** - * update data server expireTime - */ - void renewNode(); + /** update data server expireTime */ + void renewNode(); - boolean handleSlotTableChange(SlotTableChangeEvent event); + boolean handleSlotTableChange(SlotTableChangeEvent event); - /** - * get provider data - * @param dataInfoId - * @return - */ - ProvideData fetchData(String dataInfoId); + /** + * get provider data + * + * @param dataInfoId + * @return + */ + ProvideData fetchData(String dataInfoId); - /** - * @param zonename zone is null, get all session - * @return - */ - public List getSessionServerList(String zonename); + /** + * @param zonename zone is null, get all session + * @return + */ + public List getSessionServerList(String zonename); - public Set getDataServerList(); + public Set getDataServerList(); - public Set getMetaServerList(); + public Set getMetaServerList(); - long getSessionServerEpoch(); + long getSessionServerEpoch(); - /** - * get all datacenters - * @return - */ - Set getDataCenters(); + /** + * get all datacenters + * + * @return + */ + Set getDataCenters(); } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractChannelHandler.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractChannelHandler.java index 0663f8f56..1fb1c6362 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractChannelHandler.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractChannelHandler.java @@ -22,108 +22,112 @@ import com.alipay.sofa.registry.remoting.ChannelHandler; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-14 13:57 yuzhi.lyz Exp $ */ public abstract class AbstractChannelHandler implements ChannelHandler { - private final Logger connectLog; - protected final Logger exchangeLog; + private final Logger connectLog; + protected final Logger exchangeLog; - protected AbstractChannelHandler(Logger connectLog, Logger exchangeLog) { - this.connectLog = connectLog; - this.exchangeLog = exchangeLog; - } + protected AbstractChannelHandler(Logger connectLog, Logger exchangeLog) { + this.connectLog = connectLog; + this.exchangeLog = exchangeLog; + } - @Override - public void connected(Channel channel) { - connectLog.info("{} node connected, channel {}", getConnectNodeType(), channel); - } + @Override + public void connected(Channel channel) { + connectLog.info("{} node connected, channel {}", getConnectNodeType(), channel); + } - @Override - public void disconnected(Channel channel) { - connectLog.info("{} node disconnected, channel {}", getConnectNodeType(), channel); - } + @Override + public void disconnected(Channel channel) { + connectLog.info("{} node disconnected, channel {}", getConnectNodeType(), channel); + } - protected abstract Node.NodeType getConnectNodeType(); + protected abstract Node.NodeType getConnectNodeType(); - @Override - public void caught(Channel channel, T message, Throwable exception) { - exchangeLog.error("{} caughtException, channel {}, msg={}", getConnectNodeType(), channel, - message, exception); - } + @Override + public void caught(Channel channel, T message, Throwable exception) { + exchangeLog.error( + "{} caughtException, channel {}, msg={}", + getConnectNodeType(), + channel, + message, + exception); + } - @Override - public void received(Channel channel, T message) { - // only support as async - throw new UnsupportedOperationException(); - } + @Override + public void received(Channel channel, T message) { + // only support as async + throw new UnsupportedOperationException(); + } - @Override - public Object reply(Channel channel, T request) { - try { - logRequest(channel, request); - checkParam(request); - return doHandle(channel, request); - } catch (Throwable e) { - exchangeLog.error("[{}] handle request failed", getClassName(), e); - return buildFailedResponse(e.getMessage()); - } + @Override + public Object reply(Channel channel, T request) { + try { + logRequest(channel, request); + checkParam(request); + return doHandle(channel, request); + } catch (Throwable e) { + exchangeLog.error("[{}] handle request failed", getClassName(), e); + return buildFailedResponse(e.getMessage()); } + } - /** - * check params if valid - * - * @param request - * @throws RuntimeException - */ - public void checkParam(T request) throws RuntimeException { - } + /** + * check params if valid + * + * @param request + * @throws RuntimeException + */ + public void checkParam(T request) throws RuntimeException {} - /** - * execute - * - * @param request - * @return - */ - public abstract Object doHandle(Channel channel, T request); + /** + * execute + * + * @param request + * @return + */ + public abstract Object doHandle(Channel channel, T request); - /** - * build failed response - * - * @param msg - * @return - */ - public Object buildFailedResponse(String msg) { - throw new RuntimeException(msg); - } + /** + * build failed response + * + * @param msg + * @return + */ + public Object buildFailedResponse(String msg) { + throw new RuntimeException(msg); + } - /** - * print request - * - * @param request - */ - protected void logRequest(Channel channel, T request) { - if (exchangeLog.isInfoEnabled()) { - StringBuilder sb = new StringBuilder(256); - sb.append("[").append(getClassName()).append("] "); - sb.append("Remote:").append(RemotingHelper.getChannelRemoteAddress(channel)) - .append(" Request:").append(request); - exchangeLog.info(sb.toString()); - } + /** + * print request + * + * @param request + */ + protected void logRequest(Channel channel, T request) { + if (exchangeLog.isInfoEnabled()) { + StringBuilder sb = new StringBuilder(256); + sb.append("[").append(getClassName()).append("] "); + sb.append("Remote:") + .append(RemotingHelper.getChannelRemoteAddress(channel)) + .append(" Request:") + .append(request); + exchangeLog.info(sb.toString()); } + } - /** - * get simple name of this class - * - * @return - */ - private String getClassName() { - return this.getClass().getSimpleName(); - } + /** + * get simple name of this class + * + * @return + */ + private String getClassName() { + return this.getClass().getSimpleName(); + } - @Override - public HandlerType getType() { - return HandlerType.PROCESSER; - } + @Override + public HandlerType getType() { + return HandlerType.PROCESSER; + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractClientHandler.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractClientHandler.java index 28eac2a1c..4da897959 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractClientHandler.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractClientHandler.java @@ -20,16 +20,15 @@ import com.alipay.sofa.registry.log.LoggerFactory; /** - * * @author shangyu.wh * @version $Id: ClientHandler.java, v 0.1 2017-11-28 18:06 shangyu.wh Exp $ */ public abstract class AbstractClientHandler extends AbstractChannelHandler { - private static final Logger LOGGER_EXCHANGE = LoggerFactory.getLogger("CLI-EXCHANGE"); - private static final Logger LOGGER_CONNECT = LoggerFactory.getLogger("CLI-CONNECT"); + private static final Logger LOGGER_EXCHANGE = LoggerFactory.getLogger("CLI-EXCHANGE"); + private static final Logger LOGGER_CONNECT = LoggerFactory.getLogger("CLI-CONNECT"); - public AbstractClientHandler() { - super(LOGGER_CONNECT, LOGGER_EXCHANGE); - } -} \ No newline at end of file + public AbstractClientHandler() { + super(LOGGER_CONNECT, LOGGER_EXCHANGE); + } +} diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractServerHandler.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractServerHandler.java index e33f3aac0..233ac1cca 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractServerHandler.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/AbstractServerHandler.java @@ -20,17 +20,16 @@ import com.alipay.sofa.registry.log.LoggerFactory; /** - * * @author shangyu.wh * @version $Id: ServerHandler.java, v 0.1 2017-11-28 18:06 shangyu.wh Exp $ */ public abstract class AbstractServerHandler extends AbstractChannelHandler { - private static final Logger LOGGER_CONNECT = LoggerFactory.getLogger("SRV-CONNECT"); + private static final Logger LOGGER_CONNECT = LoggerFactory.getLogger("SRV-CONNECT"); - private static final Logger LOGGER_EXCHANGE = LoggerFactory.getLogger("SRV-EXCHANGE"); + private static final Logger LOGGER_EXCHANGE = LoggerFactory.getLogger("SRV-EXCHANGE"); - public AbstractServerHandler() { - super(LOGGER_CONNECT, LOGGER_EXCHANGE); - } -} \ No newline at end of file + public AbstractServerHandler() { + super(LOGGER_CONNECT, LOGGER_EXCHANGE); + } +} diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ClientSideExchanger.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ClientSideExchanger.java index 47db945f2..b09dbeb50 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ClientSideExchanger.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ClientSideExchanger.java @@ -33,177 +33,183 @@ import com.alipay.sofa.registry.util.ConcurrentUtils; import com.alipay.sofa.registry.util.WakeUpLoopRunnable; import com.google.common.collect.Sets; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.annotation.PostConstruct; import java.util.*; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author yuzhi.lyz * @version v 0.1 2020-11-29 12:08 yuzhi.lyz Exp $ */ public abstract class ClientSideExchanger implements NodeExchanger { - private static final Logger LOGGER = LoggerFactory.getLogger(ClientSideExchanger.class); - protected final String serverType; - - @Autowired - protected Exchange boltExchange; - - protected volatile Set serverIps = Sets.newHashSet(); - private final Connector connector; - - protected ClientSideExchanger(String serverType) { - this.serverType = serverType; - this.connector = new Connector(); + private static final Logger LOGGER = LoggerFactory.getLogger(ClientSideExchanger.class); + protected final String serverType; + + @Autowired protected Exchange boltExchange; + + protected volatile Set serverIps = Sets.newHashSet(); + private final Connector connector; + + protected ClientSideExchanger(String serverType) { + this.serverType = serverType; + this.connector = new Connector(); + } + + @PostConstruct + public void init() { + ConcurrentUtils.createDaemonThread(serverType + "-async-connector", connector).start(); + LOGGER.info("init connector"); + } + + @Override + public Response request(Request request) throws RequestException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "serverPort={} to server, url:{}, request body:{} ", + getServerPort(), + request.getRequestUrl(), + request.getRequestBody()); } - @PostConstruct - public void init() { - ConcurrentUtils.createDaemonThread(serverType + "-async-connector", connector).start(); - LOGGER.info("init connector"); + final URL url = request.getRequestUrl(); + if (url == null) { + throw new RequestException("null url", request); } - - @Override - public Response request(Request request) throws RequestException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("serverPort={} to server, url:{}, request body:{} ", getServerPort(), request.getRequestUrl(), - request.getRequestBody()); - } - - final URL url = request.getRequestUrl(); - if (url == null) { - throw new RequestException("null url", request); - } - Client client = boltExchange.getClient(serverType); - final int timeout = request.getTimeout() != null ? request.getTimeout() : getRpcTimeoutMillis(); - try { - CallbackHandler callback = request.getCallBackHandler(); - if (callback == null) { - final Object result = client.sendSync(url, request.getRequestBody(), timeout); - return () -> result; - } else { - client.sendCallback(url, request.getRequestBody(), callback, timeout); - return () -> Response.ResultStatus.SUCCESSFUL; - } - } catch (Throwable e) { - throw new RequestException(serverType + "Exchanger request error! Request url:" + url, request, e); - } + Client client = boltExchange.getClient(serverType); + final int timeout = request.getTimeout() != null ? request.getTimeout() : getRpcTimeoutMillis(); + try { + CallbackHandler callback = request.getCallBackHandler(); + if (callback == null) { + final Object result = client.sendSync(url, request.getRequestBody(), timeout); + return () -> result; + } else { + client.sendCallback(url, request.getRequestBody(), callback, timeout); + return () -> Response.ResultStatus.SUCCESSFUL; + } + } catch (Throwable e) { + throw new RequestException( + serverType + "Exchanger request error! Request url:" + url, request, e); } - - public Response requestRaw(String ip, Object raw) throws RequestException { - Request req = new Request() { - @Override - public Object getRequestBody() { - return raw; - } - - @Override - public URL getRequestUrl() { - return new URL(ip, getServerPort()); - } + } + + public Response requestRaw(String ip, Object raw) throws RequestException { + Request req = + new Request() { + @Override + public Object getRequestBody() { + return raw; + } + + @Override + public URL getRequestUrl() { + return new URL(ip, getServerPort()); + } }; - return request(req); + return request(req); + } + + @Override + public Client connectServer() { + Set ips = serverIps; + if (!ips.isEmpty()) { + int count = tryConnectAllServer(ips); + if (count == 0) { + throw new RuntimeException("failed to connect any servers, " + ips); + } } - - @Override - public Client connectServer() { - Set ips = serverIps; - if (!ips.isEmpty()) { - int count = tryConnectAllServer(ips); - if (count == 0) { - throw new RuntimeException("failed to connect any servers, " + ips); - } - } - return getClient(); + return getClient(); + } + + public Client getClient() { + return boltExchange.getClient(serverType); + } + + protected int tryConnectAllServer(Set ips) { + int connectCount = 0; + for (String node : ips) { + URL url = new URL(node, getServerPort()); + try { + connect(url); + connectCount++; + } catch (Throwable e) { + LOGGER.error("Exchanger connect server error!url:" + url, e); + } } - - public Client getClient() { - return boltExchange.getClient(serverType); - } - - protected int tryConnectAllServer(Set ips) { - int connectCount = 0; - for (String node : ips) { - URL url = new URL(node, getServerPort()); - try { - connect(url); - connectCount++; - } catch (Throwable e) { - LOGGER.error("Exchanger connect server error!url:" + url, e); - } - } - return connectCount; - } - - public Channel connect(URL url) { - Client client = getClient(); + return connectCount; + } + + public Channel connect(URL url) { + Client client = getClient(); + if (client == null) { + synchronized (this) { + client = getClient(); if (client == null) { - synchronized (this) { - client = getClient(); - if (client == null) { - client = boltExchange.connect(serverType, getConnNum(), url, - getClientHandlers().toArray(new ChannelHandler[0])); - } - } + client = + boltExchange.connect( + serverType, + getConnNum(), + url, + getClientHandlers().toArray(new ChannelHandler[0])); } - Channel channel = client.getChannel(url); + } + } + Channel channel = client.getChannel(url); + if (channel == null) { + synchronized (this) { + channel = client.getChannel(url); if (channel == null) { - synchronized (this) { - channel = client.getChannel(url); - if (channel == null) { - channel = client.connect(url); - } - } + channel = client.connect(url); } - return channel; + } } + return channel; + } - public Map> getConnections() { - Client client = boltExchange.getClient(serverType); - if (client == null) { - return Collections.emptyMap(); - } - return ((BoltClient) client).getConnections(); + public Map> getConnections() { + Client client = boltExchange.getClient(serverType); + if (client == null) { + return Collections.emptyMap(); } + return ((BoltClient) client).getConnections(); + } - public void notifyConnectServerAsync() { - connector.wakeup(); - } + public void notifyConnectServerAsync() { + connector.wakeup(); + } - private final class Connector extends WakeUpLoopRunnable { + private final class Connector extends WakeUpLoopRunnable { - @Override - public void runUnthrowable() { - Set ips = serverIps; - try { - tryConnectAllServer(ips); - } catch (Throwable e) { - LOGGER.error("failded to connect {}", ips, e); - } - } + @Override + public void runUnthrowable() { + Set ips = serverIps; + try { + tryConnectAllServer(ips); + } catch (Throwable e) { + LOGGER.error("failded to connect {}", ips, e); + } + } - @Override - public int getWaitingMillis() { - return 3000; - } + @Override + public int getWaitingMillis() { + return 3000; } + } - public abstract int getRpcTimeoutMillis(); + public abstract int getRpcTimeoutMillis(); - public abstract int getServerPort(); + public abstract int getServerPort(); - public int getConnNum() { - return 1; - } + public int getConnNum() { + return 1; + } - protected abstract Collection getClientHandlers(); + protected abstract Collection getClientHandlers(); - public Set getServerIps() { - return serverIps; - } + public Set getServerIps() { + return serverIps; + } - public void setServerIps(Collection serverIps) { - this.serverIps = Collections.unmodifiableSet(Sets.newHashSet(serverIps)); - } + public void setServerIps(Collection serverIps) { + this.serverIps = Collections.unmodifiableSet(Sets.newHashSet(serverIps)); + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ListenClientChannelHandler.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ListenClientChannelHandler.java index 1168921da..c09cb85f6 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ListenClientChannelHandler.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ListenClientChannelHandler.java @@ -19,29 +19,28 @@ import com.alipay.sofa.registry.remoting.Channel; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-14 15:09 yuzhi.lyz Exp $ */ public abstract class ListenClientChannelHandler extends AbstractClientHandler { - @Override - public Object doHandle(Channel channel, Object request) { - throw new UnsupportedOperationException(); - } + @Override + public Object doHandle(Channel channel, Object request) { + throw new UnsupportedOperationException(); + } - @Override - public Object buildFailedResponse(String msg) { - throw new UnsupportedOperationException(); - } + @Override + public Object buildFailedResponse(String msg) { + throw new UnsupportedOperationException(); + } - @Override - public Class interest() { - return null; - } + @Override + public Class interest() { + return null; + } - @Override - public HandlerType getType() { - return HandlerType.LISENTER; - } + @Override + public HandlerType getType() { + return HandlerType.LISENTER; + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ListenServerChannelHandler.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ListenServerChannelHandler.java index ada273932..c5d5ee08d 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ListenServerChannelHandler.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ListenServerChannelHandler.java @@ -19,29 +19,28 @@ import com.alipay.sofa.registry.remoting.Channel; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-14 14:42 yuzhi.lyz Exp $ */ public abstract class ListenServerChannelHandler extends AbstractServerHandler { - @Override - public Object doHandle(Channel channel, Object request) { - throw new UnsupportedOperationException(); - } + @Override + public Object doHandle(Channel channel, Object request) { + throw new UnsupportedOperationException(); + } - @Override - public Object buildFailedResponse(String msg) { - throw new UnsupportedOperationException(); - } + @Override + public Object buildFailedResponse(String msg) { + throw new UnsupportedOperationException(); + } - @Override - public Class interest() { - return null; - } + @Override + public Class interest() { + return null; + } - @Override - public HandlerType getType() { - return HandlerType.LISENTER; - } + @Override + public HandlerType getType() { + return HandlerType.LISENTER; + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/RemotingHelper.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/RemotingHelper.java index b56f94bba..c4c78e601 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/RemotingHelper.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/RemotingHelper.java @@ -17,19 +17,16 @@ package com.alipay.sofa.registry.server.shared.remoting; import com.alipay.sofa.registry.remoting.Channel; - import java.net.InetSocketAddress; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-14 11:39 yuzhi.lyz Exp $ */ public final class RemotingHelper { - private RemotingHelper() { - } + private RemotingHelper() {} - public static InetSocketAddress getChannelRemoteAddress(Channel channel) { - return channel == null ? null : channel.getRemoteAddress(); - } + public static InetSocketAddress getChannelRemoteAddress(Channel channel) { + return channel == null ? null : channel.getRemoteAddress(); + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ServerSideExchanger.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ServerSideExchanger.java index 487415b6f..cc76265d1 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ServerSideExchanger.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/ServerSideExchanger.java @@ -29,82 +29,85 @@ import com.alipay.sofa.registry.remoting.exchange.message.Request; import com.alipay.sofa.registry.remoting.exchange.message.Response; import com.alipay.sofa.registry.util.CollectionUtils; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Collection; import java.util.Optional; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author yuzhi.lyz * @version v 0.1 2020-12-18 11:40 yuzhi.lyz Exp $ */ public abstract class ServerSideExchanger implements NodeExchanger { - private static final Logger LOGGER = LoggerFactory.getLogger(ServerSideExchanger.class); + private static final Logger LOGGER = LoggerFactory.getLogger(ServerSideExchanger.class); - @Autowired - protected Exchange boltExchange; + @Autowired protected Exchange boltExchange; - @Override - public Response request(Request request) throws RequestException { - final URL url = request.getRequestUrl(); - if (url == null) { - throw new RequestException("null url", request); - } - return request(url, request); + @Override + public Response request(Request request) throws RequestException { + final URL url = request.getRequestUrl(); + if (url == null) { + throw new RequestException("null url", request); } + return request(url, request); + } - public Response request(URL url, Request request) throws RequestException { - if (LOGGER.isDebugEnabled()) { - LOGGER.debug("serverPort={} to client, url:{}, request body:{} ", getServerPort(), url, - request.getRequestBody()); - } - final Server server = boltExchange.getServer(getServerPort()); - if (server == null) { - throw new RequestException("no server for " + url + "," + getServerPort(), request); - } - final int timeout = request.getTimeout() != null ? request.getTimeout() : getRpcTimeoutMillis(); - Channel channel = null; - if (url == null) { - channel = choseChannel(server); - } else { - channel = server.getChannel(url); - } - - if (channel == null || !channel.isConnected()) { - throw new RequestChannelClosedException(getServerPort() + ", channel may be closed, " + url, request); - } - try { - if (request.getCallBackHandler() != null) { - server.sendCallback(channel, request.getRequestBody(), request.getCallBackHandler(), timeout); - return () -> Response.ResultStatus.SUCCESSFUL; - } else { - final Object result = server.sendSync(channel, request.getRequestBody(), timeout); - return () -> result; - } - } catch (Throwable e) { - throw new RequestException(getServerPort() + ", Exchanger request error! Request url:" + url, request, e); - } + public Response request(URL url, Request request) throws RequestException { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug( + "serverPort={} to client, url:{}, request body:{} ", + getServerPort(), + url, + request.getRequestBody()); + } + final Server server = boltExchange.getServer(getServerPort()); + if (server == null) { + throw new RequestException("no server for " + url + "," + getServerPort(), request); + } + final int timeout = request.getTimeout() != null ? request.getTimeout() : getRpcTimeoutMillis(); + Channel channel = null; + if (url == null) { + channel = choseChannel(server); + } else { + channel = server.getChannel(url); } - private Channel choseChannel(Server server) { - Collection channels = server.getChannels(); - Optional channelOptional = CollectionUtils.getRandom(channels); - if (channelOptional.isPresent()) { - Channel channel = channelOptional.get(); - if (channel.isConnected()) { - return channel; - } - } - return null; + if (channel == null || !channel.isConnected()) { + throw new RequestChannelClosedException( + getServerPort() + ", channel may be closed, " + url, request); } + try { + if (request.getCallBackHandler() != null) { + server.sendCallback( + channel, request.getRequestBody(), request.getCallBackHandler(), timeout); + return () -> Response.ResultStatus.SUCCESSFUL; + } else { + final Object result = server.sendSync(channel, request.getRequestBody(), timeout); + return () -> result; + } + } catch (Throwable e) { + throw new RequestException( + getServerPort() + ", Exchanger request error! Request url:" + url, request, e); + } + } - @Override - public Client connectServer() { - throw new UnsupportedOperationException(); + private Channel choseChannel(Server server) { + Collection channels = server.getChannels(); + Optional channelOptional = CollectionUtils.getRandom(channels); + if (channelOptional.isPresent()) { + Channel channel = channelOptional.get(); + if (channel.isConnected()) { + return channel; + } } + return null; + } + + @Override + public Client connectServer() { + throw new UnsupportedOperationException(); + } - public abstract int getRpcTimeoutMillis(); + public abstract int getRpcTimeoutMillis(); - public abstract int getServerPort(); + public abstract int getServerPort(); } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/SlotTableChangeEventHandler.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/SlotTableChangeEventHandler.java index 5c4b1b13a..0af8b73a9 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/SlotTableChangeEventHandler.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/remoting/SlotTableChangeEventHandler.java @@ -26,44 +26,41 @@ /** * @author chen.zhu - *

- * Feb 24, 2021 + *

Feb 24, 2021 */ public class SlotTableChangeEventHandler extends AbstractClientHandler { - @Autowired - private MetaServerService metaServerService; + @Autowired private MetaServerService metaServerService; - @Override - protected Node.NodeType getConnectNodeType() { - return Node.NodeType.META; - } + @Override + protected Node.NodeType getConnectNodeType() { + return Node.NodeType.META; + } - @Override - public void checkParam(SlotTableChangeEvent request) throws RuntimeException { - super.checkParam(request); - ParaCheckUtil.checkNotNull(request, "SlotTableChangeEvent"); - } + @Override + public void checkParam(SlotTableChangeEvent request) throws RuntimeException { + super.checkParam(request); + ParaCheckUtil.checkNotNull(request, "SlotTableChangeEvent"); + } - @Override - public Object doHandle(Channel channel, SlotTableChangeEvent request) { - boolean result = metaServerService.handleSlotTableChange(request); - if (result) { - return CommonResponse - .buildSuccessResponse("successfully triggered slot-table retrieval"); - } else { - return CommonResponse - .buildFailedResponse("won't update slot-table, check [AbstractMetaServerService] log"); - } + @Override + public Object doHandle(Channel channel, SlotTableChangeEvent request) { + boolean result = metaServerService.handleSlotTableChange(request); + if (result) { + return CommonResponse.buildSuccessResponse("successfully triggered slot-table retrieval"); + } else { + return CommonResponse.buildFailedResponse( + "won't update slot-table, check [AbstractMetaServerService] log"); } + } - @Override - public Object buildFailedResponse(String msg) { - return CommonResponse.buildFailedResponse(msg); - } + @Override + public Object buildFailedResponse(String msg) { + return CommonResponse.buildFailedResponse(msg); + } - @Override - public Class interest() { - return SlotTableChangeEvent.class; - } + @Override + public Class interest() { + return SlotTableChangeEvent.class; + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/resource/MetricsResource.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/resource/MetricsResource.java index bbe7de6a4..eba15a033 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/resource/MetricsResource.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/resource/MetricsResource.java @@ -18,30 +18,30 @@ import io.prometheus.client.CollectorRegistry; import io.prometheus.client.exporter.common.TextFormat; - +import java.io.OutputStreamWriter; +import java.io.Writer; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import javax.ws.rs.core.StreamingOutput; -import java.io.OutputStreamWriter; -import java.io.Writer; @Path("metrics") public class MetricsResource { - @GET - @Produces(TextFormat.CONTENT_TYPE_004) - public Response metrics() { - return Response - .ok() - .type(TextFormat.CONTENT_TYPE_004) - .entity((StreamingOutput) - output -> { - try (final Writer writer = new OutputStreamWriter(output)) { - TextFormat.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples()); - } - }) - .build(); - } + @GET + @Produces(TextFormat.CONTENT_TYPE_004) + public Response metrics() { + return Response.ok() + .type(TextFormat.CONTENT_TYPE_004) + .entity( + (StreamingOutput) + output -> { + try (final Writer writer = new OutputStreamWriter(output)) { + TextFormat.write004( + writer, CollectorRegistry.defaultRegistry.metricFamilySamples()); + } + }) + .build(); + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/resource/SlotGenericResource.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/resource/SlotGenericResource.java index e5d5e5252..1c0941889 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/resource/SlotGenericResource.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/resource/SlotGenericResource.java @@ -19,41 +19,39 @@ import com.alipay.sofa.registry.common.model.GenericResponse; import com.alipay.sofa.registry.common.model.slot.SlotTable; import com.alipay.sofa.registry.server.shared.slot.SlotTableRecorder; - +import java.util.concurrent.atomic.AtomicReference; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; -import java.util.concurrent.atomic.AtomicReference; /** * @author chen.zhu - *

- * Jan 12, 2021 + *

Jan 12, 2021 */ @Path("openapi/v1/slot") public class SlotGenericResource implements SlotTableRecorder { - private AtomicReference slotTableRef = new AtomicReference<>(SlotTable.INIT); + private AtomicReference slotTableRef = new AtomicReference<>(SlotTable.INIT); - @GET - @Path("/table") - @Produces(MediaType.APPLICATION_JSON) - public GenericResponse slotTable() { - SlotTable slotTable = slotTableRef.get(); - return new GenericResponse().fillSucceed(slotTable); - } + @GET + @Path("/table") + @Produces(MediaType.APPLICATION_JSON) + public GenericResponse slotTable() { + SlotTable slotTable = slotTableRef.get(); + return new GenericResponse().fillSucceed(slotTable); + } - @GET - @Path("/epoch") - @Produces(MediaType.APPLICATION_JSON) - public GenericResponse epoch() { - Long epoch = slotTableRef.get().getEpoch(); - return new GenericResponse().fillSucceed(epoch); - } + @GET + @Path("/epoch") + @Produces(MediaType.APPLICATION_JSON) + public GenericResponse epoch() { + Long epoch = slotTableRef.get().getEpoch(); + return new GenericResponse().fillSucceed(epoch); + } - @Override - public void record(SlotTable slotTable) { - this.slotTableRef.set(slotTable); - } + @Override + public void record(SlotTable slotTable) { + this.slotTableRef.set(slotTable); + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/DiskSlotTableRecorder.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/DiskSlotTableRecorder.java index 37261712d..1ececca50 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/DiskSlotTableRecorder.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/DiskSlotTableRecorder.java @@ -23,23 +23,21 @@ /** * @author chen.zhu - *

- * Dec 25, 2020 + *

Dec 25, 2020 */ public class DiskSlotTableRecorder implements SlotTableRecorder { - private static final Logger logger = LoggerFactory.getLogger(DiskSlotTableRecorder.class); - - @Override - public void record(SlotTable slotTable) { - try { - String slotStr = JsonUtils.writeValueAsString(slotTable); - if (logger.isInfoEnabled()) { - logger.info("[record] record slot: {}", slotStr); - } - } catch (Exception e) { - logger.error("[record]", e); - } + private static final Logger logger = LoggerFactory.getLogger(DiskSlotTableRecorder.class); + @Override + public void record(SlotTable slotTable) { + try { + String slotStr = JsonUtils.writeValueAsString(slotTable); + if (logger.isInfoEnabled()) { + logger.info("[record] record slot: {}", slotStr); + } + } catch (Exception e) { + logger.error("[record]", e); } + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/SlotTableRecorder.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/SlotTableRecorder.java index 52ec632c8..feedb6a30 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/SlotTableRecorder.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/SlotTableRecorder.java @@ -20,10 +20,9 @@ /** * @author chen.zhu - *

- * Dec 25, 2020 + *

Dec 25, 2020 */ public interface SlotTableRecorder { - void record(SlotTable slotTable); + void record(SlotTable slotTable); } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/SlotTableUtils.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/SlotTableUtils.java index 5b57d5261..76c70b581 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/SlotTableUtils.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/slot/SlotTableUtils.java @@ -21,72 +21,70 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.google.common.collect.Maps; -import org.apache.commons.lang.StringUtils; - import java.util.Map; +import org.apache.commons.lang.StringUtils; /** * @author chen.zhu - *

- * Jan 21, 2021 + *

Jan 21, 2021 */ public class SlotTableUtils { - private static final Logger logger = LoggerFactory.getLogger(SlotTableUtils.class); + private static final Logger logger = LoggerFactory.getLogger(SlotTableUtils.class); - public static Map getSlotTableLeaderCount(SlotTable slotTable) { - Map leaderCounter = Maps.newHashMap(); - for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { - Slot slot = entry.getValue(); - incrCount(leaderCounter, slot.getLeader()); - } - return leaderCounter; + public static Map getSlotTableLeaderCount(SlotTable slotTable) { + Map leaderCounter = Maps.newHashMap(); + for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { + Slot slot = entry.getValue(); + incrCount(leaderCounter, slot.getLeader()); } + return leaderCounter; + } - public static Map getSlotTableSlotCount(SlotTable slotTable) { - Map slotCounter = Maps.newHashMap(); - for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { - Slot slot = entry.getValue(); - incrCount(slotCounter, slot.getLeader()); - for (String follower : slot.getFollowers()) { - incrCount(slotCounter, follower); - } - } - return slotCounter; + public static Map getSlotTableSlotCount(SlotTable slotTable) { + Map slotCounter = Maps.newHashMap(); + for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { + Slot slot = entry.getValue(); + incrCount(slotCounter, slot.getLeader()); + for (String follower : slot.getFollowers()) { + incrCount(slotCounter, follower); + } } + return slotCounter; + } - private static void incrCount(Map counter, String dataServer) { - Integer count = counter.get(dataServer); - if (count == null) { - count = 0; - } - counter.put(dataServer, count + 1); + private static void incrCount(Map counter, String dataServer) { + Integer count = counter.get(dataServer); + if (count == null) { + count = 0; } + counter.put(dataServer, count + 1); + } - public static boolean isValidSlotTable(SlotTable slotTable) { - return checkNoDupLeaderAndFollowers(slotTable) && checkNoLeaderEmpty(slotTable); - } + public static boolean isValidSlotTable(SlotTable slotTable) { + return checkNoDupLeaderAndFollowers(slotTable) && checkNoLeaderEmpty(slotTable); + } - private static boolean checkNoDupLeaderAndFollowers(SlotTable slotTable) { - for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { - Slot slot = entry.getValue(); - if (slot.getFollowers().contains(slot.getLeader())) { - logger.error( - "[checkNoDupLeaderAndFollowers] slot[{}] leader and follower duplicates", slot); - return false; - } - } - return true; + private static boolean checkNoDupLeaderAndFollowers(SlotTable slotTable) { + for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { + Slot slot = entry.getValue(); + if (slot.getFollowers().contains(slot.getLeader())) { + logger.error( + "[checkNoDupLeaderAndFollowers] slot[{}] leader and follower duplicates", slot); + return false; + } } + return true; + } - private static boolean checkNoLeaderEmpty(SlotTable slotTable) { - for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { - Slot slot = entry.getValue(); - if (StringUtils.isEmpty(slot.getLeader())) { - logger.error("[checkNoLeaderEmpty] slot[{}] empty leader", slot); - return false; - } - } - return true; + private static boolean checkNoLeaderEmpty(SlotTable slotTable) { + for (Map.Entry entry : slotTable.getSlotMap().entrySet()) { + Slot slot = entry.getValue(); + if (StringUtils.isEmpty(slot.getLeader())) { + logger.error("[checkNoLeaderEmpty] slot[{}] empty leader", slot); + return false; + } } + return true; + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/AddressUtil.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/AddressUtil.java index dd71c471c..14ba51915 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/AddressUtil.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/AddressUtil.java @@ -22,45 +22,43 @@ import java.util.Map; /** - * * @author xiaojian.xj * @version $Id: AddressUtil.java, v 0.1 2020年12月13日 15:18 xiaojian.xj Exp $ */ public final class AddressUtil { - private AddressUtil() { - } + private AddressUtil() {} - //public static String buildURL(String address, Map> params) { - // if (CollectionUtils.isEmpty(params)) { - // return address; - // } - // URIBuilder builder = null; - // try { - // builder = new URIBuilder(address); - // - // for (Map.Entry> entry : params.entrySet()) { - // String key = entry.getDataKey(); - // for (String value : entry.getDataValue()) { - // builder.addParameter(key, value); - // - // } - // } - // return builder.build().toString(); - // } catch (URISyntaxException e) { - // LOGGER.error("build url error.", e); - // return null; - // } - //} + // public static String buildURL(String address, Map> params) { + // if (CollectionUtils.isEmpty(params)) { + // return address; + // } + // URIBuilder builder = null; + // try { + // builder = new URIBuilder(address); + // + // for (Map.Entry> entry : params.entrySet()) { + // String key = entry.getDataKey(); + // for (String value : entry.getDataValue()) { + // builder.addParameter(key, value); + // + // } + // } + // return builder.build().toString(); + // } catch (URISyntaxException e) { + // LOGGER.error("build url error.", e); + // return null; + // } + // } - public static String buildURL(String address, Map> params) { - List querys = new ArrayList<>(); - for (Map.Entry> entry : params.entrySet()) { - String key = entry.getKey(); - for (String value : entry.getValue()) { - querys.add(key + "=" + value); - } - } - String queryStr = String.join("&", querys); - return address + "?" + queryStr; + public static String buildURL(String address, Map> params) { + List querys = new ArrayList<>(); + for (Map.Entry> entry : params.entrySet()) { + String key = entry.getKey(); + for (String value : entry.getValue()) { + querys.add(key + "=" + value); + } } -} \ No newline at end of file + String queryStr = String.join("&", querys); + return address + "?" + queryStr; + } +} diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/DatumUtils.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/DatumUtils.java index 465ab49a0..97c346d08 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/DatumUtils.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/DatumUtils.java @@ -22,7 +22,6 @@ import com.alipay.sofa.registry.common.model.store.*; import com.google.common.collect.Lists; import com.google.common.collect.Maps; - import java.util.Collections; import java.util.List; import java.util.Map; @@ -32,46 +31,67 @@ * @since 2019/2/12 */ public final class DatumUtils { - private DatumUtils() { - } + private DatumUtils() {} - public static Map intern(Map versionMap) { - Map ret = Maps.newHashMapWithExpectedSize(versionMap.size()); - versionMap.forEach((k, v) -> ret.put(WordCache.getWordCache(k), v)); - return ret; - } + public static Map intern(Map versionMap) { + Map ret = Maps.newHashMapWithExpectedSize(versionMap.size()); + versionMap.forEach((k, v) -> ret.put(WordCache.getWordCache(k), v)); + return ret; + } - public static Map getVersions(Map datumMap) { - Map versions = Maps.newHashMapWithExpectedSize(datumMap.size()); - datumMap.forEach((k, v) -> versions.put(k, v.getVersion())); - return versions; - } + public static Map getVersions(Map datumMap) { + Map versions = Maps.newHashMapWithExpectedSize(datumMap.size()); + datumMap.forEach((k, v) -> versions.put(k, v.getVersion())); + return versions; + } - public static SubDatum newEmptySubDatum(Subscriber subscriber, String datacenter) { - SubDatum datum = new SubDatum(subscriber.getDataInfoId(), datacenter, - ValueConstants.DEFAULT_NO_DATUM_VERSION, Collections.emptyList(), - subscriber.getDataId(), subscriber.getInstanceId(), subscriber.getGroup()); - return datum; - } + public static SubDatum newEmptySubDatum(Subscriber subscriber, String datacenter) { + SubDatum datum = + new SubDatum( + subscriber.getDataInfoId(), + datacenter, + ValueConstants.DEFAULT_NO_DATUM_VERSION, + Collections.emptyList(), + subscriber.getDataId(), + subscriber.getInstanceId(), + subscriber.getGroup()); + return datum; + } - public static SubDatum newEmptySubDatum(DataInfo dataInfo, String datacenter) { - SubDatum datum = new SubDatum(dataInfo.getDataInfoId(), datacenter, - ValueConstants.DEFAULT_NO_DATUM_VERSION, Collections.emptyList(), dataInfo.getDataId(), - dataInfo.getInstanceId(), dataInfo.getGroup()); - return datum; - } + public static SubDatum newEmptySubDatum(DataInfo dataInfo, String datacenter) { + SubDatum datum = + new SubDatum( + dataInfo.getDataInfoId(), + datacenter, + ValueConstants.DEFAULT_NO_DATUM_VERSION, + Collections.emptyList(), + dataInfo.getDataId(), + dataInfo.getInstanceId(), + dataInfo.getGroup()); + return datum; + } - public static SubDatum of(Datum datum) { - List publishers = Lists.newArrayListWithCapacity(datum.publisherSize()); - for (Publisher publisher : datum.getPubMap().values()) { - final URL srcAddress = publisher.getSourceAddress(); - // temp publisher the srcAddress maybe null - final String srcAddressString = srcAddress == null ? null : srcAddress - .getAddressString(); - publishers.add(new SubPublisher(publisher.getCell(), publisher.getDataList(), publisher - .getClientId(), srcAddressString, publisher.getRegisterTimestamp())); - } - return new SubDatum(datum.getDataInfoId(), datum.getDataCenter(), datum.getVersion(), - publishers, datum.getDataId(), datum.getInstanceId(), datum.getGroup()); + public static SubDatum of(Datum datum) { + List publishers = Lists.newArrayListWithCapacity(datum.publisherSize()); + for (Publisher publisher : datum.getPubMap().values()) { + final URL srcAddress = publisher.getSourceAddress(); + // temp publisher the srcAddress maybe null + final String srcAddressString = srcAddress == null ? null : srcAddress.getAddressString(); + publishers.add( + new SubPublisher( + publisher.getCell(), + publisher.getDataList(), + publisher.getClientId(), + srcAddressString, + publisher.getRegisterTimestamp())); } + return new SubDatum( + datum.getDataInfoId(), + datum.getDataCenter(), + datum.getVersion(), + publishers, + datum.getDataId(), + datum.getInstanceId(), + datum.getGroup()); + } } diff --git a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/NodeUtils.java b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/NodeUtils.java index eec4e7a09..03250af93 100644 --- a/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/NodeUtils.java +++ b/server/server/shared/src/main/java/com/alipay/sofa/registry/server/shared/util/NodeUtils.java @@ -18,27 +18,26 @@ import com.alipay.sofa.registry.common.model.Node; import com.alipay.sofa.registry.common.model.slot.DataNodeSlot; - import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author chen.zhu - *

- * Jan 12, 2021 + *

Jan 12, 2021 */ public class NodeUtils { - public static List transferNodeToIpList(Collection nodes) { - List result = new ArrayList<>(nodes.size()); - nodes.forEach(node -> result.add(node.getNodeUrl().getIpAddress())); - return result; - } + public static List transferNodeToIpList(Collection nodes) { + List result = new ArrayList<>(nodes.size()); + nodes.forEach(node -> result.add(node.getNodeUrl().getIpAddress())); + return result; + } - public static List transferDataNodeSlotToIpList(Collection eles) { - List result = new ArrayList<>(eles.size()); - eles.forEach(ele -> result.add(ele.getDataNode())); - return result; - } + public static List transferDataNodeSlotToIpList( + Collection eles) { + List result = new ArrayList<>(eles.size()); + eles.forEach(ele -> result.add(ele.getDataNode())); + return result; + } } diff --git a/server/server/shared/src/test/java/com/alipay/sofa/registry/server/shared/util/DatumUtilsTest.java b/server/server/shared/src/test/java/com/alipay/sofa/registry/server/shared/util/DatumUtilsTest.java index f355f011d..63e017459 100644 --- a/server/server/shared/src/test/java/com/alipay/sofa/registry/server/shared/util/DatumUtilsTest.java +++ b/server/server/shared/src/test/java/com/alipay/sofa/registry/server/shared/util/DatumUtilsTest.java @@ -21,20 +21,19 @@ import org.junit.Test; /** - @author xuanbei - @since 2019/2/12 + * @author xuanbei + * @since 2019/2/12 */ public class DatumUtilsTest { - @Test - public void testNewDatumIfNull() { - Datum datum = new Datum(); - datum.setVersion(19092L); - datum.setDataId("test-dataId"); - datum.setDataCenter("test-dataCenter"); + @Test + public void testNewDatumIfNull() { + Datum datum = new Datum(); + datum.setVersion(19092L); + datum.setDataId("test-dataId"); + datum.setDataCenter("test-dataCenter"); - Subscriber subscriber = new Subscriber(); - subscriber.setDataId("subscriber-dataId"); - subscriber.setGroup("DEFAULT_GROUP"); - - } + Subscriber subscriber = new Subscriber(); + subscriber.setDataId("subscriber-dataId"); + subscriber.setGroup("DEFAULT_GROUP"); + } } diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/DBResponse.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/DBResponse.java index 5062fa37f..a74e387b5 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/DBResponse.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/DBResponse.java @@ -20,146 +20,143 @@ /** * DBResponse - * + * * @author shangyu.wh * @version $Id: DBResponse.java, v 0.1 2018-04-18 16:35 shangyu.wh Exp $ */ public class DBResponse implements Serializable { - private final Object entity; - - private final OperationStatus operationStatus; - - /** - * @param entity - * @param operationStatus - */ - public DBResponse(Object entity, OperationStatus operationStatus) { - this.entity = entity; - this.operationStatus = operationStatus; - } - - /** - * generate response ok - * - * @return - */ - public static DBResponseBuilder ok() { - return setStatus(OperationStatus.SUCCESS); - } - - /** - * generate response ok - * - * @param entity - * @return - */ - public static DBResponseBuilder ok(Object entity) { - DBResponseBuilder b = ok(); - b.entity(entity); - return b; - } - - /** - * set operationStatus to NOTFOUND - * - * @return - */ - public static DBResponseBuilder notfound() { - return setStatus(OperationStatus.NOTFOUND); - } - - /** - * set operationStatus - * - * @param status - * @return - */ - protected static DBResponseBuilder setStatus(OperationStatus status) { - DBResponseBuilder b = DBResponseBuilder.getInstance(); - b.status(status); - return b; - } - - /** - * Getter method for property entity. - * - * @return property value of entity - */ - public Object getEntity() { - return entity; - } - - /** - * Getter method for property operationStatus. - * - * @return property value of operationStatus - */ - public OperationStatus getOperationStatus() { - return operationStatus; - } - - /** - * DBResponseBuilder - */ - public static class DBResponseBuilder { - private static final DBResponseBuilder instance = new DBResponseBuilder(); - - private DBResponseBuilder() { - } - - /** - * get DBResponseBuilder instance - * - * @return - */ - public static DBResponseBuilder getInstance() { - return instance; - } - - private Object entity; - - private OperationStatus operationStatus; - - /** - * build func - * - * @return - */ - public DBResponse build() { - final DBResponse r = new DBResponse(entity, operationStatus); - reset(); - return r; - } - - private void reset() { - operationStatus = null; - entity = null; - } - - /** - * set operationStatus status - * - * @param status - * @return - */ - public DBResponseBuilder status(OperationStatus status) { - if (status == null) { - throw new IllegalArgumentException(); - } - this.operationStatus = status; - return this; - } - - /** - * set entity - * - * @param entity - * @return - */ - public DBResponseBuilder entity(Object entity) { - this.entity = entity; - return this; - } - } -} \ No newline at end of file + private final Object entity; + + private final OperationStatus operationStatus; + + /** + * @param entity + * @param operationStatus + */ + public DBResponse(Object entity, OperationStatus operationStatus) { + this.entity = entity; + this.operationStatus = operationStatus; + } + + /** + * generate response ok + * + * @return + */ + public static DBResponseBuilder ok() { + return setStatus(OperationStatus.SUCCESS); + } + + /** + * generate response ok + * + * @param entity + * @return + */ + public static DBResponseBuilder ok(Object entity) { + DBResponseBuilder b = ok(); + b.entity(entity); + return b; + } + + /** + * set operationStatus to NOTFOUND + * + * @return + */ + public static DBResponseBuilder notfound() { + return setStatus(OperationStatus.NOTFOUND); + } + + /** + * set operationStatus + * + * @param status + * @return + */ + protected static DBResponseBuilder setStatus(OperationStatus status) { + DBResponseBuilder b = DBResponseBuilder.getInstance(); + b.status(status); + return b; + } + + /** + * Getter method for property entity. + * + * @return property value of entity + */ + public Object getEntity() { + return entity; + } + + /** + * Getter method for property operationStatus. + * + * @return property value of operationStatus + */ + public OperationStatus getOperationStatus() { + return operationStatus; + } + + /** DBResponseBuilder */ + public static class DBResponseBuilder { + private static final DBResponseBuilder instance = new DBResponseBuilder(); + + private DBResponseBuilder() {} + + /** + * get DBResponseBuilder instance + * + * @return + */ + public static DBResponseBuilder getInstance() { + return instance; + } + + private Object entity; + + private OperationStatus operationStatus; + + /** + * build func + * + * @return + */ + public DBResponse build() { + final DBResponse r = new DBResponse(entity, operationStatus); + reset(); + return r; + } + + private void reset() { + operationStatus = null; + entity = null; + } + + /** + * set operationStatus status + * + * @param status + * @return + */ + public DBResponseBuilder status(OperationStatus status) { + if (status == null) { + throw new IllegalArgumentException(); + } + this.operationStatus = status; + return this; + } + + /** + * set entity + * + * @param entity + * @return + */ + public DBResponseBuilder entity(Object entity) { + this.entity = entity; + return this; + } + } +} diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/OperationStatus.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/OperationStatus.java index 4114059f9..0fffb9e76 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/OperationStatus.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/OperationStatus.java @@ -17,17 +17,13 @@ package com.alipay.sofa.registry.store.api; /** - @author xuanbei - @since 2019/2/12 + * @author xuanbei + * @since 2019/2/12 */ public enum OperationStatus { - /** - * The operation was successful. - */ - SUCCESS, + /** The operation was successful. */ + SUCCESS, - /** - * The requested key/data pair was not found. - */ - NOTFOUND + /** The requested key/data pair was not found. */ + NOTFOUND } diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/annotation/ReadOnLeader.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/annotation/ReadOnLeader.java index 5bd53e2f8..5b8b5f7be 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/annotation/ReadOnLeader.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/annotation/ReadOnLeader.java @@ -16,18 +16,16 @@ */ package com.alipay.sofa.registry.store.api.annotation; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.Target; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - /** - * * @author shangyu.wh * @version $Id: ReadOnLeader.java, v 0.1 2018-05-29 22:25 shangyu.wh Exp $ */ -@Target({ ElementType.METHOD }) +@Target({ElementType.METHOD}) @Retention(RUNTIME) -public @interface ReadOnLeader { -} \ No newline at end of file +public @interface ReadOnLeader {} diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RegistryRepository.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RegistryRepository.java index b6f632d4c..6d800a6a0 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RegistryRepository.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RegistryRepository.java @@ -17,22 +17,20 @@ package com.alipay.sofa.registry.store.api.driver; import com.alipay.sofa.registry.store.api.driver.RepositoryManager.RepositoryType; - import javax.annotation.PostConstruct; /** - * * @author xiaojian.xj * @version $Id: RegistryRepository.java, v 0.1 2021年01月15日 13:52 xiaojian.xj Exp $ */ public interface RegistryRepository { - public boolean accept(RepositoryType repositoryType); + public boolean accept(RepositoryType repositoryType); - public Class getInterfaceClass(); + public Class getInterfaceClass(); - @PostConstruct - default void init() { - RepositoryManager.registerRepository(this); - } -} \ No newline at end of file + @PostConstruct + default void init() { + RepositoryManager.registerRepository(this); + } +} diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RepositoryConfig.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RepositoryConfig.java index bee17a40c..aedb737e7 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RepositoryConfig.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RepositoryConfig.java @@ -17,51 +17,47 @@ package com.alipay.sofa.registry.store.api.driver; import com.alipay.sofa.registry.store.api.driver.RepositoryManager.RepositoryType; -import org.springframework.boot.context.properties.ConfigurationProperties; - import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.springframework.boot.context.properties.ConfigurationProperties; /** - * * @author xiaojian.xj * @version $Id: RepositoryConfig.java, v 0.1 2021年01月17日 14:08 xiaojian.xj Exp $ */ @ConfigurationProperties(prefix = RepositoryConfig.PRE_FIX) public class RepositoryConfig { - public static final String PRE_FIX = "jdbc"; + public static final String PRE_FIX = "jdbc"; - //application.properties - private String globalRepositoryType; - /** - * set RepositoryType config to Repository - */ - private static final Map repositoryConfig = new ConcurrentHashMap<>(); + // application.properties + private String globalRepositoryType; + /** set RepositoryType config to Repository */ + private static final Map repositoryConfig = new ConcurrentHashMap<>(); - public RepositoryType getRepositoryType(Class clazz) { - - if (repositoryConfig.containsKey(clazz)) { - return repositoryConfig.get(clazz); - } - return RepositoryType.getByCode(globalRepositoryType); - } - - /** - * Getter method for property globalRepositoryType. - * - * @return property value of globalRepositoryType - */ - public String getGlobalRepositoryType() { - return globalRepositoryType; - } + public RepositoryType getRepositoryType(Class clazz) { - /** - * Setter method for property globalRepositoryType. - * - * @param globalRepositoryType value to be assigned to property globalRepositoryType - */ - public void setGlobalRepositoryType(String globalRepositoryType) { - this.globalRepositoryType = globalRepositoryType; + if (repositoryConfig.containsKey(clazz)) { + return repositoryConfig.get(clazz); } -} \ No newline at end of file + return RepositoryType.getByCode(globalRepositoryType); + } + + /** + * Getter method for property globalRepositoryType. + * + * @return property value of globalRepositoryType + */ + public String getGlobalRepositoryType() { + return globalRepositoryType; + } + + /** + * Setter method for property globalRepositoryType. + * + * @param globalRepositoryType value to be assigned to property globalRepositoryType + */ + public void setGlobalRepositoryType(String globalRepositoryType) { + this.globalRepositoryType = globalRepositoryType; + } +} diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RepositoryManager.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RepositoryManager.java index 30577e9a3..0fba5873d 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RepositoryManager.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/driver/RepositoryManager.java @@ -19,95 +19,93 @@ import com.alipay.sofa.common.profile.StringUtil; import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author xiaojian.xj * @version $Id: RepositoryManager.java, v 0.1 2021年01月15日 12:03 xiaojian.xj Exp $ */ public class RepositoryManager { - private static final Logger REPOSITORY_LOGGER = LoggerFactory - .getLogger( - RepositoryManager.class, - "[RepositoryManager]"); + private static final Logger REPOSITORY_LOGGER = + LoggerFactory.getLogger(RepositoryManager.class, "[RepositoryManager]"); - private final static Map raftRegisterRepositorys = new ConcurrentHashMap<>(); + private static final Map raftRegisterRepositorys = + new ConcurrentHashMap<>(); - private final static Map jdbcRegisterRepositorys = new ConcurrentHashMap<>(); + private static final Map jdbcRegisterRepositorys = + new ConcurrentHashMap<>(); - @Autowired - private RepositoryConfig repositoryConfig; + @Autowired private RepositoryConfig repositoryConfig; - public static synchronized void registerRepository(RegistryRepository repository) { + public static synchronized void registerRepository(RegistryRepository repository) { - if (repository == null) { - throw new RuntimeException("register repository is null."); - } + if (repository == null) { + throw new RuntimeException("register repository is null."); + } - if (repository.accept(RepositoryType.RAFT)) { - raftRegisterRepositorys.putIfAbsent(repository.getInterfaceClass(), repository); - REPOSITORY_LOGGER.info("raft registerRaftRepository: " + repository); - } else if (repository.accept(RepositoryType.JDBC)) { - jdbcRegisterRepositorys.putIfAbsent(repository.getInterfaceClass(), repository); - REPOSITORY_LOGGER.info("jdbc registerRaftRepository: " + repository); - } else { - throw new RuntimeException("register repository accept is invalid."); - } + if (repository.accept(RepositoryType.RAFT)) { + raftRegisterRepositorys.putIfAbsent(repository.getInterfaceClass(), repository); + REPOSITORY_LOGGER.info("raft registerRaftRepository: " + repository); + } else if (repository.accept(RepositoryType.JDBC)) { + jdbcRegisterRepositorys.putIfAbsent(repository.getInterfaceClass(), repository); + REPOSITORY_LOGGER.info("jdbc registerRaftRepository: " + repository); + } else { + throw new RuntimeException("register repository accept is invalid."); } + } - public RegistryRepository getRepository(Class clazz) { + public RegistryRepository getRepository(Class clazz) { - RepositoryType driver = repositoryConfig.getRepositoryType(clazz); - RegistryRepository registryRepository = null; - if (driver == RepositoryType.JDBC) { - registryRepository = jdbcRegisterRepositorys.get(clazz); - } else if (driver == RepositoryType.RAFT) { - registryRepository = raftRegisterRepositorys.get(clazz); - } - if (registryRepository == null) { - REPOSITORY_LOGGER.error("repository not exist for class: " + clazz); - throw new RuntimeException("repository not exist."); - } - return registryRepository; + RepositoryType driver = repositoryConfig.getRepositoryType(clazz); + RegistryRepository registryRepository = null; + if (driver == RepositoryType.JDBC) { + registryRepository = jdbcRegisterRepositorys.get(clazz); + } else if (driver == RepositoryType.RAFT) { + registryRepository = raftRegisterRepositorys.get(clazz); + } + if (registryRepository == null) { + REPOSITORY_LOGGER.error("repository not exist for class: " + clazz); + throw new RuntimeException("repository not exist."); } + return registryRepository; + } - public enum RepositoryType { + public enum RepositoryType { + RAFT("raft:driver"), - RAFT("raft:driver"), + JDBC("jdbc:driver"), + ; - JDBC("jdbc:driver"), ; + private String code; - private String code; + RepositoryType(String code) { + this.code = code; + } - RepositoryType(String code) { - this.code = code; - } + public static RepositoryType getByCode(String code) { + if (StringUtil.isBlank(code)) { + return null; + } - public static RepositoryType getByCode(String code) { - if (StringUtil.isBlank(code)) { - return null; - } - - for (RepositoryType value : RepositoryType.values()) { - if (StringUtil.equals(value.getCode(), code)) { - return value; - } - } - REPOSITORY_LOGGER.error("error repository type: " + code); - return null; + for (RepositoryType value : RepositoryType.values()) { + if (StringUtil.equals(value.getCode(), code)) { + return value; } + } + REPOSITORY_LOGGER.error("error repository type: " + code); + return null; + } - /** - * Getter method for property code. - * - * @return property value of code - */ - public String getCode() { - return code; - } + /** + * Getter method for property code. + * + * @return property value of code + */ + public String getCode() { + return code; } -} \ No newline at end of file + } +} diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/AbstractLeaderElector.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/AbstractLeaderElector.java index ec0fbb091..00af41c84 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/AbstractLeaderElector.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/AbstractLeaderElector.java @@ -17,209 +17,205 @@ package com.alipay.sofa.registry.store.api.elector; import com.alipay.sofa.common.profile.StringUtil; +import com.alipay.sofa.registry.net.NetUtil; import com.alipay.sofa.registry.util.ConcurrentUtils; import com.alipay.sofa.registry.util.LoopRunnable; import com.google.common.collect.Lists; - -import javax.annotation.PostConstruct; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; +import javax.annotation.PostConstruct; /** * @author chen.zhu - *

- * Mar 10, 2021 + *

Mar 10, 2021 */ public abstract class AbstractLeaderElector implements LeaderElector { - private final List leaderAwares = Lists.newCopyOnWriteArrayList(); + private final List leaderAwares = Lists.newCopyOnWriteArrayList(); - private volatile LeaderInfo leaderInfo = LeaderInfo.hasNoLeader; + private volatile LeaderInfo leaderInfo = LeaderInfo.hasNoLeader; - private volatile boolean isObserver = false; + private volatile boolean isObserver = false; + @Override + public void registerLeaderAware(LeaderAware leaderAware) { + leaderAwares.add(leaderAware); + } + + @PostConstruct + public void init() { + ConcurrentUtils.createDaemonThread("LeaderElectorTrigger", new LeaderElectorTrigger()).start(); + } + + private class LeaderElectorTrigger extends LoopRunnable { @Override - public void registerLeaderAware(LeaderAware leaderAware) { - leaderAwares.add(leaderAware); + public void runUnthrowable() { + elect(); } - @PostConstruct - public void init() { - ConcurrentUtils.createDaemonThread("LeaderElectorTrigger", new LeaderElectorTrigger()).start(); + @Override + public void waitingUnthrowable() { + ConcurrentUtils.sleepUninterruptibly(1, TimeUnit.SECONDS); } + } + + public void elect() { + synchronized (this) { + if (isObserver) { + leaderInfo = doQuery(); + } else { + leaderInfo = doElect(); + } + + if (amILeader()) { + onIamLeader(); + } else { + onIamNotLeader(); + } + } + } + + @Override + public String myself() { + return NetUtil.getLocalAddress().getHostAddress(); + } + /** + * start compete leader + * + * @return + */ + @Override + public synchronized void change2Follow() { + this.isObserver = false; + } + + /** + * stop compete leader + * + * @return + */ + @Override + public synchronized void change2Observer() { + this.isObserver = true; + } + /** + * query leader + * + * @return + */ + protected abstract LeaderInfo doQuery(); + + /** + * elector leader + * + * @return + */ + protected abstract LeaderInfo doElect(); + + /** + * Am i elector boolean. + * + * @return the boolean + */ + @Override + public boolean amILeader() { + return leaderInfo != null + && StringUtil.equals(myself(), leaderInfo.leader) + && System.currentTimeMillis() < leaderInfo.expireTimestamp; + } + + protected boolean amILeader(String leader) { + return StringUtil.equals(myself(), leader) + && System.currentTimeMillis() < leaderInfo.expireTimestamp; + } + + /** + * Gets get elector. + * + * @return the get elector + */ + @Override + public String getLeader() { + if (leaderInfo == null) { + return LeaderInfo.hasNoLeader.leader; + } + return leaderInfo.leader; + } + + /** + * Gets get elector epoch. + * + * @return the get elector epoch + */ + @Override + public long getLeaderEpoch() { + if (leaderInfo == null) { + return LeaderInfo.hasNoLeader.epoch; + } + return leaderInfo.epoch; + } - private class LeaderElectorTrigger extends LoopRunnable { - - @Override - public void runUnthrowable() { - elect(); - } + /** notify when change to elector */ + private void onIamNotLeader() { + for (LeaderAware leaderAware : leaderAwares) { + leaderAware.followNotify(); + } + } - @Override - public void waitingUnthrowable() { - ConcurrentUtils.sleepUninterruptibly(1, TimeUnit.SECONDS); - } + /** notify when change to follow */ + private void onIamLeader() { + for (LeaderAware leaderAware : leaderAwares) { + leaderAware.leaderNotify(); } + } + public static class LeaderInfo { - public void elect() { - synchronized (this) { - if (isObserver) { - leaderInfo = doQuery(); - } else { - leaderInfo = doElect(); - } - - if (amILeader()) { - onIamLeader(); - } else { - onIamNotLeader(); - } - } - } + public static final long initEpoch = -1L; + public static final LeaderInfo hasNoLeader = new LeaderInfo(initEpoch); - @Override - public String myself() { - return NetUtil.getLocalAddress().getHostAddress(); - } - /** - * start compete leader - * @return - */ - @Override - public synchronized void change2Follow() { - this.isObserver = false; - } + private long epoch; - /** - * stop compete leader - * @return - */ - @Override - public synchronized void change2Observer() { - this.isObserver = true; - } - /** - * query leader - * @return - */ - protected abstract LeaderInfo doQuery(); + private String leader; - /** - * elector leader - * @return - */ - protected abstract LeaderInfo doElect(); + private long expireTimestamp; - /** - * Am i elector boolean. - * - * @return the boolean - */ - @Override - public boolean amILeader() { - return leaderInfo != null && StringUtil.equals(myself(), leaderInfo.leader) - && System.currentTimeMillis() < leaderInfo.expireTimestamp; + public LeaderInfo(long epoch) { + this.epoch = epoch; } - protected boolean amILeader(String leader) { - return StringUtil.equals(myself(), leader) - && System.currentTimeMillis() < leaderInfo.expireTimestamp; + public LeaderInfo(long epoch, String leader, Date lastHeartbeat, long duration) { + this.leader = leader; + this.epoch = epoch; + this.expireTimestamp = lastHeartbeat.getTime() + duration / 2; } /** - * Gets get elector. + * Getter method for property epoch. * - * @return the get elector + * @return property value of epoch */ - @Override - public String getLeader() { - if (leaderInfo == null) { - return LeaderInfo.hasNoLeader.leader; - } - return leaderInfo.leader; + public long getEpoch() { + return epoch; } /** - * Gets get elector epoch. + * Getter method for property leader. * - * @return the get elector epoch + * @return property value of leader */ - @Override - public long getLeaderEpoch() { - if (leaderInfo == null) { - return LeaderInfo.hasNoLeader.epoch; - } - return leaderInfo.epoch; - } - - /** - * notify when change to elector - */ - private void onIamNotLeader() { - for(LeaderAware leaderAware : leaderAwares) { - leaderAware.followNotify(); - } + public String getLeader() { + return leader; } /** - * notify when change to follow + * Getter method for property expireTimestamp. + * + * @return property value of expireTimestamp */ - private void onIamLeader() { - for(LeaderAware leaderAware : leaderAwares) { - leaderAware.leaderNotify(); - } + public long getExpireTimestamp() { + return expireTimestamp; } - - public static class LeaderInfo { - - public static final long initEpoch = -1L; - public static final LeaderInfo hasNoLeader = new LeaderInfo(initEpoch); - - private long epoch; - - private String leader; - - private long expireTimestamp; - - public LeaderInfo(long epoch) { - this.epoch = epoch; - } - - public LeaderInfo(long epoch, String leader, Date lastHeartbeat, long duration) { - this.leader = leader; - this.epoch = epoch; - this.expireTimestamp = lastHeartbeat.getTime() + duration/2; - } - - - /** - * Getter method for property epoch. - * - * @return property value of epoch - */ - public long getEpoch() { - return epoch; - } - - /** - * Getter method for property leader. - * - * @return property value of leader - */ - public String getLeader() { - return leader; - } - - /** - * Getter method for property expireTimestamp. - * - * @return property value of expireTimestamp - */ - public long getExpireTimestamp() { - return expireTimestamp; - } - } - + } } diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/LeaderAware.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/LeaderAware.java index 5688e6a77..833fadffd 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/LeaderAware.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/LeaderAware.java @@ -18,17 +18,12 @@ /** * @author chen.zhu - *

- * Nov 21, 2020 + *

Nov 21, 2020 */ public interface LeaderAware { - /** - * notify listeners when I'm elector. - */ - void leaderNotify(); + /** notify listeners when I'm elector. */ + void leaderNotify(); - /** - * notify listeners when I'm not elector. - */ - void followNotify(); + /** notify listeners when I'm not elector. */ + void followNotify(); } diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/LeaderElector.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/LeaderElector.java index f9a7189eb..8aaca1f2b 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/LeaderElector.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/elector/LeaderElector.java @@ -20,59 +20,61 @@ /** * @author chen.zhu - *

- * Mar 09, 2021 + *

Mar 09, 2021 */ public interface LeaderElector { - void registerLeaderAware(LeaderAware leaderAware); + void registerLeaderAware(LeaderAware leaderAware); - default String myself() { - return NetUtil.getLocalAddress().getHostAddress(); - } + default String myself() { + return NetUtil.getLocalAddress().getHostAddress(); + } - /** - * start compete leader - * @return - */ - void change2Follow(); + /** + * start compete leader + * + * @return + */ + void change2Follow(); - /** - * stop compete leader - * @return - */ - void change2Observer(); + /** + * stop compete leader + * + * @return + */ + void change2Observer(); - /** - * Am i elector boolean. - * - * @return the boolean - */ - boolean amILeader(); + /** + * Am i elector boolean. + * + * @return the boolean + */ + boolean amILeader(); - /** - * Gets get elector. - * - * @return the get elector - */ - String getLeader(); + /** + * Gets get elector. + * + * @return the get elector + */ + String getLeader(); + /** + * Gets get elector epoch. + * + * @return the get elector epoch + */ + long getLeaderEpoch(); - /** - * Gets get elector epoch. - * - * @return the get elector epoch - */ - long getLeaderEpoch(); - - - enum ElectorRole { - LEADER, FOLLOWER,; - } - - enum ElectorState { - INIT, COMPETING, STOP,; - } - + enum ElectorRole { + LEADER, + FOLLOWER, + ; + } + enum ElectorState { + INIT, + COMPETING, + STOP, + ; + } } diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/meta/ProvideDataRepository.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/meta/ProvideDataRepository.java index 9a66186dd..ef6793114 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/meta/ProvideDataRepository.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/meta/ProvideDataRepository.java @@ -20,37 +20,35 @@ /** * @author chen.zhu - *

- * Mar 09, 2021 + *

Mar 09, 2021 */ public interface ProvideDataRepository { - /** - * save or update provideData - * - * @param dataCenter - * @param key - * @param value - * @return - */ - boolean put(String dataCenter, String key, String value); + /** + * save or update provideData + * + * @param dataCenter + * @param key + * @param value + * @return + */ + boolean put(String dataCenter, String key, String value); - /** - * query provideData by key - * - * @param dataCenter - * @param key - * @return - */ - DBResponse get(String dataCenter, String key); - - /** - * delete provideData - * - * @param dataCenter - * @param key - * @return - */ - boolean remove(String dataCenter, String key); + /** + * query provideData by key + * + * @param dataCenter + * @param key + * @return + */ + DBResponse get(String dataCenter, String key); + /** + * delete provideData + * + * @param dataCenter + * @param key + * @return + */ + boolean remove(String dataCenter, String key); } diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/AppRevisionHeartbeatRepository.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/AppRevisionHeartbeatRepository.java index 4cc5b6819..d013f69d1 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/AppRevisionHeartbeatRepository.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/AppRevisionHeartbeatRepository.java @@ -19,19 +19,17 @@ import com.alipay.sofa.registry.store.api.driver.RegistryRepository; /** - * * @author xiaojian.xj * @version $Id: AppRevisionHeartbeatRepository.java, v 0.1 2021年02月09日 17:09 xiaojian.xj Exp $ */ public interface AppRevisionHeartbeatRepository extends RegistryRepository { + @Override + default Class getInterfaceClass() { + return AppRevisionHeartbeatRepository.class; + } - @Override - default Class getInterfaceClass() { - return AppRevisionHeartbeatRepository.class; - } - - public void doAppRevisionHeartbeat(); + public void doAppRevisionHeartbeat(); - public void doAppRevisionGc(String dataCenter, int silenceHour); -} \ No newline at end of file + public void doAppRevisionGc(String dataCenter, int silenceHour); +} diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/AppRevisionRepository.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/AppRevisionRepository.java index a8c3df25f..0a0a9eff0 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/AppRevisionRepository.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/AppRevisionRepository.java @@ -20,35 +20,34 @@ import com.alipay.sofa.registry.store.api.driver.RegistryRepository; /** - * * @author xiaojian.xj * @version $Id: AppRevisionRepository.java, v 0.1 2021年01月17日 13:54 xiaojian.xj Exp $ */ public interface AppRevisionRepository extends RegistryRepository { - @Override - default Class getInterfaceClass() { - return AppRevisionRepository.class; - } + @Override + default Class getInterfaceClass() { + return AppRevisionRepository.class; + } - /** - * persistence appRevision - * @param appRevision - */ - public void register(AppRevision appRevision) throws Exception; + /** + * persistence appRevision + * + * @param appRevision + */ + public void register(AppRevision appRevision) throws Exception; - /** - * refresh - */ - public void refresh(String dataCenter); + /** refresh */ + public void refresh(String dataCenter); - /** - * get AppRevision - * @param dataCenter - * @param revision - * @return - */ - public AppRevision queryRevision(String dataCenter, String revision); + /** + * get AppRevision + * + * @param dataCenter + * @param revision + * @return + */ + public AppRevision queryRevision(String dataCenter, String revision); - public AppRevision heartbeat(String dataCenter, String revision); -} \ No newline at end of file + public AppRevision heartbeat(String dataCenter, String revision); +} diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/InterfaceAppsRepository.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/InterfaceAppsRepository.java index 3090f525f..7d0babae7 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/InterfaceAppsRepository.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/repository/InterfaceAppsRepository.java @@ -16,41 +16,43 @@ */ package com.alipay.sofa.registry.store.api.repository; - import com.alipay.sofa.registry.common.model.appmeta.InterfaceMapping; import com.alipay.sofa.registry.store.api.driver.RegistryRepository; - import java.util.Set; /** - * * @author xiaojian.xj * @version $Id: InterfaceAppsRepository.java, v 0.1 2021年01月24日 19:33 xiaojian.xj Exp $ */ public interface InterfaceAppsRepository extends RegistryRepository { - @Override - default Class getInterfaceClass() { - return InterfaceAppsRepository.class; - } + @Override + default Class getInterfaceClass() { + return InterfaceAppsRepository.class; + } - /** - * get revisions by interfaceName - * @param dataInfoId - * @return return - */ - InterfaceMapping getAppNames(String dataCenter, String dataInfoId); - /** - * insert - * @param dataCenter - * @param appName - * @return - */ - default int batchSave(String dataCenter, String appName, Set interfaceName) {return 0;} + /** + * get revisions by interfaceName + * + * @param dataInfoId + * @return return + */ + InterfaceMapping getAppNames(String dataCenter, String dataInfoId); + /** + * insert + * + * @param dataCenter + * @param appName + * @return + */ + default int batchSave(String dataCenter, String appName, Set interfaceName) { + return 0; + } - /** - * refresh when startup - * @param dataCenter - */ - void loadMetadata(String dataCenter); -} \ No newline at end of file + /** + * refresh when startup + * + * @param dataCenter + */ + void loadMetadata(String dataCenter); +} diff --git a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/spring/SpringContext.java b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/spring/SpringContext.java index 2f98ce21b..4812e6409 100644 --- a/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/spring/SpringContext.java +++ b/server/store/api/src/main/java/com/alipay/sofa/registry/store/api/spring/SpringContext.java @@ -18,14 +18,13 @@ /** * @author chen.zhu - *

- * Mar 15, 2021 + *

Mar 15, 2021 */ public final class SpringContext { - public static final String META_STORE_API_JDBC = "JDBC"; + public static final String META_STORE_API_JDBC = "JDBC"; - public static final String META_STORE_API_RAFT = "RAFT"; + public static final String META_STORE_API_RAFT = "RAFT"; - public static final String META_SERVER_CLOUD_MODEL = "CLOUD"; + public static final String META_SERVER_CLOUD_MODEL = "CLOUD"; } diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcConfiguration.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcConfiguration.java index 0051a324b..ffc792ab9 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcConfiguration.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcConfiguration.java @@ -16,12 +16,14 @@ */ package com.alipay.sofa.registry.jdbc.config; +import static com.alibaba.druid.pool.DruidDataSourceFactory.*; + import com.alibaba.druid.filter.logging.Slf4jLogFilter; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.alipay.sofa.registry.jdbc.elector.MetaJdbcLeaderElector; +import com.alipay.sofa.registry.jdbc.repository.batch.AppRevisionBatchQueryCallable; import com.alipay.sofa.registry.jdbc.repository.batch.AppRevisionHeartbeatBatchCallable; import com.alipay.sofa.registry.jdbc.repository.batch.InterfaceAppBatchQueryCallable; -import com.alipay.sofa.registry.jdbc.repository.batch.AppRevisionBatchQueryCallable; import com.alipay.sofa.registry.jdbc.repository.impl.AppRevisionHeartbeatJdbcRepository; import com.alipay.sofa.registry.jdbc.repository.impl.AppRevisionJdbcRepository; import com.alipay.sofa.registry.jdbc.repository.impl.InterfaceAppsJdbcRepository; @@ -31,6 +33,8 @@ import com.alipay.sofa.registry.store.api.repository.AppRevisionRepository; import com.alipay.sofa.registry.store.api.repository.InterfaceAppsRepository; import com.alipay.sofa.registry.util.SystemUtils; +import java.util.Properties; +import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; @@ -40,13 +44,8 @@ import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.support.TransactionTemplate; -import javax.sql.DataSource; -import java.util.Properties; - -import static com.alibaba.druid.pool.DruidDataSourceFactory.*; /** - * * @author xiaojian.xj * @version $Id: JdbcConfiguration.java, v 0.1 2021年01月17日 16:28 xiaojian.xj Exp $ */ @@ -54,169 +53,172 @@ @EnableConfigurationProperties public class JdbcConfiguration { - @Configuration - @MapperScan(basePackages = "com.alipay.sofa.registry.jdbc.mapper") - public static class MybatisBeanConfiguration { - @Bean - public JdbcDriverConfig jdbcDriverConfig() { - return new JdbcDriverConfigBean(); - } - - @Bean - public Slf4jLogFilter logFilter() { - Slf4jLogFilter filter = new Slf4jLogFilter(); - filter.setResultSetLogEnabled(true); - filter.setConnectionLogEnabled(true); - filter.setStatementParameterClearLogEnable(true); - filter.setStatementCreateAfterLogEnabled(true); - filter.setStatementCloseAfterLogEnabled(true); - filter.setStatementParameterSetLogEnabled(true); - filter.setStatementPrepareAfterLogEnabled(true); - filter.setStatementExecutableSqlLogEnable(true); - return filter; - } - - /** - * create datasource - * @return - * @throws Exception - */ - @Bean - public DataSource dataSource(JdbcDriverConfig jdbcDriverConfig, Slf4jLogFilter logFilter) - throws Exception { - Properties props = new Properties(); - props.put(PROP_DRIVERCLASSNAME, SystemUtils.getSystem(PROP_DRIVERCLASSNAME, jdbcDriverConfig.getDriverClassName())); - props.put(PROP_URL, SystemUtils.getSystem(PROP_URL, jdbcDriverConfig.getUrl())); - props.put(PROP_USERNAME, SystemUtils.getSystem(PROP_USERNAME, jdbcDriverConfig.getUsername())); - props.put(PROP_PASSWORD, SystemUtils.getSystem(PROP_PASSWORD, jdbcDriverConfig.getPassword())); - - // todo connection pool config - props.put(PROP_MINIDLE, jdbcDriverConfig.getMinIdle() + ""); - props.put(PROP_MAXACTIVE, jdbcDriverConfig.getMaxActive() + ""); - props.put(PROP_MAXWAIT, jdbcDriverConfig.getMaxWait() + ""); - props.put(PROP_REMOVEABANDONED, "true"); - props.put(PROP_REMOVEABANDONEDTIMEOUT, "30"); - props.put(PROP_LOGABANDONED, "true"); - props.put(PROP_INIT, "true"); - - // log filter - //props.put(PROP_FILTERS, logFilter); - - DataSource dataSource = DruidDataSourceFactory.createDataSource(props); - - return dataSource; - } - - /** - * create sqlSessionFactory - * @param dataSource - * @return - * @throws Exception - */ - @Bean - public SqlSessionFactory sqlSessionFactory(DataSource dataSource, - JdbcDriverConfig jdbcDriverConfig) - throws Exception { - SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); - factoryBean.setDataSource(dataSource); - //factoryBean.setTypeAliasesPackage(jdbcDriverConfig.getTypeAliasesPackage()); - factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver() - .getResources(jdbcDriverConfig.getMapperLocations())); - - return factoryBean.getObject(); - } - - @Bean - public DataSourceTransactionManager transactionManager(DataSource dataSource) { - DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(); - transactionManager.setDataSource(dataSource); - return transactionManager; - } - - @Bean - public TransactionTemplate transactionTemplate(DataSourceTransactionManager transactionManager) { - TransactionTemplate transactionTemplate = new TransactionTemplate(); - transactionTemplate.setTransactionManager(transactionManager); - return transactionTemplate; - } - } - - @Configuration - public static class MetadataBeanConfiguration { - @Bean - public MetadataConfig metadataConfig() { - return new MetadataConfigBean(); - } - - @Bean - public MetaElectorConfig metaElectorConfig() { - return new MetaElectorConfigBean(); - } - } - - @Configuration - public static class RepositoryBeanConfiguration { - - /** - * JDBC Repository - */ - @Bean - public AppRevisionRepository appRevisionJdbcRepository() { - return new AppRevisionJdbcRepository(); - } - - @Bean - public InterfaceAppsRepository interfaceAppsJdbcRepository() { - return new InterfaceAppsJdbcRepository(); - } - - @Bean - public AppRevisionHeartbeatRepository appRevisionHeartbeatJdbcRepository() { - return new AppRevisionHeartbeatJdbcRepository(); - } - - @Bean - public MetaJdbcLeaderElector jdbcLeaderElector() { - return new MetaJdbcLeaderElector(); - } - - @Bean - public MetaJdbcLeaderElector.ElectorRoleService leaderService(MetaJdbcLeaderElector leaderElector) { - MetaJdbcLeaderElector.LeaderService leaderService = leaderElector.new LeaderService(); - leaderElector.addElectorRoleService(leaderService); - return leaderService; - } - - @Bean - public MetaJdbcLeaderElector.ElectorRoleService followService(MetaJdbcLeaderElector leaderElector) { - MetaJdbcLeaderElector.FollowService followService = leaderElector.new FollowService(); - leaderElector.addElectorRoleService(followService); - return followService; - } - - @Bean - public ProvideDataRepository provideDataJdbcRepository() { - return new ProvideDataJdbcRepository(); - } - - /** - * batch callable - */ - @Bean - public AppRevisionBatchQueryCallable appRevisionBatchQueryCallable() { - return new AppRevisionBatchQueryCallable(); - } - - @Bean - public InterfaceAppBatchQueryCallable interfaceAppBatchQueryCallable() { - return new InterfaceAppBatchQueryCallable(); - } - - @Bean - public AppRevisionHeartbeatBatchCallable appRevisionHeartbeatBatchCallable() { - return new AppRevisionHeartbeatBatchCallable(); - } - - } - -} \ No newline at end of file + @Configuration + @MapperScan(basePackages = "com.alipay.sofa.registry.jdbc.mapper") + public static class MybatisBeanConfiguration { + @Bean + public JdbcDriverConfig jdbcDriverConfig() { + return new JdbcDriverConfigBean(); + } + + @Bean + public Slf4jLogFilter logFilter() { + Slf4jLogFilter filter = new Slf4jLogFilter(); + filter.setResultSetLogEnabled(true); + filter.setConnectionLogEnabled(true); + filter.setStatementParameterClearLogEnable(true); + filter.setStatementCreateAfterLogEnabled(true); + filter.setStatementCloseAfterLogEnabled(true); + filter.setStatementParameterSetLogEnabled(true); + filter.setStatementPrepareAfterLogEnabled(true); + filter.setStatementExecutableSqlLogEnable(true); + return filter; + } + + /** + * create datasource + * + * @return + * @throws Exception + */ + @Bean + public DataSource dataSource(JdbcDriverConfig jdbcDriverConfig, Slf4jLogFilter logFilter) + throws Exception { + Properties props = new Properties(); + props.put( + PROP_DRIVERCLASSNAME, + SystemUtils.getSystem(PROP_DRIVERCLASSNAME, jdbcDriverConfig.getDriverClassName())); + props.put(PROP_URL, SystemUtils.getSystem(PROP_URL, jdbcDriverConfig.getUrl())); + props.put( + PROP_USERNAME, SystemUtils.getSystem(PROP_USERNAME, jdbcDriverConfig.getUsername())); + props.put( + PROP_PASSWORD, SystemUtils.getSystem(PROP_PASSWORD, jdbcDriverConfig.getPassword())); + + // todo connection pool config + props.put(PROP_MINIDLE, jdbcDriverConfig.getMinIdle() + ""); + props.put(PROP_MAXACTIVE, jdbcDriverConfig.getMaxActive() + ""); + props.put(PROP_MAXWAIT, jdbcDriverConfig.getMaxWait() + ""); + props.put(PROP_REMOVEABANDONED, "true"); + props.put(PROP_REMOVEABANDONEDTIMEOUT, "30"); + props.put(PROP_LOGABANDONED, "true"); + props.put(PROP_INIT, "true"); + + // log filter + // props.put(PROP_FILTERS, logFilter); + + DataSource dataSource = DruidDataSourceFactory.createDataSource(props); + + return dataSource; + } + + /** + * create sqlSessionFactory + * + * @param dataSource + * @return + * @throws Exception + */ + @Bean + public SqlSessionFactory sqlSessionFactory( + DataSource dataSource, JdbcDriverConfig jdbcDriverConfig) throws Exception { + SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); + factoryBean.setDataSource(dataSource); + // factoryBean.setTypeAliasesPackage(jdbcDriverConfig.getTypeAliasesPackage()); + factoryBean.setMapperLocations( + new PathMatchingResourcePatternResolver() + .getResources(jdbcDriverConfig.getMapperLocations())); + + return factoryBean.getObject(); + } + + @Bean + public DataSourceTransactionManager transactionManager(DataSource dataSource) { + DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(); + transactionManager.setDataSource(dataSource); + return transactionManager; + } + + @Bean + public TransactionTemplate transactionTemplate( + DataSourceTransactionManager transactionManager) { + TransactionTemplate transactionTemplate = new TransactionTemplate(); + transactionTemplate.setTransactionManager(transactionManager); + return transactionTemplate; + } + } + + @Configuration + public static class MetadataBeanConfiguration { + @Bean + public MetadataConfig metadataConfig() { + return new MetadataConfigBean(); + } + + @Bean + public MetaElectorConfig metaElectorConfig() { + return new MetaElectorConfigBean(); + } + } + + @Configuration + public static class RepositoryBeanConfiguration { + + /** JDBC Repository */ + @Bean + public AppRevisionRepository appRevisionJdbcRepository() { + return new AppRevisionJdbcRepository(); + } + + @Bean + public InterfaceAppsRepository interfaceAppsJdbcRepository() { + return new InterfaceAppsJdbcRepository(); + } + + @Bean + public AppRevisionHeartbeatRepository appRevisionHeartbeatJdbcRepository() { + return new AppRevisionHeartbeatJdbcRepository(); + } + + @Bean + public MetaJdbcLeaderElector jdbcLeaderElector() { + return new MetaJdbcLeaderElector(); + } + + @Bean + public MetaJdbcLeaderElector.ElectorRoleService leaderService( + MetaJdbcLeaderElector leaderElector) { + MetaJdbcLeaderElector.LeaderService leaderService = leaderElector.new LeaderService(); + leaderElector.addElectorRoleService(leaderService); + return leaderService; + } + + @Bean + public MetaJdbcLeaderElector.ElectorRoleService followService( + MetaJdbcLeaderElector leaderElector) { + MetaJdbcLeaderElector.FollowService followService = leaderElector.new FollowService(); + leaderElector.addElectorRoleService(followService); + return followService; + } + + @Bean + public ProvideDataRepository provideDataJdbcRepository() { + return new ProvideDataJdbcRepository(); + } + + /** batch callable */ + @Bean + public AppRevisionBatchQueryCallable appRevisionBatchQueryCallable() { + return new AppRevisionBatchQueryCallable(); + } + + @Bean + public InterfaceAppBatchQueryCallable interfaceAppBatchQueryCallable() { + return new InterfaceAppBatchQueryCallable(); + } + + @Bean + public AppRevisionHeartbeatBatchCallable appRevisionHeartbeatBatchCallable() { + return new AppRevisionHeartbeatBatchCallable(); + } + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcDriverConfig.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcDriverConfig.java index 5bdc61e11..3f50455f4 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcDriverConfig.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcDriverConfig.java @@ -17,30 +17,28 @@ package com.alipay.sofa.registry.jdbc.config; /** - * * @author xiaojian.xj - * @version $Id: JdbcDriverConfig.java, v 0.1 2021年01月17日 17:28 xiaojian.xj Exp - * $ + * @version $Id: JdbcDriverConfig.java, v 0.1 2021年01月17日 17:28 xiaojian.xj Exp $ */ public interface JdbcDriverConfig { - String getDriverClassName(); + String getDriverClassName(); - String getUrl(); + String getUrl(); - String getUsername(); + String getUsername(); - String getPassword(); + String getPassword(); - // get domain path - String getTypeAliasesPackage(); + // get domain path + String getTypeAliasesPackage(); - // get mapper.xml path - String getMapperLocations(); + // get mapper.xml path + String getMapperLocations(); - int getMinIdle(); + int getMinIdle(); - int getMaxActive(); + int getMaxActive(); - int getMaxWait(); -} \ No newline at end of file + int getMaxWait(); +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcDriverConfigBean.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcDriverConfigBean.java index 382b8347a..7258b80d1 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcDriverConfigBean.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/JdbcDriverConfigBean.java @@ -19,200 +19,200 @@ import org.springframework.boot.context.properties.ConfigurationProperties; /** - * * @author xiaojian.xj * @version $Id: JdbcDriverConfigBean.java, v 0.1 2021年01月17日 16:39 xiaojian.xj Exp $ */ @ConfigurationProperties(prefix = JdbcDriverConfigBean.PRE_FIX) public class JdbcDriverConfigBean implements JdbcDriverConfig { - public static final String PRE_FIX = "jdbc"; - - private String driverClassName = "com.mysql.jdbc.Driver"; - - private String url = "jdbc:mysql://127.0.0.1:2883/metadatadb?useUnicode=true&characterEncoding=utf8"; - - private String username = "username"; - - private String password = "password"; - - private String typeAliasesPackage; - - private String mapperLocations = "classpath:mapper/*.xml"; - - private int minIdle = 3; - - private int maxActive = 5; - - private int maxWait = 3000; - - /** - * Getter method for property driverClassName. - * - * @return property value of driverClassName - */ - @Override - public String getDriverClassName() { - return driverClassName; - } - - /** - * Setter method for property driverClassName. - * - * @param driverClassName value to be assigned to property driverClassName - */ - public void setDriverClassName(String driverClassName) { - this.driverClassName = driverClassName; - } - - /** - * Getter method for property url. - * - * @return property value of url - */ - @Override - public String getUrl() { - return url; - } - - /** - * Setter method for property url. - * - * @param url value to be assigned to property url - */ - public void setUrl(String url) { - this.url = url; - } - - /** - * Getter method for property username. - * - * @return property value of username - */ - public String getUsername() { - return username; - } - - /** - * Setter method for property username. - * - * @param username value to be assigned to property username - */ - public void setUsername(String username) { - this.username = username; - } - - /** - * Getter method for property password. - * - * @return property value of password - */ - @Override - public String getPassword() { - return password; - } - - /** - * Setter method for property password. - * - * @param password value to be assigned to property password - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * Getter method for property typeAliasesPackage. - * - * @return property value of typeAliasesPackage - */ - @Override - public String getTypeAliasesPackage() { - return typeAliasesPackage; - } - - /** - * Setter method for property typeAliasesPackage. - * - * @param typeAliasesPackage value to be assigned to property typeAliasesPackage - */ - public void setTypeAliasesPackage(String typeAliasesPackage) { - this.typeAliasesPackage = typeAliasesPackage; - } - - /** - * Getter method for property mapperLocations. - * - * @return property value of mapperLocations - */ - @Override - public String getMapperLocations() { - return mapperLocations; - } - - /** - * Setter method for property mapperLocations. - * - * @param mapperLocations value to be assigned to property mapperLocations - */ - public void setMapperLocations(String mapperLocations) { - this.mapperLocations = mapperLocations; - } - - /** - * Getter method for property minIdle. - * - * @return property value of minIdle - */ - @Override - public int getMinIdle() { - return minIdle; - } - - /** - * Setter method for property minIdle. - * - * @param minIdle value to be assigned to property minIdle - */ - public void setMinIdle(int minIdle) { - this.minIdle = minIdle; - } - - /** - * Getter method for property maxActive. - * - * @return property value of maxActive - */ - @Override - public int getMaxActive() { - return maxActive; - } - - /** - * Setter method for property maxActive. - * - * @param maxActive value to be assigned to property maxActive - */ - public void setMaxActive(int maxActive) { - this.maxActive = maxActive; - } - - /** - * Getter method for property maxWait. - * - * @return property value of maxWait - */ - @Override - public int getMaxWait() { - return maxWait; - } - - /** - * Setter method for property maxWait. - * - * @param maxWait value to be assigned to property maxWait - */ - public void setMaxWait(int maxWait) { - this.maxWait = maxWait; - } -} \ No newline at end of file + public static final String PRE_FIX = "jdbc"; + + private String driverClassName = "com.mysql.jdbc.Driver"; + + private String url = + "jdbc:mysql://127.0.0.1:2883/metadatadb?useUnicode=true&characterEncoding=utf8"; + + private String username = "username"; + + private String password = "password"; + + private String typeAliasesPackage; + + private String mapperLocations = "classpath:mapper/*.xml"; + + private int minIdle = 3; + + private int maxActive = 5; + + private int maxWait = 3000; + + /** + * Getter method for property driverClassName. + * + * @return property value of driverClassName + */ + @Override + public String getDriverClassName() { + return driverClassName; + } + + /** + * Setter method for property driverClassName. + * + * @param driverClassName value to be assigned to property driverClassName + */ + public void setDriverClassName(String driverClassName) { + this.driverClassName = driverClassName; + } + + /** + * Getter method for property url. + * + * @return property value of url + */ + @Override + public String getUrl() { + return url; + } + + /** + * Setter method for property url. + * + * @param url value to be assigned to property url + */ + public void setUrl(String url) { + this.url = url; + } + + /** + * Getter method for property username. + * + * @return property value of username + */ + public String getUsername() { + return username; + } + + /** + * Setter method for property username. + * + * @param username value to be assigned to property username + */ + public void setUsername(String username) { + this.username = username; + } + + /** + * Getter method for property password. + * + * @return property value of password + */ + @Override + public String getPassword() { + return password; + } + + /** + * Setter method for property password. + * + * @param password value to be assigned to property password + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * Getter method for property typeAliasesPackage. + * + * @return property value of typeAliasesPackage + */ + @Override + public String getTypeAliasesPackage() { + return typeAliasesPackage; + } + + /** + * Setter method for property typeAliasesPackage. + * + * @param typeAliasesPackage value to be assigned to property typeAliasesPackage + */ + public void setTypeAliasesPackage(String typeAliasesPackage) { + this.typeAliasesPackage = typeAliasesPackage; + } + + /** + * Getter method for property mapperLocations. + * + * @return property value of mapperLocations + */ + @Override + public String getMapperLocations() { + return mapperLocations; + } + + /** + * Setter method for property mapperLocations. + * + * @param mapperLocations value to be assigned to property mapperLocations + */ + public void setMapperLocations(String mapperLocations) { + this.mapperLocations = mapperLocations; + } + + /** + * Getter method for property minIdle. + * + * @return property value of minIdle + */ + @Override + public int getMinIdle() { + return minIdle; + } + + /** + * Setter method for property minIdle. + * + * @param minIdle value to be assigned to property minIdle + */ + public void setMinIdle(int minIdle) { + this.minIdle = minIdle; + } + + /** + * Getter method for property maxActive. + * + * @return property value of maxActive + */ + @Override + public int getMaxActive() { + return maxActive; + } + + /** + * Setter method for property maxActive. + * + * @param maxActive value to be assigned to property maxActive + */ + public void setMaxActive(int maxActive) { + this.maxActive = maxActive; + } + + /** + * Getter method for property maxWait. + * + * @return property value of maxWait + */ + @Override + public int getMaxWait() { + return maxWait; + } + + /** + * Setter method for property maxWait. + * + * @param maxWait value to be assigned to property maxWait + */ + public void setMaxWait(int maxWait) { + this.maxWait = maxWait; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetaElectorConfig.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetaElectorConfig.java index da47fc51a..91e9fb186 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetaElectorConfig.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetaElectorConfig.java @@ -17,13 +17,12 @@ package com.alipay.sofa.registry.jdbc.config; /** - * * @author xiaojian.xj * @version $Id: MetaElectorConfig.java, v 0.1 2021年03月17日 16:49 xiaojian.xj Exp $ */ public interface MetaElectorConfig { - String getDataCenter(); + String getDataCenter(); - long getLockExpireDuration(); -} \ No newline at end of file + long getLockExpireDuration(); +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetaElectorConfigBean.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetaElectorConfigBean.java index 3896bcca0..2070fc1e7 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetaElectorConfigBean.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetaElectorConfigBean.java @@ -19,44 +19,43 @@ import org.springframework.boot.context.properties.ConfigurationProperties; /** - * * @author xiaojian.xj * @version $Id: MetaElectorConfigBean.java, v 0.1 2021年03月17日 16:49 xiaojian.xj Exp $ */ @ConfigurationProperties(prefix = MetaElectorConfigBean.PRE_FIX) public class MetaElectorConfigBean implements MetaElectorConfig { - public static final String PRE_FIX = "meta.server.elector"; - - private String dataCenter; - - private long lockExpireDuration = 20 * 1000; - - @Override - public String getDataCenter() { - return dataCenter; - } - - @Override - public long getLockExpireDuration() { - return lockExpireDuration; - } - - /** - * Setter method for property dataCenter. - * - * @param dataCenter value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } - - /** - * Setter method for property lockExpireDuration. - * - * @param lockExpireDuration value to be assigned to property lockExpireDuration - */ - public void setLockExpireDuration(long lockExpireDuration) { - this.lockExpireDuration = lockExpireDuration; - } -} \ No newline at end of file + public static final String PRE_FIX = "meta.server.elector"; + + private String dataCenter; + + private long lockExpireDuration = 20 * 1000; + + @Override + public String getDataCenter() { + return dataCenter; + } + + @Override + public long getLockExpireDuration() { + return lockExpireDuration; + } + + /** + * Setter method for property dataCenter. + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } + + /** + * Setter method for property lockExpireDuration. + * + * @param lockExpireDuration value to be assigned to property lockExpireDuration + */ + public void setLockExpireDuration(long lockExpireDuration) { + this.lockExpireDuration = lockExpireDuration; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetadataConfig.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetadataConfig.java index fd532db4d..be0ffa853 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetadataConfig.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetadataConfig.java @@ -17,13 +17,12 @@ package com.alipay.sofa.registry.jdbc.config; /** - * * @author xiaojian.xj * @version $Id: MetadataConfig.java, v 0.1 2021年02月24日 15:20 xiaojian.xj Exp $ */ public interface MetadataConfig { - int getInterfaceAppsRefreshLimit(); + int getInterfaceAppsRefreshLimit(); - int getRevisionGcLimit(); -} \ No newline at end of file + int getRevisionGcLimit(); +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetadataConfigBean.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetadataConfigBean.java index adc49dbbb..505a94d4c 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetadataConfigBean.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/config/MetadataConfigBean.java @@ -19,54 +19,52 @@ import org.springframework.boot.context.properties.ConfigurationProperties; /** - * * @author xiaojian.xj * @version $Id: MetadataConfigBean.java, v 0.1 2021年02月24日 15:21 xiaojian.xj Exp $ */ @ConfigurationProperties(prefix = MetadataConfigBean.PRE_FIX) public class MetadataConfigBean implements MetadataConfig { - public static final String PRE_FIX = "metadata.server"; - - private int interfaceAppsRefreshLimit = 1000; + public static final String PRE_FIX = "metadata.server"; - private int revisionGcLimit = 100; + private int interfaceAppsRefreshLimit = 1000; + private int revisionGcLimit = 100; - /** - * Getter method for property interfaceAppsRefreshLimit. - * - * @return property value of interfaceAppsRefreshLimit - */ - public int getInterfaceAppsRefreshLimit() { - return interfaceAppsRefreshLimit; - } + /** + * Getter method for property interfaceAppsRefreshLimit. + * + * @return property value of interfaceAppsRefreshLimit + */ + public int getInterfaceAppsRefreshLimit() { + return interfaceAppsRefreshLimit; + } - /** - * Setter method for property interfaceAppsRefreshLimit. - * - * @param interfaceAppsRefreshLimit value to be assigned to property interfaceAppsRefreshLimit - */ - public void setInterfaceAppsRefreshLimit(int interfaceAppsRefreshLimit) { - this.interfaceAppsRefreshLimit = interfaceAppsRefreshLimit; - } + /** + * Setter method for property interfaceAppsRefreshLimit. + * + * @param interfaceAppsRefreshLimit value to be assigned to property interfaceAppsRefreshLimit + */ + public void setInterfaceAppsRefreshLimit(int interfaceAppsRefreshLimit) { + this.interfaceAppsRefreshLimit = interfaceAppsRefreshLimit; + } - /** - * Getter method for property revisionGcLimit. - * - * @return property value of revisionGcLimit - */ - @Override - public int getRevisionGcLimit() { - return revisionGcLimit; - } + /** + * Getter method for property revisionGcLimit. + * + * @return property value of revisionGcLimit + */ + @Override + public int getRevisionGcLimit() { + return revisionGcLimit; + } - /** - * Setter method for property revisionGcLimit. - * - * @param revisionGcLimit value to be assigned to property revisionGcLimit - */ - public void setRevisionGcLimit(int revisionGcLimit) { - this.revisionGcLimit = revisionGcLimit; - } -} \ No newline at end of file + /** + * Setter method for property revisionGcLimit. + * + * @param revisionGcLimit value to be assigned to property revisionGcLimit + */ + public void setRevisionGcLimit(int revisionGcLimit) { + this.revisionGcLimit = revisionGcLimit; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/convertor/AppRevisionDomainConvertor.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/convertor/AppRevisionDomainConvertor.java index 345e777ea..0597afe34 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/convertor/AppRevisionDomainConvertor.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/convertor/AppRevisionDomainConvertor.java @@ -21,67 +21,66 @@ import com.alipay.sofa.registry.jdbc.domain.AppRevisionDomain; import com.alipay.sofa.registry.util.JsonUtils; import com.fasterxml.jackson.core.type.TypeReference; -import org.springframework.util.CollectionUtils; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; +import org.springframework.util.CollectionUtils; /** - * * @author xiaojian.xj * @version $Id: AppRevisionDomainConvertor.java, v 0.1 2021年01月18日 19:00 xiaojian.xj Exp $ */ public class AppRevisionDomainConvertor { - public static final TypeReference BASE_FORMAT = new TypeReference>>() { - }; - public static final TypeReference SERVICE_FORMAT = new TypeReference>() { - }; + public static final TypeReference BASE_FORMAT = + new TypeReference>>() {}; + public static final TypeReference SERVICE_FORMAT = + new TypeReference>() {}; - public static AppRevisionDomain convert2Domain(AppRevision appRevision) { - if (appRevision == null) { - return null; - } - AppRevisionDomain domain = new AppRevisionDomain(); - domain.setAppName(appRevision.getAppName()); - domain.setDataCenter(appRevision.getDataCenter()); - domain.setRevision(appRevision.getRevision()); - domain.setClientVersion(appRevision.getClientVersion()); - domain.setBaseParams(JsonUtils.writeValueAsString(appRevision.getBaseParams())); - domain.setServiceParams(JsonUtils.writeValueAsString(appRevision.getInterfaceMap())); - return domain; + public static AppRevisionDomain convert2Domain(AppRevision appRevision) { + if (appRevision == null) { + return null; } + AppRevisionDomain domain = new AppRevisionDomain(); + domain.setAppName(appRevision.getAppName()); + domain.setDataCenter(appRevision.getDataCenter()); + domain.setRevision(appRevision.getRevision()); + domain.setClientVersion(appRevision.getClientVersion()); + domain.setBaseParams(JsonUtils.writeValueAsString(appRevision.getBaseParams())); + domain.setServiceParams(JsonUtils.writeValueAsString(appRevision.getInterfaceMap())); + return domain; + } - public static AppRevision convert2Revision(AppRevisionDomain domain) { + public static AppRevision convert2Revision(AppRevisionDomain domain) { - if (domain == null) { - return null; - } - - AppRevision appRevision = new AppRevision(); - appRevision.setDataCenter(domain.getDataCenter()); - appRevision.setAppName(domain.getAppName()); - appRevision.setRevision(domain.getRevision()); - appRevision.setClientVersion(domain.getClientVersion()); - appRevision.setBaseParams(JsonUtils.read(domain.getBaseParams(), BASE_FORMAT)); - appRevision.setInterfaceMap(JsonUtils.read(domain.getServiceParams(), SERVICE_FORMAT)); - appRevision.setLastHeartbeat(domain.getGmtModify()); - return appRevision; + if (domain == null) { + return null; } - public static List convert2Revisions(List domains) { - if (CollectionUtils.isEmpty(domains)) { - return Collections.EMPTY_LIST; - } + AppRevision appRevision = new AppRevision(); + appRevision.setDataCenter(domain.getDataCenter()); + appRevision.setAppName(domain.getAppName()); + appRevision.setRevision(domain.getRevision()); + appRevision.setClientVersion(domain.getClientVersion()); + appRevision.setBaseParams(JsonUtils.read(domain.getBaseParams(), BASE_FORMAT)); + appRevision.setInterfaceMap(JsonUtils.read(domain.getServiceParams(), SERVICE_FORMAT)); + appRevision.setLastHeartbeat(domain.getGmtModify()); + return appRevision; + } + + public static List convert2Revisions(List domains) { + if (CollectionUtils.isEmpty(domains)) { + return Collections.EMPTY_LIST; + } - List revisions = new ArrayList<>(); - for (AppRevisionDomain domain : domains) { - AppRevision revision = convert2Revision(domain); - if (revision != null) { - revisions.add(revision); - } - } - return revisions; + List revisions = new ArrayList<>(); + for (AppRevisionDomain domain : domains) { + AppRevision revision = convert2Revision(domain); + if (revision != null) { + revisions.add(revision); + } } -} \ No newline at end of file + return revisions; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppInterfaceIndexQueryModel.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppInterfaceIndexQueryModel.java index d968ed707..48bc35e3d 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppInterfaceIndexQueryModel.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppInterfaceIndexQueryModel.java @@ -19,77 +19,72 @@ import com.google.common.base.Objects; /** - * * @author xiaojian.xj * @version $Id: AppInterfaceIndexQueryModel.java, v 0.1 2021年01月24日 19:08 xiaojian.xj Exp $ */ public class AppInterfaceIndexQueryModel { - /** - * local data center - */ - private String dataCenter; + /** local data center */ + private String dataCenter; - /** - * appName - */ - private String appName; + /** appName */ + private String appName; - public AppInterfaceIndexQueryModel(String dataCenter, String appName) { - this.dataCenter = dataCenter; - this.appName = appName; - } + public AppInterfaceIndexQueryModel(String dataCenter, String appName) { + this.dataCenter = dataCenter; + this.appName = appName; + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof AppInterfaceIndexQueryModel)) { - return false; - } - AppInterfaceIndexQueryModel that = (AppInterfaceIndexQueryModel) o; - return Objects.equal(dataCenter, that.dataCenter) && Objects.equal(appName, that.appName); + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - @Override - public int hashCode() { - return Objects.hashCode(dataCenter, appName); + if (!(o instanceof AppInterfaceIndexQueryModel)) { + return false; } + AppInterfaceIndexQueryModel that = (AppInterfaceIndexQueryModel) o; + return Objects.equal(dataCenter, that.dataCenter) && Objects.equal(appName, that.appName); + } - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } + @Override + public int hashCode() { + return Objects.hashCode(dataCenter, appName); + } - /** - * Setter method for property dataCenter. - * - * @param dataCenter value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } - /** - * Getter method for property appName. - * - * @return property value of appName - */ - public String getAppName() { - return appName; - } + /** + * Setter method for property dataCenter. + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } - /** - * Setter method for property appName. - * - * @param appName value to be assigned to property appName - */ - public void setAppName(String appName) { - this.appName = appName; - } -} \ No newline at end of file + /** + * Getter method for property appName. + * + * @return property value of appName + */ + public String getAppName() { + return appName; + } + + /** + * Setter method for property appName. + * + * @param appName value to be assigned to property appName + */ + public void setAppName(String appName) { + this.appName = appName; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppRevisionDomain.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppRevisionDomain.java index fcf1f6164..0f8cd012c 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppRevisionDomain.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppRevisionDomain.java @@ -19,226 +19,197 @@ import java.util.Date; /** - * * @author xiaojian.xj - * @version $Id: AppRevisionDomain.java, v 0.1 2021年01月18日 17:51 xiaojian.xj Exp - * $ + * @version $Id: AppRevisionDomain.java, v 0.1 2021年01月18日 17:51 xiaojian.xj Exp $ */ public class AppRevisionDomain { - /** - * primary key - */ - private long id; - - /** - * local data center - */ - private String dataCenter; - - /** - * revision - */ - private String revision; - - /** - * appName - */ - private String appName; - - /** - * clientVersion - */ - private String clientVersion; - - /** - * base_params - */ - private String baseParams; - - /** - * service_params - */ - private String serviceParams; - - /** - * create time - */ - private Date gmtCreate; - - /** - * last update time - */ - private Date gmtModify; - - /** - * Getter method for property id. - * - * @return property value of id - */ - public long getId() { - return id; - } - - /** - * Setter method for property id. - * - * @param id - * value to be assigned to property id - */ - public void setId(long id) { - this.id = id; - } - - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } - - /** - * Setter method for property dataCenter. - * - * @param dataCenter - * value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } - - /** - * Getter method for property revision. - * - * @return property value of revision - */ - public String getRevision() { - return revision; - } - - /** - * Setter method for property revision. - * - * @param revision - * value to be assigned to property revision - */ - public void setRevision(String revision) { - this.revision = revision; - } - - /** - * Getter method for property appName. - * - * @return property value of appName - */ - public String getAppName() { - return appName; - } - - /** - * Setter method for property appName. - * - * @param appName - * value to be assigned to property appName - */ - public void setAppName(String appName) { - this.appName = appName; - } - - /** - * Getter method for property baseParams. - * - * @return property value of baseParams - */ - public String getBaseParams() { - return baseParams; - } - - /** - * Setter method for property baseParams. - * - * @param baseParams - * value to be assigned to property baseParams - */ - public void setBaseParams(String baseParams) { - this.baseParams = baseParams; - } - - /** - * Getter method for property serviceParams. - * - * @return property value of serviceParams - */ - public String getServiceParams() { - return serviceParams; - } - - /** - * Setter method for property serviceParams. - * - * @param serviceParams - * value to be assigned to property serviceParams - */ - public void setServiceParams(String serviceParams) { - this.serviceParams = serviceParams; - } - - /** - * Getter method for property gmtCreate. - * - * @return property value of gmtCreate - */ - public Date getGmtCreate() { - return gmtCreate; - } - - /** - * Setter method for property gmtCreate. - * - * @param gmtCreate - * value to be assigned to property gmtCreate - */ - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } - - /** - * Getter method for property gmtModify. - * - * @return property value of gmtModify - */ - public Date getGmtModify() { - return gmtModify; - } - - /** - * Setter method for property gmtModify. - * - * @param gmtModify - * value to be assigned to property gmtModify - */ - public void setGmtModify(Date gmtModify) { - this.gmtModify = gmtModify; - } - - /** - * Getter method for property clientVersion. - * - * @return property value of clientVersion - */ - public String getClientVersion() { - return clientVersion; - } - - /** - * Setter method for property clientVersion. - * - * @param clientVersion - * value to be assigned to property clientVersion - */ - public void setClientVersion(String clientVersion) { - this.clientVersion = clientVersion; - } -} \ No newline at end of file + /** primary key */ + private long id; + + /** local data center */ + private String dataCenter; + + /** revision */ + private String revision; + + /** appName */ + private String appName; + + /** clientVersion */ + private String clientVersion; + + /** base_params */ + private String baseParams; + + /** service_params */ + private String serviceParams; + + /** create time */ + private Date gmtCreate; + + /** last update time */ + private Date gmtModify; + + /** + * Getter method for property id. + * + * @return property value of id + */ + public long getId() { + return id; + } + + /** + * Setter method for property id. + * + * @param id value to be assigned to property id + */ + public void setId(long id) { + this.id = id; + } + + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * Setter method for property dataCenter. + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } + + /** + * Getter method for property revision. + * + * @return property value of revision + */ + public String getRevision() { + return revision; + } + + /** + * Setter method for property revision. + * + * @param revision value to be assigned to property revision + */ + public void setRevision(String revision) { + this.revision = revision; + } + + /** + * Getter method for property appName. + * + * @return property value of appName + */ + public String getAppName() { + return appName; + } + + /** + * Setter method for property appName. + * + * @param appName value to be assigned to property appName + */ + public void setAppName(String appName) { + this.appName = appName; + } + + /** + * Getter method for property baseParams. + * + * @return property value of baseParams + */ + public String getBaseParams() { + return baseParams; + } + + /** + * Setter method for property baseParams. + * + * @param baseParams value to be assigned to property baseParams + */ + public void setBaseParams(String baseParams) { + this.baseParams = baseParams; + } + + /** + * Getter method for property serviceParams. + * + * @return property value of serviceParams + */ + public String getServiceParams() { + return serviceParams; + } + + /** + * Setter method for property serviceParams. + * + * @param serviceParams value to be assigned to property serviceParams + */ + public void setServiceParams(String serviceParams) { + this.serviceParams = serviceParams; + } + + /** + * Getter method for property gmtCreate. + * + * @return property value of gmtCreate + */ + public Date getGmtCreate() { + return gmtCreate; + } + + /** + * Setter method for property gmtCreate. + * + * @param gmtCreate value to be assigned to property gmtCreate + */ + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + + /** + * Getter method for property gmtModify. + * + * @return property value of gmtModify + */ + public Date getGmtModify() { + return gmtModify; + } + + /** + * Setter method for property gmtModify. + * + * @param gmtModify value to be assigned to property gmtModify + */ + public void setGmtModify(Date gmtModify) { + this.gmtModify = gmtModify; + } + + /** + * Getter method for property clientVersion. + * + * @return property value of clientVersion + */ + public String getClientVersion() { + return clientVersion; + } + + /** + * Setter method for property clientVersion. + * + * @param clientVersion value to be assigned to property clientVersion + */ + public void setClientVersion(String clientVersion) { + this.clientVersion = clientVersion; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppRevisionQueryModel.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppRevisionQueryModel.java index 6b72dcdb3..ad1ddf739 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppRevisionQueryModel.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/AppRevisionQueryModel.java @@ -19,76 +19,71 @@ import com.google.common.base.Objects; /** - * * @author xiaojian.xj * @version $Id: AppRevisionQueryModel.java, v 0.1 2021年01月24日 16:26 xiaojian.xj Exp $ */ public class AppRevisionQueryModel { - /** - * local data center - */ - private String dataCenter; + /** local data center */ + private String dataCenter; - /** - * revision - */ - private String revision; + /** revision */ + private String revision; - public AppRevisionQueryModel(String dataCenter, String revision) { - this.dataCenter = dataCenter; - this.revision = revision; - } + public AppRevisionQueryModel(String dataCenter, String revision) { + this.dataCenter = dataCenter; + this.revision = revision; + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof AppRevisionQueryModel)) { - return false; - } - AppRevisionQueryModel that = (AppRevisionQueryModel) o; - return Objects.equal(dataCenter, that.dataCenter) && Objects.equal(revision, that.revision); + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - @Override - public int hashCode() { - return Objects.hashCode(dataCenter, revision); + if (!(o instanceof AppRevisionQueryModel)) { + return false; } + AppRevisionQueryModel that = (AppRevisionQueryModel) o; + return Objects.equal(dataCenter, that.dataCenter) && Objects.equal(revision, that.revision); + } - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } + @Override + public int hashCode() { + return Objects.hashCode(dataCenter, revision); + } - /** - * Setter method for property dataCenter. - * - * @param dataCenter value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } - /** - * Getter method for property revision. - * - * @return property value of revision - */ - public String getRevision() { - return revision; - } + /** + * Setter method for property dataCenter. + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } - /** - * Setter method for property revision. - * - * @param revision value to be assigned to property revision - */ - public void setRevision(String revision) { - this.revision = revision; - } -} \ No newline at end of file + /** + * Getter method for property revision. + * + * @return property value of revision + */ + public String getRevision() { + return revision; + } + + /** + * Setter method for property revision. + * + * @param revision value to be assigned to property revision + */ + public void setRevision(String revision) { + this.revision = revision; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/DistributeLockDomain.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/DistributeLockDomain.java index 061162125..6e1af3146 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/DistributeLockDomain.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/DistributeLockDomain.java @@ -19,221 +19,213 @@ import java.util.Date; /** - * * @author xiaojian.xj * @version $Id: DistributeLockDomain.java, v 0.1 2021年03月12日 14:34 xiaojian.xj Exp $ */ public class DistributeLockDomain { - /** - * primary key - */ - private long id; - - /** - * local data center - */ - private String dataCenter; - - /** - * lock name - */ - private String lockName; - - /** - * lock owner - */ - private String owner; - - /** - * duration(millisecond) - */ - private long duration; - - /** - * create - */ - private Date gmtCreate; - - /** - * last update timestamp - */ - private Date gmtModified; - - /** - * current timestamp in db - */ - private Date gmtDbServerTime; - - public DistributeLockDomain() { - } - - public DistributeLockDomain(String dataCenter, String lockName, String owner, long duration) { - this.dataCenter = dataCenter; - this.lockName = lockName; - this.owner = owner; - this.duration = duration; - } - - /** - * Getter method for property id. - * - * @return property value of id - */ - public long getId() { - return id; - } - - /** - * Setter method for property id. - * - * @param id value to be assigned to property id - */ - public void setId(long id) { - this.id = id; - } - - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } - - /** - * Setter method for property dataCenter. - * - * @param dataCenter value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } - - /** - * Getter method for property lockName. - * - * @return property value of lockName - */ - public String getLockName() { - return lockName; - } - - /** - * Setter method for property lockName. - * - * @param lockName value to be assigned to property lockName - */ - public void setLockName(String lockName) { - this.lockName = lockName; - } - - /** - * Getter method for property owner. - * - * @return property value of owner - */ - public String getOwner() { - return owner; - } - - /** - * Setter method for property owner. - * - * @param owner value to be assigned to property owner - */ - public void setOwner(String owner) { - this.owner = owner; - } - - /** - * Getter method for property duration. - * - * @return property value of duration - */ - public long getDuration() { - return duration; - } - - /** - * Setter method for property duration. - * - * @param duration value to be assigned to property duration - */ - public void setDuration(long duration) { - this.duration = duration; - } - - /** - * Getter method for property gmtCreate. - * - * @return property value of gmtCreate - */ - public Date getGmtCreate() { - return gmtCreate; - } - - /** - * Setter method for property gmtCreate. - * - * @param gmtCreate value to be assigned to property gmtCreate - */ - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } - - /** - * Getter method for property gmtModified. - * - * @return property value of gmtModified - */ - public Date getGmtModified() { - return gmtModified; - } - - /** - * Setter method for property gmtModified. - * - * @param gmtModified value to be assigned to property gmtModified - */ - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } - - /** - * Getter method for property gmtDbServerTime. - * - * @return property value of gmtDbServerTime - */ - public Date getGmtDbServerTime() { - return gmtDbServerTime; - } - - /** - * Setter method for property gmtDbServerTime. - * - * @param gmtDbServerTime value to be assigned to property gmtDbServerTime - */ - public void setGmtDbServerTime(Date gmtDbServerTime) { - this.gmtDbServerTime = gmtDbServerTime; - } - - public boolean expire() { - - return gmtDbServerTime.getTime() > gmtModified.getTime() + duration; - } - - @Override - public String toString() { - return "DistributeLock{" + - "dataCenter='" + dataCenter + '\'' + - ", lockName='" + lockName + '\'' + - ", owner='" + owner + '\'' + - ", duration=" + duration + - ", gmtCreate=" + gmtCreate + - ", gmtModified=" + gmtModified + - ", gmtDbServerTime=" + gmtDbServerTime + - '}'; - } -} \ No newline at end of file + /** primary key */ + private long id; + + /** local data center */ + private String dataCenter; + + /** lock name */ + private String lockName; + + /** lock owner */ + private String owner; + + /** duration(millisecond) */ + private long duration; + + /** create */ + private Date gmtCreate; + + /** last update timestamp */ + private Date gmtModified; + + /** current timestamp in db */ + private Date gmtDbServerTime; + + public DistributeLockDomain() {} + + public DistributeLockDomain(String dataCenter, String lockName, String owner, long duration) { + this.dataCenter = dataCenter; + this.lockName = lockName; + this.owner = owner; + this.duration = duration; + } + + /** + * Getter method for property id. + * + * @return property value of id + */ + public long getId() { + return id; + } + + /** + * Setter method for property id. + * + * @param id value to be assigned to property id + */ + public void setId(long id) { + this.id = id; + } + + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * Setter method for property dataCenter. + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } + + /** + * Getter method for property lockName. + * + * @return property value of lockName + */ + public String getLockName() { + return lockName; + } + + /** + * Setter method for property lockName. + * + * @param lockName value to be assigned to property lockName + */ + public void setLockName(String lockName) { + this.lockName = lockName; + } + + /** + * Getter method for property owner. + * + * @return property value of owner + */ + public String getOwner() { + return owner; + } + + /** + * Setter method for property owner. + * + * @param owner value to be assigned to property owner + */ + public void setOwner(String owner) { + this.owner = owner; + } + + /** + * Getter method for property duration. + * + * @return property value of duration + */ + public long getDuration() { + return duration; + } + + /** + * Setter method for property duration. + * + * @param duration value to be assigned to property duration + */ + public void setDuration(long duration) { + this.duration = duration; + } + + /** + * Getter method for property gmtCreate. + * + * @return property value of gmtCreate + */ + public Date getGmtCreate() { + return gmtCreate; + } + + /** + * Setter method for property gmtCreate. + * + * @param gmtCreate value to be assigned to property gmtCreate + */ + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + + /** + * Getter method for property gmtModified. + * + * @return property value of gmtModified + */ + public Date getGmtModified() { + return gmtModified; + } + + /** + * Setter method for property gmtModified. + * + * @param gmtModified value to be assigned to property gmtModified + */ + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } + + /** + * Getter method for property gmtDbServerTime. + * + * @return property value of gmtDbServerTime + */ + public Date getGmtDbServerTime() { + return gmtDbServerTime; + } + + /** + * Setter method for property gmtDbServerTime. + * + * @param gmtDbServerTime value to be assigned to property gmtDbServerTime + */ + public void setGmtDbServerTime(Date gmtDbServerTime) { + this.gmtDbServerTime = gmtDbServerTime; + } + + public boolean expire() { + + return gmtDbServerTime.getTime() > gmtModified.getTime() + duration; + } + + @Override + public String toString() { + return "DistributeLock{" + + "dataCenter='" + + dataCenter + + '\'' + + ", lockName='" + + lockName + + '\'' + + ", owner='" + + owner + + '\'' + + ", duration=" + + duration + + ", gmtCreate=" + + gmtCreate + + ", gmtModified=" + + gmtModified + + ", gmtDbServerTime=" + + gmtDbServerTime + + '}'; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/FollowCompeteLockDomain.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/FollowCompeteLockDomain.java index 6dc95b4b4..7abe0465e 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/FollowCompeteLockDomain.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/FollowCompeteLockDomain.java @@ -19,142 +19,124 @@ import java.util.Date; /** - * * @author xiaojian.xj - * @version $Id: FollowCompeteLockDomain.java, v 0.1 2021年03月16日 11:39 - * xiaojian.xj Exp $ + * @version $Id: FollowCompeteLockDomain.java, v 0.1 2021年03月16日 11:39 xiaojian.xj Exp $ */ public class FollowCompeteLockDomain { - /** - * local data center - */ - private String dataCenter; - - /** - * lock name - */ - private String lockName; - - /** - * lock owner - */ - private String owner; - - /** - * last update timestamp - */ - private Date gmtModified; - - /** - * try to compete new owner - */ - private String newOwner; - - public FollowCompeteLockDomain() { - } - - public FollowCompeteLockDomain(String dataCenter, String lockName, - String owner, Date gmtModified, String newOwner) { - this.dataCenter = dataCenter; - this.lockName = lockName; - this.owner = owner; - this.gmtModified = gmtModified; - this.newOwner = newOwner; - } - - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } - - /** - * Setter method for property dataCenter. - * - * @param dataCenter - * value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } - - /** - * Getter method for property lockName. - * - * @return property value of lockName - */ - public String getLockName() { - return lockName; - } - - /** - * Setter method for property lockName. - * - * @param lockName - * value to be assigned to property lockName - */ - public void setLockName(String lockName) { - this.lockName = lockName; - } - - /** - * Getter method for property owner. - * - * @return property value of owner - */ - public String getOwner() { - return owner; - } - - /** - * Setter method for property owner. - * - * @param owner - * value to be assigned to property owner - */ - public void setOwner(String owner) { - this.owner = owner; - } - - /** - * Getter method for property gmtModified. - * - * @return property value of gmtModified - */ - public Date getGmtModified() { - return gmtModified; - } - - /** - * Setter method for property gmtModified. - * - * @param gmtModified - * value to be assigned to property gmtModified - */ - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } - - /** - * Getter method for property newOwner. - * - * @return property value of newOwner - */ - public String getNewOwner() { - return newOwner; - } - - /** - * Setter method for property newOwner. - * - * @param newOwner - * value to be assigned to property newOwner - */ - public void setNewOwner(String newOwner) { - this.newOwner = newOwner; - } -} \ No newline at end of file + /** local data center */ + private String dataCenter; + + /** lock name */ + private String lockName; + + /** lock owner */ + private String owner; + + /** last update timestamp */ + private Date gmtModified; + + /** try to compete new owner */ + private String newOwner; + + public FollowCompeteLockDomain() {} + + public FollowCompeteLockDomain( + String dataCenter, String lockName, String owner, Date gmtModified, String newOwner) { + this.dataCenter = dataCenter; + this.lockName = lockName; + this.owner = owner; + this.gmtModified = gmtModified; + this.newOwner = newOwner; + } + + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * Setter method for property dataCenter. + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } + + /** + * Getter method for property lockName. + * + * @return property value of lockName + */ + public String getLockName() { + return lockName; + } + + /** + * Setter method for property lockName. + * + * @param lockName value to be assigned to property lockName + */ + public void setLockName(String lockName) { + this.lockName = lockName; + } + + /** + * Getter method for property owner. + * + * @return property value of owner + */ + public String getOwner() { + return owner; + } + + /** + * Setter method for property owner. + * + * @param owner value to be assigned to property owner + */ + public void setOwner(String owner) { + this.owner = owner; + } + + /** + * Getter method for property gmtModified. + * + * @return property value of gmtModified + */ + public Date getGmtModified() { + return gmtModified; + } + + /** + * Setter method for property gmtModified. + * + * @param gmtModified value to be assigned to property gmtModified + */ + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } + + /** + * Getter method for property newOwner. + * + * @return property value of newOwner + */ + public String getNewOwner() { + return newOwner; + } + + /** + * Setter method for property newOwner. + * + * @param newOwner value to be assigned to property newOwner + */ + public void setNewOwner(String newOwner) { + this.newOwner = newOwner; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/InterfaceAppIndexQueryModel.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/InterfaceAppIndexQueryModel.java index ba7aac576..370d59aa4 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/InterfaceAppIndexQueryModel.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/InterfaceAppIndexQueryModel.java @@ -19,78 +19,73 @@ import com.google.common.base.Objects; /** - * * @author xiaojian.xj * @version $Id: InterfaceAppIndexQueryModel.java, v 0.1 2021年01月24日 19:07 xiaojian.xj Exp $ */ public class InterfaceAppIndexQueryModel { - /** - * local data center - */ - private String dataCenter; + /** local data center */ + private String dataCenter; - /** - * interfaceName - */ - private String interfaceName; + /** interfaceName */ + private String interfaceName; - public InterfaceAppIndexQueryModel(String dataCenter, String interfaceName) { - this.dataCenter = dataCenter; - this.interfaceName = interfaceName; - } + public InterfaceAppIndexQueryModel(String dataCenter, String interfaceName) { + this.dataCenter = dataCenter; + this.interfaceName = interfaceName; + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (!(o instanceof InterfaceAppIndexQueryModel)) { - return false; - } - InterfaceAppIndexQueryModel that = (InterfaceAppIndexQueryModel) o; - return Objects.equal(dataCenter, that.dataCenter) - && Objects.equal(interfaceName, that.interfaceName); + @Override + public boolean equals(Object o) { + if (this == o) { + return true; } - - @Override - public int hashCode() { - return Objects.hashCode(dataCenter, interfaceName); + if (!(o instanceof InterfaceAppIndexQueryModel)) { + return false; } + InterfaceAppIndexQueryModel that = (InterfaceAppIndexQueryModel) o; + return Objects.equal(dataCenter, that.dataCenter) + && Objects.equal(interfaceName, that.interfaceName); + } - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } + @Override + public int hashCode() { + return Objects.hashCode(dataCenter, interfaceName); + } - /** - * Setter method for property dataCenter. - * - * @param dataCenter value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } - /** - * Getter method for property interfaceName. - * - * @return property value of interfaceName - */ - public String getInterfaceName() { - return interfaceName; - } + /** + * Setter method for property dataCenter. + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } - /** - * Setter method for property interfaceName. - * - * @param interfaceName value to be assigned to property interfaceName - */ - public void setInterfaceName(String interfaceName) { - this.interfaceName = interfaceName; - } -} \ No newline at end of file + /** + * Getter method for property interfaceName. + * + * @return property value of interfaceName + */ + public String getInterfaceName() { + return interfaceName; + } + + /** + * Setter method for property interfaceName. + * + * @param interfaceName value to be assigned to property interfaceName + */ + public void setInterfaceName(String interfaceName) { + this.interfaceName = interfaceName; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/InterfaceAppsIndexDomain.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/InterfaceAppsIndexDomain.java index feffbbcfe..463651479 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/InterfaceAppsIndexDomain.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/InterfaceAppsIndexDomain.java @@ -17,214 +17,185 @@ package com.alipay.sofa.registry.jdbc.domain; import com.alipay.sofa.registry.util.MessageDigests; - import java.sql.Timestamp; import java.util.Date; /** - * * @author xiaojian.xj - * @version $Id: InterfaceAppsIndexDomain.java, v 0.1 2021年01月24日 17:05 - * xiaojian.xj Exp $ + * @version $Id: InterfaceAppsIndexDomain.java, v 0.1 2021年01月24日 17:05 xiaojian.xj Exp $ */ public class InterfaceAppsIndexDomain { - /** - * primary key - */ - private long id; - - /** - * local data center - */ - private String dataCenter; - - /** - * interfaceName - */ - private String interfaceName; - - /** - * appName - */ - private String appName; - - /** - * reference - */ - private boolean reference; - - /** - * hashcode - */ - private String hashcode; - - /** - * create time - */ - private Date gmtCreate; - - /** - * last update time - */ - private Timestamp gmtModify; - - public InterfaceAppsIndexDomain() { - } - - public InterfaceAppsIndexDomain(String dataCenter, String interfaceName, - String appName) { - this.dataCenter = dataCenter; - this.interfaceName = interfaceName; - this.appName = appName; - // uk: dataCenter + appName + 32char - this.hashcode = MessageDigests.getMd5String(interfaceName); - } - - /** - * Getter method for property id. - * - * @return property value of id - */ - public long getId() { - return id; - } - - /** - * Setter method for property id. - * - * @param id - * value to be assigned to property id - */ - public void setId(long id) { - this.id = id; - } - - /** - * Getter method for property dataCenter. - * - * @return property value of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } - - /** - * Setter method for property dataCenter. - * - * @param dataCenter - * value to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } - - /** - * Getter method for property interfaceName. - * - * @return property value of interfaceName - */ - public String getInterfaceName() { - return interfaceName; - } - - /** - * Setter method for property interfaceName. - * - * @param interfaceName - * value to be assigned to property interfaceName - */ - public void setInterfaceName(String interfaceName) { - this.interfaceName = interfaceName; - } - - /** - * Getter method for property appName. - * - * @return property value of appName - */ - public String getAppName() { - return appName; - } - - /** - * Setter method for property appName. - * - * @param appName - * value to be assigned to property appName - */ - public void setAppName(String appName) { - this.appName = appName; - } - - public boolean isReference() { - return reference; - } - - /** - * Setter method for property reference. - * - * @param reference - * value to be assigned to property reference - */ - public void setReference(boolean reference) { - this.reference = reference; - } - - /** - * Getter method for property gmtCreate. - * - * @return property value of gmtCreate - */ - public Date getGmtCreate() { - return gmtCreate; - } - - /** - * Setter method for property gmtCreate. - * - * @param gmtCreate - * value to be assigned to property gmtCreate - */ - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } - - /** - * Getter method for property gmtModify. - * - * @return property value of gmtModify - */ - public Timestamp getGmtModify() { - return gmtModify; - } - - /** - * Setter method for property gmtModify. - * - * @param gmtModify - * value to be assigned to property gmtModify - */ - public void setGmtModify(Timestamp gmtModify) { - this.gmtModify = gmtModify; - } - - /** - * Getter method for property hashcode. - * - * @return property value of hashcode - */ - public String getHashcode() { - return hashcode; - } - - /** - * Setter method for property hashcode. - * - * @param hashcode - * value to be assigned to property hashcode - */ - public void setHashcode(String hashcode) { - this.hashcode = hashcode; - } -} \ No newline at end of file + /** primary key */ + private long id; + + /** local data center */ + private String dataCenter; + + /** interfaceName */ + private String interfaceName; + + /** appName */ + private String appName; + + /** reference */ + private boolean reference; + + /** hashcode */ + private String hashcode; + + /** create time */ + private Date gmtCreate; + + /** last update time */ + private Timestamp gmtModify; + + public InterfaceAppsIndexDomain() {} + + public InterfaceAppsIndexDomain(String dataCenter, String interfaceName, String appName) { + this.dataCenter = dataCenter; + this.interfaceName = interfaceName; + this.appName = appName; + // uk: dataCenter + appName + 32char + this.hashcode = MessageDigests.getMd5String(interfaceName); + } + + /** + * Getter method for property id. + * + * @return property value of id + */ + public long getId() { + return id; + } + + /** + * Setter method for property id. + * + * @param id value to be assigned to property id + */ + public void setId(long id) { + this.id = id; + } + + /** + * Getter method for property dataCenter. + * + * @return property value of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * Setter method for property dataCenter. + * + * @param dataCenter value to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } + + /** + * Getter method for property interfaceName. + * + * @return property value of interfaceName + */ + public String getInterfaceName() { + return interfaceName; + } + + /** + * Setter method for property interfaceName. + * + * @param interfaceName value to be assigned to property interfaceName + */ + public void setInterfaceName(String interfaceName) { + this.interfaceName = interfaceName; + } + + /** + * Getter method for property appName. + * + * @return property value of appName + */ + public String getAppName() { + return appName; + } + + /** + * Setter method for property appName. + * + * @param appName value to be assigned to property appName + */ + public void setAppName(String appName) { + this.appName = appName; + } + + public boolean isReference() { + return reference; + } + + /** + * Setter method for property reference. + * + * @param reference value to be assigned to property reference + */ + public void setReference(boolean reference) { + this.reference = reference; + } + + /** + * Getter method for property gmtCreate. + * + * @return property value of gmtCreate + */ + public Date getGmtCreate() { + return gmtCreate; + } + + /** + * Setter method for property gmtCreate. + * + * @param gmtCreate value to be assigned to property gmtCreate + */ + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + + /** + * Getter method for property gmtModify. + * + * @return property value of gmtModify + */ + public Timestamp getGmtModify() { + return gmtModify; + } + + /** + * Setter method for property gmtModify. + * + * @param gmtModify value to be assigned to property gmtModify + */ + public void setGmtModify(Timestamp gmtModify) { + this.gmtModify = gmtModify; + } + + /** + * Getter method for property hashcode. + * + * @return property value of hashcode + */ + public String getHashcode() { + return hashcode; + } + + /** + * Setter method for property hashcode. + * + * @param hashcode value to be assigned to property hashcode + */ + public void setHashcode(String hashcode) { + this.hashcode = hashcode; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/ProvideDataDomain.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/ProvideDataDomain.java index 2ba169498..0ed041e87 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/ProvideDataDomain.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/domain/ProvideDataDomain.java @@ -19,163 +19,142 @@ import java.util.Date; /** - * * @author xiaojian.xj - * @version $Id: ProvideDataDomain.java, v 0.1 2021年03月13日 19:29 xiaojian.xj Exp - * $ + * @version $Id: ProvideDataDomain.java, v 0.1 2021年03月13日 19:29 xiaojian.xj Exp $ */ public class ProvideDataDomain { - /** - * primary dataKey - */ - private long id; - - /** - * local data center - */ - private String dataCenter; - - /** - * data dataKey - */ - private String dataKey; - - /** - * data dataValue - */ - private String dataValue; - - /** - * create time - */ - private Date gmtCreate; - - /** - * last update time - */ - private Date gmtModified; - - public ProvideDataDomain() { - } - - public ProvideDataDomain(String dataCenter, String key, String value) { - this.dataCenter = dataCenter; - this.dataKey = key; - this.dataValue = value; - } - - /** - * Getter method for property id. - * - * @return property dataValue of id - */ - public long getId() { - return id; - } - - /** - * Setter method for property id. - * - * @param id - * dataValue to be assigned to property id - */ - public void setId(long id) { - this.id = id; - } - - /** - * Getter method for property dataCenter. - * - * @return property dataValue of dataCenter - */ - public String getDataCenter() { - return dataCenter; - } - - /** - * Setter method for property dataCenter. - * - * @param dataCenter - * dataValue to be assigned to property dataCenter - */ - public void setDataCenter(String dataCenter) { - this.dataCenter = dataCenter; - } - - /** - * Getter method for property dataKey. - * - * @return property dataValue of dataKey - */ - public String getDataKey() { - return dataKey; - } - - /** - * Setter method for property dataKey. - * - * @param dataKey - * dataValue to be assigned to property dataKey - */ - public void setDataKey(String dataKey) { - this.dataKey = dataKey; - } - - /** - * Getter method for property dataValue. - * - * @return property dataValue of dataValue - */ - public String getDataValue() { - return dataValue; - } - - /** - * Setter method for property dataValue. - * - * @param dataValue - * dataValue to be assigned to property dataValue - */ - public void setDataValue(String dataValue) { - this.dataValue = dataValue; - } - - /** - * Getter method for property gmtCreate. - * - * @return property dataValue of gmtCreate - */ - public Date getGmtCreate() { - return gmtCreate; - } - - /** - * Setter method for property gmtCreate. - * - * @param gmtCreate - * dataValue to be assigned to property gmtCreate - */ - public void setGmtCreate(Date gmtCreate) { - this.gmtCreate = gmtCreate; - } - - /** - * Getter method for property gmtModified. - * - * @return property dataValue of gmtModified - */ - public Date getGmtModified() { - return gmtModified; - } - - /** - * Setter method for property gmtModified. - * - * @param gmtModified - * dataValue to be assigned to property gmtModified - */ - public void setGmtModified(Date gmtModified) { - this.gmtModified = gmtModified; - } -} \ No newline at end of file + /** primary dataKey */ + private long id; + + /** local data center */ + private String dataCenter; + + /** data dataKey */ + private String dataKey; + + /** data dataValue */ + private String dataValue; + + /** create time */ + private Date gmtCreate; + + /** last update time */ + private Date gmtModified; + + public ProvideDataDomain() {} + + public ProvideDataDomain(String dataCenter, String key, String value) { + this.dataCenter = dataCenter; + this.dataKey = key; + this.dataValue = value; + } + + /** + * Getter method for property id. + * + * @return property dataValue of id + */ + public long getId() { + return id; + } + + /** + * Setter method for property id. + * + * @param id dataValue to be assigned to property id + */ + public void setId(long id) { + this.id = id; + } + + /** + * Getter method for property dataCenter. + * + * @return property dataValue of dataCenter + */ + public String getDataCenter() { + return dataCenter; + } + + /** + * Setter method for property dataCenter. + * + * @param dataCenter dataValue to be assigned to property dataCenter + */ + public void setDataCenter(String dataCenter) { + this.dataCenter = dataCenter; + } + + /** + * Getter method for property dataKey. + * + * @return property dataValue of dataKey + */ + public String getDataKey() { + return dataKey; + } + + /** + * Setter method for property dataKey. + * + * @param dataKey dataValue to be assigned to property dataKey + */ + public void setDataKey(String dataKey) { + this.dataKey = dataKey; + } + + /** + * Getter method for property dataValue. + * + * @return property dataValue of dataValue + */ + public String getDataValue() { + return dataValue; + } + + /** + * Setter method for property dataValue. + * + * @param dataValue dataValue to be assigned to property dataValue + */ + public void setDataValue(String dataValue) { + this.dataValue = dataValue; + } + + /** + * Getter method for property gmtCreate. + * + * @return property dataValue of gmtCreate + */ + public Date getGmtCreate() { + return gmtCreate; + } + + /** + * Setter method for property gmtCreate. + * + * @param gmtCreate dataValue to be assigned to property gmtCreate + */ + public void setGmtCreate(Date gmtCreate) { + this.gmtCreate = gmtCreate; + } + + /** + * Getter method for property gmtModified. + * + * @return property dataValue of gmtModified + */ + public Date getGmtModified() { + return gmtModified; + } + + /** + * Setter method for property gmtModified. + * + * @param gmtModified dataValue to be assigned to property gmtModified + */ + public void setGmtModified(Date gmtModified) { + this.gmtModified = gmtModified; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/elector/MetaJdbcLeaderElector.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/elector/MetaJdbcLeaderElector.java index 899eff694..f090b2565 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/elector/MetaJdbcLeaderElector.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/elector/MetaJdbcLeaderElector.java @@ -24,185 +24,192 @@ import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.store.api.elector.AbstractLeaderElector; import com.google.common.collect.Maps; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.Map; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author xiaojian.xj * @version $Id: MetaJdbcLeaderElector.java, v 0.1 2021年03月12日 10:18 xiaojian.xj Exp $ */ public class MetaJdbcLeaderElector extends AbstractLeaderElector { - private static final Logger LOG = LoggerFactory.getLogger("META-ELECTOR", - "[MetaJdbcLeaderElector]"); + private static final Logger LOG = + LoggerFactory.getLogger("META-ELECTOR", "[MetaJdbcLeaderElector]"); + private static final String lockName = "META-MASTER"; - private static final String lockName = "META-MASTER"; + @Autowired private DistributeLockMapper distributeLockMapper; - @Autowired - private DistributeLockMapper distributeLockMapper; + @Autowired private MetaElectorConfig metaElectorConfig; - @Autowired - private MetaElectorConfig metaElectorConfig; + private Map electorRoleMap = Maps.newConcurrentMap(); - private Map electorRoleMap = Maps.newConcurrentMap(); - - - /** - * start elect, return current leader - * @return - */ - @Override - protected LeaderInfo doElect() { - DistributeLockDomain lock = distributeLockMapper.queryDistLock(metaElectorConfig.getDataCenter(), lockName); - - /** - * compete and return leader - */ - if (lock == null) { - return competeLeader(metaElectorConfig.getDataCenter()); - } + /** + * start elect, return current leader + * + * @return + */ + @Override + protected LeaderInfo doElect() { + DistributeLockDomain lock = + distributeLockMapper.queryDistLock(metaElectorConfig.getDataCenter(), lockName); - ElectorRole role = amILeader(lock.getOwner()) ? ElectorRole.LEADER : ElectorRole.FOLLOWER; - lock = electorRoleMap.get(role).onWorking(lock, myself()); - return new LeaderInfo(lock.getGmtModified().getTime(), lock.getOwner(), lock.getGmtModified(), lock.getDuration()); + /** compete and return leader */ + if (lock == null) { + return competeLeader(metaElectorConfig.getDataCenter()); } - /** - * compete and return leader - * @param dataCenter - * @return - */ - private LeaderInfo competeLeader(String dataCenter) { - DistributeLockDomain lock = new DistributeLockDomain(dataCenter, lockName, myself(), metaElectorConfig.getLockExpireDuration()); - try { - // throw exception if insert fail - distributeLockMapper.competeLockOnInsert(lock); - // compete finish. - lock = distributeLockMapper.queryDistLock(dataCenter, lockName); - - if (LOG.isInfoEnabled()) { - LOG.info("meta: {} compete success, become leader.", myself()); - } - } catch (Throwable t) { - // compete leader error, query current leader - lock = distributeLockMapper.queryDistLock(dataCenter, lockName); - if (LOG.isInfoEnabled()) { - LOG.info("meta: {} compete error, leader is: {}.", myself(), lock.getOwner()); - } - } - return new LeaderInfo(lock.getGmtModified().getTime(), lock.getOwner(), lock.getGmtModified(), lock.getDuration()); + ElectorRole role = amILeader(lock.getOwner()) ? ElectorRole.LEADER : ElectorRole.FOLLOWER; + lock = electorRoleMap.get(role).onWorking(lock, myself()); + return new LeaderInfo( + lock.getGmtModified().getTime(), + lock.getOwner(), + lock.getGmtModified(), + lock.getDuration()); + } + + /** + * compete and return leader + * + * @param dataCenter + * @return + */ + private LeaderInfo competeLeader(String dataCenter) { + DistributeLockDomain lock = + new DistributeLockDomain( + dataCenter, lockName, myself(), metaElectorConfig.getLockExpireDuration()); + try { + // throw exception if insert fail + distributeLockMapper.competeLockOnInsert(lock); + // compete finish. + lock = distributeLockMapper.queryDistLock(dataCenter, lockName); + + if (LOG.isInfoEnabled()) { + LOG.info("meta: {} compete success, become leader.", myself()); + } + } catch (Throwable t) { + // compete leader error, query current leader + lock = distributeLockMapper.queryDistLock(dataCenter, lockName); + if (LOG.isInfoEnabled()) { + LOG.info("meta: {} compete error, leader is: {}.", myself(), lock.getOwner()); + } } - - /** - * query current leader - * @return - */ - @Override - protected LeaderInfo doQuery() { - DistributeLockDomain lock = distributeLockMapper.queryDistLock(metaElectorConfig.getDataCenter(), lockName); - if (lock == null) { - return LeaderInfo.hasNoLeader; - } - - return new LeaderInfo(lock.getGmtModified().getTime(), lock.getOwner(), lock.getGmtModified(), lock.getDuration()); + return new LeaderInfo( + lock.getGmtModified().getTime(), + lock.getOwner(), + lock.getGmtModified(), + lock.getDuration()); + } + + /** + * query current leader + * + * @return + */ + @Override + protected LeaderInfo doQuery() { + DistributeLockDomain lock = + distributeLockMapper.queryDistLock(metaElectorConfig.getDataCenter(), lockName); + if (lock == null) { + return LeaderInfo.hasNoLeader; } - public interface ElectorRoleService { - DistributeLockDomain onWorking(DistributeLockDomain lock, String myself); + return new LeaderInfo( + lock.getGmtModified().getTime(), + lock.getOwner(), + lock.getGmtModified(), + lock.getDuration()); + } - ElectorRole support(); - } + public interface ElectorRoleService { + DistributeLockDomain onWorking(DistributeLockDomain lock, String myself); - public class LeaderService implements ElectorRoleService { + ElectorRole support(); + } - private final Logger LOG = LoggerFactory.getLogger("META-ELECTOR", "[Leader]"); + public class LeaderService implements ElectorRoleService { - @Autowired - private DistributeLockMapper distributeLockMapper; + private final Logger LOG = LoggerFactory.getLogger("META-ELECTOR", "[Leader]"); - @Override - public DistributeLockDomain onWorking(DistributeLockDomain lock, String myself) { + @Autowired private DistributeLockMapper distributeLockMapper; - try { - /** - * as leader, do heartbeat - */ - distributeLockMapper.ownerHeartbeat(lock); - if (LOG.isInfoEnabled()) { - LOG.info("leader heartbeat: {}", myself); - } - return distributeLockMapper.queryDistLock(lock.getDataCenter(), lock.getLockName()); - } catch (Throwable t) { - LOG.error("leader:{} heartbeat error.", myself, t); - } - return lock; + @Override + public DistributeLockDomain onWorking(DistributeLockDomain lock, String myself) { + try { + /** as leader, do heartbeat */ + distributeLockMapper.ownerHeartbeat(lock); + if (LOG.isInfoEnabled()) { + LOG.info("leader heartbeat: {}", myself); } + return distributeLockMapper.queryDistLock(lock.getDataCenter(), lock.getLockName()); + } catch (Throwable t) { + LOG.error("leader:{} heartbeat error.", myself, t); + } + return lock; + } - @Override - public ElectorRole support() { - return ElectorRole.LEADER; - } + @Override + public ElectorRole support() { + return ElectorRole.LEADER; } + } - public class FollowService implements ElectorRoleService { - - private final Logger LOG = LoggerFactory.getLogger("META-ELECTOR", - "[FOLLOW]"); - - @Autowired - private DistributeLockMapper distributeLockMapper; - - @Override - public DistributeLockDomain onWorking(DistributeLockDomain lock, String myself) { - /** - * as follow, do compete if lock expire - */ - if (lock.expire()) { - if (LOG.isInfoEnabled()) { - LOG.info("lock expire: {}, meta elector start: {}", lock, myself); - } - distributeLockMapper.competeLockOnUpdate(new FollowCompeteLockDomain(lock.getDataCenter(), - lock.getLockName(), lock.getOwner(), lock.getGmtModified(), myself)); - DistributeLockDomain newLock = distributeLockMapper.queryDistLock(lock.getDataCenter(), lock.getLockName()); - if (LOG.isInfoEnabled()) { - LOG.info("elector finish, new lock: {}", lock); - } - return newLock; - } - return lock; - } + public class FollowService implements ElectorRoleService { - @Override - public ElectorRole support() { - return ElectorRole.FOLLOWER; - } - } + private final Logger LOG = LoggerFactory.getLogger("META-ELECTOR", "[FOLLOW]"); - public void addElectorRoleService(ElectorRoleService service) { - electorRoleMap.put(service.support(), service); - } + @Autowired private DistributeLockMapper distributeLockMapper; - /** - * Setter method for property distributeLockMapper. - * - * @param distributeLockMapper value to be assigned to property distributeLockMapper - */ - public void setDistributeLockMapper(DistributeLockMapper distributeLockMapper) { - this.distributeLockMapper = distributeLockMapper; + @Override + public DistributeLockDomain onWorking(DistributeLockDomain lock, String myself) { + /** as follow, do compete if lock expire */ + if (lock.expire()) { + if (LOG.isInfoEnabled()) { + LOG.info("lock expire: {}, meta elector start: {}", lock, myself); + } + distributeLockMapper.competeLockOnUpdate( + new FollowCompeteLockDomain( + lock.getDataCenter(), + lock.getLockName(), + lock.getOwner(), + lock.getGmtModified(), + myself)); + DistributeLockDomain newLock = + distributeLockMapper.queryDistLock(lock.getDataCenter(), lock.getLockName()); + if (LOG.isInfoEnabled()) { + LOG.info("elector finish, new lock: {}", lock); + } + return newLock; + } + return lock; } - /** - * Setter method for property metaElectorConfig. - * - * @param metaElectorConfig value to be assigned to property metaElectorConfig - */ - public void setMetaElectorConfig(MetaElectorConfig metaElectorConfig) { - this.metaElectorConfig = metaElectorConfig; + @Override + public ElectorRole support() { + return ElectorRole.FOLLOWER; } + } + + public void addElectorRoleService(ElectorRoleService service) { + electorRoleMap.put(service.support(), service); + } + + /** + * Setter method for property distributeLockMapper. + * + * @param distributeLockMapper value to be assigned to property distributeLockMapper + */ + public void setDistributeLockMapper(DistributeLockMapper distributeLockMapper) { + this.distributeLockMapper = distributeLockMapper; + } + + /** + * Setter method for property metaElectorConfig. + * + * @param metaElectorConfig value to be assigned to property metaElectorConfig + */ + public void setMetaElectorConfig(MetaElectorConfig metaElectorConfig) { + this.metaElectorConfig = metaElectorConfig; + } } - - diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/AppInterfaceQueryException.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/AppInterfaceQueryException.java index 7a09e2b7c..0fa85628e 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/AppInterfaceQueryException.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/AppInterfaceQueryException.java @@ -17,14 +17,12 @@ package com.alipay.sofa.registry.jdbc.exception; /** - * * @author xiaojian.xj - * @version $Id: RevisionNotExistException.java, v 0.1 2021年02月03日 15:59 - * xiaojian.xj Exp $ + * @version $Id: RevisionNotExistException.java, v 0.1 2021年02月03日 15:59 xiaojian.xj Exp $ */ public class AppInterfaceQueryException extends RuntimeException { - public AppInterfaceQueryException(String app) { - super(String.format("query interfaces by app: %s error.", app)); - } -} \ No newline at end of file + public AppInterfaceQueryException(String app) { + super(String.format("query interfaces by app: %s error.", app)); + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/InterfaceAppQueryException.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/InterfaceAppQueryException.java index 1733db45e..c260b61c1 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/InterfaceAppQueryException.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/InterfaceAppQueryException.java @@ -17,14 +17,12 @@ package com.alipay.sofa.registry.jdbc.exception; /** - * * @author xiaojian.xj - * @version $Id: RevisionNotExistException.java, v 0.1 2021年02月03日 15:59 - * xiaojian.xj Exp $ + * @version $Id: RevisionNotExistException.java, v 0.1 2021年02月03日 15:59 xiaojian.xj Exp $ */ public class InterfaceAppQueryException extends RuntimeException { - public InterfaceAppQueryException(String service) { - super(String.format("query apps by service: %s error.", service)); - } -} \ No newline at end of file + public InterfaceAppQueryException(String service) { + super(String.format("query apps by service: %s error.", service)); + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/RevisionNotExistException.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/RevisionNotExistException.java index 8ca6b15a4..395847294 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/RevisionNotExistException.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/exception/RevisionNotExistException.java @@ -17,14 +17,12 @@ package com.alipay.sofa.registry.jdbc.exception; /** - * * @author xiaojian.xj - * @version $Id: RevisionNotExistException.java, v 0.1 2021年02月03日 15:59 - * xiaojian.xj Exp $ + * @version $Id: RevisionNotExistException.java, v 0.1 2021年02月03日 15:59 xiaojian.xj Exp $ */ public class RevisionNotExistException extends RuntimeException { - public RevisionNotExistException(String revision) { - super(String.format("revision: %s not exist.", revision)); - } -} \ No newline at end of file + public RevisionNotExistException(String revision) { + super(String.format("revision: %s not exist.", revision)); + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/AppRevisionMapper.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/AppRevisionMapper.java index 2150536a2..c7549fbec 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/AppRevisionMapper.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/AppRevisionMapper.java @@ -19,67 +19,70 @@ import com.alipay.sofa.registry.common.model.store.AppRevision; import com.alipay.sofa.registry.jdbc.domain.AppRevisionDomain; import com.alipay.sofa.registry.jdbc.domain.AppRevisionQueryModel; -import org.apache.ibatis.annotations.Param; import java.util.List; +import org.apache.ibatis.annotations.Param; /** - * * @author xiaojian.xj * @version $Id: AppRevisionMapper.java, v 0.1 2021年01月18日 17:49 xiaojian.xj Exp $ */ public interface AppRevisionMapper { - /** - * save record - * @param appRevision - * @return effect record count - */ - public int insert(AppRevisionDomain appRevision); + /** + * save record + * + * @param appRevision + * @return effect record count + */ + public int insert(AppRevisionDomain appRevision); - /** - * query revision - * @param dataCenter - * @param revision - * @return - */ - public AppRevisionDomain queryRevision(@Param("dataCenter") String dataCenter, - @Param("revision") String revision); + /** + * query revision + * + * @param dataCenter + * @param revision + * @return + */ + public AppRevisionDomain queryRevision( + @Param("dataCenter") String dataCenter, @Param("revision") String revision); - /** - * batch query - * @param querys - * @return - */ - public List batchQuery(List querys); + /** + * batch query + * + * @param querys + * @return + */ + public List batchQuery(List querys); - /** - * check if revision exist - * @param query - * @return revision - */ - AppRevisionDomain checkExist(AppRevisionQueryModel query); + /** + * check if revision exist + * + * @param query + * @return revision + */ + AppRevisionDomain checkExist(AppRevisionQueryModel query); - /** - * - * @param heartbeats - */ - void batchHeartbeat(List heartbeats); + /** @param heartbeats */ + void batchHeartbeat(List heartbeats); - /** - * query app_revision silence beyond silenceHour - * @param dataCenter - * @param silenceHour - * @return - */ - public List queryGcRevision(@Param("dataCenter") String dataCenter, - @Param("silenceHour") int silenceHour, - @Param("limitCount") int limitCount); + /** + * query app_revision silence beyond silenceHour + * + * @param dataCenter + * @param silenceHour + * @return + */ + public List queryGcRevision( + @Param("dataCenter") String dataCenter, + @Param("silenceHour") int silenceHour, + @Param("limitCount") int limitCount); - /** - * delete - * @param dataCenter - * @param revision - */ - public void deleteAppRevision(@Param("dataCenter") String dataCenter, - @Param("revision") String revision); -} \ No newline at end of file + /** + * delete + * + * @param dataCenter + * @param revision + */ + public void deleteAppRevision( + @Param("dataCenter") String dataCenter, @Param("revision") String revision); +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/DistributeLockMapper.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/DistributeLockMapper.java index eb8ae2d0e..51ab98ad5 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/DistributeLockMapper.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/DistributeLockMapper.java @@ -21,42 +21,39 @@ import org.apache.ibatis.annotations.Param; /** - * * @author xiaojian.xj * @version $Id: DistributeLockMapper.java, v 0.1 2021年03月12日 10:51 xiaojian.xj Exp $ */ public interface DistributeLockMapper { - /** - * query by dataCenter and lockName - * @param dataCenter - * @param lockName - * @return - */ - public DistributeLockDomain queryDistLock(@Param("dataCenter") String dataCenter, - @Param("lockName") String lockName); - - /** - * compete lock, it will throw exception if lockName existed - * @param lock - */ - public void competeLockOnInsert(DistributeLockDomain lock) throws Exception; - - /** - * compete lock with cas - * @param competeLock - * @return - */ - public void competeLockOnUpdate(FollowCompeteLockDomain competeLock); - - /** - * renew lock last update time - */ - public void ownerHeartbeat(DistributeLockDomain lock); - - - /** - * force reset owner and duration - */ - public void forceRefresh(DistributeLockDomain lock); -} \ No newline at end of file + /** + * query by dataCenter and lockName + * + * @param dataCenter + * @param lockName + * @return + */ + public DistributeLockDomain queryDistLock( + @Param("dataCenter") String dataCenter, @Param("lockName") String lockName); + + /** + * compete lock, it will throw exception if lockName existed + * + * @param lock + */ + public void competeLockOnInsert(DistributeLockDomain lock) throws Exception; + + /** + * compete lock with cas + * + * @param competeLock + * @return + */ + public void competeLockOnUpdate(FollowCompeteLockDomain competeLock); + + /** renew lock last update time */ + public void ownerHeartbeat(DistributeLockDomain lock); + + /** force reset owner and duration */ + public void forceRefresh(DistributeLockDomain lock); +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/InterfaceAppsIndexMapper.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/InterfaceAppsIndexMapper.java index a4d00ffcd..e53d77d9c 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/InterfaceAppsIndexMapper.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/InterfaceAppsIndexMapper.java @@ -18,59 +18,64 @@ import com.alipay.sofa.registry.jdbc.domain.InterfaceAppIndexQueryModel; import com.alipay.sofa.registry.jdbc.domain.InterfaceAppsIndexDomain; -import org.apache.ibatis.annotations.Param; - import java.sql.Timestamp; import java.util.List; +import org.apache.ibatis.annotations.Param; /** - * * @author xiaojian.xj * @version $Id: InterfaceAppsIndexMapper.java, v 0.1 2021年01月24日 17:04 xiaojian.xj Exp $ */ public interface InterfaceAppsIndexMapper { - /** - * query by interfaceName - * @param dataCenter - * @param interfaceName - * @return - */ - public List queryByInterfaceName(@Param("dataCenter") String dataCenter, - @Param("interfaceName") String interfaceName); + /** + * query by interfaceName + * + * @param dataCenter + * @param interfaceName + * @return + */ + public List queryByInterfaceName( + @Param("dataCenter") String dataCenter, @Param("interfaceName") String interfaceName); - /** - * batch query by interfaceName - * @param querys - * @return - */ - public List batchQueryByInterface(List querys); + /** + * batch query by interfaceName + * + * @param querys + * @return + */ + public List batchQueryByInterface( + List querys); - /** - * insert - * @param domains - * @return effect rows number - */ - public int insert(List domains); + /** + * insert + * + * @param domains + * @return effect rows number + */ + public int insert(List domains); - /** - * query domains which gmt_modified is after than maxUpdate - * @param dataCenter - * @param maxUpdate - * @returns - */ - List queryModifyAfterThan(@Param("dataCenter") String dataCenter, - @Param("maxUpdate") Timestamp maxUpdate, - @Param("limitCount") int limitCount); + /** + * query domains which gmt_modified is after than maxUpdate + * + * @param dataCenter + * @param maxUpdate + * @returns + */ + List queryModifyAfterThan( + @Param("dataCenter") String dataCenter, + @Param("maxUpdate") Timestamp maxUpdate, + @Param("limitCount") int limitCount); - /** - * query domains which gmt_modified equal maxUpdate - * @param dataCenter - * @param maxUpdate - * @returns - */ - List queryModifyEquals(@Param("dataCenter") String dataCenter, - @Param("maxUpdate") Timestamp maxUpdate); + /** + * query domains which gmt_modified equal maxUpdate + * + * @param dataCenter + * @param maxUpdate + * @returns + */ + List queryModifyEquals( + @Param("dataCenter") String dataCenter, @Param("maxUpdate") Timestamp maxUpdate); - int getTotalCount(@Param("dataCenter") String dataCenter); -} \ No newline at end of file + int getTotalCount(@Param("dataCenter") String dataCenter); +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/ProvideDataMapper.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/ProvideDataMapper.java index 9b3d5b88a..ca33d75f9 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/ProvideDataMapper.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/mapper/ProvideDataMapper.java @@ -20,29 +20,27 @@ import org.apache.ibatis.annotations.Param; /** - * * @author xiaojian.xj * @version $Id: ProvideDataMapper.java, v 0.1 2021年03月12日 11:05 xiaojian.xj Exp $ */ public interface ProvideDataMapper { - /** - * insert or update provideData - * @param data - */ - public void save(ProvideDataDomain data); + /** + * insert or update provideData + * + * @param data + */ + public void save(ProvideDataDomain data); - /** - * query provideData - */ - public ProvideDataDomain query(@Param("dataCenter") String dataCenter, - @Param("dataKey") String dataKey); + /** query provideData */ + public ProvideDataDomain query( + @Param("dataCenter") String dataCenter, @Param("dataKey") String dataKey); - /** - * remove provideData - * @param dataCenter - * @param dataKey - */ - public void remove(@Param("dataCenter") String dataCenter, - @Param("dataKey") String dataKey); -} \ No newline at end of file + /** + * remove provideData + * + * @param dataCenter + * @param dataKey + */ + public void remove(@Param("dataCenter") String dataCenter, @Param("dataKey") String dataKey); +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/JdbcRepository.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/JdbcRepository.java index d812dd2aa..c91c6a02a 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/JdbcRepository.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/JdbcRepository.java @@ -20,14 +20,13 @@ import com.alipay.sofa.registry.store.api.driver.RepositoryManager.RepositoryType; /** - * * @author xiaojian.xj * @version $Id: JdbcRepository.java, v 0.1 2021年01月17日 15:50 xiaojian.xj Exp $ */ public interface JdbcRepository extends RegistryRepository { - @Override - default boolean accept(RepositoryType repositoryType) { - return repositoryType == RepositoryType.JDBC; - } -} \ No newline at end of file + @Override + default boolean accept(RepositoryType repositoryType) { + return repositoryType == RepositoryType.JDBC; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/AppRevisionBatchQueryCallable.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/AppRevisionBatchQueryCallable.java index e0096b414..992caddbe 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/AppRevisionBatchQueryCallable.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/AppRevisionBatchQueryCallable.java @@ -24,73 +24,76 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.util.BatchCallableRunnable; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.CollectionUtils; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; /** - * * @author xiaojian.xj * @version $Id: AppRevisionBatchQueryCallable.java, v 0.1 2021年01月24日 14:01 xiaojian.xj Exp $ */ -public class AppRevisionBatchQueryCallable extends - BatchCallableRunnable { +public class AppRevisionBatchQueryCallable + extends BatchCallableRunnable { - private static final Logger LOG = LoggerFactory.getLogger("METADATA-EXCHANGE", - "[AppRevisionBatchQuery]"); - @Autowired - private AppRevisionMapper appRevisionMapper; + private static final Logger LOG = + LoggerFactory.getLogger("METADATA-EXCHANGE", "[AppRevisionBatchQuery]"); + @Autowired private AppRevisionMapper appRevisionMapper; - /** - * batch query app_revision - * @param taskEvents - * @return - */ - @Override - public boolean batchProcess(List taskEvents) { + /** + * batch query app_revision + * + * @param taskEvents + * @return + */ + @Override + public boolean batchProcess(List taskEvents) { - if (CollectionUtils.isEmpty(taskEvents)) { - return true; - } - if (LOG.isInfoEnabled()) { - LOG.info("commit app_revision query, task size: " + taskEvents.size()); - } - List querys = taskEvents.stream().map(task -> task.getData()).collect(Collectors.toList()); - List domains = appRevisionMapper.batchQuery(querys); + if (CollectionUtils.isEmpty(taskEvents)) { + return true; + } + if (LOG.isInfoEnabled()) { + LOG.info("commit app_revision query, task size: " + taskEvents.size()); + } + List querys = + taskEvents.stream().map(task -> task.getData()).collect(Collectors.toList()); + List domains = appRevisionMapper.batchQuery(querys); - Map queryResult = new HashMap<>(); - domains.forEach(domain -> { - AppRevision appRevision = queryResult.get(domain.getRevision()); - if (appRevision != null) { - return; - } - queryResult.putIfAbsent(domain.getRevision(), AppRevisionDomainConvertor.convert2Revision(domain)); + Map queryResult = new HashMap<>(); + domains.forEach( + domain -> { + AppRevision appRevision = queryResult.get(domain.getRevision()); + if (appRevision != null) { + return; + } + queryResult.putIfAbsent( + domain.getRevision(), AppRevisionDomainConvertor.convert2Revision(domain)); }); - taskEvents.forEach(taskEvent -> { - String revision = taskEvent.getData().getRevision(); - InvokeFuture future = taskEvent.getFuture(); - future.putResponse(queryResult.get(revision)); + taskEvents.forEach( + taskEvent -> { + String revision = taskEvent.getData().getRevision(); + InvokeFuture future = taskEvent.getFuture(); + future.putResponse(queryResult.get(revision)); }); - return true; - } + return true; + } - @Override - protected void setBatchSize() { - this.batchSize = 200; - } + @Override + protected void setBatchSize() { + this.batchSize = 200; + } - @Override - protected void setTimeUnit() { - this.timeUnit = TimeUnit.MILLISECONDS; - } + @Override + protected void setTimeUnit() { + this.timeUnit = TimeUnit.MILLISECONDS; + } - @Override - protected void setSleep() { - this.sleep = 20; - } -} \ No newline at end of file + @Override + protected void setSleep() { + this.sleep = 20; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/AppRevisionHeartbeatBatchCallable.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/AppRevisionHeartbeatBatchCallable.java index e06f4a0f8..c6fb77311 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/AppRevisionHeartbeatBatchCallable.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/AppRevisionHeartbeatBatchCallable.java @@ -21,65 +21,67 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.util.BatchCallableRunnable; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.CollectionUtils; - import java.util.List; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; /** - * * @author xiaojian.xj * @version $Id: AppRevisionHeartbeatBatchCallable.java, v 0.1 2021年02月09日 17:52 xiaojian.xj Exp $ */ -public class AppRevisionHeartbeatBatchCallable extends - BatchCallableRunnable { +public class AppRevisionHeartbeatBatchCallable + extends BatchCallableRunnable { - private static final Logger LOG = LoggerFactory.getLogger("METADATA-EXCHANGE", - "[AppRevisionHeartbeatBatch]"); + private static final Logger LOG = + LoggerFactory.getLogger("METADATA-EXCHANGE", "[AppRevisionHeartbeatBatch]"); - @Autowired - private AppRevisionMapper appRevisionMapper; + @Autowired private AppRevisionMapper appRevisionMapper; - /** - * batch update gmt_modified - * @param tasks - * @return - */ - @Override - public boolean batchProcess(List tasks) { + /** + * batch update gmt_modified + * + * @param tasks + * @return + */ + @Override + public boolean batchProcess(List tasks) { - if (CollectionUtils.isEmpty(tasks)) { - return true; - } - if (LOG.isInfoEnabled()) { - LOG.info("update app_revision gmt_modified, task size: " + tasks.size()); - } - List heartbeats = tasks.stream().map(task -> task.getData()) - .filter(appRevision -> appRevision.getLastHeartbeat() != null).collect(Collectors.toList()); + if (CollectionUtils.isEmpty(tasks)) { + return true; + } + if (LOG.isInfoEnabled()) { + LOG.info("update app_revision gmt_modified, task size: " + tasks.size()); + } + List heartbeats = + tasks.stream() + .map(task -> task.getData()) + .filter(appRevision -> appRevision.getLastHeartbeat() != null) + .collect(Collectors.toList()); - appRevisionMapper.batchHeartbeat(heartbeats); - tasks.forEach(taskEvent -> { - InvokeFuture future = taskEvent.getFuture(); - future.putResponse(taskEvent.getData()); + appRevisionMapper.batchHeartbeat(heartbeats); + tasks.forEach( + taskEvent -> { + InvokeFuture future = taskEvent.getFuture(); + future.putResponse(taskEvent.getData()); }); - return true; - } + return true; + } - @Override - protected void setBatchSize() { - this.batchSize = 200; - } + @Override + protected void setBatchSize() { + this.batchSize = 200; + } - @Override - protected void setSleep() { - this.sleep = 100; - } + @Override + protected void setSleep() { + this.sleep = 100; + } - @Override - protected void setTimeUnit() { - this.timeUnit = TimeUnit.MILLISECONDS; - } -} \ No newline at end of file + @Override + protected void setTimeUnit() { + this.timeUnit = TimeUnit.MILLISECONDS; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/InterfaceAppBatchQueryCallable.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/InterfaceAppBatchQueryCallable.java index ebec4d978..2d2f83ef4 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/InterfaceAppBatchQueryCallable.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/batch/InterfaceAppBatchQueryCallable.java @@ -25,81 +25,97 @@ import com.alipay.sofa.registry.util.BatchCallableRunnable; import com.alipay.sofa.registry.util.TimestampUtil; import com.google.common.collect.Sets; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.CollectionUtils; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; /** - * * @author xiaojian.xj * @version $Id: InterfaceAppBatchQueryCallable.java, v 0.1 2021年01月26日 14:45 xiaojian.xj Exp $ */ public class InterfaceAppBatchQueryCallable - extends - BatchCallableRunnable { + extends BatchCallableRunnable { - private static final Logger LOG = LoggerFactory.getLogger("METADATA-EXCHANGE", - "[InterfaceAppBatchQuery]"); + private static final Logger LOG = + LoggerFactory.getLogger("METADATA-EXCHANGE", "[InterfaceAppBatchQuery]"); - @Autowired - private InterfaceAppsIndexMapper interfaceAppsIndexMapper; + @Autowired private InterfaceAppsIndexMapper interfaceAppsIndexMapper; - @Override - public boolean batchProcess(List taskEvents) { + @Override + public boolean batchProcess(List taskEvents) { - if (CollectionUtils.isEmpty(taskEvents)) { - return true; - } - if (LOG.isInfoEnabled()) { - LOG.info("commit interface_apps_index interface query, task size: " + taskEvents.size()); - } - List querys = taskEvents.stream().map(task -> task.getData()).collect(Collectors.toList()); - List domains = interfaceAppsIndexMapper.batchQueryByInterface(querys); + if (CollectionUtils.isEmpty(taskEvents)) { + return true; + } + if (LOG.isInfoEnabled()) { + LOG.info("commit interface_apps_index interface query, task size: " + taskEvents.size()); + } + List querys = + taskEvents.stream().map(task -> task.getData()).collect(Collectors.toList()); + List domains = interfaceAppsIndexMapper.batchQueryByInterface(querys); - Map/**app*/> indexResult = new HashMap<>(); - Map versionResult = new HashMap<>(); - domains.forEach(domain -> { - indexResult.computeIfAbsent(domain.getInterfaceName(), k -> Sets.newConcurrentHashSet()).add(domain.getAppName()); + Map< + String + /** interfaces */ + , + Set + /** app */ + > + indexResult = new HashMap<>(); + Map< + String + /** interfaces */ + , + Long + /** version */ + > + versionResult = new HashMap<>(); + domains.forEach( + domain -> { + indexResult + .computeIfAbsent(domain.getInterfaceName(), k -> Sets.newConcurrentHashSet()) + .add(domain.getAppName()); - Long v1 = versionResult.get(domain.getInterfaceName()); - long v2 = TimestampUtil.getNanosLong(domain.getGmtModify()); - if (v1 == null || v2 > v1) { - versionResult.put(domain.getInterfaceName(), v2); - } + Long v1 = versionResult.get(domain.getInterfaceName()); + long v2 = TimestampUtil.getNanosLong(domain.getGmtModify()); + if (v1 == null || v2 > v1) { + versionResult.put(domain.getInterfaceName(), v2); + } }); - taskEvents.forEach(taskEvent -> { - String interfaceName = taskEvent.getData().getInterfaceName(); - InvokeFuture future = taskEvent.getFuture(); - Set appNames = indexResult.get(interfaceName); - Long version = versionResult.get(interfaceName); + taskEvents.forEach( + taskEvent -> { + String interfaceName = taskEvent.getData().getInterfaceName(); + InvokeFuture future = taskEvent.getFuture(); + Set appNames = indexResult.get(interfaceName); + Long version = versionResult.get(interfaceName); - if (appNames == null || version == null) { - future.putResponse(new InterfaceMapping(-1)); - } else { - future.putResponse(new InterfaceMapping(version, appNames)); - } + if (appNames == null || version == null) { + future.putResponse(new InterfaceMapping(-1)); + } else { + future.putResponse(new InterfaceMapping(version, appNames)); + } }); - return true; - } + return true; + } - @Override - protected void setBatchSize() { - this.batchSize = 200; - } + @Override + protected void setBatchSize() { + this.batchSize = 200; + } - @Override - protected void setTimeUnit() { - this.timeUnit = TimeUnit.MILLISECONDS; - } + @Override + protected void setTimeUnit() { + this.timeUnit = TimeUnit.MILLISECONDS; + } - @Override - protected void setSleep() { - this.sleep = 20; - } -} \ No newline at end of file + @Override + protected void setSleep() { + this.sleep = 20; + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/AppRevisionHeartbeatJdbcRepository.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/AppRevisionHeartbeatJdbcRepository.java index c89622407..da720e542 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/AppRevisionHeartbeatJdbcRepository.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/AppRevisionHeartbeatJdbcRepository.java @@ -29,98 +29,101 @@ import com.alipay.sofa.registry.util.BatchCallableRunnable.InvokeFuture; import com.alipay.sofa.registry.util.BatchCallableRunnable.TaskEvent; import com.alipay.sofa.registry.util.SingleFlight; -import org.springframework.beans.factory.annotation.Autowired; -import javax.annotation.PostConstruct; -import javax.annotation.Resource; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author xiaojian.xj * @version $Id: AppRevisionHeartbeatJdbcRepository.java, v 0.1 2021年02月09日 17:14 xiaojian.xj Exp $ */ -public class AppRevisionHeartbeatJdbcRepository implements AppRevisionHeartbeatRepository, - JdbcRepository { - - private static final Logger LOG = LoggerFactory.getLogger( - "METADATA-EXCHANGE", - "[AppRevisionHeartbeat]"); - - @Resource - private AppRevisionJdbcRepository appRevisionJdbcRepository; - - @Autowired - private AppRevisionMapper appRevisionMapper; - - @Autowired - private AppRevisionHeartbeatBatchCallable appRevisionHeartbeatBatchCallable; - - @Autowired - private MetadataConfig metadataConfig; - - private SingleFlight singleFlight = new SingleFlight(); - - private Integer REVISION_GC_LIMIT; - - @PostConstruct - public void postConstruct() { - REVISION_GC_LIMIT = metadataConfig.getRevisionGcLimit(); - } - - @Override - public void doAppRevisionHeartbeat() { - - try { - singleFlight.execute("app_revision_heartbeat", () -> { - Map heartbeatMap = appRevisionJdbcRepository.getHeartbeatMap(); - - Map futureMap = new HashMap<>(); - for (Entry entry : heartbeatMap.entrySet()) { - TaskEvent taskEvent = appRevisionHeartbeatBatchCallable.new TaskEvent(entry.getValue()); - InvokeFuture future = appRevisionHeartbeatBatchCallable.commit(taskEvent); - futureMap.put(entry.getKey(), future); - } - - for (Entry entry : futureMap.entrySet()) { - - InvokeFuture future = entry.getValue(); - try { - future.getResponse(); - } catch (InterruptedException e) { - LOG.error(String.format("app_revision: %s heartbeat error.", entry.getKey().getRevision()), e); - } - } - return null; - }); - } catch (Exception e) { - LOG.error("app_revision heartbeat error.", e); - } - +public class AppRevisionHeartbeatJdbcRepository + implements AppRevisionHeartbeatRepository, JdbcRepository { + + private static final Logger LOG = + LoggerFactory.getLogger("METADATA-EXCHANGE", "[AppRevisionHeartbeat]"); + + @Resource private AppRevisionJdbcRepository appRevisionJdbcRepository; + + @Autowired private AppRevisionMapper appRevisionMapper; + + @Autowired private AppRevisionHeartbeatBatchCallable appRevisionHeartbeatBatchCallable; + + @Autowired private MetadataConfig metadataConfig; + + private SingleFlight singleFlight = new SingleFlight(); + + private Integer REVISION_GC_LIMIT; + + @PostConstruct + public void postConstruct() { + REVISION_GC_LIMIT = metadataConfig.getRevisionGcLimit(); + } + + @Override + public void doAppRevisionHeartbeat() { + + try { + singleFlight.execute( + "app_revision_heartbeat", + () -> { + Map heartbeatMap = + appRevisionJdbcRepository.getHeartbeatMap(); + + Map futureMap = new HashMap<>(); + for (Entry entry : heartbeatMap.entrySet()) { + TaskEvent taskEvent = + appRevisionHeartbeatBatchCallable.new TaskEvent(entry.getValue()); + InvokeFuture future = appRevisionHeartbeatBatchCallable.commit(taskEvent); + futureMap.put(entry.getKey(), future); + } + + for (Entry entry : futureMap.entrySet()) { + + InvokeFuture future = entry.getValue(); + try { + future.getResponse(); + } catch (InterruptedException e) { + LOG.error( + String.format( + "app_revision: %s heartbeat error.", entry.getKey().getRevision()), + e); + } + } + return null; + }); + } catch (Exception e) { + LOG.error("app_revision heartbeat error.", e); } - - @Override - public void doAppRevisionGc(String dataCenter, int silenceHour) { - - try { - singleFlight.execute("app_revision_gc", () -> { - - List appRevisions = AppRevisionDomainConvertor.convert2Revisions(appRevisionMapper.queryGcRevision(dataCenter, silenceHour, REVISION_GC_LIMIT)); - - if (LOG.isInfoEnabled()) { - LOG.info("app_revision tobe gc size: " + appRevisions.size()); - } - for (AppRevision appRevision : appRevisions) { - // delete app_revision - appRevisionMapper.deleteAppRevision(dataCenter, appRevision.getRevision()); - } - - return null; - }); - } catch (Exception e) { - LOG.error("app_revision gc error.", e); - } + } + + @Override + public void doAppRevisionGc(String dataCenter, int silenceHour) { + + try { + singleFlight.execute( + "app_revision_gc", + () -> { + List appRevisions = + AppRevisionDomainConvertor.convert2Revisions( + appRevisionMapper.queryGcRevision(dataCenter, silenceHour, REVISION_GC_LIMIT)); + + if (LOG.isInfoEnabled()) { + LOG.info("app_revision tobe gc size: " + appRevisions.size()); + } + for (AppRevision appRevision : appRevisions) { + // delete app_revision + appRevisionMapper.deleteAppRevision(dataCenter, appRevision.getRevision()); + } + + return null; + }); + } catch (Exception e) { + LOG.error("app_revision gc error.", e); } -} \ No newline at end of file + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/AppRevisionJdbcRepository.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/AppRevisionJdbcRepository.java index 8683a86aa..069ea8864 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/AppRevisionJdbcRepository.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/AppRevisionJdbcRepository.java @@ -32,181 +32,175 @@ import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; -import org.springframework.beans.factory.annotation.Autowired; -import javax.annotation.Resource; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; +import javax.annotation.Resource; +import org.springframework.beans.factory.annotation.Autowired; /** - * * @author xiaojian.xj * @version $Id: AppRevisionJdbcRepository.java, v 0.1 2021年01月17日 15:45 xiaojian.xj Exp $ */ public class AppRevisionJdbcRepository implements AppRevisionRepository, JdbcRepository { - private static final Logger LOG = LoggerFactory - .getLogger( - "METADATA-EXCHANGE", - "[AppRevision]"); + private static final Logger LOG = LoggerFactory.getLogger("METADATA-EXCHANGE", "[AppRevision]"); - /** - * map: - */ - private final LoadingCache registry; + /** map: */ + private final LoadingCache registry; - private final Map revisionQueryMap = new ConcurrentHashMap<>(); + private final Map revisionQueryMap = new ConcurrentHashMap<>(); - /** - * map: - */ - private final Cache heartbeatMap; + /** map: */ + private final Cache heartbeatMap; - @Autowired - private AppRevisionMapper appRevisionMapper; + @Autowired private AppRevisionMapper appRevisionMapper; - @Autowired - private AppRevisionBatchQueryCallable appRevisionBatchQueryCallable; + @Autowired private AppRevisionBatchQueryCallable appRevisionBatchQueryCallable; - @Resource - private InterfaceAppsJdbcRepository interfaceAppsJdbcRepository; + @Resource private InterfaceAppsJdbcRepository interfaceAppsJdbcRepository; - public AppRevisionJdbcRepository() { - this.registry = CacheBuilder.newBuilder().maximumSize(10000L) + public AppRevisionJdbcRepository() { + this.registry = + CacheBuilder.newBuilder() + .maximumSize(10000L) .expireAfterAccess(60, TimeUnit.MINUTES) - .build(new CacheLoader() { - @Override - public AppRevision load(AppRevisionQueryModel query) throws InterruptedException { + .build( + new CacheLoader() { + @Override + public AppRevision load(AppRevisionQueryModel query) throws InterruptedException { TaskEvent task = appRevisionBatchQueryCallable.new TaskEvent(query); InvokeFuture future = appRevisionBatchQueryCallable.commit(task); if (future.isSuccess()) { - Object response = future.getResponse(); - if (response == null) { - throw new RevisionNotExistException(query.getRevision()); - } - AppRevision appRevision = (AppRevision) response; - return appRevision; - } else { + Object response = future.getResponse(); + if (response == null) { throw new RevisionNotExistException(query.getRevision()); + } + AppRevision appRevision = (AppRevision) response; + return appRevision; + } else { + throw new RevisionNotExistException(query.getRevision()); } - } - }); + } + }); - this.heartbeatMap = CacheBuilder.newBuilder().maximumSize(10000L) - .expireAfterAccess(60, TimeUnit.MINUTES).build(); + this.heartbeatMap = + CacheBuilder.newBuilder() + .maximumSize(10000L) + .expireAfterAccess(60, TimeUnit.MINUTES) + .build(); + } + + @Override + public void register(AppRevision appRevision) throws Exception { + if (appRevision == null) { + throw new RuntimeException("jdbc register app revision error, appRevision is null."); + } + AppRevisionQueryModel key = + new AppRevisionQueryModel(appRevision.getDataCenter(), appRevision.getRevision()); + + // query cache, if not exist then query database + try { + AppRevision revision = registry.get(key); + if (revision != null) { + heartbeatMap.put( + key, + new AppRevision(appRevision.getDataCenter(), appRevision.getRevision(), new Date())); + return; + } + } catch (Throwable e) { + if (e.getCause() instanceof RevisionNotExistException) { + LOG.info(String.format("new revision: %s register.", appRevision.getRevision())); + } else { + LOG.error(String.format("new revision: %s register error.", appRevision.getRevision()), e); + throw e; + } } - @Override - public void register(AppRevision appRevision) throws Exception { - if (appRevision == null) { - throw new RuntimeException("jdbc register app revision error, appRevision is null."); - } - AppRevisionQueryModel key = new AppRevisionQueryModel(appRevision.getDataCenter(), - appRevision.getRevision()); - - // query cache, if not exist then query database - try { - AppRevision revision = registry.get(key); - if (revision != null) { - heartbeatMap.put(key, - new AppRevision(appRevision.getDataCenter(), appRevision.getRevision(), - new Date())); - return; - } - } catch (Throwable e) { - if (e.getCause() instanceof RevisionNotExistException) { - LOG.info(String.format("new revision: %s register.", appRevision.getRevision())); - } else { - LOG.error( - String.format("new revision: %s register error.", appRevision.getRevision()), e); - throw e; - } - } + // new revision, save into database - // new revision, save into database + // it will ignore ON DUPLICATE KEY, return effect rows number + interfaceAppsJdbcRepository.batchSave( + appRevision.getDataCenter(), + appRevision.getAppName(), + appRevision.getInterfaceMap().keySet()); - // it will ignore ON DUPLICATE KEY, return effect rows number - interfaceAppsJdbcRepository.batchSave(appRevision.getDataCenter(), - appRevision.getAppName(), appRevision.getInterfaceMap().keySet()); + // it will ignore ON DUPLICATE KEY + appRevisionMapper.insert(AppRevisionDomainConvertor.convert2Domain(appRevision)); - // it will ignore ON DUPLICATE KEY - appRevisionMapper.insert(AppRevisionDomainConvertor.convert2Domain(appRevision)); + registry.put(key, appRevision); + heartbeatMap.put( + key, new AppRevision(appRevision.getDataCenter(), appRevision.getRevision(), new Date())); + } - registry.put(key, appRevision); - heartbeatMap.put(key, - new AppRevision(appRevision.getDataCenter(), appRevision.getRevision(), new Date())); + @Override + public void refresh(String dataCenter) { + try { + interfaceAppsJdbcRepository.refresh(dataCenter); + } catch (Throwable e) { + LOG.error("jdbc refresh revisions failed ", e); + throw new RuntimeException("jdbc refresh revision failed", e); } - - @Override - public void refresh(String dataCenter) { - - try { - interfaceAppsJdbcRepository.refresh(dataCenter); - } catch (Throwable e) { - LOG.error("jdbc refresh revisions failed ", e); - throw new RuntimeException("jdbc refresh revision failed", e); - } + } + + @Override + public AppRevision queryRevision(String dataCenter, String revision) { + + try { + + AppRevisionQueryModel appRevisionQuery = revisionQueryMap.get(revision); + if (appRevisionQuery == null) { + appRevisionQuery = new AppRevisionQueryModel(dataCenter, revision); + revisionQueryMap.putIfAbsent(revision, appRevisionQuery); + } + return registry.get(appRevisionQuery); + } catch (ExecutionException e) { + LOG.error(String.format("jdbc refresh revision failed, revision: %s", revision), e); + throw new RuntimeException("jdbc refresh revision failed", e); } - - @Override - public AppRevision queryRevision(String dataCenter, String revision) { - - try { - - AppRevisionQueryModel appRevisionQuery = revisionQueryMap.get(revision); - if (appRevisionQuery == null) { - appRevisionQuery = new AppRevisionQueryModel(dataCenter, revision); - revisionQueryMap.putIfAbsent(revision, appRevisionQuery); - } - return registry.get(appRevisionQuery); - } catch (ExecutionException e) { - LOG.error(String.format("jdbc refresh revision failed, revision: %s", revision), e); - throw new RuntimeException("jdbc refresh revision failed", e); + } + + @Override + public AppRevision heartbeat(String dataCenter, String revision) { + try { + AppRevisionQueryModel appRevisionQuery = revisionQueryMap.get(revision); + if (appRevisionQuery == null) { + appRevisionQuery = new AppRevisionQueryModel(dataCenter, revision); + revisionQueryMap.putIfAbsent(revision, appRevisionQuery); + } + + try { + AppRevision appRevision = heartbeatMap.getIfPresent(appRevisionQuery); + if (appRevision != null) { + appRevision.setLastHeartbeat(new Date()); + } else { + appRevision = new AppRevision(dataCenter, revision, new Date()); } - } - - @Override - public AppRevision heartbeat(String dataCenter, String revision) { - try { - AppRevisionQueryModel appRevisionQuery = revisionQueryMap.get(revision); - if (appRevisionQuery == null) { - appRevisionQuery = new AppRevisionQueryModel(dataCenter, revision); - revisionQueryMap.putIfAbsent(revision, appRevisionQuery); - } - - try { - AppRevision appRevision = heartbeatMap.getIfPresent(appRevisionQuery); - if (appRevision != null) { - appRevision.setLastHeartbeat(new Date()); - } else { - appRevision = new AppRevision(dataCenter, revision, new Date()); - } - heartbeatMap.put(appRevisionQuery, appRevision); - return appRevision; - } catch (Throwable e) { - if (e.getCause() instanceof RevisionNotExistException) { - LOG.info(String.format("revision: %s heartbeat, not exist in db.", revision)); - } - return null; - } - } catch (Exception e) { - LOG.error(String.format("jdbc revision heartbeat failed, revision: %s", revision), e); - return null; + heartbeatMap.put(appRevisionQuery, appRevision); + return appRevision; + } catch (Throwable e) { + if (e.getCause() instanceof RevisionNotExistException) { + LOG.info(String.format("revision: %s heartbeat, not exist in db.", revision)); } - - } - - /** - * Getter method for property heartbeatMap. - * - * @return property value of heartbeatMap - */ - public Map getHeartbeatMap() { - return heartbeatMap.asMap(); + return null; + } + } catch (Exception e) { + LOG.error(String.format("jdbc revision heartbeat failed, revision: %s", revision), e); + return null; } -} \ No newline at end of file + } + + /** + * Getter method for property heartbeatMap. + * + * @return property value of heartbeatMap + */ + public Map getHeartbeatMap() { + return heartbeatMap.asMap(); + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/InterfaceAppsJdbcRepository.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/InterfaceAppsJdbcRepository.java index 688cc71ce..aa94865d5 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/InterfaceAppsJdbcRepository.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/InterfaceAppsJdbcRepository.java @@ -32,16 +32,15 @@ import com.alipay.sofa.registry.util.MathUtils; import com.alipay.sofa.registry.util.TimestampUtil; import com.google.common.collect.Sets; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.CollectionUtils; - -import javax.annotation.PostConstruct; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; +import javax.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; /** * @author xiaojian.xj @@ -49,185 +48,185 @@ */ public class InterfaceAppsJdbcRepository implements InterfaceAppsRepository, JdbcRepository { - private static final Logger LOG = LoggerFactory.getLogger( - "METADATA-EXCHANGE", - "[InterfaceApps]"); - - private volatile Timestamp lastModifyTimestamp = new Timestamp(-1); - - /** - * map: - */ - protected final Map interfaceApps = new ConcurrentHashMap<>(); - - @Autowired - private InterfaceAppBatchQueryCallable interfaceAppBatchQueryCallable; - - @Autowired - private InterfaceAppsIndexMapper interfaceAppsIndexMapper; - - private int refreshLimit; - - @Autowired - private MetadataConfig metadataConfig; - - @PostConstruct - public void postConstruct() { - refreshLimit = metadataConfig.getInterfaceAppsRefreshLimit(); + private static final Logger LOG = LoggerFactory.getLogger("METADATA-EXCHANGE", "[InterfaceApps]"); + + private volatile Timestamp lastModifyTimestamp = new Timestamp(-1); + + /** map: */ + protected final Map interfaceApps = new ConcurrentHashMap<>(); + + @Autowired private InterfaceAppBatchQueryCallable interfaceAppBatchQueryCallable; + + @Autowired private InterfaceAppsIndexMapper interfaceAppsIndexMapper; + + private int refreshLimit; + + @Autowired private MetadataConfig metadataConfig; + + @PostConstruct + public void postConstruct() { + refreshLimit = metadataConfig.getInterfaceAppsRefreshLimit(); + } + + @Override + public void loadMetadata(String dataCenter) { + // load interface_apps_version when session server startup, + // in order to avoid large request on database after session startup, + // it will load almost all record of this dataCenter, + // but not promise load 100% records of this dataCenter, + // eg: records insert or update after interfaceAppsIndexMapper.getTotalCount + // and beyond refreshCount will not be load in this method, they will be load in next schedule + final int total = interfaceAppsIndexMapper.getTotalCount(dataCenter); + final int refreshCount = MathUtils.divideCeil(total, refreshLimit); + LOG.info( + "begin load metadata, total count mapping {}, rounds={}, dataCenter={}", + total, + refreshCount, + dataCenter); + int refreshTotal = 0; + for (int i = 0; i < refreshCount; i++) { + final int num = this.refresh(dataCenter); + LOG.info("load metadata in round={}, num={}", i, num); + refreshTotal += num; + if (num == 0) { + break; + } } - - @Override - public void loadMetadata(String dataCenter) { - // load interface_apps_version when session server startup, - // in order to avoid large request on database after session startup, - // it will load almost all record of this dataCenter, - // but not promise load 100% records of this dataCenter, - // eg: records insert or update after interfaceAppsIndexMapper.getTotalCount - // and beyond refreshCount will not be load in this method, they will be load in next schedule - final int total = interfaceAppsIndexMapper.getTotalCount(dataCenter); - final int refreshCount = MathUtils.divideCeil(total, refreshLimit); - LOG.info("begin load metadata, total count mapping {}, rounds={}, dataCenter={}", total, - refreshCount, dataCenter); - int refreshTotal = 0; - for (int i = 0; i < refreshCount; i++) { - final int num = this.refresh(dataCenter); - LOG.info("load metadata in round={}, num={}", i, num); - refreshTotal += num; - if (num == 0) { - break; - } - } - LOG.info("finish load metadata, total={}", refreshTotal); + LOG.info("finish load metadata, total={}", refreshTotal); + } + + /** + * get revisions by interfaceName + * + * @param dataInfoId + * @return return appNames + */ + @Override + public InterfaceMapping getAppNames(String dataCenter, String dataInfoId) { + InterfaceMapping appNames = interfaceApps.get(dataInfoId); + if (appNames != null) { + return appNames; } - /** - * get revisions by interfaceName - * - * @param dataInfoId - * @return return appNames - */ - @Override - public InterfaceMapping getAppNames(String dataCenter, String dataInfoId) { - InterfaceMapping appNames = interfaceApps.get(dataInfoId); - if (appNames != null) { - return appNames; - } + final InterfaceAppIndexQueryModel query = + new InterfaceAppIndexQueryModel(dataCenter, dataInfoId); - final InterfaceAppIndexQueryModel query = new InterfaceAppIndexQueryModel(dataCenter, - dataInfoId); - - TaskEvent task = interfaceAppBatchQueryCallable.new TaskEvent(query); - InvokeFuture future = interfaceAppBatchQueryCallable.commit(task); - try { - if (future.isSuccess()) { - Object response = future.getResponse(); - if (response == null) { - appNames = new InterfaceMapping(-1); - } else { - appNames = (InterfaceMapping) response; - } - LOG.info("update interfaceMapping {}, {}", dataInfoId, appNames); - interfaceApps.put(dataInfoId, appNames); - return appNames; - } - LOG.error("query appNames by interface: {} fail.", dataInfoId); - throw new InterfaceAppQueryException(dataInfoId); - - } catch (Throwable e) { - LOG.error("query appNames by interface: {} error.", dataInfoId, e); - throw new RuntimeException(String.format("query appNames by interface: %s error.", - dataInfoId), e); + TaskEvent task = interfaceAppBatchQueryCallable.new TaskEvent(query); + InvokeFuture future = interfaceAppBatchQueryCallable.commit(task); + try { + if (future.isSuccess()) { + Object response = future.getResponse(); + if (response == null) { + appNames = new InterfaceMapping(-1); + } else { + appNames = (InterfaceMapping) response; } + LOG.info("update interfaceMapping {}, {}", dataInfoId, appNames); + interfaceApps.put(dataInfoId, appNames); + return appNames; + } + LOG.error("query appNames by interface: {} fail.", dataInfoId); + throw new InterfaceAppQueryException(dataInfoId); + + } catch (Throwable e) { + LOG.error("query appNames by interface: {} error.", dataInfoId, e); + throw new RuntimeException( + String.format("query appNames by interface: %s error.", dataInfoId), e); } - - /** - * insert - * - * @param dataCenter - * @param appName - * @param interfaceNames - */ - @Override - public int batchSave(String dataCenter, String appName, Set interfaceNames) { - List saves = new ArrayList<>(); - for (String interfaceName : interfaceNames) { - saves.add(new InterfaceAppsIndexDomain(dataCenter, interfaceName, appName)); - } - - return interfaceAppsIndexMapper.insert(saves); + } + + /** + * insert + * + * @param dataCenter + * @param appName + * @param interfaceNames + */ + @Override + public int batchSave(String dataCenter, String appName, Set interfaceNames) { + List saves = new ArrayList<>(); + for (String interfaceName : interfaceNames) { + saves.add(new InterfaceAppsIndexDomain(dataCenter, interfaceName, appName)); } - /** - * refresh interfaceNames index - */ - private synchronized void triggerRefreshCache(InterfaceAppsIndexDomain domain) { - InterfaceMapping mapping = interfaceApps.get(domain.getInterfaceName()); - final long nanosLong = TimestampUtil.getNanosLong(domain.getGmtModify()); - if (mapping == null) { - if (domain.isReference()) { - mapping = new InterfaceMapping(nanosLong, domain.getAppName()); - } else { - mapping = new InterfaceMapping(nanosLong); - } - if (LOG.isInfoEnabled()) { - LOG.info("refresh interface: {}, ref: {}, app: {}, mapping: {}", - domain.getInterfaceName(), domain.isReference(), domain.getAppName(), mapping); - } - interfaceApps.put(domain.getInterfaceName(), mapping); - return; - } - if (nanosLong >= mapping.getNanosVersion()) { - InterfaceMapping newMapping = null; - if (domain.isReference()) { - newMapping = new InterfaceMapping(nanosLong, mapping.getApps(), domain.getAppName()); - } else { - Set prev = Sets.newHashSet(mapping.getApps()); - prev.remove(domain.getAppName()); - newMapping = new InterfaceMapping(nanosLong, prev, domain.getAppName()); - } - if (LOG.isInfoEnabled()) { - LOG.info( - "update interface mapping: {}, ref: {}, app: {}, newMapping: {}, oldMapping: {}", - domain.getInterfaceName(), domain.isReference(), domain.getAppName(), - newMapping, mapping); - } - interfaceApps.put(domain.getInterfaceName(), newMapping); - } else { - LOG.info("ignored refresh index {}, current mapping={}", domain, mapping); - } + return interfaceAppsIndexMapper.insert(saves); + } + + /** refresh interfaceNames index */ + private synchronized void triggerRefreshCache(InterfaceAppsIndexDomain domain) { + InterfaceMapping mapping = interfaceApps.get(domain.getInterfaceName()); + final long nanosLong = TimestampUtil.getNanosLong(domain.getGmtModify()); + if (mapping == null) { + if (domain.isReference()) { + mapping = new InterfaceMapping(nanosLong, domain.getAppName()); + } else { + mapping = new InterfaceMapping(nanosLong); + } + if (LOG.isInfoEnabled()) { + LOG.info( + "refresh interface: {}, ref: {}, app: {}, mapping: {}", + domain.getInterfaceName(), + domain.isReference(), + domain.getAppName(), + mapping); + } + interfaceApps.put(domain.getInterfaceName(), mapping); + return; + } + if (nanosLong >= mapping.getNanosVersion()) { + InterfaceMapping newMapping = null; + if (domain.isReference()) { + newMapping = new InterfaceMapping(nanosLong, mapping.getApps(), domain.getAppName()); + } else { + Set prev = Sets.newHashSet(mapping.getApps()); + prev.remove(domain.getAppName()); + newMapping = new InterfaceMapping(nanosLong, prev, domain.getAppName()); + } + if (LOG.isInfoEnabled()) { + LOG.info( + "update interface mapping: {}, ref: {}, app: {}, newMapping: {}, oldMapping: {}", + domain.getInterfaceName(), + domain.isReference(), + domain.getAppName(), + newMapping, + mapping); + } + interfaceApps.put(domain.getInterfaceName(), newMapping); + } else { + LOG.info("ignored refresh index {}, current mapping={}", domain, mapping); + } + } + + public synchronized int refresh(String dataCenter) { + final Timestamp last = lastModifyTimestamp; + List afters = + interfaceAppsIndexMapper.queryModifyAfterThan(dataCenter, last, refreshLimit); + List equals = + interfaceAppsIndexMapper.queryModifyEquals(dataCenter, last); + if (LOG.isInfoEnabled()) { + LOG.info( + "refresh lastTimestamp={}, equals={}, afters={},", last, equals.size(), afters.size()); } - public synchronized int refresh(String dataCenter) { - final Timestamp last = lastModifyTimestamp; - List afters = interfaceAppsIndexMapper.queryModifyAfterThan( - dataCenter, last, refreshLimit); - List equals = interfaceAppsIndexMapper.queryModifyEquals( - dataCenter, last); - if (LOG.isInfoEnabled()) { - LOG.info("refresh lastTimestamp={}, equals={}, afters={},", last, equals.size(), - afters.size()); - } - - equals.addAll(afters); - if (CollectionUtils.isEmpty(equals)) { - return 0; - } - - // trigger refresh interface index, must be sorted by gmtModify - for (InterfaceAppsIndexDomain interfaceApps : equals) { - triggerRefreshCache(interfaceApps); - } + equals.addAll(afters); + if (CollectionUtils.isEmpty(equals)) { + return 0; + } - // update MAX_MODIFY_TIMESTAMP - InterfaceAppsIndexDomain max = equals.get(equals.size() - 1); - if (lastModifyTimestamp.before(max.getGmtModify())) { - this.lastModifyTimestamp = max.getGmtModify(); - LOG.info("update lastModifyTimestamp {} to {}", last, lastModifyTimestamp); - } else { - LOG.info("skip update lastModifyTimestamp {}, got={}", lastModifyTimestamp, - max.getGmtModify()); - } - return equals.size(); + // trigger refresh interface index, must be sorted by gmtModify + for (InterfaceAppsIndexDomain interfaceApps : equals) { + triggerRefreshCache(interfaceApps); } -} \ No newline at end of file + // update MAX_MODIFY_TIMESTAMP + InterfaceAppsIndexDomain max = equals.get(equals.size() - 1); + if (lastModifyTimestamp.before(max.getGmtModify())) { + this.lastModifyTimestamp = max.getGmtModify(); + LOG.info("update lastModifyTimestamp {} to {}", last, lastModifyTimestamp); + } else { + LOG.info( + "skip update lastModifyTimestamp {}, got={}", lastModifyTimestamp, max.getGmtModify()); + } + return equals.size(); + } +} diff --git a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/ProvideDataJdbcRepository.java b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/ProvideDataJdbcRepository.java index 6446ffdc3..adae6fe47 100644 --- a/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/ProvideDataJdbcRepository.java +++ b/server/store/jdbc/src/main/java/com/alipay/sofa/registry/jdbc/repository/impl/ProvideDataJdbcRepository.java @@ -25,44 +25,41 @@ import org.springframework.beans.factory.annotation.Autowired; /** - * * @author xiaojian.xj * @version $Id: ProvideDataJdbcRepository.java, v 0.1 2021年03月13日 19:20 xiaojian.xj Exp $ */ public class ProvideDataJdbcRepository implements ProvideDataRepository { - private static final Logger LOG = LoggerFactory.getLogger("META-PROVIDEDATA", - "[ProvideData]"); + private static final Logger LOG = LoggerFactory.getLogger("META-PROVIDEDATA", "[ProvideData]"); - @Autowired - private ProvideDataMapper provideDataMapper; + @Autowired private ProvideDataMapper provideDataMapper; - @Override - public boolean put(String dataCenter, String key, String value) { + @Override + public boolean put(String dataCenter, String key, String value) { - ProvideDataDomain data = new ProvideDataDomain(dataCenter, key, value); - provideDataMapper.save(data); - if (LOG.isInfoEnabled()) { - LOG.info("put provideData, dataCenter: {}, key: {}, value: {}", dataCenter, key, value); - } - return true; + ProvideDataDomain data = new ProvideDataDomain(dataCenter, key, value); + provideDataMapper.save(data); + if (LOG.isInfoEnabled()) { + LOG.info("put provideData, dataCenter: {}, key: {}, value: {}", dataCenter, key, value); } + return true; + } - @Override - public DBResponse get(String dataCenter, String key) { - ProvideDataDomain data = provideDataMapper.query(dataCenter, key); - if (data == null) { - return DBResponse.notfound().build(); - } - return DBResponse.ok(data.getDataValue()).build(); + @Override + public DBResponse get(String dataCenter, String key) { + ProvideDataDomain data = provideDataMapper.query(dataCenter, key); + if (data == null) { + return DBResponse.notfound().build(); } + return DBResponse.ok(data.getDataValue()).build(); + } - @Override - public boolean remove(String dataCenter, String key) { - provideDataMapper.remove(dataCenter, key); - if (LOG.isInfoEnabled()) { - LOG.info("remove provideData, dataCenter: {}, key: {}", dataCenter, key); - } - return true; + @Override + public boolean remove(String dataCenter, String key) { + provideDataMapper.remove(dataCenter, key); + if (LOG.isInfoEnabled()) { + LOG.info("remove provideData, dataCenter: {}, key: {}", dataCenter, key); } -} \ No newline at end of file + return true; + } +} diff --git a/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/AbstractH2DbTestBase.java b/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/AbstractH2DbTestBase.java index 9d8d3c34b..00a677e9b 100644 --- a/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/AbstractH2DbTestBase.java +++ b/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/AbstractH2DbTestBase.java @@ -17,6 +17,13 @@ package com.alipay.sofa.registry.jdbc; import com.alipay.sofa.registry.util.FileUtils; +import java.io.File; +import java.io.IOException; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.SQLException; +import java.util.Arrays; +import javax.sql.DataSource; import org.apache.commons.lang.StringUtils; import org.apache.logging.log4j.util.Strings; import org.h2.tools.Server; @@ -30,104 +37,93 @@ import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import javax.sql.DataSource; -import java.io.File; -import java.io.IOException; -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.Arrays; - /** * @author chen.zhu - *

- * Mar 15, 2021 + *

Mar 15, 2021 */ @ActiveProfiles("test") @SpringBootTest(classes = AbstractH2DbTestBase.JdbcTestConfig.class) @RunWith(SpringJUnit4ClassRunner.class) public class AbstractH2DbTestBase extends AbstractTest implements ApplicationContextAware { - public static final String TABLE_STRUCTURE = "sql/h2/create_table.sql"; - public static final String TABLE_DATA = "sql/h2/base_info.sql"; + public static final String TABLE_STRUCTURE = "sql/h2/create_table.sql"; + public static final String TABLE_DATA = "sql/h2/base_info.sql"; - protected final String KEY_H2_PORT = "h2Port"; - private Server h2Server; + protected final String KEY_H2_PORT = "h2Port"; + private Server h2Server; - protected DataSource dataSource; + protected DataSource dataSource; - protected ApplicationContext applicationContext; + protected ApplicationContext applicationContext; - @Before - public void setUpTestDataSource() throws SQLException, IOException { - executeSqlScript(prepareDatas()); - } + @Before + public void setUpTestDataSource() throws SQLException, IOException { + executeSqlScript(prepareDatas()); + } - protected void startH2Server() throws SQLException { + protected void startH2Server() throws SQLException { - int h2Port = Integer.parseInt(System.getProperty(KEY_H2_PORT, "9123")); - h2Server = Server.createTcpServer("-tcpPort", String.valueOf(h2Port), "-tcpAllowOthers"); - h2Server.start(); - // new Console().runTool(); - } + int h2Port = Integer.parseInt(System.getProperty(KEY_H2_PORT, "9123")); + h2Server = Server.createTcpServer("-tcpPort", String.valueOf(h2Port), "-tcpAllowOthers"); + h2Server.start(); + // new Console().runTool(); + } - protected String prepareDatas() { - return ""; - } + protected String prepareDatas() { + return ""; + } - protected String prepareDatasFromFile(String path) throws IOException { - return readFileAsString(path); - } + protected String prepareDatasFromFile(String path) throws IOException { + return readFileAsString(path); + } - public static String readFileAsString(String fileName) { - try { - return Arrays.toString(FileUtils.readFileToByteArray(new File(fileName))); - } catch (Throwable th) { - return ""; - } + public static String readFileAsString(String fileName) { + try { + return Arrays.toString(FileUtils.readFileToByteArray(new File(fileName))); + } catch (Throwable th) { + return ""; } + } - protected void executeSqlScript(String prepareSql) throws SQLException { - if (StringUtils.isEmpty(prepareSql)) { - return; - } - Connection conn = null; - PreparedStatement stmt = null; - try { - conn = dataSource.getConnection(); - conn.setAutoCommit(false); - if (!Strings.isEmpty(prepareSql)) { - for (String sql : prepareSql.split(";")) { - logger.debug("[setup][data]{}", sql.trim()); - stmt = conn.prepareStatement(sql); - stmt.executeUpdate(); - } - } - conn.commit(); - - } catch (Exception ex) { - logger.error("[SetUpTestDataSource][fail]:", ex); - if (null != conn) { - conn.rollback(); - } - } finally { - if (null != stmt) { - stmt.close(); - } - if (null != conn) { - conn.setAutoCommit(true); - conn.close(); - } - } + protected void executeSqlScript(String prepareSql) throws SQLException { + if (StringUtils.isEmpty(prepareSql)) { + return; } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = dataSource.getConnection(); + conn.setAutoCommit(false); + if (!Strings.isEmpty(prepareSql)) { + for (String sql : prepareSql.split(";")) { + logger.debug("[setup][data]{}", sql.trim()); + stmt = conn.prepareStatement(sql); + stmt.executeUpdate(); + } + } + conn.commit(); + + } catch (Exception ex) { + logger.error("[SetUpTestDataSource][fail]:", ex); + if (null != conn) { + conn.rollback(); + } + } finally { + if (null != stmt) { + stmt.close(); + } + if (null != conn) { + conn.setAutoCommit(true); + conn.close(); + } } + } - @SpringBootApplication - public static class JdbcTestConfig { + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } - } + @SpringBootApplication + public static class JdbcTestConfig {} } diff --git a/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/AbstractTest.java b/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/AbstractTest.java index 33df15c41..ef3c92329 100644 --- a/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/AbstractTest.java +++ b/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/AbstractTest.java @@ -22,12 +22,6 @@ import com.alipay.sofa.registry.observer.UnblockingObserver; import com.alipay.sofa.registry.util.NamedThreadFactory; import io.netty.util.ResourceLeakDetector; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.rules.TestName; - import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -47,245 +41,252 @@ import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BooleanSupplier; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.rules.TestName; /** * @author chen.zhu - *

- * Mar 15, 2021 + *

Mar 15, 2021 */ public class AbstractTest { - protected final Logger logger = LoggerFactory.getLogger(getClass()); + protected final Logger logger = LoggerFactory.getLogger(getClass()); - protected ExecutorService executors; + protected ExecutorService executors; - protected ScheduledExecutorService scheduled; + protected ScheduledExecutorService scheduled; - @Rule - public TestName name = new TestName(); + @Rule public TestName name = new TestName(); - public static final Random random = new Random(); + public static final Random random = new Random(); - @BeforeClass - public static void beforeAbstractTestClass() { - System.setProperty("spring.main.show_banner", "false"); - } - - @Before - public void beforeAbstractTest() throws Exception { - - ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); - Thread.interrupted();//clear interrupt + @BeforeClass + public static void beforeAbstractTestClass() { + System.setProperty("spring.main.show_banner", "false"); + } - executors = Executors.newCachedThreadPool(new NamedThreadFactory(name.getMethodName())); - scheduled = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), - new NamedThreadFactory("sched-" + name.getMethodName())); - if (logger.isInfoEnabled()) { - logger.info(remarkableMessage("[begin test][{}]"), name.getMethodName()); - } - } + @Before + public void beforeAbstractTest() throws Exception { - @After - public void afterAbstractTest() throws IOException, NoSuchMethodException, - InvocationTargetException, IllegalAccessException { - executors.shutdownNow(); - scheduled.shutdownNow(); + ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); + Thread.interrupted(); // clear interrupt - logger.info(remarkableMessage("[end test][{}]"), name.getMethodName()); + executors = Executors.newCachedThreadPool(new NamedThreadFactory(name.getMethodName())); + scheduled = + Executors.newScheduledThreadPool( + Runtime.getRuntime().availableProcessors(), + new NamedThreadFactory("sched-" + name.getMethodName())); + if (logger.isInfoEnabled()) { + logger.info(remarkableMessage("[begin test][{}]"), name.getMethodName()); } - - protected static void setEnv(Map newenv) throws Exception { - try { - Class processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); - Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); - theEnvironmentField.setAccessible(true); - Map env = (Map) theEnvironmentField.get(null); - env.putAll(newenv); - Field theCaseInsensitiveEnvironmentField = processEnvironmentClass - .getDeclaredField("theCaseInsensitiveEnvironment"); - theCaseInsensitiveEnvironmentField.setAccessible(true); - Map cienv = (Map) theCaseInsensitiveEnvironmentField - .get(null); - cienv.putAll(newenv); - } catch (NoSuchFieldException e) { - Class[] classes = Collections.class.getDeclaredClasses(); - Map env = System.getenv(); - for (Class cl : classes) { - if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { - Field field = cl.getDeclaredField("m"); - field.setAccessible(true); - Object obj = field.get(env); - Map map = (Map) obj; - map.clear(); - map.putAll(newenv); - } - } + } + + @After + public void afterAbstractTest() + throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { + executors.shutdownNow(); + scheduled.shutdownNow(); + + logger.info(remarkableMessage("[end test][{}]"), name.getMethodName()); + } + + protected static void setEnv(Map newenv) throws Exception { + try { + Class processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); + Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); + theEnvironmentField.setAccessible(true); + Map env = (Map) theEnvironmentField.get(null); + env.putAll(newenv); + Field theCaseInsensitiveEnvironmentField = + processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment"); + theCaseInsensitiveEnvironmentField.setAccessible(true); + Map cienv = + (Map) theCaseInsensitiveEnvironmentField.get(null); + cienv.putAll(newenv); + } catch (NoSuchFieldException e) { + Class[] classes = Collections.class.getDeclaredClasses(); + Map env = System.getenv(); + for (Class cl : classes) { + if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { + Field field = cl.getDeclaredField("m"); + field.setAccessible(true); + Object obj = field.get(env); + Map map = (Map) obj; + map.clear(); + map.putAll(newenv); } + } } + } - public static void setFinalStatic(Field field, Object newValue) throws Exception { - field.setAccessible(true); + public static void setFinalStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); - field.set(null, newValue); - } + field.set(null, newValue); + } - protected String remarkableMessage(String msg) { - return String.format("--------------------------%s--------------------------\r\n", msg); - } + protected String remarkableMessage(String msg) { + return String.format("--------------------------%s--------------------------\r\n", msg); + } - protected void waitForAnyKeyToExit() throws IOException { - logger.info("type any key to exit.................."); - waitForAnyKey(); - } + protected void waitForAnyKeyToExit() throws IOException { + logger.info("type any key to exit.................."); + waitForAnyKey(); + } - protected void waitForAnyKey() throws IOException { - System.in.read(); - } + protected void waitForAnyKey() throws IOException { + System.in.read(); + } - protected void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier) - throws TimeoutException, - InterruptedException { + protected void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier) + throws TimeoutException, InterruptedException { - waitConditionUntilTimeOut(booleanSupplier, 5000, 2); - } + waitConditionUntilTimeOut(booleanSupplier, 5000, 2); + } - protected static void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier, - int waitTimeMilli) throws TimeoutException, - InterruptedException { + protected static void waitConditionUntilTimeOut( + BooleanSupplier booleanSupplier, int waitTimeMilli) + throws TimeoutException, InterruptedException { - waitConditionUntilTimeOut(booleanSupplier, waitTimeMilli, 2); - } + waitConditionUntilTimeOut(booleanSupplier, waitTimeMilli, 2); + } - protected static void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier, - int waitTimeMilli, int intervalMilli) - throws TimeoutException, - InterruptedException { - - long maxTime = System.currentTimeMillis() + waitTimeMilli; - - while (true) { - boolean result = booleanSupplier.getAsBoolean(); - if (result) { - return; - } - if (System.currentTimeMillis() >= maxTime) { - throw new TimeoutException("timeout still false:" + waitTimeMilli); - } - Thread.sleep(intervalMilli); - } - } + protected static void waitConditionUntilTimeOut( + BooleanSupplier booleanSupplier, int waitTimeMilli, int intervalMilli) + throws TimeoutException, InterruptedException { + + long maxTime = System.currentTimeMillis() + waitTimeMilli; - public static int randomPort() { - return randomPort(10000, 20000, null); + while (true) { + boolean result = booleanSupplier.getAsBoolean(); + if (result) { + return; + } + if (System.currentTimeMillis() >= maxTime) { + throw new TimeoutException("timeout still false:" + waitTimeMilli); + } + Thread.sleep(intervalMilli); } + } - public static int randomPort(int min, int max, Set different) { + public static int randomPort() { + return randomPort(10000, 20000, null); + } - Random random = new Random(); + public static int randomPort(int min, int max, Set different) { - for (int i = min; i <= max; i++) { - int port = min + random.nextInt(max - min + 1); - if ((different == null || !different.contains(port)) && isUsable(port)) { - return port; - } - } + Random random = new Random(); - throw new IllegalStateException(String.format("random port not found:(%d, %d)", min, max)); + for (int i = min; i <= max; i++) { + int port = min + random.nextInt(max - min + 1); + if ((different == null || !different.contains(port)) && isUsable(port)) { + return port; + } } - public static int netmask = (1 << 8) - 1; + throw new IllegalStateException(String.format("random port not found:(%d, %d)", min, max)); + } - public static String randomIp() { - return String.format("%d.%d.%d.%d", (Math.abs(random.nextInt()) % netmask + 1), - (Math.abs(random.nextInt()) % netmask + 1), (Math.abs(random.nextInt()) % netmask + 1), - (Math.abs(random.nextInt()) % netmask + 1)); - } + public static int netmask = (1 << 8) - 1; - protected static boolean isUsable(int port) { + public static String randomIp() { + return String.format( + "%d.%d.%d.%d", + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1)); + } - try (ServerSocket s = new ServerSocket()) { - s.bind(new InetSocketAddress(port)); - return true; - } catch (IOException e) { - } - return false; - } + protected static boolean isUsable(int port) { - public static String getDc() { - return "DEFAULT_DC"; + try (ServerSocket s = new ServerSocket()) { + s.bind(new InetSocketAddress(port)); + return true; + } catch (IOException e) { } + return false; + } - public static String randomString() { + public static String getDc() { + return "DEFAULT_DC"; + } - return randomString(1 << 10); - } + public static String randomString() { - public static String randomString(int length) { + return randomString(1 << 10); + } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - sb.append((char) ('a' + (int) (26 * Math.random()))); - } + public static String randomString(int length) { - return sb.toString(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + sb.append((char) ('a' + (int) (26 * Math.random()))); } - public static class NotifyObserversCounter implements UnblockingObserver { + return sb.toString(); + } - private final AtomicInteger counter = new AtomicInteger(0); + public static class NotifyObserversCounter implements UnblockingObserver { - @Override - public void update(Observable source, Object message) { - counter.getAndIncrement(); - } + private final AtomicInteger counter = new AtomicInteger(0); - public int getCounter() { - return counter.get(); - } + @Override + public void update(Observable source, Object message) { + counter.getAndIncrement(); } - public static class ConcurrentExecutor implements Executor { + public int getCounter() { + return counter.get(); + } + } - private final int tasks; + public static class ConcurrentExecutor implements Executor { - private final CyclicBarrier barrier; + private final int tasks; - private final CountDownLatch latch; + private final CyclicBarrier barrier; - private final ExecutorService executors; + private final CountDownLatch latch; - public ConcurrentExecutor(int tasks, ExecutorService executors) { - this.tasks = tasks; - this.barrier = new CyclicBarrier(tasks); - this.latch = new CountDownLatch(tasks); - this.executors = executors; - } + private final ExecutorService executors; - @Override - public void execute(final Runnable command) { - for (int i = 0; i < tasks; i++) { - executors.execute(new Runnable() { - @Override - public void run() { - try { - barrier.await(); - command.run(); - } catch (Exception ignore) { - } - - latch.countDown(); - } - }); - } - try { - latch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } + public ConcurrentExecutor(int tasks, ExecutorService executors) { + this.tasks = tasks; + this.barrier = new CyclicBarrier(tasks); + this.latch = new CountDownLatch(tasks); + this.executors = executors; + } + + @Override + public void execute(final Runnable command) { + for (int i = 0; i < tasks; i++) { + executors.execute( + new Runnable() { + @Override + public void run() { + try { + barrier.await(); + command.run(); + } catch (Exception ignore) { + } + + latch.countDown(); + } + }); + } + try { + latch.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } } + } } diff --git a/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/elector/MetaJdbcLeaderElectorTest.java b/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/elector/MetaJdbcLeaderElectorTest.java index 1a09aea37..58dc02834 100644 --- a/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/elector/MetaJdbcLeaderElectorTest.java +++ b/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/elector/MetaJdbcLeaderElectorTest.java @@ -18,11 +18,10 @@ import com.alipay.sofa.registry.jdbc.AbstractH2DbTestBase; import com.alipay.sofa.registry.store.api.elector.AbstractLeaderElector; +import java.util.concurrent.TimeoutException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; -import java.util.concurrent.TimeoutException; - /** * @author zhuchen @@ -30,25 +29,25 @@ */ public class MetaJdbcLeaderElectorTest extends AbstractH2DbTestBase { - private MetaJdbcLeaderElector leaderElector; + private MetaJdbcLeaderElector leaderElector; - @Before - public void beforeMetaJdbcLeaderElectorTest() { - leaderElector = applicationContext.getBean(MetaJdbcLeaderElector.class); - } + @Before + public void beforeMetaJdbcLeaderElectorTest() { + leaderElector = applicationContext.getBean(MetaJdbcLeaderElector.class); + } - @Test - public void testDoElect() throws TimeoutException, InterruptedException { - Assert.assertNotNull(leaderElector); - leaderElector.change2Follow(); - waitConditionUntilTimeOut(()->leaderElector.amILeader(), 5000); - } + @Test + public void testDoElect() throws TimeoutException, InterruptedException { + Assert.assertNotNull(leaderElector); + leaderElector.change2Follow(); + waitConditionUntilTimeOut(() -> leaderElector.amILeader(), 5000); + } - @Test - public void testDoQuery() throws TimeoutException, InterruptedException { - leaderElector.change2Follow(); - waitConditionUntilTimeOut(()->leaderElector.amILeader(), 5000); - AbstractLeaderElector.LeaderInfo leaderInfo = leaderElector.doQuery(); - Assert.assertEquals(leaderInfo.getLeader(), leaderElector.myself()); - } -} \ No newline at end of file + @Test + public void testDoQuery() throws TimeoutException, InterruptedException { + leaderElector.change2Follow(); + waitConditionUntilTimeOut(() -> leaderElector.amILeader(), 5000); + AbstractLeaderElector.LeaderInfo leaderInfo = leaderElector.doQuery(); + Assert.assertEquals(leaderInfo.getLeader(), leaderElector.myself()); + } +} diff --git a/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/repository/impl/ProvideDataJdbcRepositoryTest.java b/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/repository/impl/ProvideDataJdbcRepositoryTest.java index a45781397..098373579 100644 --- a/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/repository/impl/ProvideDataJdbcRepositoryTest.java +++ b/server/store/jdbc/src/test/java/com/alipay/sofa/registry/jdbc/repository/impl/ProvideDataJdbcRepositoryTest.java @@ -25,20 +25,21 @@ public class ProvideDataJdbcRepositoryTest extends AbstractH2DbTestBase { - @Autowired - private ProvideDataRepository provideDataJdbcRepository; + @Autowired private ProvideDataRepository provideDataJdbcRepository; - @Test - public void testPut() { - provideDataJdbcRepository.put(getDc(), "key", "val"); - Assert.assertEquals("val", provideDataJdbcRepository.get(getDc(), "key").getEntity()); - } + @Test + public void testPut() { + provideDataJdbcRepository.put(getDc(), "key", "val"); + Assert.assertEquals("val", provideDataJdbcRepository.get(getDc(), "key").getEntity()); + } - @Test - public void testRemove() { - provideDataJdbcRepository.put(getDc(), "key", "val"); - Assert.assertEquals("val", provideDataJdbcRepository.get(getDc(), "key").getEntity()); - provideDataJdbcRepository.remove(getDc(), "key"); - Assert.assertEquals(OperationStatus.NOTFOUND, provideDataJdbcRepository.get(getDc(), "key").getOperationStatus()); - } -} \ No newline at end of file + @Test + public void testRemove() { + provideDataJdbcRepository.put(getDc(), "key", "val"); + Assert.assertEquals("val", provideDataJdbcRepository.get(getDc(), "key").getEntity()); + provideDataJdbcRepository.remove(getDc(), "key"); + Assert.assertEquals( + OperationStatus.NOTFOUND, + provideDataJdbcRepository.get(getDc(), "key").getOperationStatus()); + } +} diff --git a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/CommandCodec.java b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/CommandCodec.java index 277e2d3e5..c33b0a754 100644 --- a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/CommandCodec.java +++ b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/CommandCodec.java @@ -21,36 +21,38 @@ /** * Command codec - * @author boyan (boyan@alibaba-inc.com) * - * 2018-Apr-25 1:30:30 PM + * @author boyan (boyan@alibaba-inc.com) + *

2018-Apr-25 1:30:30 PM */ public class CommandCodec { - /** - * encode the command,returns the byte array. - * @param obj - * @return - */ - public static byte[] encodeCommand(Object obj) { - try { - return SerializerManager.getSerializer(SerializerManager.Hessian2).serialize(obj); - } catch (CodecException e) { - throw new IllegalStateException(e); - } + /** + * encode the command,returns the byte array. + * + * @param obj + * @return + */ + public static byte[] encodeCommand(Object obj) { + try { + return SerializerManager.getSerializer(SerializerManager.Hessian2).serialize(obj); + } catch (CodecException e) { + throw new IllegalStateException(e); } + } - /** - * Decode the command object from byte array. - * @param content - * @param clazz - * @return - */ - public static T decodeCommand(byte[] content, Class clazz) { - try { - return SerializerManager.getSerializer(SerializerManager.Hessian2).deserialize(content, - clazz.getName()); - } catch (CodecException e) { - throw new IllegalStateException(e); - } + /** + * Decode the command object from byte array. + * + * @param content + * @param clazz + * @return + */ + public static T decodeCommand(byte[] content, Class clazz) { + try { + return SerializerManager.getSerializer(SerializerManager.Hessian2) + .deserialize(content, clazz.getName()); + } catch (CodecException e) { + throw new IllegalStateException(e); } + } } diff --git a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/NotifyLeaderChange.java b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/NotifyLeaderChange.java index a85efaa8c..23eac0c13 100644 --- a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/NotifyLeaderChange.java +++ b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/NotifyLeaderChange.java @@ -17,61 +17,60 @@ package com.alipay.sofa.registry.jraft.command; import com.alipay.sofa.jraft.entity.PeerId; - import java.io.Serializable; /** - * * @author shangyu.wh * @version $Id: NotifyLeaderChange.java, v 0.1 2018-06-23 14:32 shangyu.wh Exp $ */ public class NotifyLeaderChange implements Serializable { - private final PeerId leader; + private final PeerId leader; - private String sender; + private String sender; - /** - * constructor - * @param leader - */ - public NotifyLeaderChange(PeerId leader) { - this.leader = leader; - } + /** + * constructor + * + * @param leader + */ + public NotifyLeaderChange(PeerId leader) { + this.leader = leader; + } - /** - * Getter method for property leader. - * - * @return property value of leader - */ - public PeerId getLeader() { - return leader; - } + /** + * Getter method for property leader. + * + * @return property value of leader + */ + public PeerId getLeader() { + return leader; + } - /** - * Getter method for property sender. - * - * @return property value of sender - */ - public String getSender() { - return sender; - } + /** + * Getter method for property sender. + * + * @return property value of sender + */ + public String getSender() { + return sender; + } - /** - * Setter method for property sender. - * - * @param sender value to be assigned to property sender - */ - public void setSender(String sender) { - this.sender = sender; - } + /** + * Setter method for property sender. + * + * @param sender value to be assigned to property sender + */ + public void setSender(String sender) { + this.sender = sender; + } - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("NotifyLeaderChange{"); - sb.append("leader=").append(leader); - sb.append(", sender='").append(sender).append('\''); - sb.append('}'); - return sb.toString(); - } -} \ No newline at end of file + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("NotifyLeaderChange{"); + sb.append("leader=").append(leader); + sb.append(", sender='").append(sender).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/ProcessRequest.java b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/ProcessRequest.java index 5c69aed67..960fea3c6 100644 --- a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/ProcessRequest.java +++ b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/ProcessRequest.java @@ -20,107 +20,105 @@ import java.util.Arrays; /** - * * @author shangyu.wh * @version $Id: ProcessRequest.java, v 0.1 2018-05-21 17:36 shangyu.wh Exp $ */ public class ProcessRequest implements Serializable { - /** invoke method */ - private String methodName; - - /** invoke method arguments name */ - private String[] methodArgSigs; - - /** invoke method arguments object */ - private Object[] methodArgs; - - /** traget service unique name */ - private String serviceName; - - public ProcessRequest() { - } - - /** - * Getter method for property methodName. - * - * @return property value of methodName - */ - public String getMethodName() { - return methodName; - } - - /** - * Setter method for property methodName. - * - * @param methodName value to be assigned to property methodName - */ - public void setMethodName(String methodName) { - this.methodName = methodName; - } - - /** - * Getter method for property methodArgSigs. - * - * @return property value of methodArgSigs - */ - public String[] getMethodArgSigs() { - return methodArgSigs; - } - - /** - * Setter method for property methodArgSigs. - * - * @param methodArgSigs value to be assigned to property methodArgSigs - */ - public void setMethodArgSigs(String[] methodArgSigs) { - this.methodArgSigs = methodArgSigs; - } - - /** - * Getter method for property methodArgs. - * - * @return property value of methodArgs - */ - public Object[] getMethodArgs() { - return methodArgs; - } - - /** - * Setter method for property methodArgs. - * - * @param methodArgs value to be assigned to property methodArgs - */ - public void setMethodArgs(Object[] methodArgs) { - this.methodArgs = methodArgs; - } - - /** - * Getter method for property serviceName. - * - * @return property value of serviceName - */ - public String getServiceName() { - return serviceName; - } - - /** - * Setter method for property serviceName. - * - * @param serviceName value to be assigned to property serviceName - */ - public void setServiceName(String serviceName) { - this.serviceName = serviceName; - } - - @Override - public String toString() { - final StringBuilder sb = new StringBuilder("ProcessRequest{"); - sb.append("methodName='").append(methodName).append('\''); - sb.append(", methodArgSigs=").append(Arrays.toString(methodArgSigs)); - sb.append(", methodArgs=").append(Arrays.toString(methodArgs)); - sb.append(", serviceName='").append(serviceName).append('\''); - sb.append('}'); - return sb.toString(); - } -} \ No newline at end of file + /** invoke method */ + private String methodName; + + /** invoke method arguments name */ + private String[] methodArgSigs; + + /** invoke method arguments object */ + private Object[] methodArgs; + + /** traget service unique name */ + private String serviceName; + + public ProcessRequest() {} + + /** + * Getter method for property methodName. + * + * @return property value of methodName + */ + public String getMethodName() { + return methodName; + } + + /** + * Setter method for property methodName. + * + * @param methodName value to be assigned to property methodName + */ + public void setMethodName(String methodName) { + this.methodName = methodName; + } + + /** + * Getter method for property methodArgSigs. + * + * @return property value of methodArgSigs + */ + public String[] getMethodArgSigs() { + return methodArgSigs; + } + + /** + * Setter method for property methodArgSigs. + * + * @param methodArgSigs value to be assigned to property methodArgSigs + */ + public void setMethodArgSigs(String[] methodArgSigs) { + this.methodArgSigs = methodArgSigs; + } + + /** + * Getter method for property methodArgs. + * + * @return property value of methodArgs + */ + public Object[] getMethodArgs() { + return methodArgs; + } + + /** + * Setter method for property methodArgs. + * + * @param methodArgs value to be assigned to property methodArgs + */ + public void setMethodArgs(Object[] methodArgs) { + this.methodArgs = methodArgs; + } + + /** + * Getter method for property serviceName. + * + * @return property value of serviceName + */ + public String getServiceName() { + return serviceName; + } + + /** + * Setter method for property serviceName. + * + * @param serviceName value to be assigned to property serviceName + */ + public void setServiceName(String serviceName) { + this.serviceName = serviceName; + } + + @Override + public String toString() { + final StringBuilder sb = new StringBuilder("ProcessRequest{"); + sb.append("methodName='").append(methodName).append('\''); + sb.append(", methodArgSigs=").append(Arrays.toString(methodArgSigs)); + sb.append(", methodArgs=").append(Arrays.toString(methodArgs)); + sb.append(", serviceName='").append(serviceName).append('\''); + sb.append('}'); + return sb.toString(); + } +} diff --git a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/ProcessResponse.java b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/ProcessResponse.java index 7a521cf3b..26cf20e2d 100644 --- a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/ProcessResponse.java +++ b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/command/ProcessResponse.java @@ -19,162 +19,156 @@ import java.io.Serializable; /** - * * @author shangyu.wh * @version $Id: Response.java, v 0.1 2018-05-21 14:22 shangyu.wh Exp $ */ public class ProcessResponse implements Serializable { - private final Object entity; - - private final Boolean success; - - private final String redirect; - - /** - * constructor - * - * @param entity - * @param success - * @param redirect - */ - public ProcessResponse(Object entity, Boolean success, String redirect) { - this.entity = entity; - this.success = success; - this.redirect = redirect; - } - - /** - * response ok - * - * @return - */ - public static ResponseBuilder ok() { - return setStatus(true); - } - - /** - * response ok - * - * @param entity - * @return - */ - public static ResponseBuilder ok(Object entity) { - ResponseBuilder b = ok(); - b.entity(entity); - return b; - } - - /** - * response fail - * - * @return - */ - public static ResponseBuilder fail() { - return setStatus(false); - } - - /** - * response fail - * - * @param errorMsg - * @return - */ - public static ResponseBuilder fail(String errorMsg) { - ResponseBuilder b = fail(); - b.entity(errorMsg); - return b; - } - - /** - * response redirect - * - * @param leader - * @return - */ - public static ResponseBuilder redirect(String leader) { - ResponseBuilder b = fail(); - b.entity("Not leader"); - b.redirect(leader); - return b; - } - - protected static ResponseBuilder setStatus(Boolean status) { - ResponseBuilder b = new ResponseBuilder(); - b.status(status); - return b; - } - - /** - * Getter method for property entity. - * - * @return property value of entity - */ - public Object getEntity() { - return entity; - } - - /** - * Getter method for property success. - * - * @return property value of success - */ - public Boolean getSuccess() { - return success; - } - - /** - * Getter method for property redirect. - * - * @return property value of redirect - */ - public String getRedirect() { - return redirect; - } - - /** - * ResponseBuilder - */ - public static class ResponseBuilder { - private Object entity; - - private Boolean success; - private String redirect; - - public ProcessResponse build() { - final ProcessResponse r = new ProcessResponse(entity, success, - redirect); - reset(); - return r; - } - - private void reset() { - success = null; - entity = null; - redirect = null; - } - - public ResponseBuilder status(Boolean status) { - if (status == null) { - throw new IllegalArgumentException( - "response status can not be null!"); - } - this.success = status; - return this; - } - - public ResponseBuilder entity(Object entity) { - this.entity = entity; - return this; - } - - public ResponseBuilder redirect(String redirect) { - if (redirect == null) { - throw new IllegalArgumentException( - "redirect leader can not be null!"); - } - this.redirect = redirect; - return this; - } - } -} \ No newline at end of file + private final Object entity; + + private final Boolean success; + + private final String redirect; + + /** + * constructor + * + * @param entity + * @param success + * @param redirect + */ + public ProcessResponse(Object entity, Boolean success, String redirect) { + this.entity = entity; + this.success = success; + this.redirect = redirect; + } + + /** + * response ok + * + * @return + */ + public static ResponseBuilder ok() { + return setStatus(true); + } + + /** + * response ok + * + * @param entity + * @return + */ + public static ResponseBuilder ok(Object entity) { + ResponseBuilder b = ok(); + b.entity(entity); + return b; + } + + /** + * response fail + * + * @return + */ + public static ResponseBuilder fail() { + return setStatus(false); + } + + /** + * response fail + * + * @param errorMsg + * @return + */ + public static ResponseBuilder fail(String errorMsg) { + ResponseBuilder b = fail(); + b.entity(errorMsg); + return b; + } + + /** + * response redirect + * + * @param leader + * @return + */ + public static ResponseBuilder redirect(String leader) { + ResponseBuilder b = fail(); + b.entity("Not leader"); + b.redirect(leader); + return b; + } + + protected static ResponseBuilder setStatus(Boolean status) { + ResponseBuilder b = new ResponseBuilder(); + b.status(status); + return b; + } + + /** + * Getter method for property entity. + * + * @return property value of entity + */ + public Object getEntity() { + return entity; + } + + /** + * Getter method for property success. + * + * @return property value of success + */ + public Boolean getSuccess() { + return success; + } + + /** + * Getter method for property redirect. + * + * @return property value of redirect + */ + public String getRedirect() { + return redirect; + } + + /** ResponseBuilder */ + public static class ResponseBuilder { + private Object entity; + + private Boolean success; + private String redirect; + + public ProcessResponse build() { + final ProcessResponse r = new ProcessResponse(entity, success, redirect); + reset(); + return r; + } + + private void reset() { + success = null; + entity = null; + redirect = null; + } + + public ResponseBuilder status(Boolean status) { + if (status == null) { + throw new IllegalArgumentException("response status can not be null!"); + } + this.success = status; + return this; + } + + public ResponseBuilder entity(Object entity) { + this.entity = entity; + return this; + } + + public ResponseBuilder redirect(String redirect) { + if (redirect == null) { + throw new IllegalArgumentException("redirect leader can not be null!"); + } + this.redirect = redirect; + return this; + } + } +} diff --git a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/config/RaftConfiguration.java b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/config/RaftConfiguration.java index af3812cf2..7e1461656 100644 --- a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/config/RaftConfiguration.java +++ b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/config/RaftConfiguration.java @@ -25,7 +25,6 @@ import org.springframework.context.annotation.Configuration; /** - * * @author xiaojian.xj * @version $Id: JdbcConfiguration.java, v 0.1 2021年01月17日 16:28 xiaojian.xj Exp $ */ @@ -33,17 +32,16 @@ @EnableConfigurationProperties public class RaftConfiguration { - @Configuration - public static class RepositoryBeanConfiguration { - @Bean - public InterfaceAppsRepository interfaceAppsRaftRepository() { - return new InterfaceAppsRaftRepository(); - } - - @Bean - public AppRevisionHeartbeatRepository appRevisionHeartbeatRaftRepository() { - return new AppRevisionHeartbeatRaftRepository(); - } + @Configuration + public static class RepositoryBeanConfiguration { + @Bean + public InterfaceAppsRepository interfaceAppsRaftRepository() { + return new InterfaceAppsRaftRepository(); } -} \ No newline at end of file + @Bean + public AppRevisionHeartbeatRepository appRevisionHeartbeatRaftRepository() { + return new AppRevisionHeartbeatRaftRepository(); + } + } +} diff --git a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/AppRevisionHeartbeatRaftRepository.java b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/AppRevisionHeartbeatRaftRepository.java index 09ab88c72..6cc7f9acf 100644 --- a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/AppRevisionHeartbeatRaftRepository.java +++ b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/AppRevisionHeartbeatRaftRepository.java @@ -19,20 +19,15 @@ import com.alipay.sofa.registry.store.api.repository.AppRevisionHeartbeatRepository; /** - * * @author xiaojian.xj * @version $Id: AppRevisionHeartbeatRaftRepository.java, v 0.1 2021年02月09日 17:15 xiaojian.xj Exp $ */ -public class AppRevisionHeartbeatRaftRepository implements AppRevisionHeartbeatRepository, - RaftRepository { - - @Override - public void doAppRevisionHeartbeat() { - - } +public class AppRevisionHeartbeatRaftRepository + implements AppRevisionHeartbeatRepository, RaftRepository { - @Override - public void doAppRevisionGc(String dataCenter, int silenceHour) { + @Override + public void doAppRevisionHeartbeat() {} - } -} \ No newline at end of file + @Override + public void doAppRevisionGc(String dataCenter, int silenceHour) {} +} diff --git a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/InterfaceAppsRaftRepository.java b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/InterfaceAppsRaftRepository.java index d39834cc3..104c97313 100644 --- a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/InterfaceAppsRaftRepository.java +++ b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/InterfaceAppsRaftRepository.java @@ -22,7 +22,6 @@ import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; import com.alipay.sofa.registry.store.api.repository.InterfaceAppsRepository; - import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @@ -31,37 +30,34 @@ * @version $Id: InterfaceAppsRaftRepository.java, v 0.1 2021年01月24日 19:44 xiaojian.xj Exp $ */ public class InterfaceAppsRaftRepository implements InterfaceAppsRepository, RaftRepository { - protected static final Logger LOG = LoggerFactory - .getLogger(InterfaceAppsRaftRepository.class); + protected static final Logger LOG = LoggerFactory.getLogger(InterfaceAppsRaftRepository.class); - /** - * map: - */ - protected final Map interfaceApps = new ConcurrentHashMap<>(); + /** map: */ + protected final Map interfaceApps = new ConcurrentHashMap<>(); - @Override - public void loadMetadata(String dataCenter) { - //FIXME - } + @Override + public void loadMetadata(String dataCenter) { + // FIXME + } - @Override - public InterfaceMapping getAppNames(String dataCenter, String dataInfoId) { - final InterfaceMapping ret = interfaceApps.get(dataInfoId); - return ret; - } + @Override + public InterfaceMapping getAppNames(String dataCenter, String dataInfoId) { + final InterfaceMapping ret = interfaceApps.get(dataInfoId); + return ret; + } - public void onNewRevision(AppRevision rev) { + public void onNewRevision(AppRevision rev) { - if (rev.getInterfaceMap() == null) { - LOG.warn("AppRevision no interface, {}", rev); - return; - } - - for (Map.Entry entry : rev.getInterfaceMap().entrySet()) { - String serviceId = entry.getKey(); - InterfaceMapping interfaceMapping = interfaceApps.computeIfAbsent(serviceId, k -> new InterfaceMapping(-1)); - interfaceMapping.getApps().add(rev.getAppName()); - } + if (rev.getInterfaceMap() == null) { + LOG.warn("AppRevision no interface, {}", rev); + return; + } + for (Map.Entry entry : rev.getInterfaceMap().entrySet()) { + String serviceId = entry.getKey(); + InterfaceMapping interfaceMapping = + interfaceApps.computeIfAbsent(serviceId, k -> new InterfaceMapping(-1)); + interfaceMapping.getApps().add(rev.getAppName()); } -} \ No newline at end of file + } +} diff --git a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/RaftRepository.java b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/RaftRepository.java index 73e1b93e0..be3b50625 100644 --- a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/RaftRepository.java +++ b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/repository/impl/RaftRepository.java @@ -20,14 +20,13 @@ import com.alipay.sofa.registry.store.api.driver.RepositoryManager.RepositoryType; /** - * * @author xiaojian.xj * @version $Id: RaftRepository.java, v 0.1 2021年01月17日 15:56 xiaojian.xj Exp $ */ public interface RaftRepository extends RegistryRepository { - @Override - default boolean accept(RepositoryType repositoryType) { - return repositoryType == RepositoryType.RAFT; - } -} \ No newline at end of file + @Override + default boolean accept(RepositoryType repositoryType) { + return repositoryType == RepositoryType.RAFT; + } +} diff --git a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/revision/AppRevisionRegistry.java b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/revision/AppRevisionRegistry.java index da93731d3..3de0ee491 100644 --- a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/revision/AppRevisionRegistry.java +++ b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/revision/AppRevisionRegistry.java @@ -19,31 +19,29 @@ import com.alipay.sofa.registry.common.model.store.AppRevision; import com.alipay.sofa.registry.log.Logger; import com.alipay.sofa.registry.log.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; - import java.util.List; +import org.springframework.beans.factory.annotation.Autowired; public class AppRevisionRegistry { - @Autowired - private AppRevisionService appRevisionService; - private static final Logger LOGGER = LoggerFactory.getLogger(AppRevisionService.class); + @Autowired private AppRevisionService appRevisionService; + private static final Logger LOGGER = LoggerFactory.getLogger(AppRevisionService.class); - public void register(AppRevision appRevision) { - if (appRevisionService.existed(appRevision.getRevision())) { - return; - } - appRevisionService.add(appRevision); - LOGGER.info("register new revision: {}", appRevision.getRevision()); + public void register(AppRevision appRevision) { + if (appRevisionService.existed(appRevision.getRevision())) { + return; } + appRevisionService.add(appRevision); + LOGGER.info("register new revision: {}", appRevision.getRevision()); + } - public List checkRevisions(String keysDigest) { - if (keysDigest.equals(appRevisionService.getKeysDigest())) { - return null; - } - return appRevisionService.getKeys(); + public List checkRevisions(String keysDigest) { + if (keysDigest.equals(appRevisionService.getKeysDigest())) { + return null; } + return appRevisionService.getKeys(); + } - public List fetchRevisions(List keys) { - return appRevisionService.getMulti(keys); - } + public List fetchRevisions(List keys) { + return appRevisionService.getMulti(keys); + } } diff --git a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/revision/AppRevisionService.java b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/revision/AppRevisionService.java index 44b399e2d..eed736863 100644 --- a/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/revision/AppRevisionService.java +++ b/server/store/jraft/src/main/java/com/alipay/sofa/registry/jraft/revision/AppRevisionService.java @@ -18,25 +18,24 @@ import com.alipay.sofa.registry.common.model.store.AppRevision; import com.alipay.sofa.registry.store.api.annotation.ReadOnLeader; - import java.util.List; public interface AppRevisionService { - @ReadOnLeader - AppRevision get(String revision); + @ReadOnLeader + AppRevision get(String revision); - @ReadOnLeader - boolean existed(String revision); + @ReadOnLeader + boolean existed(String revision); - void add(AppRevision appRevision); + void add(AppRevision appRevision); - @ReadOnLeader - String getKeysDigest(); + @ReadOnLeader + String getKeysDigest(); - @ReadOnLeader - List getKeys(); + @ReadOnLeader + List getKeys(); - @ReadOnLeader - List getMulti(List keys); + @ReadOnLeader + List getMulti(List keys); } diff --git a/test/src/main/java/com/alipay/sofa/registry/server/test/TestRegistryMain.java b/test/src/main/java/com/alipay/sofa/registry/server/test/TestRegistryMain.java index a0d98d08c..77d889804 100644 --- a/test/src/main/java/com/alipay/sofa/registry/server/test/TestRegistryMain.java +++ b/test/src/main/java/com/alipay/sofa/registry/server/test/TestRegistryMain.java @@ -16,61 +16,59 @@ */ package com.alipay.sofa.registry.server.test; +import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_DATA_CENTER; +import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_ZONE; + import com.alipay.sofa.registry.net.NetUtil; import com.alipay.sofa.registry.server.integration.RegistryApplication; import com.alipay.sofa.registry.util.FileUtils; -import org.springframework.context.ConfigurableApplicationContext; - import java.io.File; import java.util.HashMap; import java.util.Map; - -import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_DATA_CENTER; -import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_ZONE; +import org.springframework.context.ConfigurableApplicationContext; /** - @author xuanbei - @since 2019/3/9 + * @author xuanbei + * @since 2019/3/9 */ public class TestRegistryMain { - public static final String LOCAL_ADDRESS = NetUtil.getLocalAddress().getHostAddress(); + public static final String LOCAL_ADDRESS = NetUtil.getLocalAddress().getHostAddress(); - private Map configs = new HashMap<>(); + private Map configs = new HashMap<>(); - public TestRegistryMain() { - configs.put("nodes.metaNode", DEFAULT_DATA_CENTER + ":" + LOCAL_ADDRESS); - configs.put("nodes.localDataCenter", DEFAULT_DATA_CENTER); - configs.put("nodes.localRegion", DEFAULT_ZONE); - } + public TestRegistryMain() { + configs.put("nodes.metaNode", DEFAULT_DATA_CENTER + ":" + LOCAL_ADDRESS); + configs.put("nodes.localDataCenter", DEFAULT_DATA_CENTER); + configs.put("nodes.localRegion", DEFAULT_ZONE); + } - public void startRegistry() throws Exception { - for (Map.Entry entry : configs.entrySet()) { - System.setProperty(entry.getKey(), entry.getValue()); - } - FileUtils.forceDelete(new File(System.getProperty("user.home") + File.separator - + "raftData")); - RegistryApplication.main(new String[] {}); - Thread.sleep(3000); + public void startRegistry() throws Exception { + for (Map.Entry entry : configs.entrySet()) { + System.setProperty(entry.getKey(), entry.getValue()); } + FileUtils.forceDelete(new File(System.getProperty("user.home") + File.separator + "raftData")); + RegistryApplication.main(new String[] {}); + Thread.sleep(3000); + } - public void stopRegistry() throws Exception { - RegistryApplication.stop(); - } + public void stopRegistry() throws Exception { + RegistryApplication.stop(); + } - public void startRegistryWithConfig(Map configs) throws Exception { - this.configs.putAll(configs); - this.startRegistry(); - } + public void startRegistryWithConfig(Map configs) throws Exception { + this.configs.putAll(configs); + this.startRegistry(); + } - public ConfigurableApplicationContext getMetaApplicationContext() { - return RegistryApplication.getMetaApplicationContext(); - } + public ConfigurableApplicationContext getMetaApplicationContext() { + return RegistryApplication.getMetaApplicationContext(); + } - public ConfigurableApplicationContext getSessionApplicationContext() { - return RegistryApplication.getSessionApplicationContext(); - } + public ConfigurableApplicationContext getSessionApplicationContext() { + return RegistryApplication.getSessionApplicationContext(); + } - public ConfigurableApplicationContext getDataApplicationContext() { - return RegistryApplication.getDataApplicationContext(); - } + public ConfigurableApplicationContext getDataApplicationContext() { + return RegistryApplication.getDataApplicationContext(); + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryApplicationTest.java b/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryApplicationTest.java index d271d7a63..2ac7f5dde 100644 --- a/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryApplicationTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryApplicationTest.java @@ -18,6 +18,4 @@ import static org.junit.Assert.*; -public class RegistryApplicationTest { - -} \ No newline at end of file +public class RegistryApplicationTest {} diff --git a/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryConsumer.java b/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryConsumer.java index 833c5d1e3..0e102d0f7 100644 --- a/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryConsumer.java +++ b/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryConsumer.java @@ -28,46 +28,49 @@ /** * @author chen.zhu - *

- * Nov 18, 2020 + *

Nov 18, 2020 */ public class RegistryConsumer { - private final static Logger logger = LoggerFactory - .getLogger(RegistryConsumer.class); + private static final Logger logger = LoggerFactory.getLogger(RegistryConsumer.class); - public static void main(String[] args) throws InterruptedException { - DefaultRegistryClient registryClient = new DefaultRegistryClient( - new DefaultRegistryClientConfigBuilder().setRegistryEndpoint("127.0.0.1") - .setRegistryEndpointPort(9603).build()); - registryClient.init(); + public static void main(String[] args) throws InterruptedException { + DefaultRegistryClient registryClient = + new DefaultRegistryClient( + new DefaultRegistryClientConfigBuilder() + .setRegistryEndpoint("127.0.0.1") + .setRegistryEndpointPort(9603) + .build()); + registryClient.init(); - // 构造订阅者注册表 - String dataId = "com.alipay.test.demo.service:1.0@DEFAULT"; - SubscriberRegistration registration = new SubscriberRegistration(dataId, + // 构造订阅者注册表 + String dataId = "com.alipay.test.demo.service:1.0@DEFAULT"; + SubscriberRegistration registration = + new SubscriberRegistration( + dataId, new SubscriberDataObserver() { - @Override - public void handleData(String dataId, UserData userData) { - // UserData 中包含有 zoneData 和 localZone, - // zoneData 中是服务端推送过来的多个 zone 以及 zone 内发布的数据列表 - // localZone 表示当前应用处于哪个 zone。 - logger.info("receive data success, dataId: {}, data: {}", dataId, userData); - } + @Override + public void handleData(String dataId, UserData userData) { + // UserData 中包含有 zoneData 和 localZone, + // zoneData 中是服务端推送过来的多个 zone 以及 zone 内发布的数据列表 + // localZone 表示当前应用处于哪个 zone。 + logger.info("receive data success, dataId: {}, data: {}", dataId, userData); + } }); - // 订阅者分组必须和发布者分组一致,未设置默认为 DEFAULT_GROUP - registration.setGroup("TEST_GROUP"); - registration.setAppName("test-app"); - // 设置订阅维度,ScopeEnum 共有三种级别 zone, dataCenter, global。 - // zone: 逻辑机房内订阅,仅可订阅到应用所处逻辑机房内的发布者发布的数据 - // dataCenter: 机房内订阅,可订阅到应用所处机房内的发布者发布的数据 - // global: 全局订阅,可订阅到当前服务注册中心部署的所有机房内的发布者发布的数据 - registration.setScopeEnum(ScopeEnum.global); + // 订阅者分组必须和发布者分组一致,未设置默认为 DEFAULT_GROUP + registration.setGroup("TEST_GROUP"); + registration.setAppName("test-app"); + // 设置订阅维度,ScopeEnum 共有三种级别 zone, dataCenter, global。 + // zone: 逻辑机房内订阅,仅可订阅到应用所处逻辑机房内的发布者发布的数据 + // dataCenter: 机房内订阅,可订阅到应用所处机房内的发布者发布的数据 + // global: 全局订阅,可订阅到当前服务注册中心部署的所有机房内的发布者发布的数据 + registration.setScopeEnum(ScopeEnum.global); - // 将注册表注册进客户端获取订阅者模型,订阅到的数据会以回调的方式通知 `SubscriberDataObserver` - Subscriber subscriber = registryClient.register(registration); + // 将注册表注册进客户端获取订阅者模型,订阅到的数据会以回调的方式通知 `SubscriberDataObserver` + Subscriber subscriber = registryClient.register(registration); - while (!Thread.currentThread().isInterrupted()) { - Thread.sleep(10000); - } + while (!Thread.currentThread().isInterrupted()) { + Thread.sleep(10000); } + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryProvider.java b/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryProvider.java index 414bdfb35..7105d6e00 100644 --- a/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryProvider.java +++ b/test/src/test/java/com/alipay/sofa/registry/server/integration/RegistryProvider.java @@ -16,45 +16,41 @@ */ package com.alipay.sofa.registry.server.integration; -import com.alipay.sofa.jraft.util.OnlyForTest; import com.alipay.sofa.registry.client.api.Publisher; -import com.alipay.sofa.registry.client.api.RegistryClient; import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; import com.alipay.sofa.registry.client.provider.DefaultRegistryClient; -import com.alipay.sofa.registry.client.provider.DefaultRegistryClientConfig; import com.alipay.sofa.registry.client.provider.DefaultRegistryClientConfigBuilder; /** * @author chen.zhu - *

- * Nov 18, 2020 + *

Nov 18, 2020 */ public class RegistryProvider { - public static void main(String[] args) throws InterruptedException { + public static void main(String[] args) throws InterruptedException { - DefaultRegistryClient registryClient = new DefaultRegistryClient( - new DefaultRegistryClientConfigBuilder() - .setRegistryEndpoint("127.0.0.1") - .setRegistryEndpointPort(9603).build()); - registryClient.init(); - // 构造发布者注册表 - String dataId = "com.alipay.test.demo.service:1.0@DEFAULT"; - PublisherRegistration registration = new PublisherRegistration(dataId); - // 如需指定分组,可主动设置分组,未设置默认为 DEFAULT_GROUP - registration.setGroup("TEST_GROUP"); - // 设置应用名,非必要条件 - registration.setAppName("test-app"); + DefaultRegistryClient registryClient = + new DefaultRegistryClient( + new DefaultRegistryClientConfigBuilder() + .setRegistryEndpoint("127.0.0.1") + .setRegistryEndpointPort(9603) + .build()); + registryClient.init(); + // 构造发布者注册表 + String dataId = "com.alipay.test.demo.service:1.0@DEFAULT"; + PublisherRegistration registration = new PublisherRegistration(dataId); + // 如需指定分组,可主动设置分组,未设置默认为 DEFAULT_GROUP + registration.setGroup("TEST_GROUP"); + // 设置应用名,非必要条件 + registration.setAppName("test-app"); - // 将注册表注册进客户端获取发布者模型,并发布数据 - Publisher publisher = registryClient.register(registration, - "127.0.0.1:12200?xx=zz"); - - while (!Thread.currentThread().isInterrupted()) { - Thread.sleep(10000); - } - // 如需覆盖上次发布的数据可以使用发布者模型重新发布数据 - // publisher.republish("10.10.1.1:12200?xx=zz"); - } + // 将注册表注册进客户端获取发布者模型,并发布数据 + Publisher publisher = registryClient.register(registration, "127.0.0.1:12200?xx=zz"); + while (!Thread.currentThread().isInterrupted()) { + Thread.sleep(10000); + } + // 如需覆盖上次发布的数据可以使用发布者模型重新发布数据 + // publisher.republish("10.10.1.1:12200?xx=zz"); + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/test/AbstractTest.java b/test/src/test/java/com/alipay/sofa/registry/test/AbstractTest.java index 630d32440..863517713 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/AbstractTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/AbstractTest.java @@ -22,12 +22,6 @@ import com.alipay.sofa.registry.observer.UnblockingObserver; import com.alipay.sofa.registry.util.NamedThreadFactory; import io.netty.util.ResourceLeakDetector; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.rules.TestName; - import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; @@ -41,245 +35,252 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BooleanSupplier; +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.rules.TestName; /** * @author chen.zhu - *

- * Mar 15, 2021 + *

Mar 15, 2021 */ public class AbstractTest { - protected final Logger logger = LoggerFactory.getLogger(getClass()); + protected final Logger logger = LoggerFactory.getLogger(getClass()); - protected ExecutorService executors; + protected ExecutorService executors; - protected ScheduledExecutorService scheduled; + protected ScheduledExecutorService scheduled; - @Rule - public TestName name = new TestName(); + @Rule public TestName name = new TestName(); - public static final Random random = new Random(); + public static final Random random = new Random(); - @BeforeClass - public static void beforeAbstractTestClass() { - System.setProperty("spring.main.show_banner", "false"); - } - - @Before - public void beforeAbstractTest() throws Exception { - - ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); - Thread.interrupted();//clear interrupt + @BeforeClass + public static void beforeAbstractTestClass() { + System.setProperty("spring.main.show_banner", "false"); + } - executors = Executors.newCachedThreadPool(new NamedThreadFactory(name.getMethodName())); - scheduled = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), - new NamedThreadFactory("sched-" + name.getMethodName())); - if (logger.isInfoEnabled()) { - logger.info(remarkableMessage("[begin test][{}]"), name.getMethodName()); - } - } + @Before + public void beforeAbstractTest() throws Exception { - @After - public void afterAbstractTest() throws IOException, NoSuchMethodException, - InvocationTargetException, IllegalAccessException { - executors.shutdownNow(); - scheduled.shutdownNow(); + ResourceLeakDetector.setLevel(ResourceLeakDetector.Level.PARANOID); + Thread.interrupted(); // clear interrupt - logger.info(remarkableMessage("[end test][{}]"), name.getMethodName()); + executors = Executors.newCachedThreadPool(new NamedThreadFactory(name.getMethodName())); + scheduled = + Executors.newScheduledThreadPool( + Runtime.getRuntime().availableProcessors(), + new NamedThreadFactory("sched-" + name.getMethodName())); + if (logger.isInfoEnabled()) { + logger.info(remarkableMessage("[begin test][{}]"), name.getMethodName()); } - - protected static void setEnv(Map newenv) throws Exception { - try { - Class processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); - Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); - theEnvironmentField.setAccessible(true); - Map env = (Map) theEnvironmentField.get(null); - env.putAll(newenv); - Field theCaseInsensitiveEnvironmentField = processEnvironmentClass - .getDeclaredField("theCaseInsensitiveEnvironment"); - theCaseInsensitiveEnvironmentField.setAccessible(true); - Map cienv = (Map) theCaseInsensitiveEnvironmentField - .get(null); - cienv.putAll(newenv); - } catch (NoSuchFieldException e) { - Class[] classes = Collections.class.getDeclaredClasses(); - Map env = System.getenv(); - for (Class cl : classes) { - if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { - Field field = cl.getDeclaredField("m"); - field.setAccessible(true); - Object obj = field.get(env); - Map map = (Map) obj; - map.clear(); - map.putAll(newenv); - } - } + } + + @After + public void afterAbstractTest() + throws IOException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { + executors.shutdownNow(); + scheduled.shutdownNow(); + + logger.info(remarkableMessage("[end test][{}]"), name.getMethodName()); + } + + protected static void setEnv(Map newenv) throws Exception { + try { + Class processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment"); + Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment"); + theEnvironmentField.setAccessible(true); + Map env = (Map) theEnvironmentField.get(null); + env.putAll(newenv); + Field theCaseInsensitiveEnvironmentField = + processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment"); + theCaseInsensitiveEnvironmentField.setAccessible(true); + Map cienv = + (Map) theCaseInsensitiveEnvironmentField.get(null); + cienv.putAll(newenv); + } catch (NoSuchFieldException e) { + Class[] classes = Collections.class.getDeclaredClasses(); + Map env = System.getenv(); + for (Class cl : classes) { + if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { + Field field = cl.getDeclaredField("m"); + field.setAccessible(true); + Object obj = field.get(env); + Map map = (Map) obj; + map.clear(); + map.putAll(newenv); } + } } + } - public static void setFinalStatic(Field field, Object newValue) throws Exception { - field.setAccessible(true); + public static void setFinalStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); - Field modifiersField = Field.class.getDeclaredField("modifiers"); - modifiersField.setAccessible(true); - modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); - field.set(null, newValue); - } + field.set(null, newValue); + } - protected String remarkableMessage(String msg) { - return String.format("--------------------------%s--------------------------\r\n", msg); - } + protected String remarkableMessage(String msg) { + return String.format("--------------------------%s--------------------------\r\n", msg); + } - protected void waitForAnyKeyToExit() throws IOException { - logger.info("type any key to exit.................."); - waitForAnyKey(); - } + protected void waitForAnyKeyToExit() throws IOException { + logger.info("type any key to exit.................."); + waitForAnyKey(); + } - protected void waitForAnyKey() throws IOException { - System.in.read(); - } + protected void waitForAnyKey() throws IOException { + System.in.read(); + } - protected void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier) - throws TimeoutException, - InterruptedException { + protected void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier) + throws TimeoutException, InterruptedException { - waitConditionUntilTimeOut(booleanSupplier, 5000, 2); - } + waitConditionUntilTimeOut(booleanSupplier, 5000, 2); + } - protected static void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier, - int waitTimeMilli) throws TimeoutException, - InterruptedException { + protected static void waitConditionUntilTimeOut( + BooleanSupplier booleanSupplier, int waitTimeMilli) + throws TimeoutException, InterruptedException { - waitConditionUntilTimeOut(booleanSupplier, waitTimeMilli, 2); - } + waitConditionUntilTimeOut(booleanSupplier, waitTimeMilli, 2); + } - protected static void waitConditionUntilTimeOut(BooleanSupplier booleanSupplier, - int waitTimeMilli, int intervalMilli) - throws TimeoutException, - InterruptedException { - - long maxTime = System.currentTimeMillis() + waitTimeMilli; - - while (true) { - boolean result = booleanSupplier.getAsBoolean(); - if (result) { - return; - } - if (System.currentTimeMillis() >= maxTime) { - throw new TimeoutException("timeout still false:" + waitTimeMilli); - } - Thread.sleep(intervalMilli); - } - } + protected static void waitConditionUntilTimeOut( + BooleanSupplier booleanSupplier, int waitTimeMilli, int intervalMilli) + throws TimeoutException, InterruptedException { + + long maxTime = System.currentTimeMillis() + waitTimeMilli; - public static int randomPort() { - return randomPort(10000, 20000, null); + while (true) { + boolean result = booleanSupplier.getAsBoolean(); + if (result) { + return; + } + if (System.currentTimeMillis() >= maxTime) { + throw new TimeoutException("timeout still false:" + waitTimeMilli); + } + Thread.sleep(intervalMilli); } + } - public static int randomPort(int min, int max, Set different) { + public static int randomPort() { + return randomPort(10000, 20000, null); + } - Random random = new Random(); + public static int randomPort(int min, int max, Set different) { - for (int i = min; i <= max; i++) { - int port = min + random.nextInt(max - min + 1); - if ((different == null || !different.contains(port)) && isUsable(port)) { - return port; - } - } + Random random = new Random(); - throw new IllegalStateException(String.format("random port not found:(%d, %d)", min, max)); + for (int i = min; i <= max; i++) { + int port = min + random.nextInt(max - min + 1); + if ((different == null || !different.contains(port)) && isUsable(port)) { + return port; + } } - public static int netmask = (1 << 8) - 1; + throw new IllegalStateException(String.format("random port not found:(%d, %d)", min, max)); + } - public static String randomIp() { - return String.format("%d.%d.%d.%d", (Math.abs(random.nextInt()) % netmask + 1), - (Math.abs(random.nextInt()) % netmask + 1), (Math.abs(random.nextInt()) % netmask + 1), - (Math.abs(random.nextInt()) % netmask + 1)); - } + public static int netmask = (1 << 8) - 1; - protected static boolean isUsable(int port) { + public static String randomIp() { + return String.format( + "%d.%d.%d.%d", + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1), + (Math.abs(random.nextInt()) % netmask + 1)); + } - try (ServerSocket s = new ServerSocket()) { - s.bind(new InetSocketAddress(port)); - return true; - } catch (IOException e) { - } - return false; - } + protected static boolean isUsable(int port) { - public static String getDc() { - return "DEFAULT_DC"; + try (ServerSocket s = new ServerSocket()) { + s.bind(new InetSocketAddress(port)); + return true; + } catch (IOException e) { } + return false; + } - public static String randomString() { + public static String getDc() { + return "DEFAULT_DC"; + } - return randomString(1 << 10); - } + public static String randomString() { - public static String randomString(int length) { + return randomString(1 << 10); + } - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < length; i++) { - sb.append((char) ('a' + (int) (26 * Math.random()))); - } + public static String randomString(int length) { - return sb.toString(); + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < length; i++) { + sb.append((char) ('a' + (int) (26 * Math.random()))); } - public static class NotifyObserversCounter implements UnblockingObserver { + return sb.toString(); + } - private final AtomicInteger counter = new AtomicInteger(0); + public static class NotifyObserversCounter implements UnblockingObserver { - @Override - public void update(Observable source, Object message) { - counter.getAndIncrement(); - } + private final AtomicInteger counter = new AtomicInteger(0); - public int getCounter() { - return counter.get(); - } + @Override + public void update(Observable source, Object message) { + counter.getAndIncrement(); } - public static class ConcurrentExecutor implements Executor { + public int getCounter() { + return counter.get(); + } + } - private final int tasks; + public static class ConcurrentExecutor implements Executor { - private final CyclicBarrier barrier; + private final int tasks; - private final CountDownLatch latch; + private final CyclicBarrier barrier; - private final ExecutorService executors; + private final CountDownLatch latch; - public ConcurrentExecutor(int tasks, ExecutorService executors) { - this.tasks = tasks; - this.barrier = new CyclicBarrier(tasks); - this.latch = new CountDownLatch(tasks); - this.executors = executors; - } + private final ExecutorService executors; - @Override - public void execute(final Runnable command) { - for (int i = 0; i < tasks; i++) { - executors.execute(new Runnable() { - @Override - public void run() { - try { - barrier.await(); - command.run(); - } catch (Exception ignore) { - } - - latch.countDown(); - } - }); - } - try { - latch.await(); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - } + public ConcurrentExecutor(int tasks, ExecutorService executors) { + this.tasks = tasks; + this.barrier = new CyclicBarrier(tasks); + this.latch = new CountDownLatch(tasks); + this.executors = executors; + } + + @Override + public void execute(final Runnable command) { + for (int i = 0; i < tasks; i++) { + executors.execute( + new Runnable() { + @Override + public void run() { + try { + barrier.await(); + command.run(); + } catch (Exception ignore) { + } + + latch.countDown(); + } + }); + } + try { + latch.await(); + } catch (InterruptedException e) { + throw new RuntimeException(e); + } } + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/test/BaseIntegrationTest.java b/test/src/test/java/com/alipay/sofa/registry/test/BaseIntegrationTest.java index edc851b2a..fc94203d0 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/BaseIntegrationTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/BaseIntegrationTest.java @@ -16,6 +16,9 @@ */ package com.alipay.sofa.registry.test; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.junit.Assert.assertTrue; + import com.alipay.remoting.Connection; import com.alipay.sofa.registry.client.api.RegistryClientConfig; import com.alipay.sofa.registry.client.api.SubscriberDataObserver; @@ -29,7 +32,6 @@ import com.alipay.sofa.registry.common.model.CommonResponse; import com.alipay.sofa.registry.common.model.ConnectId; import com.alipay.sofa.registry.common.model.constants.ValueConstants; -import com.alipay.sofa.registry.common.model.metaserver.Lease; import com.alipay.sofa.registry.common.model.sessionserver.CancelAddressRequest; import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.log.Logger; @@ -38,237 +40,245 @@ import com.alipay.sofa.registry.remoting.Channel; import com.alipay.sofa.registry.remoting.jersey.JerseyClient; import com.alipay.sofa.registry.server.test.TestRegistryMain; -import com.alipay.sofa.registry.util.FileUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.logging.log4j.util.Strings; +import java.io.*; +import java.lang.reflect.Field; +import java.util.*; +import java.util.concurrent.atomic.AtomicBoolean; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; import org.h2.tools.Server; import org.junit.Before; import org.junit.BeforeClass; -import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.logging.LoggingSystem; import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.test.context.ActiveProfiles; -import javax.sql.DataSource; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import java.io.*; -import java.lang.reflect.Field; -import java.sql.PreparedStatement; -import java.sql.SQLException; -import java.util.*; -import java.util.concurrent.atomic.AtomicBoolean; - -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; -import static org.junit.Assert.assertTrue; - -/** - * @author xuanbei 18/12/1 - */ +/** @author xuanbei 18/12/1 */ @SpringBootConfiguration @SpringBootTest public class BaseIntegrationTest extends AbstractTest { - protected static final Logger LOGGER = LoggerFactory - .getLogger(BaseIntegrationTest.class); - private static final AtomicBoolean STARTED = new AtomicBoolean( - false); + protected static final Logger LOGGER = LoggerFactory.getLogger(BaseIntegrationTest.class); + private static final AtomicBoolean STARTED = new AtomicBoolean(false); - public static final String LOCAL_ADDRESS = NetUtil - .getLocalAddress() - .getHostAddress(); - public static final String LOCAL_DATACENTER = "DefaultDataCenter"; - public static final String LOCAL_REGION = "DEFAULT_ZONE"; - private static final int CLIENT_OFF_MAX_WAIT_TIME = 30; - protected static ConfigurableApplicationContext metaApplicationContext; - protected static ConfigurableApplicationContext sessionApplicationContext; - protected static ConfigurableApplicationContext dataApplicationContext; + public static final String LOCAL_ADDRESS = NetUtil.getLocalAddress().getHostAddress(); + public static final String LOCAL_DATACENTER = "DefaultDataCenter"; + public static final String LOCAL_REGION = "DEFAULT_ZONE"; + private static final int CLIENT_OFF_MAX_WAIT_TIME = 30; + protected static ConfigurableApplicationContext metaApplicationContext; + protected static ConfigurableApplicationContext sessionApplicationContext; + protected static ConfigurableApplicationContext dataApplicationContext; - protected static DefaultRegistryClient registryClient1; + protected static DefaultRegistryClient registryClient1; - protected static DefaultRegistryClient registryClient2; + protected static DefaultRegistryClient registryClient2; - protected static Channel sessionChannel; + protected static Channel sessionChannel; - protected static Channel dataChannel; + protected static Channel dataChannel; - protected static Channel metaChannel; + protected static Channel metaChannel; - protected static int sessionPort = 9603; - protected static int metaPort = 9615; - protected static int dataPort = 9622; + protected static int sessionPort = 9603; + protected static int metaPort = 9615; + protected static int dataPort = 9622; - @Value("${meta.server.raftServerPort}") - protected int raftPort; + @Value("${meta.server.raftServerPort}") + protected int raftPort; - @Value("${session.server.serverPort}") - protected int sessionServerPort; + @Value("${session.server.serverPort}") + protected int sessionServerPort; - @Value("${data.server.syncDataPort}") - protected int syncDataPort; + @Value("${data.server.syncDataPort}") + protected int syncDataPort; - protected Server h2Server = new Server(); + protected Server h2Server = new Server(); - @BeforeClass - public static void beforeClass() throws Exception { - System.setProperty(LoggingSystem.SYSTEM_PROPERTY, - "org.springframework.boot.logging.log4j2.Log4J2LoggingSystem"); - System.setProperty("spring.profiles.active", "integrate"); - System.setProperty("lease.duration", "2"); - } + @BeforeClass + public static void beforeClass() throws Exception { + System.setProperty( + LoggingSystem.SYSTEM_PROPERTY, + "org.springframework.boot.logging.log4j2.Log4J2LoggingSystem"); + System.setProperty("spring.profiles.active", "integrate"); + System.setProperty("lease.duration", "2"); + } - @Before - public void before() throws Exception { -// h2Server.start(); -// Class.forName("org.h2.driver"); - startServerIfNecessary(); - initRegistryClientAndChannel(); - } + @Before + public void before() throws Exception { + // h2Server.start(); + // Class.forName("org.h2.driver"); + startServerIfNecessary(); + initRegistryClientAndChannel(); + } - public static void startServerIfNecessary() throws Exception { - if (STARTED.compareAndSet(false, true)) { - Map configs = new HashMap<>(); - configs.put("nodes.metaNode", LOCAL_DATACENTER + ":" + LOCAL_ADDRESS); - configs.put("nodes.localDataCenter", LOCAL_DATACENTER); - configs.put("nodes.localRegion", LOCAL_REGION); + public static void startServerIfNecessary() throws Exception { + if (STARTED.compareAndSet(false, true)) { + Map configs = new HashMap<>(); + configs.put("nodes.metaNode", LOCAL_DATACENTER + ":" + LOCAL_ADDRESS); + configs.put("nodes.localDataCenter", LOCAL_DATACENTER); + configs.put("nodes.localRegion", LOCAL_REGION); - TestRegistryMain testRegistryMain = new TestRegistryMain(); - testRegistryMain.startRegistryWithConfig(configs); - metaApplicationContext = testRegistryMain.getMetaApplicationContext(); - sessionApplicationContext = testRegistryMain.getSessionApplicationContext(); - dataApplicationContext = testRegistryMain.getDataApplicationContext(); - initRegistryClientAndChannel(); - Thread.sleep(1000 * 20); - } + TestRegistryMain testRegistryMain = new TestRegistryMain(); + testRegistryMain.startRegistryWithConfig(configs); + metaApplicationContext = testRegistryMain.getMetaApplicationContext(); + sessionApplicationContext = testRegistryMain.getSessionApplicationContext(); + dataApplicationContext = testRegistryMain.getDataApplicationContext(); + initRegistryClientAndChannel(); + Thread.sleep(1000 * 20); } + } - private static void initRegistryClientAndChannel() { - if (registryClient1 == null) { - RegistryClientConfig config = DefaultRegistryClientConfigBuilder.start() - .setSyncConfigRetryInterval(60000).setAppName("testApp1") - .setDataCenter(LOCAL_DATACENTER).setZone(LOCAL_REGION) - .setRegistryEndpoint(LOCAL_ADDRESS).setRegistryEndpointPort(sessionPort).build(); - registryClient1 = new DefaultRegistryClient(config); - registryClient1.init(); - } + private static void initRegistryClientAndChannel() { + if (registryClient1 == null) { + RegistryClientConfig config = + DefaultRegistryClientConfigBuilder.start() + .setSyncConfigRetryInterval(60000) + .setAppName("testApp1") + .setDataCenter(LOCAL_DATACENTER) + .setZone(LOCAL_REGION) + .setRegistryEndpoint(LOCAL_ADDRESS) + .setRegistryEndpointPort(sessionPort) + .build(); + registryClient1 = new DefaultRegistryClient(config); + registryClient1.init(); + } - if (registryClient2 == null) { - RegistryClientConfig config = DefaultRegistryClientConfigBuilder.start() - .setAppName("testApp2").setDataCenter(LOCAL_DATACENTER) - .setRegistryEndpoint(LOCAL_ADDRESS).setZone(LOCAL_REGION) - .setRegistryEndpointPort(sessionPort).build(); - registryClient2 = new DefaultRegistryClient(config); - registryClient2.init(); - } + if (registryClient2 == null) { + RegistryClientConfig config = + DefaultRegistryClientConfigBuilder.start() + .setAppName("testApp2") + .setDataCenter(LOCAL_DATACENTER) + .setRegistryEndpoint(LOCAL_ADDRESS) + .setZone(LOCAL_REGION) + .setRegistryEndpointPort(sessionPort) + .build(); + registryClient2 = new DefaultRegistryClient(config); + registryClient2.init(); + } - if (sessionChannel == null || dataChannel == null || metaChannel == null) { - sessionChannel = JerseyClient.getInstance() - .connect(new URL(LOCAL_ADDRESS, sessionPort)); - dataChannel = JerseyClient.getInstance().connect(new URL(LOCAL_ADDRESS, dataPort)); - metaChannel = JerseyClient.getInstance().connect(new URL(LOCAL_ADDRESS, metaPort)); - } + if (sessionChannel == null || dataChannel == null || metaChannel == null) { + sessionChannel = JerseyClient.getInstance().connect(new URL(LOCAL_ADDRESS, sessionPort)); + dataChannel = JerseyClient.getInstance().connect(new URL(LOCAL_ADDRESS, dataPort)); + metaChannel = JerseyClient.getInstance().connect(new URL(LOCAL_ADDRESS, metaPort)); } + } - public static class MySubscriberDataObserver implements SubscriberDataObserver { - public volatile String dataId; - public volatile UserData userData; + public static class MySubscriberDataObserver implements SubscriberDataObserver { + public volatile String dataId; + public volatile UserData userData; - @Override - public void handleData(String dataId, UserData data) { - this.dataId = dataId; - this.userData = data; - LOGGER.info("handleData: {}, {}", dataId, data); - } + @Override + public void handleData(String dataId, UserData data) { + this.dataId = dataId; + this.userData = data; + LOGGER.info("handleData: {}, {}", dataId, data); } + } - protected static void clientOff() throws Exception { - startServerIfNecessary(); - List connectIds = new ArrayList<>(); - connectIds - .add(ConnectId.parse(LOCAL_ADDRESS + ":" + getSourcePort(registryClient1) - + ValueConstants.CONNECT_ID_SPLIT + LOCAL_ADDRESS + ":9600")); - connectIds - .add(ConnectId.parse(LOCAL_ADDRESS + ":" + getSourcePort(registryClient2) - + ValueConstants.CONNECT_ID_SPLIT + LOCAL_ADDRESS + ":9600")); - CommonResponse response = sessionChannel + protected static void clientOff() throws Exception { + startServerIfNecessary(); + List connectIds = new ArrayList<>(); + connectIds.add( + ConnectId.parse( + LOCAL_ADDRESS + + ":" + + getSourcePort(registryClient1) + + ValueConstants.CONNECT_ID_SPLIT + + LOCAL_ADDRESS + + ":9600")); + connectIds.add( + ConnectId.parse( + LOCAL_ADDRESS + + ":" + + getSourcePort(registryClient2) + + ValueConstants.CONNECT_ID_SPLIT + + LOCAL_ADDRESS + + ":9600")); + CommonResponse response = + sessionChannel .getWebTarget() .path("api/clients/off") .request() - .post(Entity.entity(new CancelAddressRequest(connectIds), MediaType.APPLICATION_JSON), + .post( + Entity.entity(new CancelAddressRequest(connectIds), MediaType.APPLICATION_JSON), CommonResponse.class); - LOGGER.info("client of {}", connectIds); - assertTrue(response.isSuccess()); - int times = 0; - while (times++ < CLIENT_OFF_MAX_WAIT_TIME) { - if (clientOffSuccess()) { - return; - } - Thread.sleep(500); - } - throw new RuntimeException("clientOff failed."); + LOGGER.info("client of {}", connectIds); + assertTrue(response.isSuccess()); + int times = 0; + while (times++ < CLIENT_OFF_MAX_WAIT_TIME) { + if (clientOffSuccess()) { + return; + } + Thread.sleep(500); } + throw new RuntimeException("clientOff failed."); + } - private static boolean clientOffSuccess() { - String sessionDigestCount = sessionChannel.getWebTarget().path("digest/data/count") - .request(APPLICATION_JSON).get(String.class); - String dataDigestCount = dataChannel.getWebTarget().path("digest/datum/count") - .request(APPLICATION_JSON).get(String.class); - return sessionDigestCount - .equals("Subscriber count: 0, Publisher count: 0, Watcher count: 0") - && (dataDigestCount.equals("CacheDigest datum cache is empty") || dataDigestCount - .contains("[Publisher] size of publisher in DefaultDataCenter is 0")); - } + private static boolean clientOffSuccess() { + String sessionDigestCount = + sessionChannel + .getWebTarget() + .path("digest/data/count") + .request(APPLICATION_JSON) + .get(String.class); + String dataDigestCount = + dataChannel + .getWebTarget() + .path("digest/datum/count") + .request(APPLICATION_JSON) + .get(String.class); + return sessionDigestCount.equals("Subscriber count: 0, Publisher count: 0, Watcher count: 0") + && (dataDigestCount.equals("CacheDigest datum cache is empty") + || dataDigestCount.contains("[Publisher] size of publisher in DefaultDataCenter is 0")); + } - protected static int getSourcePort(DefaultRegistryClient registryClient) throws Exception { - Field workerThreadField = DefaultRegistryClient.class.getDeclaredField("workerThread"); - workerThreadField.setAccessible(true); - WorkerThread workerThread = (WorkerThread) workerThreadField.get(registryClient); + protected static int getSourcePort(DefaultRegistryClient registryClient) throws Exception { + Field workerThreadField = DefaultRegistryClient.class.getDeclaredField("workerThread"); + workerThreadField.setAccessible(true); + WorkerThread workerThread = (WorkerThread) workerThreadField.get(registryClient); - Field clientField = AbstractWorkerThread.class.getDeclaredField("client"); - clientField.setAccessible(true); - Client client = (Client) clientField.get(workerThread); - client.ensureConnected(); + Field clientField = AbstractWorkerThread.class.getDeclaredField("client"); + clientField.setAccessible(true); + Client client = (Client) clientField.get(workerThread); + client.ensureConnected(); - Field clientConnectionField = ClientConnection.class.getDeclaredField("clientConnection"); - clientConnectionField.setAccessible(true); - Connection clientConnection = (Connection) clientConnectionField.get(client); - return clientConnection.getLocalPort(); - } + Field clientConnectionField = ClientConnection.class.getDeclaredField("clientConnection"); + clientConnectionField.setAccessible(true); + Connection clientConnection = (Connection) clientConnectionField.get(client); + return clientConnection.getLocalPort(); + } - protected Object bytes2Object(byte[] bytes) throws IOException, ClassNotFoundException { - Object object = null; - if (bytes != null) { - ByteArrayInputStream bis = new ByteArrayInputStream(bytes); - ObjectInputStream input = null; - try { - input = new ObjectInputStream(bis); - object = input.readObject(); - } finally { - if (input != null) { - input.close(); - } - } + protected Object bytes2Object(byte[] bytes) throws IOException, ClassNotFoundException { + Object object = null; + if (bytes != null) { + ByteArrayInputStream bis = new ByteArrayInputStream(bytes); + ObjectInputStream input = null; + try { + input = new ObjectInputStream(bis); + object = input.readObject(); + } finally { + if (input != null) { + input.close(); } - return object; + } } + return object; + } - protected byte[] object2bytes(Object object) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - ObjectOutputStream javaos = null; - try { - javaos = new ObjectOutputStream(bos); - javaos.writeObject(object); - } finally { - try { - javaos.close(); - } catch (IOException ioe) { - //do nothing - } - } - return bos.toByteArray(); + protected byte[] object2bytes(Object object) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + ObjectOutputStream javaos = null; + try { + javaos = new ObjectOutputStream(bos); + javaos.writeObject(object); + } finally { + try { + javaos.close(); + } catch (IOException ioe) { + // do nothing + } } -} \ No newline at end of file + return bos.toByteArray(); + } +} diff --git a/test/src/test/java/com/alipay/sofa/registry/test/elector/MetaElectorTest.java b/test/src/test/java/com/alipay/sofa/registry/test/elector/MetaElectorTest.java index 8e1baceec..47361aaf7 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/elector/MetaElectorTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/elector/MetaElectorTest.java @@ -16,6 +16,9 @@ */ package com.alipay.sofa.registry.test.elector; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + import com.alipay.sofa.common.profile.StringUtil; import com.alipay.sofa.registry.common.model.store.URL; import com.alipay.sofa.registry.jdbc.config.MetaElectorConfigBean; @@ -26,13 +29,6 @@ import com.alipay.sofa.registry.test.BaseIntegrationTest; import com.alipay.sofa.registry.util.ConcurrentUtils; import com.alipay.sofa.registry.util.LoopRunnable; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.MockitoAnnotations; -import org.springframework.test.context.junit4.SpringRunner; - import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; @@ -42,159 +38,162 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; - -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoAnnotations; +import org.springframework.test.context.junit4.SpringRunner; /** - * * @author xiaojian.xj * @version $Id: MetaElectorTest.java, v 0.1 2021年03月15日 14:04 xiaojian.xj Exp $ */ @RunWith(SpringRunner.class) public class MetaElectorTest extends BaseIntegrationTest { - protected final Logger logger = LoggerFactory.getLogger(getClass()); - - private MetaJdbcLeaderElector leaderElector1; - - private MetaJdbcLeaderElector leaderElector2; - - private MetaJdbcLeaderElector leaderElector3; - - private DistributeLockMapper distributeLockMapper; - - private MetaElectorConfigBean metaElectorConfigBean; - - private String dataCenter = "DefaultDataCenter:MetaElectorTest" + System.currentTimeMillis(); - - private MetaJdbcLeaderElector.ElectorRoleService leaderService; - - private MetaJdbcLeaderElector.ElectorRoleService followService; - - private CountDownLatch countDownLatch = new CountDownLatch(1); - @Before - public void beforeMetaElectorTest() { - MockitoAnnotations.initMocks(this); - - distributeLockMapper = metaApplicationContext.getBean("distributeLockMapper", - DistributeLockMapper.class); - metaElectorConfigBean = metaApplicationContext.getBean("metaElectorConfig", - MetaElectorConfigBean.class); - leaderService = metaApplicationContext.getBean("leaderService", - MetaJdbcLeaderElector.ElectorRoleService.class); - followService = metaApplicationContext.getBean("followService", - MetaJdbcLeaderElector.ElectorRoleService.class); - - leaderElector1 = buildLeaderElector(); - leaderElector2 = buildLeaderElector(); - leaderElector3 = buildLeaderElector(); - - when(leaderElector1.myself()).thenReturn("127.0.0.1:12101"); - when(leaderElector2.myself()).thenReturn("127.0.0.1:12102"); - when(leaderElector3.myself()).thenReturn("127.0.0.1:12103"); + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + private MetaJdbcLeaderElector leaderElector1; + + private MetaJdbcLeaderElector leaderElector2; + + private MetaJdbcLeaderElector leaderElector3; + + private DistributeLockMapper distributeLockMapper; + + private MetaElectorConfigBean metaElectorConfigBean; + + private String dataCenter = "DefaultDataCenter:MetaElectorTest" + System.currentTimeMillis(); + + private MetaJdbcLeaderElector.ElectorRoleService leaderService; + + private MetaJdbcLeaderElector.ElectorRoleService followService; + + private CountDownLatch countDownLatch = new CountDownLatch(1); + + @Before + public void beforeMetaElectorTest() { + MockitoAnnotations.initMocks(this); + + distributeLockMapper = + metaApplicationContext.getBean("distributeLockMapper", DistributeLockMapper.class); + metaElectorConfigBean = + metaApplicationContext.getBean("metaElectorConfig", MetaElectorConfigBean.class); + leaderService = + metaApplicationContext.getBean( + "leaderService", MetaJdbcLeaderElector.ElectorRoleService.class); + followService = + metaApplicationContext.getBean( + "followService", MetaJdbcLeaderElector.ElectorRoleService.class); + + leaderElector1 = buildLeaderElector(); + leaderElector2 = buildLeaderElector(); + leaderElector3 = buildLeaderElector(); + + when(leaderElector1.myself()).thenReturn("127.0.0.1:12101"); + when(leaderElector2.myself()).thenReturn("127.0.0.1:12102"); + when(leaderElector3.myself()).thenReturn("127.0.0.1:12103"); + } + + private MetaJdbcLeaderElector buildLeaderElector() { + MetaJdbcLeaderElector leaderElector = spy(new MetaJdbcLeaderElector()); + metaElectorConfigBean.setLockExpireDuration(3000L); + metaElectorConfigBean.setDataCenter(dataCenter); + leaderElector.addElectorRoleService(leaderService); + leaderElector.addElectorRoleService(followService); + leaderElector.setDistributeLockMapper(distributeLockMapper); + leaderElector.setMetaElectorConfig(metaElectorConfigBean); + return leaderElector; + } + + @Test + public void testElector() throws InterruptedException { + ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1); + ConcurrentUtils.createDaemonThread("LeaderElectorTrigger", new LeaderElectorTrigger()).start(); + + leaderElector1.change2Follow(); + leaderElector2.change2Follow(); + leaderElector3.change2Follow(); + + Thread.sleep(5 * 1000); + logger.info("leaderElector1 leader: {}", leaderElector1.getLeader()); + logger.info("leaderElector2 leader: {}", leaderElector2.getLeader()); + logger.info("leaderElector3 leader: {}", leaderElector3.getLeader()); + Assert.assertTrue( + leaderElector1.amILeader() || leaderElector2.amILeader() || leaderElector3.amILeader()); + + leaderElector1.change2Observer(); + leaderElector2.change2Observer(); + + Thread.sleep(5 * 1000); + + logger.info("leaderElector1 leader: {}", leaderElector1.getLeader()); + logger.info("leaderElector2 leader: {}", leaderElector2.getLeader()); + logger.info("leaderElector3 leader: {}", leaderElector3.getLeader()); + Assert.assertTrue(!leaderElector1.amILeader()); + Assert.assertTrue(StringUtil.equals(leaderElector1.getLeader(), leaderElector3.myself())); + Assert.assertTrue(!leaderElector2.amILeader()); + Assert.assertTrue(StringUtil.equals(leaderElector2.getLeader(), leaderElector3.myself())); + Assert.assertTrue(leaderElector3.amILeader()); + Assert.assertTrue(StringUtil.equals(leaderElector3.getLeader(), leaderElector3.myself())); + } + + class LeaderElectorTrigger extends LoopRunnable { + + @Override + public void runUnthrowable() { + ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); + + fixedThreadPool.submit( + () -> { + leaderElector1.elect(); + }); + fixedThreadPool.submit( + () -> { + leaderElector2.elect(); + }); + fixedThreadPool.submit( + () -> { + leaderElector3.elect(); + }); } - private MetaJdbcLeaderElector buildLeaderElector() { - MetaJdbcLeaderElector leaderElector = spy(new MetaJdbcLeaderElector()); - metaElectorConfigBean.setLockExpireDuration(3000L); - metaElectorConfigBean.setDataCenter(dataCenter); - leaderElector.addElectorRoleService(leaderService); - leaderElector.addElectorRoleService(followService); - leaderElector.setDistributeLockMapper(distributeLockMapper); - leaderElector.setMetaElectorConfig(metaElectorConfigBean); - return leaderElector; - + @Override + public void waitingUnthrowable() { + ConcurrentUtils.sleepUninterruptibly(1, TimeUnit.SECONDS); } + } - @Test - public void testElector() throws InterruptedException { - ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1); - ConcurrentUtils.createDaemonThread("LeaderElectorTrigger", new LeaderElectorTrigger()).start(); - - leaderElector1.change2Follow(); - leaderElector2.change2Follow(); - leaderElector3.change2Follow(); - - Thread.sleep(5 * 1000); - logger.info("leaderElector1 leader: {}", leaderElector1.getLeader()); - logger.info("leaderElector2 leader: {}", leaderElector2.getLeader()); - logger.info("leaderElector3 leader: {}", leaderElector3.getLeader()); - Assert.assertTrue(leaderElector1.amILeader() - || leaderElector2.amILeader() - || leaderElector3.amILeader()); - - leaderElector1.change2Observer(); - leaderElector2.change2Observer(); - - Thread.sleep(5 * 1000); - - logger.info("leaderElector1 leader: {}", leaderElector1.getLeader()); - logger.info("leaderElector2 leader: {}", leaderElector2.getLeader()); - logger.info("leaderElector3 leader: {}", leaderElector3.getLeader()); - Assert.assertTrue(!leaderElector1.amILeader()); - Assert.assertTrue(StringUtil.equals(leaderElector1.getLeader(), leaderElector3.myself())); - Assert.assertTrue(!leaderElector2.amILeader()); - Assert.assertTrue(StringUtil.equals(leaderElector2.getLeader(), leaderElector3.myself())); - Assert.assertTrue(leaderElector3.amILeader()); - Assert.assertTrue(StringUtil.equals(leaderElector3.getLeader(), leaderElector3.myself())); + public static URL randomURL() { + return new URL("127.0.0.1", randomPort()); + } - } + public static int randomPort() { + return randomPort(10000, 20000, null); + } - class LeaderElectorTrigger extends LoopRunnable { - - @Override - public void runUnthrowable() { - ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3); - - fixedThreadPool.submit(() -> { - leaderElector1.elect(); - }); - fixedThreadPool.submit(() -> { - leaderElector2.elect(); - }); - fixedThreadPool.submit(() -> { - leaderElector3.elect(); - }); - } - - @Override - public void waitingUnthrowable() { - ConcurrentUtils.sleepUninterruptibly(1, TimeUnit.SECONDS); - } - } + public static int randomPort(int min, int max, Set different) { - public static URL randomURL() { - return new URL("127.0.0.1", randomPort()); - - } + Random random = new Random(); - public static int randomPort() { - return randomPort(10000, 20000, null); + for (int i = min; i <= max; i++) { + int port = min + random.nextInt(max - min + 1); + if ((different == null || !different.contains(port)) && isUsable(port)) { + return port; + } } - public static int randomPort(int min, int max, Set different) { + throw new IllegalStateException(String.format("random port not found:(%d, %d)", min, max)); + } - Random random = new Random(); + protected static boolean isUsable(int port) { - for (int i = min; i <= max; i++) { - int port = min + random.nextInt(max - min + 1); - if ((different == null || !different.contains(port)) && isUsable(port)) { - return port; - } - } - - throw new IllegalStateException(String.format("random port not found:(%d, %d)", min, max)); + try (ServerSocket s = new ServerSocket()) { + s.bind(new InetSocketAddress(port)); + return true; + } catch (IOException e) { } - - protected static boolean isUsable(int port) { - - try (ServerSocket s = new ServerSocket()) { - s.bind(new InetSocketAddress(port)); - return true; - } catch (IOException e) { - } - return false; - } - -} \ No newline at end of file + return false; + } +} diff --git a/test/src/test/java/com/alipay/sofa/registry/test/elector/ProvideDataTest.java b/test/src/test/java/com/alipay/sofa/registry/test/elector/ProvideDataTest.java index 049710e3a..c1ae6f7a3 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/elector/ProvideDataTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/elector/ProvideDataTest.java @@ -17,7 +17,6 @@ package com.alipay.sofa.registry.test.elector; import com.alipay.sofa.common.profile.StringUtil; -import com.alipay.sofa.registry.jdbc.domain.ProvideDataDomain; import com.alipay.sofa.registry.store.api.DBResponse; import com.alipay.sofa.registry.store.api.meta.ProvideDataRepository; import com.alipay.sofa.registry.test.BaseIntegrationTest; @@ -29,32 +28,30 @@ import org.springframework.test.context.junit4.SpringRunner; /** - * * @author xiaojian.xj * @version $Id: ProvideDataTest.java, v 0.1 2021年03月15日 15:32 xiaojian.xj Exp $ */ @RunWith(SpringRunner.class) public class ProvideDataTest extends BaseIntegrationTest { - private ProvideDataRepository provideDataRepository; - - @Before - public void beforeProvideDataTest() { - MockitoAnnotations.initMocks(this); + private ProvideDataRepository provideDataRepository; - provideDataRepository = metaApplicationContext.getBean("provideDataJdbcRepository", - ProvideDataRepository.class); - } + @Before + public void beforeProvideDataTest() { + MockitoAnnotations.initMocks(this); - @Test - public void testProvideData() { - String dataCenter = "DefaultDataCenter:ProvideDataTest"; - String key = "keyA" + System.currentTimeMillis(); - String value = "valueA" + System.currentTimeMillis(); - provideDataRepository.put(dataCenter, key, value); + provideDataRepository = + metaApplicationContext.getBean("provideDataJdbcRepository", ProvideDataRepository.class); + } - DBResponse dbResponse = provideDataRepository.get(dataCenter, key); - Assert.assertTrue(StringUtil.equals(value, (String) dbResponse.getEntity())); - } + @Test + public void testProvideData() { + String dataCenter = "DefaultDataCenter:ProvideDataTest"; + String key = "keyA" + System.currentTimeMillis(); + String value = "valueA" + System.currentTimeMillis(); + provideDataRepository.put(dataCenter, key, value); -} \ No newline at end of file + DBResponse dbResponse = provideDataRepository.get(dataCenter, key); + Assert.assertTrue(StringUtil.equals(value, (String) dbResponse.getEntity())); + } +} diff --git a/test/src/test/java/com/alipay/sofa/registry/test/metadata/MetadataTest.java b/test/src/test/java/com/alipay/sofa/registry/test/metadata/MetadataTest.java index e8107d771..3064af459 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/metadata/MetadataTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/metadata/MetadataTest.java @@ -28,164 +28,187 @@ import com.alipay.sofa.registry.server.session.strategy.AppRevisionHandlerStrategy; import com.alipay.sofa.registry.test.BaseIntegrationTest; import com.google.common.collect.Maps; +import java.util.*; +import java.util.concurrent.*; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringRunner; -import java.util.*; -import java.util.concurrent.*; /** - * * @author xiaojian.xj * @version $Id: MetadataTest.java, v 0.1 2021年02月03日 19:50 xiaojian.xj Exp $ */ @RunWith(SpringRunner.class) public class MetadataTest extends BaseIntegrationTest { - private AppRevisionHandlerStrategy appRevisionHandlerStrategy; + private AppRevisionHandlerStrategy appRevisionHandlerStrategy; - private AppRevisionCacheRegistry appRevisionCacheRegistry; + private AppRevisionCacheRegistry appRevisionCacheRegistry; - private AppRevisionHeartbeatRegistry appRevisionHeartbeatRegistry; + private AppRevisionHeartbeatRegistry appRevisionHeartbeatRegistry; - private List appRevisionList; + private List appRevisionList; - private InterfaceAppsIndexMapper interfaceAppsIndexMapper; + private InterfaceAppsIndexMapper interfaceAppsIndexMapper; - @Before - public void buildAppRevision() { - appRevisionHandlerStrategy = sessionApplicationContext.getBean( + @Before + public void buildAppRevision() { + appRevisionHandlerStrategy = + sessionApplicationContext.getBean( "appRevisionHandlerStrategy", AppRevisionHandlerStrategy.class); - appRevisionCacheRegistry = sessionApplicationContext.getBean("appRevisionCacheRegistry", - AppRevisionCacheRegistry.class); - appRevisionHeartbeatRegistry = sessionApplicationContext.getBean( + appRevisionCacheRegistry = + sessionApplicationContext.getBean( + "appRevisionCacheRegistry", AppRevisionCacheRegistry.class); + appRevisionHeartbeatRegistry = + sessionApplicationContext.getBean( "appRevisionHeartbeatRegistry", AppRevisionHeartbeatRegistry.class); - interfaceAppsIndexMapper = sessionApplicationContext.getBean("interfaceAppsIndexMapper", - InterfaceAppsIndexMapper.class); - - appRevisionList = new ArrayList<>(); - for (int i = 1; i <= 1001; i++) { - long l = System.currentTimeMillis(); - String suffix = l + "-" + i; - - String appname = "foo" + suffix; - String revision = "1111" + suffix; - - AppRevision appRevision = new AppRevision(); - appRevision.setAppName(appname); - appRevision.setRevision(revision); - appRevision.setClientVersion("1.0"); - - Map> baseParams = Maps.newHashMap(); - baseParams.put("metaBaseParam1", new ArrayList() { - { - add("metaBaseValue1"); - } - }); - appRevision.setBaseParams(baseParams); - - Map interfaceMap = Maps.newHashMap(); - String dataInfo1 = DataInfo.toDataInfoId("func1" + suffix, - ValueConstants.DEFAULT_GROUP, ValueConstants.DEFAULT_INSTANCE_ID); - String dataInfo2 = DataInfo.toDataInfoId("func2" + suffix, - ValueConstants.DEFAULT_GROUP, ValueConstants.DEFAULT_INSTANCE_ID); - - AppRevisionInterface inf1 = new AppRevisionInterface(); - AppRevisionInterface inf2 = new AppRevisionInterface(); - interfaceMap.put(dataInfo1, inf1); - interfaceMap.put(dataInfo2, inf2); - appRevision.setInterfaceMap(interfaceMap); - - inf1.setId("1"); - Map> serviceParams1 = new HashMap>(); - serviceParams1.put("metaParam2", new ArrayList() { - { - add("metaValue2"); - } - }); - inf1.setServiceParams(serviceParams1); - - inf2.setId("2"); - Map> serviceParams2 = new HashMap>(); - serviceParams1.put("metaParam3", new ArrayList() { - { - add("metaValue3"); - } - }); - inf1.setServiceParams(serviceParams2); - - appRevisionList.add(appRevision); - } + interfaceAppsIndexMapper = + sessionApplicationContext.getBean( + "interfaceAppsIndexMapper", InterfaceAppsIndexMapper.class); + + appRevisionList = new ArrayList<>(); + for (int i = 1; i <= 1001; i++) { + long l = System.currentTimeMillis(); + String suffix = l + "-" + i; + + String appname = "foo" + suffix; + String revision = "1111" + suffix; + + AppRevision appRevision = new AppRevision(); + appRevision.setAppName(appname); + appRevision.setRevision(revision); + appRevision.setClientVersion("1.0"); + + Map> baseParams = Maps.newHashMap(); + baseParams.put( + "metaBaseParam1", + new ArrayList() { + { + add("metaBaseValue1"); + } + }); + appRevision.setBaseParams(baseParams); + + Map interfaceMap = Maps.newHashMap(); + String dataInfo1 = + DataInfo.toDataInfoId( + "func1" + suffix, ValueConstants.DEFAULT_GROUP, ValueConstants.DEFAULT_INSTANCE_ID); + String dataInfo2 = + DataInfo.toDataInfoId( + "func2" + suffix, ValueConstants.DEFAULT_GROUP, ValueConstants.DEFAULT_INSTANCE_ID); + + AppRevisionInterface inf1 = new AppRevisionInterface(); + AppRevisionInterface inf2 = new AppRevisionInterface(); + interfaceMap.put(dataInfo1, inf1); + interfaceMap.put(dataInfo2, inf2); + appRevision.setInterfaceMap(interfaceMap); + + inf1.setId("1"); + Map> serviceParams1 = new HashMap>(); + serviceParams1.put( + "metaParam2", + new ArrayList() { + { + add("metaValue2"); + } + }); + inf1.setServiceParams(serviceParams1); + + inf2.setId("2"); + Map> serviceParams2 = new HashMap>(); + serviceParams1.put( + "metaParam3", + new ArrayList() { + { + add("metaValue3"); + } + }); + inf1.setServiceParams(serviceParams2); + appRevisionList.add(appRevision); + } + } + + @Test + public void register() throws ExecutionException, InterruptedException { + ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1); + List> responses = new ArrayList<>(); + + // register + for (AppRevision appRevisionRegister : appRevisionList) { + Future response = + fixedThreadPool.submit( + (Callable) + () -> { + RegisterResponse result = new RegisterResponse(); + appRevisionHandlerStrategy.handleAppRevisionRegister( + appRevisionRegister, result); + return result; + }); + responses.add(response); } - @Test - public void register() throws ExecutionException, InterruptedException { - ExecutorService fixedThreadPool = Executors.newFixedThreadPool(1); - List> responses = new ArrayList<>(); - - // register - for (AppRevision appRevisionRegister : appRevisionList) { - Future response = fixedThreadPool.submit((Callable) () -> { - RegisterResponse result = new RegisterResponse(); - appRevisionHandlerStrategy.handleAppRevisionRegister(appRevisionRegister, result); - return result; - }); - responses.add(response); - } - - for (Future future : responses) { - Assert.assertTrue(future.get().isSuccess()); - } - - // query app_revision - List> appRevisions = new ArrayList<>(); - for (AppRevision appRevisionRegister : appRevisionList) { - Future appRevision = fixedThreadPool.submit((Callable) () -> { - AppRevision revision = appRevisionCacheRegistry.getRevision(appRevisionRegister.getRevision()); - Assert.assertEquals(revision.getRevision(), appRevisionRegister.getRevision()); - return revision; - }); - appRevisions.add(appRevision); - } - - Map revisionMap = new HashMap<>(); - for (Future future : appRevisions) { - AppRevision appRevision = future.get(); - revisionMap.put(appRevision.getRevision(), appRevision); - } - - // query by interface - List>> appsFuture = new ArrayList<>(); - for (AppRevision appRevisionRegister : appRevisionList) { - for (Map.Entry entry : appRevisionRegister.getInterfaceMap().entrySet()) { - Future> submit = fixedThreadPool.submit((Callable) () -> { - String dataInfoId = entry.getKey(); - InterfaceMapping appNames = appRevisionCacheRegistry.getAppNames(dataInfoId); - Assert.assertTrue(appNames.getNanosVersion() > 0); - Assert.assertTrue(appNames.getApps().size() == 1); - Assert.assertTrue(appNames.getApps().contains(appRevisionRegister.getAppName())); - return appNames; - }); - - appsFuture.add(submit); - } - } + for (Future future : responses) { + Assert.assertTrue(future.get().isSuccess()); + } + + // query app_revision + List> appRevisions = new ArrayList<>(); + for (AppRevision appRevisionRegister : appRevisionList) { + Future appRevision = + fixedThreadPool.submit( + (Callable) + () -> { + AppRevision revision = + appRevisionCacheRegistry.getRevision(appRevisionRegister.getRevision()); + Assert.assertEquals(revision.getRevision(), appRevisionRegister.getRevision()); + return revision; + }); + appRevisions.add(appRevision); + } - for (Future> future : appsFuture) { - future.get(); - } + Map revisionMap = new HashMap<>(); + for (Future future : appRevisions) { + AppRevision appRevision = future.get(); + revisionMap.put(appRevision.getRevision(), appRevision); + } + + // query by interface + List>> appsFuture = new ArrayList<>(); + for (AppRevision appRevisionRegister : appRevisionList) { + for (Map.Entry entry : + appRevisionRegister.getInterfaceMap().entrySet()) { + Future> submit = + fixedThreadPool.submit( + (Callable) + () -> { + String dataInfoId = entry.getKey(); + InterfaceMapping appNames = appRevisionCacheRegistry.getAppNames(dataInfoId); + Assert.assertTrue(appNames.getNanosVersion() > 0); + Assert.assertTrue(appNames.getApps().size() == 1); + Assert.assertTrue( + appNames.getApps().contains(appRevisionRegister.getAppName())); + return appNames; + }); + + appsFuture.add(submit); + } + } + for (Future> future : appsFuture) { + future.get(); + } - // heartbeat - Thread.sleep(3000); - for (AppRevision appRevisionRegister : appRevisionList) { - fixedThreadPool.submit(() -> { - appRevisionHeartbeatRegistry.heartbeat(appRevisionRegister.getRevision()); - }); - } - appRevisionHeartbeatRegistry.doRevisionHeartbeat(); + // heartbeat + Thread.sleep(3000); + for (AppRevision appRevisionRegister : appRevisionList) { + fixedThreadPool.submit( + () -> { + appRevisionHeartbeatRegistry.heartbeat(appRevisionRegister.getRevision()); + }); } -} \ No newline at end of file + appRevisionHeartbeatRegistry.doRevisionHeartbeat(); + } +} diff --git a/test/src/test/java/com/alipay/sofa/registry/test/pubsub/PubSubTest.java b/test/src/test/java/com/alipay/sofa/registry/test/pubsub/PubSubTest.java index de69cae69..57d01551f 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/pubsub/PubSubTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/pubsub/PubSubTest.java @@ -16,187 +16,183 @@ */ package com.alipay.sofa.registry.test.pubsub; +import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; +import static org.junit.Assert.assertEquals; + import com.alipay.sofa.registry.client.api.model.RegistryType; import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; import com.alipay.sofa.registry.client.api.registration.SubscriberRegistration; import com.alipay.sofa.registry.core.model.ScopeEnum; import com.alipay.sofa.registry.test.BaseIntegrationTest; import com.alipay.sofa.registry.test.BaseIntegrationTest.MySubscriberDataObserver; +import java.util.concurrent.CountDownLatch; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.context.junit4.SpringRunner; - -import java.util.concurrent.CountDownLatch; -import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; -import static org.junit.Assert.assertEquals; - -/** - * @author xuanbe 18/12/2 - */ +/** @author xuanbe 18/12/2 */ @RunWith(SpringJUnit4ClassRunner.class) public class PubSubTest extends BaseIntegrationTest { - private CountDownLatch countDownLatch = new CountDownLatch(1); - /** - * Publisher test. - * - * @throws InterruptedException the interrupted exception - */ - @Test - public void publisherTest() throws InterruptedException { - LOGGER.info("--------------------------------splitter-----------------------------"); - String dataId = "test-dataId-publisherTest-" + System.nanoTime(); - String value = "test publish"; - - PublisherRegistration registration = new PublisherRegistration(dataId); - registryClient1.register(registration, value); - Thread.sleep(2000L); - - PublisherRegistration registrationNotMatch = new PublisherRegistration(dataId + "_notmatch"); - registryClient1.register(registrationNotMatch, value); - Thread.sleep(2000L); - - MySubscriberDataObserver observer = new MySubscriberDataObserver(); - SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); - subReg.setScopeEnum(ScopeEnum.dataCenter); - - registryClient1.register(subReg); - - //countDownLatch.await(); - - Thread.sleep(3 * 1000L); - // Thread.sleep(2000000L); - assertEquals(dataId, observer.dataId); - assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); - assertEquals(1, observer.userData.getZoneData().size()); - assertEquals(1, observer.userData.getZoneData().values().size()); - assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); - assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); - assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); - - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); - } - - /** - * Subscriber test. - * - * @throws InterruptedException the interrupted exception - */ - @Test - public void subscriberTest() throws InterruptedException { - String dataId = "test-dataId-subscriberTest-" + System.nanoTime(); - String value = "test subscriber"; - - MySubscriberDataObserver observer = new MySubscriberDataObserver(); - SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); - subReg.setScopeEnum(ScopeEnum.dataCenter); - registryClient1.register(subReg); - Thread.sleep(2000L); - - PublisherRegistration registration = new PublisherRegistration(dataId); - registryClient1.register(registration, value); - Thread.sleep(3000L); - - assertEquals(dataId, observer.dataId); - assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); - assertEquals(1, observer.userData.getZoneData().size()); - assertEquals(1, observer.userData.getZoneData().values().size()); - assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); - assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); - assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); - - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); - } - - /** - * Multi Client test. - * - * @throws InterruptedException the interrupted exception - */ - @Test - public void multiClientTest() throws InterruptedException { - - // registryClient1 publish data, registryClient2 subscriber - String dataId = "test-dataId-multiClientTest-" + System.nanoTime(); - String value = "test multi client publish"; - - PublisherRegistration registration = new PublisherRegistration(dataId); - registryClient1.register(registration, value); - Thread.sleep(2000L); - - MySubscriberDataObserver observer = new MySubscriberDataObserver(); - SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); - subReg.setScopeEnum(ScopeEnum.zone); - - registryClient2.register(subReg); - - Thread.sleep(2000L); - assertEquals(dataId, observer.dataId); - assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); - assertEquals(1, observer.userData.getZoneData().size()); - assertEquals(1, observer.userData.getZoneData().values().size()); - assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); - assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); - assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); - - registryClient2.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); - - // registryClient1 subscriber, registryClient2 publish data - dataId = "test-dataId-" + System.nanoTime(); - value = "test multi client subscriber"; - - observer = new MySubscriberDataObserver(); - subReg = new SubscriberRegistration(dataId, observer); - subReg.setScopeEnum(ScopeEnum.global); - registryClient1.register(subReg); - Thread.sleep(2000L); - - registration = new PublisherRegistration(dataId); - registryClient2.register(registration, value); - Thread.sleep(3000L); - - assertEquals(dataId, observer.dataId); - assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); - assertEquals(1, observer.userData.getZoneData().size()); - assertEquals(1, observer.userData.getZoneData().values().size()); - assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); - assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); - assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); - - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient2.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); - - // registryClient1 subscriber, registryClient1 and registryClient2 both publish data - dataId = "test-dataId-" + System.currentTimeMillis(); - value = "test multi client subscriber"; - - observer = new MySubscriberDataObserver(); - subReg = new SubscriberRegistration(dataId, observer); - subReg.setScopeEnum(ScopeEnum.zone); - registryClient1.register(subReg); - Thread.sleep(2000L); - - registration = new PublisherRegistration(dataId); - registryClient1.register(registration, value); - registryClient2.register(registration, value); - Thread.sleep(3000L); - - assertEquals(dataId, observer.dataId); - assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); - assertEquals(1, observer.userData.getZoneData().size()); - assertEquals(1, observer.userData.getZoneData().values().size()); - assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); - assertEquals(2, observer.userData.getZoneData().get(LOCAL_REGION).size()); - assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); - assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(1)); - - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); - registryClient2.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); - } -} \ No newline at end of file + private CountDownLatch countDownLatch = new CountDownLatch(1); + /** + * Publisher test. + * + * @throws InterruptedException the interrupted exception + */ + @Test + public void publisherTest() throws InterruptedException { + LOGGER.info("--------------------------------splitter-----------------------------"); + String dataId = "test-dataId-publisherTest-" + System.nanoTime(); + String value = "test publish"; + + PublisherRegistration registration = new PublisherRegistration(dataId); + registryClient1.register(registration, value); + Thread.sleep(2000L); + + PublisherRegistration registrationNotMatch = new PublisherRegistration(dataId + "_notmatch"); + registryClient1.register(registrationNotMatch, value); + Thread.sleep(2000L); + + MySubscriberDataObserver observer = new MySubscriberDataObserver(); + SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); + subReg.setScopeEnum(ScopeEnum.dataCenter); + + registryClient1.register(subReg); + + // countDownLatch.await(); + + Thread.sleep(3 * 1000L); + // Thread.sleep(2000000L); + assertEquals(dataId, observer.dataId); + assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); + assertEquals(1, observer.userData.getZoneData().size()); + assertEquals(1, observer.userData.getZoneData().values().size()); + assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); + assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); + assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); + + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); + } + + /** + * Subscriber test. + * + * @throws InterruptedException the interrupted exception + */ + @Test + public void subscriberTest() throws InterruptedException { + String dataId = "test-dataId-subscriberTest-" + System.nanoTime(); + String value = "test subscriber"; + + MySubscriberDataObserver observer = new MySubscriberDataObserver(); + SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); + subReg.setScopeEnum(ScopeEnum.dataCenter); + registryClient1.register(subReg); + Thread.sleep(2000L); + + PublisherRegistration registration = new PublisherRegistration(dataId); + registryClient1.register(registration, value); + Thread.sleep(3000L); + + assertEquals(dataId, observer.dataId); + assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); + assertEquals(1, observer.userData.getZoneData().size()); + assertEquals(1, observer.userData.getZoneData().values().size()); + assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); + assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); + assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); + + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); + } + + /** + * Multi Client test. + * + * @throws InterruptedException the interrupted exception + */ + @Test + public void multiClientTest() throws InterruptedException { + + // registryClient1 publish data, registryClient2 subscriber + String dataId = "test-dataId-multiClientTest-" + System.nanoTime(); + String value = "test multi client publish"; + + PublisherRegistration registration = new PublisherRegistration(dataId); + registryClient1.register(registration, value); + Thread.sleep(2000L); + + MySubscriberDataObserver observer = new MySubscriberDataObserver(); + SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); + subReg.setScopeEnum(ScopeEnum.zone); + + registryClient2.register(subReg); + + Thread.sleep(2000L); + assertEquals(dataId, observer.dataId); + assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); + assertEquals(1, observer.userData.getZoneData().size()); + assertEquals(1, observer.userData.getZoneData().values().size()); + assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); + assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); + assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); + + registryClient2.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); + + // registryClient1 subscriber, registryClient2 publish data + dataId = "test-dataId-" + System.nanoTime(); + value = "test multi client subscriber"; + + observer = new MySubscriberDataObserver(); + subReg = new SubscriberRegistration(dataId, observer); + subReg.setScopeEnum(ScopeEnum.global); + registryClient1.register(subReg); + Thread.sleep(2000L); + + registration = new PublisherRegistration(dataId); + registryClient2.register(registration, value); + Thread.sleep(3000L); + + assertEquals(dataId, observer.dataId); + assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); + assertEquals(1, observer.userData.getZoneData().size()); + assertEquals(1, observer.userData.getZoneData().values().size()); + assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); + assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); + assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); + + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient2.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); + + // registryClient1 subscriber, registryClient1 and registryClient2 both publish data + dataId = "test-dataId-" + System.currentTimeMillis(); + value = "test multi client subscriber"; + + observer = new MySubscriberDataObserver(); + subReg = new SubscriberRegistration(dataId, observer); + subReg.setScopeEnum(ScopeEnum.zone); + registryClient1.register(subReg); + Thread.sleep(2000L); + + registration = new PublisherRegistration(dataId); + registryClient1.register(registration, value); + registryClient2.register(registration, value); + Thread.sleep(3000L); + + assertEquals(dataId, observer.dataId); + assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); + assertEquals(1, observer.userData.getZoneData().size()); + assertEquals(1, observer.userData.getZoneData().values().size()); + assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); + assertEquals(2, observer.userData.getZoneData().get(LOCAL_REGION).size()); + assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); + assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(1)); + + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); + registryClient2.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); + } +} diff --git a/test/src/test/java/com/alipay/sofa/registry/test/pubsub/TempPublisherTest.java b/test/src/test/java/com/alipay/sofa/registry/test/pubsub/TempPublisherTest.java index 7c2eedbd6..5c96b2489 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/pubsub/TempPublisherTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/pubsub/TempPublisherTest.java @@ -16,6 +16,10 @@ */ package com.alipay.sofa.registry.test.pubsub; +import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; +import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; +import static org.junit.Assert.assertEquals; + import com.alipay.sofa.registry.client.api.model.RegistryType; import com.alipay.sofa.registry.client.api.model.UserData; import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; @@ -28,19 +32,14 @@ import com.alipay.sofa.registry.server.session.node.service.DataNodeService; import com.alipay.sofa.registry.server.shared.env.ServerEnv; import com.alipay.sofa.registry.test.BaseIntegrationTest; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.junit4.SpringRunner; - import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; - -import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; -import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; -import static org.junit.Assert.assertEquals; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; /** * @author xuanbei @@ -48,117 +47,121 @@ */ @RunWith(SpringRunner.class) public class TempPublisherTest extends BaseIntegrationTest { - static AtomicInteger count = new AtomicInteger(); - - @Test - public synchronized void doTest() throws Exception { - String dataId = "test-dataId-" +this.getClass().getName()+ System.currentTimeMillis(); - String value = "test publish temp data"; - AtomicReference dataIdRef = new AtomicReference<>(); - AtomicReference userDataRef = new AtomicReference<>(); - // register SubscriberRegistration - SubscriberRegistration subReg = new SubscriberRegistration(dataId, - (dataIdIn, data) -> { - dataIdRef.set(dataIdIn); - userDataRef.set(data); - System.out.println(count.getAndIncrement()+"-@@@:"+dataIdIn+":"+data); - }); - - subReg.setScopeEnum(ScopeEnum.zone); - registryClient1.register(subReg); - Thread.sleep(5000L); - assertEquals(dataId, dataIdRef.get()); - assertEquals(0, userDataRef.get().getZoneData().size()); - - // publish temp data - Publisher tempPublisher = new Publisher(); - tempPublisher.setPublishType(PublishType.TEMPORARY); - tempPublisher.setCell(LOCAL_REGION); - tempPublisher.setDataId(dataId); - tempPublisher.setGroup(DEFAULT_GROUP); - tempPublisher.setInstanceId(DEFAULT_INSTANCE_ID); - tempPublisher.setVersion(System.currentTimeMillis()); - tempPublisher.setRegisterTimestamp(System.currentTimeMillis()); - tempPublisher.setClientRegisterTimestamp(System.currentTimeMillis()); - tempPublisher.setRegisterId(UUID.randomUUID().toString()); - tempPublisher.setDataInfoId(DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, - DEFAULT_GROUP)); - tempPublisher.setSessionProcessId(ServerEnv.PROCESS_ID); - List dataBoxData = new ArrayList(1); - dataBoxData.add(new ServerDataBox(object2bytes(value))); - tempPublisher.setDataList(dataBoxData); - sessionApplicationContext.getBean(DataNodeService.class).register(tempPublisher); - - // data size is 1 - Thread.sleep(5000L); - assertEquals(dataId, dataIdRef.get()); - assertEquals(1, userDataRef.get().getZoneData().size()); - - userDataRef.set(null); - dataIdRef.set(null); - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - - // register another SubscriberRegistration, data size is 0 - subReg = new SubscriberRegistration(dataId, - (dataIdIn, data) -> { - dataIdRef.set(dataIdIn); - userDataRef.set(data); - }); - subReg.setScopeEnum(ScopeEnum.zone); - registryClient1.register(subReg); - Thread.sleep(5000L); - assertEquals(dataId, dataIdRef.get()); - assertEquals(0, userDataRef.get().getZoneData().size()); - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - } - - @Test - public synchronized void doTestPubAndTempPubSameTime() throws Exception { - String dataId = "test-same-time-pub&tempPub-" + System.currentTimeMillis(); - String value = "test same time publish"; - AtomicReference dataIdRef = new AtomicReference<>(); - AtomicReference userDataRef = new AtomicReference<>(); - - SubscriberRegistration subReg = new SubscriberRegistration(dataId, - (dataIdIn, data) -> { - dataIdRef.set(dataIdIn); - userDataRef.set(data); - }); - subReg.setScopeEnum(ScopeEnum.zone); - registryClient1.register(subReg); - Thread.sleep(5000L); - - // publish data - PublisherRegistration registration = new PublisherRegistration(dataId); - registryClient1.register(registration, "test publish"); - - Thread.sleep(5000L); - - // publish temp data - Publisher tempPublisher = new Publisher(); - tempPublisher.setPublishType(PublishType.TEMPORARY); - tempPublisher.setCell(LOCAL_REGION); - tempPublisher.setDataId(dataId); - tempPublisher.setGroup(DEFAULT_GROUP); - tempPublisher.setInstanceId(DEFAULT_INSTANCE_ID); - tempPublisher.setVersion(System.currentTimeMillis()); - tempPublisher.setRegisterTimestamp(System.currentTimeMillis()); - tempPublisher.setClientRegisterTimestamp(System.currentTimeMillis()); - tempPublisher.setRegisterId(UUID.randomUUID().toString()); - tempPublisher.setDataInfoId(DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, - DEFAULT_GROUP)); - List dataBoxData = new ArrayList(1); - dataBoxData.add(new ServerDataBox(object2bytes(value))); - tempPublisher.setDataList(dataBoxData); - tempPublisher.setSessionProcessId(ServerEnv.PROCESS_ID); - sessionApplicationContext.getBean(DataNodeService.class).register(tempPublisher); - - Thread.sleep(5000L); - - assertEquals(1, userDataRef.get().getZoneData().size()); - assertEquals(2, userDataRef.get().getZoneData().get(LOCAL_REGION).size()); - - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); - } + static AtomicInteger count = new AtomicInteger(); + + @Test + public synchronized void doTest() throws Exception { + String dataId = "test-dataId-" + this.getClass().getName() + System.currentTimeMillis(); + String value = "test publish temp data"; + AtomicReference dataIdRef = new AtomicReference<>(); + AtomicReference userDataRef = new AtomicReference<>(); + // register SubscriberRegistration + SubscriberRegistration subReg = + new SubscriberRegistration( + dataId, + (dataIdIn, data) -> { + dataIdRef.set(dataIdIn); + userDataRef.set(data); + System.out.println(count.getAndIncrement() + "-@@@:" + dataIdIn + ":" + data); + }); + + subReg.setScopeEnum(ScopeEnum.zone); + registryClient1.register(subReg); + Thread.sleep(5000L); + assertEquals(dataId, dataIdRef.get()); + assertEquals(0, userDataRef.get().getZoneData().size()); + + // publish temp data + Publisher tempPublisher = new Publisher(); + tempPublisher.setPublishType(PublishType.TEMPORARY); + tempPublisher.setCell(LOCAL_REGION); + tempPublisher.setDataId(dataId); + tempPublisher.setGroup(DEFAULT_GROUP); + tempPublisher.setInstanceId(DEFAULT_INSTANCE_ID); + tempPublisher.setVersion(System.currentTimeMillis()); + tempPublisher.setRegisterTimestamp(System.currentTimeMillis()); + tempPublisher.setClientRegisterTimestamp(System.currentTimeMillis()); + tempPublisher.setRegisterId(UUID.randomUUID().toString()); + tempPublisher.setDataInfoId(DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)); + tempPublisher.setSessionProcessId(ServerEnv.PROCESS_ID); + List dataBoxData = new ArrayList(1); + dataBoxData.add(new ServerDataBox(object2bytes(value))); + tempPublisher.setDataList(dataBoxData); + sessionApplicationContext.getBean(DataNodeService.class).register(tempPublisher); + + // data size is 1 + Thread.sleep(5000L); + assertEquals(dataId, dataIdRef.get()); + assertEquals(1, userDataRef.get().getZoneData().size()); + + userDataRef.set(null); + dataIdRef.set(null); + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + + // register another SubscriberRegistration, data size is 0 + subReg = + new SubscriberRegistration( + dataId, + (dataIdIn, data) -> { + dataIdRef.set(dataIdIn); + userDataRef.set(data); + }); + subReg.setScopeEnum(ScopeEnum.zone); + registryClient1.register(subReg); + Thread.sleep(5000L); + assertEquals(dataId, dataIdRef.get()); + assertEquals(0, userDataRef.get().getZoneData().size()); + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + } + + @Test + public synchronized void doTestPubAndTempPubSameTime() throws Exception { + String dataId = "test-same-time-pub&tempPub-" + System.currentTimeMillis(); + String value = "test same time publish"; + AtomicReference dataIdRef = new AtomicReference<>(); + AtomicReference userDataRef = new AtomicReference<>(); + + SubscriberRegistration subReg = + new SubscriberRegistration( + dataId, + (dataIdIn, data) -> { + dataIdRef.set(dataIdIn); + userDataRef.set(data); + }); + subReg.setScopeEnum(ScopeEnum.zone); + registryClient1.register(subReg); + Thread.sleep(5000L); + + // publish data + PublisherRegistration registration = new PublisherRegistration(dataId); + registryClient1.register(registration, "test publish"); + + Thread.sleep(5000L); + + // publish temp data + Publisher tempPublisher = new Publisher(); + tempPublisher.setPublishType(PublishType.TEMPORARY); + tempPublisher.setCell(LOCAL_REGION); + tempPublisher.setDataId(dataId); + tempPublisher.setGroup(DEFAULT_GROUP); + tempPublisher.setInstanceId(DEFAULT_INSTANCE_ID); + tempPublisher.setVersion(System.currentTimeMillis()); + tempPublisher.setRegisterTimestamp(System.currentTimeMillis()); + tempPublisher.setClientRegisterTimestamp(System.currentTimeMillis()); + tempPublisher.setRegisterId(UUID.randomUUID().toString()); + tempPublisher.setDataInfoId(DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)); + List dataBoxData = new ArrayList(1); + dataBoxData.add(new ServerDataBox(object2bytes(value))); + tempPublisher.setDataList(dataBoxData); + tempPublisher.setSessionProcessId(ServerEnv.PROCESS_ID); + sessionApplicationContext.getBean(DataNodeService.class).register(tempPublisher); + + Thread.sleep(5000L); + + assertEquals(1, userDataRef.get().getZoneData().size()); + assertEquals(2, userDataRef.get().getZoneData().get(LOCAL_REGION).size()); + + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/test/resource/HealthCheckTest.java b/test/src/test/java/com/alipay/sofa/registry/test/resource/HealthCheckTest.java index 447405758..199896f98 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/resource/HealthCheckTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/resource/HealthCheckTest.java @@ -16,36 +16,51 @@ */ package com.alipay.sofa.registry.test.resource; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.junit.Assert.assertTrue; + import com.alipay.sofa.registry.common.model.CommonResponse; import com.alipay.sofa.registry.test.BaseIntegrationTest; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringRunner; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; -import static org.junit.Assert.assertTrue; - /** * @author xuanbei * @since 2019/1/14 */ @RunWith(SpringRunner.class) public class HealthCheckTest extends BaseIntegrationTest { - @Test - public void metaHealthCheckTest() { - assertTrue(metaChannel.getWebTarget().path("health/check").request(APPLICATION_JSON) - .get(CommonResponse.class).isSuccess()); - } + @Test + public void metaHealthCheckTest() { + assertTrue( + metaChannel + .getWebTarget() + .path("health/check") + .request(APPLICATION_JSON) + .get(CommonResponse.class) + .isSuccess()); + } - @Test - public void dataHealthCheckTest() { - assertTrue(dataChannel.getWebTarget().path("health/check").request(APPLICATION_JSON) - .get(CommonResponse.class).isSuccess()); - } + @Test + public void dataHealthCheckTest() { + assertTrue( + dataChannel + .getWebTarget() + .path("health/check") + .request(APPLICATION_JSON) + .get(CommonResponse.class) + .isSuccess()); + } - @Test - public void sessionHealthCheckTest() { - assertTrue(sessionChannel.getWebTarget().path("health/check").request(APPLICATION_JSON) - .get(CommonResponse.class).isSuccess()); - } + @Test + public void sessionHealthCheckTest() { + assertTrue( + sessionChannel + .getWebTarget() + .path("health/check") + .request(APPLICATION_JSON) + .get(CommonResponse.class) + .isSuccess()); + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/test/resource/data/DataDigestResourceTest.java b/test/src/test/java/com/alipay/sofa/registry/test/resource/data/DataDigestResourceTest.java index 7f2395e37..6212a98cf 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/resource/data/DataDigestResourceTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/resource/data/DataDigestResourceTest.java @@ -22,143 +22,175 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; +import com.alipay.sofa.registry.client.api.model.RegistryType; +import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; +import com.alipay.sofa.registry.client.api.registration.SubscriberRegistration; +import com.alipay.sofa.registry.common.model.constants.ValueConstants; +import com.alipay.sofa.registry.common.model.dataserver.Datum; +import com.alipay.sofa.registry.common.model.store.Publisher; +import com.alipay.sofa.registry.core.model.ScopeEnum; +import com.alipay.sofa.registry.net.NetUtil; +import com.alipay.sofa.registry.test.BaseIntegrationTest; import java.util.HashMap; import java.util.List; import java.util.Map; - import javax.ws.rs.client.Entity; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; - -import com.alipay.sofa.registry.common.model.constants.ValueConstants; -import com.alipay.sofa.registry.net.NetUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringRunner; -import com.alipay.sofa.registry.client.api.model.RegistryType; -import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; -import com.alipay.sofa.registry.client.api.registration.SubscriberRegistration; -import com.alipay.sofa.registry.common.model.dataserver.Datum; -import com.alipay.sofa.registry.common.model.store.Publisher; -import com.alipay.sofa.registry.core.model.ScopeEnum; -import com.alipay.sofa.registry.test.BaseIntegrationTest; - /** * @author xuanbei * @since 2019/1/14 */ @RunWith(SpringRunner.class) public class DataDigestResourceTest extends BaseIntegrationTest { - private final static MySubscriberDataObserver observer = new MySubscriberDataObserver(); - private final static String dataId = "test-dataId-" + System.nanoTime(); - private final static String value = "DataDigestResourceTest"; - - @BeforeClass - public static void beforeClass() throws Exception { - clientOff(); - Thread.sleep(2000L); - - PublisherRegistration registration = new PublisherRegistration(dataId); - registryClient1.register(registration, value); - - Thread.sleep(2000L); - SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); - subReg.setScopeEnum(ScopeEnum.dataCenter); - registryClient1.register(subReg); - Thread.sleep(2000L); - - assertEquals(dataId, observer.dataId); - assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); - assertEquals(1, observer.userData.getZoneData().size()); - assertEquals(1, observer.userData.getZoneData().values().size()); - assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); - assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); - assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); - } - - @AfterClass - public static void afterClass() { - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); - } - - @Test - public void testGetDatumByDataInfoId() throws Exception { - Map datumMap = dataChannel.getWebTarget().path("digest/datum/query") - .queryParam("dataId", dataId).queryParam("group", DEFAULT_GROUP) + private static final MySubscriberDataObserver observer = new MySubscriberDataObserver(); + private static final String dataId = "test-dataId-" + System.nanoTime(); + private static final String value = "DataDigestResourceTest"; + + @BeforeClass + public static void beforeClass() throws Exception { + clientOff(); + Thread.sleep(2000L); + + PublisherRegistration registration = new PublisherRegistration(dataId); + registryClient1.register(registration, value); + + Thread.sleep(2000L); + SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); + subReg.setScopeEnum(ScopeEnum.dataCenter); + registryClient1.register(subReg); + Thread.sleep(2000L); + + assertEquals(dataId, observer.dataId); + assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); + assertEquals(1, observer.userData.getZoneData().size()); + assertEquals(1, observer.userData.getZoneData().values().size()); + assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); + assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); + assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); + } + + @AfterClass + public static void afterClass() { + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); + } + + @Test + public void testGetDatumByDataInfoId() throws Exception { + Map datumMap = + dataChannel + .getWebTarget() + .path("digest/datum/query") + .queryParam("dataId", dataId) + .queryParam("group", DEFAULT_GROUP) .queryParam("instanceId", DEFAULT_INSTANCE_ID) - .queryParam("dataCenter", LOCAL_DATACENTER).request(APPLICATION_JSON) - .get(new GenericType>() { - }); - assertTrue(datumMap.size() == 1); - assertEquals(dataId, datumMap.get(LOCAL_DATACENTER).getDataId()); - assertEquals(1, datumMap.get(LOCAL_DATACENTER).publisherSize()); - assertEquals(value, bytes2Object(datumMap.get(LOCAL_DATACENTER).getPubMap().values() - .iterator().next().getDataList().get(0).getBytes())); - } - - @Test - public void testGetPublishersByConnectId() throws Exception { - Map parameters = new HashMap<>(); - parameters.put(NetUtil.genHost(LOCAL_ADDRESS, getSourcePort(registryClient1)), - NetUtil.genHost(LOCAL_ADDRESS, 9600)); - Map> publisherMap = dataChannel + .queryParam("dataCenter", LOCAL_DATACENTER) + .request(APPLICATION_JSON) + .get(new GenericType>() {}); + assertTrue(datumMap.size() == 1); + assertEquals(dataId, datumMap.get(LOCAL_DATACENTER).getDataId()); + assertEquals(1, datumMap.get(LOCAL_DATACENTER).publisherSize()); + assertEquals( + value, + bytes2Object( + datumMap + .get(LOCAL_DATACENTER) + .getPubMap() + .values() + .iterator() + .next() + .getDataList() + .get(0) + .getBytes())); + } + + @Test + public void testGetPublishersByConnectId() throws Exception { + Map parameters = new HashMap<>(); + parameters.put( + NetUtil.genHost(LOCAL_ADDRESS, getSourcePort(registryClient1)), + NetUtil.genHost(LOCAL_ADDRESS, 9600)); + Map> publisherMap = + dataChannel .getWebTarget() .path("digest/connect/query") .request(APPLICATION_JSON) - .post(Entity.entity(parameters, MediaType.APPLICATION_JSON), - new GenericType>>() { - }); - assertEquals(1, publisherMap.size()); - assertEquals( - 1, - publisherMap.get( + .post( + Entity.entity(parameters, MediaType.APPLICATION_JSON), + new GenericType>>() {}); + assertEquals(1, publisherMap.size()); + assertEquals( + 1, + publisherMap + .get( NetUtil.genHost(LOCAL_ADDRESS, getSourcePort(registryClient1)) - + ValueConstants.CONNECT_ID_SPLIT + NetUtil.genHost(LOCAL_ADDRESS, 9600)) - .size()); - assertEquals( - dataId, + + ValueConstants.CONNECT_ID_SPLIT + + NetUtil.genHost(LOCAL_ADDRESS, 9600)) + .size()); + assertEquals( + dataId, + publisherMap + .get( + NetUtil.genHost(LOCAL_ADDRESS, getSourcePort(registryClient1)) + + ValueConstants.CONNECT_ID_SPLIT + + NetUtil.genHost(LOCAL_ADDRESS, 9600)) + .values() + .iterator() + .next() + .getDataId()); + assertEquals( + value, + bytes2Object( publisherMap .get( NetUtil.genHost(LOCAL_ADDRESS, getSourcePort(registryClient1)) - + ValueConstants.CONNECT_ID_SPLIT - + NetUtil.genHost(LOCAL_ADDRESS, 9600)).values().iterator().next() - .getDataId()); - assertEquals( - value, - bytes2Object(publisherMap - .get( - NetUtil.genHost(LOCAL_ADDRESS, getSourcePort(registryClient1)) - + ValueConstants.CONNECT_ID_SPLIT - + NetUtil.genHost(LOCAL_ADDRESS, 9600)).values().iterator().next() - .getDataList().get(0).getBytes())); - } - - @Test - public void testGetDatumCount() { - String countResult = dataChannel.getWebTarget().path("digest/datum/count") - .request(APPLICATION_JSON).get(String.class); - assertTrue(countResult.contains("[Publisher] size of publisher in DefaultDataCenter is 1")); - } + + ValueConstants.CONNECT_ID_SPLIT + + NetUtil.genHost(LOCAL_ADDRESS, 9600)) + .values() + .iterator() + .next() + .getDataList() + .get(0) + .getBytes())); + } + + @Test + public void testGetDatumCount() { + String countResult = + dataChannel + .getWebTarget() + .path("digest/datum/count") + .request(APPLICATION_JSON) + .get(String.class); + assertTrue(countResult.contains("[Publisher] size of publisher in DefaultDataCenter is 1")); + } - @Test - public void testGetServerListAll() throws Exception { + @Test + public void testGetServerListAll() throws Exception { - Map> sessionMap = dataChannel.getWebTarget() - .path("digest/session/serverList/query").request(APPLICATION_JSON) - .get(new GenericType>>() { - }); - assertEquals(1, sessionMap.size()); - assertEquals(1, sessionMap.get(LOCAL_DATACENTER).size()); - assertTrue(sessionMap.get(LOCAL_DATACENTER).get(0).contains(LOCAL_ADDRESS)); + Map> sessionMap = + dataChannel + .getWebTarget() + .path("digest/session/serverList/query") + .request(APPLICATION_JSON) + .get(new GenericType>>() {}); + assertEquals(1, sessionMap.size()); + assertEquals(1, sessionMap.get(LOCAL_DATACENTER).size()); + assertTrue(sessionMap.get(LOCAL_DATACENTER).get(0).contains(LOCAL_ADDRESS)); - Map> metaMap = dataChannel.getWebTarget() - .path("digest/meta/serverList/query").request(APPLICATION_JSON) - .get(new GenericType>>() { - }); - assertEquals(metaMap.get(LOCAL_DATACENTER).get(0), LOCAL_ADDRESS); - } -} \ No newline at end of file + Map> metaMap = + dataChannel + .getWebTarget() + .path("digest/meta/serverList/query") + .request(APPLICATION_JSON) + .get(new GenericType>>() {}); + assertEquals(metaMap.get(LOCAL_DATACENTER).get(0), LOCAL_ADDRESS); + } +} diff --git a/test/src/test/java/com/alipay/sofa/registry/test/resource/data/DatumApiResourceTest.java b/test/src/test/java/com/alipay/sofa/registry/test/resource/data/DatumApiResourceTest.java index 9907ab328..178559de2 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/resource/data/DatumApiResourceTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/resource/data/DatumApiResourceTest.java @@ -16,6 +16,10 @@ */ package com.alipay.sofa.registry.test.resource.data; +import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; +import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; +import static org.junit.Assert.assertEquals; + import com.alipay.sofa.registry.client.api.model.RegistryType; import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; import com.alipay.sofa.registry.client.api.registration.SubscriberRegistration; @@ -24,6 +28,9 @@ import com.alipay.sofa.registry.core.model.ScopeEnum; import com.alipay.sofa.registry.server.data.resource.DatumParam; import com.alipay.sofa.registry.test.BaseIntegrationTest; +import java.util.Map; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; import org.junit.After; import org.junit.Assert; import org.junit.Before; @@ -32,15 +39,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; -import java.util.Map; - -import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; -import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; /** * @author kezhu.wukz @@ -49,237 +47,275 @@ @RunWith(SpringRunner.class) public class DatumApiResourceTest extends BaseIntegrationTest { - private static final Logger LOGGER = LoggerFactory - .getLogger(DatumApiResourceTest.class); - - private static String publisherRegisterId = "registerId-123456789"; - - private String dataId = "test-dataId-" + System.currentTimeMillis(); - private String value = "DataDigestResourceTest"; - private String dataInfoId = DataInfo.toDataInfoId(dataId, - DEFAULT_INSTANCE_ID, DEFAULT_GROUP); - - @Before - public void before() throws Exception { - clientOff(); - Thread.sleep(2000L); - - PublisherRegistration registration = new PublisherRegistration(dataId); - registryClient1.register(registration, value); - Thread.sleep(2000L); - - MySubscriberDataObserver observer = new MySubscriberDataObserver(); - SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); - subReg.setScopeEnum(ScopeEnum.dataCenter); - registryClient1.register(subReg); - Thread.sleep(2000L); - - assertEquals(dataId, observer.dataId); - assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); - assertEquals(1, observer.userData.getZoneData().size()); - assertEquals(1, observer.userData.getZoneData().values().size()); - assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); - assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); - assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); + private static final Logger LOGGER = LoggerFactory.getLogger(DatumApiResourceTest.class); + + private static String publisherRegisterId = "registerId-123456789"; + + private String dataId = "test-dataId-" + System.currentTimeMillis(); + private String value = "DataDigestResourceTest"; + private String dataInfoId = DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP); + + @Before + public void before() throws Exception { + clientOff(); + Thread.sleep(2000L); + + PublisherRegistration registration = new PublisherRegistration(dataId); + registryClient1.register(registration, value); + Thread.sleep(2000L); + + MySubscriberDataObserver observer = new MySubscriberDataObserver(); + SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); + subReg.setScopeEnum(ScopeEnum.dataCenter); + registryClient1.register(subReg); + Thread.sleep(2000L); + + assertEquals(dataId, observer.dataId); + assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); + assertEquals(1, observer.userData.getZoneData().size()); + assertEquals(1, observer.userData.getZoneData().values().size()); + assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); + assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); + assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); + } + + @After + public void after() throws Exception { + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); + // clientOff(); + } + + @Test + public void testException() { + DatumParam datumParam = new DatumParam(); + + { + CommonResponse response = + dataChannel + .getWebTarget() + .path("datum/api/get") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); + LOGGER.info("testException for datum/api/get:" + response); + Assert.assertTrue(response.getMessage().contains("empty")); } - @After - public void after() throws Exception { - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); - // clientOff(); + { + CommonResponse response = + dataChannel + .getWebTarget() + .path("datum/api/delete") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); + LOGGER.info("testException for datum/api/delete:" + response); + Assert.assertTrue(response.getMessage().contains("empty")); } - - @Test - public void testException() { - DatumParam datumParam = new DatumParam(); - - { - CommonResponse response = dataChannel.getWebTarget().path("datum/api/get").request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); - LOGGER.info("testException for datum/api/get:" + response); - Assert.assertTrue(response.getMessage().contains("empty")); - } - - { - CommonResponse response = dataChannel.getWebTarget().path("datum/api/delete").request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); - LOGGER.info("testException for datum/api/delete:" + response); - Assert.assertTrue(response.getMessage().contains("empty")); - } - { - CommonResponse response = dataChannel.getWebTarget().path("datum/api/pub/add") - .request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); - LOGGER.info("testException for datum/api/pub/add:" + response); - Assert.assertTrue(response.getMessage().contains("empty")); - } - { - CommonResponse response = dataChannel.getWebTarget().path("datum/api/pub/delete") - .request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); - LOGGER.info("testException for datum/api/pub/delete:" + response); - Assert.assertTrue(response.getMessage().contains("empty")); - } - + { + CommonResponse response = + dataChannel + .getWebTarget() + .path("datum/api/pub/add") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); + LOGGER.info("testException for datum/api/pub/add:" + response); + Assert.assertTrue(response.getMessage().contains("empty")); } - - @Test - public void testGet() { - //test get - { - DatumParam datumParam = new DatumParam(); - datumParam.setDataInfoId(dataInfoId); - CommonResponse response = dataChannel.getWebTarget().path("datum/api/get").request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); - - LOGGER.info("testGet:" + response); - Assert.assertTrue(response.getMessage().contains(dataId)); - } - //test get not found - { - DatumParam datumParam = new DatumParam(); - datumParam.setDataInfoId(dataInfoId + System.currentTimeMillis()); - CommonResponse response = dataChannel.getWebTarget().path("datum/api/get").request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); - - LOGGER.info("testGet:" + response); - Assert.assertTrue(response.getMessage().contains("not found")); - } - + { + CommonResponse response = + dataChannel + .getWebTarget() + .path("datum/api/pub/delete") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); + LOGGER.info("testException for datum/api/pub/delete:" + response); + Assert.assertTrue(response.getMessage().contains("empty")); } - - @Test - public void testAddDeletePub() { - //add - { - DatumParam datumParam = new DatumParam(); - datumParam.setDataInfoId(dataInfoId); - String testZone = "testZone"; - datumParam.setPublisherCell(testZone); - datumParam.setPublisherDataBox("test"); - datumParam.setPublisherConnectId(LOCAL_ADDRESS + ":12345_" + LOCAL_ADDRESS + ":9600"); - datumParam.setPublisherRegisterId(publisherRegisterId); - CommonResponse response = dataChannel.getWebTarget().path("datum/api/pub/add") - .request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); - - LOGGER.info("testAddPub:" + response); - Assert.assertTrue(response.getMessage().contains(dataId)); - Assert.assertTrue(response.getMessage().contains(testZone)); - } - //delete - { - DatumParam datumParam = new DatumParam(); - datumParam.setDataInfoId(dataInfoId); - String testZone = "testZone"; - datumParam.setPublisherCell(testZone); - datumParam.setPublisherRegisterId(publisherRegisterId); - CommonResponse response = dataChannel.getWebTarget().path("datum/api/pub/delete") - .request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); - LOGGER.info("testDeletePub:" + response); - Assert.assertFalse(response.getMessage().contains(publisherRegisterId)); - } - + } + + @Test + public void testGet() { + // test get + { + DatumParam datumParam = new DatumParam(); + datumParam.setDataInfoId(dataInfoId); + CommonResponse response = + dataChannel + .getWebTarget() + .path("datum/api/get") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); + + LOGGER.info("testGet:" + response); + Assert.assertTrue(response.getMessage().contains(dataId)); } - - @Test - public void testDelete() { - //add - { - DatumParam datumParam = new DatumParam(); - datumParam.setDataInfoId(dataInfoId); - String testZone = "testZone"; - datumParam.setPublisherCell(testZone); - datumParam.setPublisherDataBox("test"); - datumParam.setPublisherConnectId(LOCAL_ADDRESS + ":12345_" + LOCAL_ADDRESS + ":9600"); - datumParam.setPublisherRegisterId(publisherRegisterId); - CommonResponse response = dataChannel.getWebTarget().path("datum/api/pub/add") - .request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); - - LOGGER.info("testAddPub:" + response); - Assert.assertTrue(response.getMessage().contains(dataId)); - Assert.assertTrue(response.getMessage().contains(testZone)); - } - //delete - { - DatumParam datumParam = new DatumParam(); - datumParam.setDataInfoId(dataInfoId); - CommonResponse response = dataChannel.getWebTarget().path("datum/api/delete").request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); - LOGGER.info("testDelete:" + response); - Assert.assertFalse(response.getMessage().contains(publisherRegisterId)); - } - + // test get not found + { + DatumParam datumParam = new DatumParam(); + datumParam.setDataInfoId(dataInfoId + System.currentTimeMillis()); + CommonResponse response = + dataChannel + .getWebTarget() + .path("datum/api/get") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); + + LOGGER.info("testGet:" + response); + Assert.assertTrue(response.getMessage().contains("not found")); } - - @Test - public void testGetDatumVersions() { - //test - { - DatumParam datumParam = new DatumParam(); - datumParam.setDataCenter(LOCAL_DATACENTER); - Map response = dataChannel.getWebTarget() - .path("datum/api/getDatumVersions").request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), Map.class); - - LOGGER.info("testGetDatumVersions:" + response); - Assert.assertTrue(response.get(dataInfoId) != null); - } - //test not found - { - DatumParam datumParam = new DatumParam(); - datumParam.setDataCenter(LOCAL_DATACENTER + System.currentTimeMillis()); - Map response = dataChannel.getWebTarget() - .path("datum/api/getDatumVersions").request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), Map.class); - - LOGGER.info("testGetDatumVersions:" + response); - Assert.assertTrue(response.get(dataInfoId) == null); - } + } + + @Test + public void testAddDeletePub() { + // add + { + DatumParam datumParam = new DatumParam(); + datumParam.setDataInfoId(dataInfoId); + String testZone = "testZone"; + datumParam.setPublisherCell(testZone); + datumParam.setPublisherDataBox("test"); + datumParam.setPublisherConnectId(LOCAL_ADDRESS + ":12345_" + LOCAL_ADDRESS + ":9600"); + datumParam.setPublisherRegisterId(publisherRegisterId); + CommonResponse response = + dataChannel + .getWebTarget() + .path("datum/api/pub/add") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); + + LOGGER.info("testAddPub:" + response); + Assert.assertTrue(response.getMessage().contains(dataId)); + Assert.assertTrue(response.getMessage().contains(testZone)); } - - @Test - public void testGetDatumVersion() { - { - DatumParam datumParam = new DatumParam(); - datumParam.setDataCenter(LOCAL_DATACENTER); - datumParam.setDataInfoId(dataInfoId); - String response = dataChannel.getWebTarget().path("datum/api/getDatumVersion") - .request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), String.class); - - LOGGER.info("testGetDatumVersions:" + response); - Assert.assertTrue(response.contains(dataInfoId)); - } - - { - DatumParam datumParam = new DatumParam(); - datumParam.setDataCenter(LOCAL_DATACENTER + System.currentTimeMillis()); - datumParam.setDataInfoId(dataInfoId); - String response = dataChannel.getWebTarget().path("datum/api/getDatumVersion") - .request() - .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), String.class); - - LOGGER.info("testGetDatumVersions:" + response); - Assert.assertTrue(response.contains(dataInfoId)); - } - + // delete + { + DatumParam datumParam = new DatumParam(); + datumParam.setDataInfoId(dataInfoId); + String testZone = "testZone"; + datumParam.setPublisherCell(testZone); + datumParam.setPublisherRegisterId(publisherRegisterId); + CommonResponse response = + dataChannel + .getWebTarget() + .path("datum/api/pub/delete") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); + LOGGER.info("testDeletePub:" + response); + Assert.assertFalse(response.getMessage().contains(publisherRegisterId)); } - - @Test - public void testGetDatumSize() { - DatumParam datumParam = new DatumParam(); - datumParam.setDataCenter(LOCAL_DATACENTER); - datumParam.setDataInfoId(dataInfoId); - Map response = dataChannel.getWebTarget().path("datum/api/getDatumSizes") - .request().get(Map.class); - - LOGGER.info("testGetDatumSize:" + response); - Assert.assertTrue(response.get(LOCAL_DATACENTER).intValue() > 0); - + } + + @Test + public void testDelete() { + // add + { + DatumParam datumParam = new DatumParam(); + datumParam.setDataInfoId(dataInfoId); + String testZone = "testZone"; + datumParam.setPublisherCell(testZone); + datumParam.setPublisherDataBox("test"); + datumParam.setPublisherConnectId(LOCAL_ADDRESS + ":12345_" + LOCAL_ADDRESS + ":9600"); + datumParam.setPublisherRegisterId(publisherRegisterId); + CommonResponse response = + dataChannel + .getWebTarget() + .path("datum/api/pub/add") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); + + LOGGER.info("testAddPub:" + response); + Assert.assertTrue(response.getMessage().contains(dataId)); + Assert.assertTrue(response.getMessage().contains(testZone)); + } + // delete + { + DatumParam datumParam = new DatumParam(); + datumParam.setDataInfoId(dataInfoId); + CommonResponse response = + dataChannel + .getWebTarget() + .path("datum/api/delete") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), CommonResponse.class); + LOGGER.info("testDelete:" + response); + Assert.assertFalse(response.getMessage().contains(publisherRegisterId)); + } + } + + @Test + public void testGetDatumVersions() { + // test + { + DatumParam datumParam = new DatumParam(); + datumParam.setDataCenter(LOCAL_DATACENTER); + Map response = + dataChannel + .getWebTarget() + .path("datum/api/getDatumVersions") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), Map.class); + + LOGGER.info("testGetDatumVersions:" + response); + Assert.assertTrue(response.get(dataInfoId) != null); + } + // test not found + { + DatumParam datumParam = new DatumParam(); + datumParam.setDataCenter(LOCAL_DATACENTER + System.currentTimeMillis()); + Map response = + dataChannel + .getWebTarget() + .path("datum/api/getDatumVersions") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), Map.class); + + LOGGER.info("testGetDatumVersions:" + response); + Assert.assertTrue(response.get(dataInfoId) == null); + } + } + + @Test + public void testGetDatumVersion() { + { + DatumParam datumParam = new DatumParam(); + datumParam.setDataCenter(LOCAL_DATACENTER); + datumParam.setDataInfoId(dataInfoId); + String response = + dataChannel + .getWebTarget() + .path("datum/api/getDatumVersion") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), String.class); + + LOGGER.info("testGetDatumVersions:" + response); + Assert.assertTrue(response.contains(dataInfoId)); } -} \ No newline at end of file + { + DatumParam datumParam = new DatumParam(); + datumParam.setDataCenter(LOCAL_DATACENTER + System.currentTimeMillis()); + datumParam.setDataInfoId(dataInfoId); + String response = + dataChannel + .getWebTarget() + .path("datum/api/getDatumVersion") + .request() + .post(Entity.entity(datumParam, MediaType.APPLICATION_JSON), String.class); + + LOGGER.info("testGetDatumVersions:" + response); + Assert.assertTrue(response.contains(dataInfoId)); + } + } + + @Test + public void testGetDatumSize() { + DatumParam datumParam = new DatumParam(); + datumParam.setDataCenter(LOCAL_DATACENTER); + datumParam.setDataInfoId(dataInfoId); + Map response = + dataChannel.getWebTarget().path("datum/api/getDatumSizes").request().get(Map.class); + + LOGGER.info("testGetDatumSize:" + response); + Assert.assertTrue(response.get(LOCAL_DATACENTER).intValue() > 0); + } +} diff --git a/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/BlacklistTest.java b/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/BlacklistTest.java index a466b988b..d88a3df75 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/BlacklistTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/BlacklistTest.java @@ -16,6 +16,12 @@ */ package com.alipay.sofa.registry.test.resource.meta; +import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; +import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.alipay.sofa.registry.client.api.model.RegistryType; import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; import com.alipay.sofa.registry.client.api.registration.SubscriberRegistration; @@ -29,25 +35,18 @@ import com.alipay.sofa.registry.test.BaseIntegrationTest; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Maps; -import org.junit.AfterClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.test.context.junit4.SpringRunner; - -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; - -import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; -import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import org.junit.AfterClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.junit4.SpringRunner; /** * @author shangyu.wh @@ -55,188 +54,194 @@ */ @RunWith(SpringRunner.class) public class BlacklistTest extends BaseIntegrationTest { - @Test - public void testBlacklistUpdate() throws Exception { + @Test + public void testBlacklistUpdate() throws Exception { - Map>> map = new HashMap<>(); - Set set1 = new HashSet<>(); - Set set2 = new HashSet<>(); - set1.add("193.165.0.1"); - set1.add("193.165.0.2"); - set2.add("193.165.0.3"); - set2.add("193.165.0.4"); + Map>> map = new HashMap<>(); + Set set1 = new HashSet<>(); + Set set2 = new HashSet<>(); + set1.add("193.165.0.1"); + set1.add("193.165.0.2"); + set2.add("193.165.0.3"); + set2.add("193.165.0.4"); - Map> map1 = Maps.newHashMap(); - map1.put(BlacklistConstants.IP_FULL, set1); + Map> map1 = Maps.newHashMap(); + map1.put(BlacklistConstants.IP_FULL, set1); - Map> map2 = Maps.newHashMap(); - map2.put(BlacklistConstants.IP_FULL, set2); + Map> map2 = Maps.newHashMap(); + map2.put(BlacklistConstants.IP_FULL, set2); - map.put(BlacklistConstants.FORBIDDEN_PUB, map1); - map.put(BlacklistConstants.FORBIDDEN_SUB_BY_PREFIX, map2); + map.put(BlacklistConstants.FORBIDDEN_PUB, map1); + map.put(BlacklistConstants.FORBIDDEN_SUB_BY_PREFIX, map2); - ObjectMapper mapper = new ObjectMapper(); + ObjectMapper mapper = new ObjectMapper(); - Result response = metaChannel + Result response = + metaChannel .getWebTarget() .path("blacklist/update") .request() - .post(Entity.entity(mapper.writeValueAsString(map), MediaType.APPLICATION_JSON), + .post( + Entity.entity(mapper.writeValueAsString(map), MediaType.APPLICATION_JSON), Result.class); - assertTrue(response.isSuccess()); + assertTrue(response.isSuccess()); + } - } + @Test + public void testBlacklistUpdatePub() throws Exception { - @Test - public void testBlacklistUpdatePub() throws Exception { + Map>> map = new HashMap<>(); + Set set1 = new HashSet<>(); + Set set2 = new HashSet<>(); + String local = NetUtil.getLocalAddress().getHostAddress(); + set1.add(local); + set2.add(local); - Map>> map = new HashMap<>(); - Set set1 = new HashSet<>(); - Set set2 = new HashSet<>(); - String local = NetUtil.getLocalAddress().getHostAddress(); - set1.add(local); - set2.add(local); + Map> map1 = Maps.newHashMap(); + map1.put(BlacklistConstants.IP_FULL, set1); - Map> map1 = Maps.newHashMap(); - map1.put(BlacklistConstants.IP_FULL, set1); + Map> map2 = Maps.newHashMap(); + map2.put(BlacklistConstants.IP_FULL, set2); - Map> map2 = Maps.newHashMap(); - map2.put(BlacklistConstants.IP_FULL, set2); + map.put(BlacklistConstants.FORBIDDEN_PUB, map1); - map.put(BlacklistConstants.FORBIDDEN_PUB, map1); + ObjectMapper mapper = new ObjectMapper(); - ObjectMapper mapper = new ObjectMapper(); - - Result response = metaChannel + Result response = + metaChannel .getWebTarget() .path("blacklist/update") .request() - .post(Entity.entity(mapper.writeValueAsString(map), MediaType.APPLICATION_JSON), + .post( + Entity.entity(mapper.writeValueAsString(map), MediaType.APPLICATION_JSON), Result.class); - assertTrue(response.isSuccess()); + assertTrue(response.isSuccess()); - //wait for new list meta dispatch to session - Thread.sleep(2000L); + // wait for new list meta dispatch to session + Thread.sleep(2000L); - String dataId = "test-dataId-blacklist"; - String value = "test blacklist"; + String dataId = "test-dataId-blacklist"; + String value = "test blacklist"; - PublisherRegistration registration = new PublisherRegistration(dataId); - registryClient1.register(registration, value); - Thread.sleep(2000L); + PublisherRegistration registration = new PublisherRegistration(dataId); + registryClient1.register(registration, value); + Thread.sleep(2000L); - MySubscriberDataObserver observer = new MySubscriberDataObserver(); - SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); - subReg.setScopeEnum(ScopeEnum.dataCenter); + MySubscriberDataObserver observer = new MySubscriberDataObserver(); + SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); + subReg.setScopeEnum(ScopeEnum.dataCenter); - registryClient1.register(subReg); + registryClient1.register(subReg); - Thread.sleep(2000L); - assertEquals(dataId, observer.dataId); - assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); + Thread.sleep(2000L); + assertEquals(dataId, observer.dataId); + assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); - Map> publisherMap = sessionChannel + Map> publisherMap = + sessionChannel .getWebTarget() .path("digest/pub/data/query") - .queryParam("dataInfoId", - DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) - .request(APPLICATION_JSON).get(new GenericType>>() { - }); - assertEquals(0, publisherMap.size()); - - Map> subscriberMap = sessionChannel + .queryParam( + "dataInfoId", DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) + .request(APPLICATION_JSON) + .get(new GenericType>>() {}); + assertEquals(0, publisherMap.size()); + + Map> subscriberMap = + sessionChannel .getWebTarget() .path("digest/sub/data/query") - .queryParam("dataInfoId", - DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) - .request(APPLICATION_JSON).get(new GenericType>>() { - }); - assertEquals(1, subscriberMap.size()); - assertEquals(1, subscriberMap.get("SUB").size()); - assertEquals(dataId, subscriberMap.get("SUB").get(0).getDataId()); - - } + .queryParam( + "dataInfoId", DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) + .request(APPLICATION_JSON) + .get(new GenericType>>() {}); + assertEquals(1, subscriberMap.size()); + assertEquals(1, subscriberMap.get("SUB").size()); + assertEquals(dataId, subscriberMap.get("SUB").get(0).getDataId()); + } - @Test - public void testBlacklistUpdateSub() throws Exception { + @Test + public void testBlacklistUpdateSub() throws Exception { - Map>> map = new HashMap<>(); - Set set1 = new HashSet<>(); - Set set2 = new HashSet<>(); - String local = NetUtil.getLocalAddress().getHostAddress(); - set1.add(local); - set2.add(local); + Map>> map = new HashMap<>(); + Set set1 = new HashSet<>(); + Set set2 = new HashSet<>(); + String local = NetUtil.getLocalAddress().getHostAddress(); + set1.add(local); + set2.add(local); - Map> map1 = Maps.newHashMap(); - map1.put(BlacklistConstants.IP_FULL, set1); + Map> map1 = Maps.newHashMap(); + map1.put(BlacklistConstants.IP_FULL, set1); - Map> map2 = Maps.newHashMap(); - map2.put(BlacklistConstants.IP_FULL, set2); + Map> map2 = Maps.newHashMap(); + map2.put(BlacklistConstants.IP_FULL, set2); - map.put(BlacklistConstants.FORBIDDEN_SUB_BY_PREFIX, map2); + map.put(BlacklistConstants.FORBIDDEN_SUB_BY_PREFIX, map2); - ObjectMapper mapper = new ObjectMapper(); + ObjectMapper mapper = new ObjectMapper(); - Result response = metaChannel + Result response = + metaChannel .getWebTarget() .path("blacklist/update") .request() - .post(Entity.entity(mapper.writeValueAsString(map), MediaType.APPLICATION_JSON), + .post( + Entity.entity(mapper.writeValueAsString(map), MediaType.APPLICATION_JSON), Result.class); - assertTrue(response.isSuccess()); + assertTrue(response.isSuccess()); - //wait for new list meta dispatch to session - Thread.sleep(2000L); + // wait for new list meta dispatch to session + Thread.sleep(2000L); - String dataId = "test-dataId-blacklist2"; - String value = "test blacklist2"; + String dataId = "test-dataId-blacklist2"; + String value = "test blacklist2"; - PublisherRegistration registration = new PublisherRegistration(dataId); - registryClient1.register(registration, value); - Thread.sleep(2000L); - MySubscriberDataObserver observer = new MySubscriberDataObserver(); - SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); - subReg.setScopeEnum(ScopeEnum.dataCenter); + PublisherRegistration registration = new PublisherRegistration(dataId); + registryClient1.register(registration, value); + Thread.sleep(2000L); + MySubscriberDataObserver observer = new MySubscriberDataObserver(); + SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); + subReg.setScopeEnum(ScopeEnum.dataCenter); - registryClient1.register(subReg); + registryClient1.register(subReg); - Thread.sleep(2000L); - assertEquals(dataId, observer.dataId); - assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); + Thread.sleep(2000L); + assertEquals(dataId, observer.dataId); + assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); - Map> publisherMap = sessionChannel + Map> publisherMap = + sessionChannel .getWebTarget() .path("digest/pub/data/query") - .queryParam("dataInfoId", - DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) - .request(APPLICATION_JSON).get(new GenericType>>() { - }); - assertEquals(1, publisherMap.size()); - assertEquals(1, publisherMap.get("PUB").size()); - assertEquals(dataId, publisherMap.get("PUB").get(0).getDataId()); - assertEquals(value, bytes2Object(publisherMap.get("PUB").get(0).getDataList().get(0) - .getBytes())); - - Map> subscriberMap = sessionChannel + .queryParam( + "dataInfoId", DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) + .request(APPLICATION_JSON) + .get(new GenericType>>() {}); + assertEquals(1, publisherMap.size()); + assertEquals(1, publisherMap.get("PUB").size()); + assertEquals(dataId, publisherMap.get("PUB").get(0).getDataId()); + assertEquals( + value, bytes2Object(publisherMap.get("PUB").get(0).getDataList().get(0).getBytes())); + + Map> subscriberMap = + sessionChannel .getWebTarget() .path("digest/sub/data/query") - .queryParam("dataInfoId", - DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) - .request(APPLICATION_JSON).get(new GenericType>>() { - }); - assertEquals(0, subscriberMap.size()); - - } - - @AfterClass - public static void afterClass() { - registryClient1.unregister("test-dataId-blacklist", DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient1.unregister("test-dataId-blacklist", DEFAULT_GROUP, RegistryType.PUBLISHER); - registryClient1 - .unregister("test-dataId-blacklist2", DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient1.unregister("test-dataId-blacklist2", DEFAULT_GROUP, RegistryType.PUBLISHER); - } + .queryParam( + "dataInfoId", DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) + .request(APPLICATION_JSON) + .get(new GenericType>>() {}); + assertEquals(0, subscriberMap.size()); + } + + @AfterClass + public static void afterClass() { + registryClient1.unregister("test-dataId-blacklist", DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient1.unregister("test-dataId-blacklist", DEFAULT_GROUP, RegistryType.PUBLISHER); + registryClient1.unregister("test-dataId-blacklist2", DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient1.unregister("test-dataId-blacklist2", DEFAULT_GROUP, RegistryType.PUBLISHER); + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/MetaDigestResourceTest.java b/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/MetaDigestResourceTest.java index ddce4c789..3a06d92f5 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/MetaDigestResourceTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/MetaDigestResourceTest.java @@ -16,44 +16,59 @@ */ package com.alipay.sofa.registry.test.resource.meta; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.junit.Assert.assertTrue; + import com.alipay.sofa.registry.test.BaseIntegrationTest; +import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringRunner; -import java.util.Map; - -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; -import static org.junit.Assert.assertTrue; - /** * @author xuanbei * @since 2019/1/14 */ @RunWith(SpringRunner.class) public class MetaDigestResourceTest extends BaseIntegrationTest { - @Test - public void testGetRegisterNodeByType() { - Map map = metaChannel.getWebTarget().path("digest/data/node/query") - .request(APPLICATION_JSON).get(Map.class); - assertTrue(map.size() == 1); - assertTrue(((Map) map.get(LOCAL_DATACENTER)).containsKey(LOCAL_ADDRESS)); + @Test + public void testGetRegisterNodeByType() { + Map map = + metaChannel + .getWebTarget() + .path("digest/data/node/query") + .request(APPLICATION_JSON) + .get(Map.class); + assertTrue(map.size() == 1); + assertTrue(((Map) map.get(LOCAL_DATACENTER)).containsKey(LOCAL_ADDRESS)); - map = metaChannel.getWebTarget().path("digest/meta/node/query").request(APPLICATION_JSON) + map = + metaChannel + .getWebTarget() + .path("digest/meta/node/query") + .request(APPLICATION_JSON) .get(Map.class); - assertTrue(map.size() == 1); - assertTrue(((Map) map.get(LOCAL_DATACENTER)).containsKey(LOCAL_ADDRESS)); + assertTrue(map.size() == 1); + assertTrue(((Map) map.get(LOCAL_DATACENTER)).containsKey(LOCAL_ADDRESS)); - map = metaChannel.getWebTarget().path("digest/session/node/query") - .request(APPLICATION_JSON).get(Map.class); - assertTrue(map.size() == 1); - assertTrue(((Map) map.get(LOCAL_DATACENTER)).containsKey(LOCAL_ADDRESS)); - } + map = + metaChannel + .getWebTarget() + .path("digest/session/node/query") + .request(APPLICATION_JSON) + .get(Map.class); + assertTrue(map.size() == 1); + assertTrue(((Map) map.get(LOCAL_DATACENTER)).containsKey(LOCAL_ADDRESS)); + } - @Test - public void testGetPushSwitch() { - Map map = metaChannel.getWebTarget().path("digest/pushSwitch").request(APPLICATION_JSON) + @Test + public void testGetPushSwitch() { + Map map = + metaChannel + .getWebTarget() + .path("digest/pushSwitch") + .request(APPLICATION_JSON) .get(Map.class); - assertTrue("open".equals(map.get("pushSwitch"))); - } + assertTrue("open".equals(map.get("pushSwitch"))); + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/ProvideDataResourceTest.java b/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/ProvideDataResourceTest.java index 0e9f4753a..034cebe51 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/ProvideDataResourceTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/ProvideDataResourceTest.java @@ -16,42 +16,49 @@ */ package com.alipay.sofa.registry.test.resource.meta; +import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; +import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; +import static org.junit.Assert.assertTrue; + import com.alipay.sofa.registry.common.model.console.PersistenceData; import com.alipay.sofa.registry.core.model.Result; import com.alipay.sofa.registry.test.BaseIntegrationTest; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.MediaType; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringRunner; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.MediaType; - -import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; -import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; -import static org.junit.Assert.assertTrue; - /** * @author xuanbei * @since 2019/1/14 */ @RunWith(SpringRunner.class) public class ProvideDataResourceTest extends BaseIntegrationTest { - @Test - public void testPersistentDataResource() throws Exception { - PersistenceData persistenceData = new PersistenceData(); - persistenceData.setData("PersistentDataResourceTest"); - persistenceData.setVersion(1024L); - persistenceData.setDataId("PersistentDataResourceTest"); - persistenceData.setGroup(DEFAULT_GROUP); - persistenceData.setInstanceId(DEFAULT_INSTANCE_ID); + @Test + public void testPersistentDataResource() throws Exception { + PersistenceData persistenceData = new PersistenceData(); + persistenceData.setData("PersistentDataResourceTest"); + persistenceData.setVersion(1024L); + persistenceData.setDataId("PersistentDataResourceTest"); + persistenceData.setGroup(DEFAULT_GROUP); + persistenceData.setInstanceId(DEFAULT_INSTANCE_ID); - Result response = metaChannel.getWebTarget().path("persistentData/put").request() + Result response = + metaChannel + .getWebTarget() + .path("persistentData/put") + .request() .post(Entity.entity(persistenceData, MediaType.APPLICATION_JSON), Result.class); - assertTrue(response.isSuccess()); - Thread.sleep(500); + assertTrue(response.isSuccess()); + Thread.sleep(500); - response = metaChannel.getWebTarget().path("persistentData/remove").request() + response = + metaChannel + .getWebTarget() + .path("persistentData/remove") + .request() .post(Entity.entity(persistenceData, MediaType.APPLICATION_JSON), Result.class); - assertTrue(response.isSuccess()); - } + assertTrue(response.isSuccess()); + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/StopPushDataSwitchTest.java b/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/StopPushDataSwitchTest.java index 3e562d220..140963681 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/StopPushDataSwitchTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/resource/meta/StopPushDataSwitchTest.java @@ -22,14 +22,6 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import java.util.concurrent.atomic.AtomicReference; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.test.context.junit4.SpringRunner; - import com.alipay.sofa.registry.client.api.model.RegistryType; import com.alipay.sofa.registry.client.api.model.UserData; import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; @@ -38,6 +30,12 @@ import com.alipay.sofa.registry.core.model.ScopeEnum; import com.alipay.sofa.registry.server.session.bootstrap.SessionServerConfig; import com.alipay.sofa.registry.test.BaseIntegrationTest; +import java.util.concurrent.atomic.AtomicReference; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.test.context.junit4.SpringRunner; /** * @author xuanbei @@ -46,61 +44,73 @@ @RunWith(SpringRunner.class) public class StopPushDataSwitchTest extends BaseIntegrationTest { - private static final Logger LOGGER = LoggerFactory.getLogger(StopPushDataSwitchTest.class); - - @Test - public void testStopPushDataSwitch() throws Exception { - // open stop push switch - assertTrue( - metaChannel.getWebTarget().path("stopPushDataSwitch/open").request(APPLICATION_JSON).get(Result.class) - .isSuccess()); - Thread.sleep(2000L); - - AtomicReference dataIdResult = new AtomicReference<>(); - AtomicReference userDataResult = new AtomicReference<>(); - - // register Publisher & Subscriber, Subscriber get no data - String dataId = "test-dataId-" + System.currentTimeMillis(); - String value = "test stop publish data switch"; - - LOGGER.info("dataidIn:" + dataId); - - SessionServerConfig sessionServerConfig = sessionApplicationContext.getBean(SessionServerConfig.class); - - LOGGER.info("sessionServerConfig.isStopPushSwitch:" + sessionServerConfig.isStopPushSwitch()); - - PublisherRegistration registration = new PublisherRegistration(dataId); - registryClient1.register(registration, value); - Thread.sleep(2000L); - - SubscriberRegistration subReg = new SubscriberRegistration(dataId, (dataIdOb, data) -> { - LOGGER.info("sub:" + data); - dataIdResult.set(dataIdOb); - userDataResult.set(data); - }); - subReg.setScopeEnum(ScopeEnum.dataCenter); - registryClient1.register(subReg); - Thread.sleep(2000L); - assertNull(dataIdResult.get()); - - // close stop push switch - assertTrue( - metaChannel.getWebTarget().path("stopPushDataSwitch/close").request(APPLICATION_JSON).get(Result.class) - .isSuccess()); - - waitConditionUntilTimeOut(()->dataIdResult.get() != null, 3000); - - // Subscriber get data, test data - assertEquals(dataId, dataIdResult.get()); - assertEquals(LOCAL_REGION, userDataResult.get().getLocalZone()); - assertEquals(1, userDataResult.get().getZoneData().size()); - assertEquals(1, userDataResult.get().getZoneData().values().size()); - assertEquals(true, userDataResult.get().getZoneData().containsKey(LOCAL_REGION)); - assertEquals(1, userDataResult.get().getZoneData().get(LOCAL_REGION).size()); - assertEquals(value, userDataResult.get().getZoneData().get(LOCAL_REGION).get(0)); - - // unregister Publisher & Subscriber - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); - } + private static final Logger LOGGER = LoggerFactory.getLogger(StopPushDataSwitchTest.class); + + @Test + public void testStopPushDataSwitch() throws Exception { + // open stop push switch + assertTrue( + metaChannel + .getWebTarget() + .path("stopPushDataSwitch/open") + .request(APPLICATION_JSON) + .get(Result.class) + .isSuccess()); + Thread.sleep(2000L); + + AtomicReference dataIdResult = new AtomicReference<>(); + AtomicReference userDataResult = new AtomicReference<>(); + + // register Publisher & Subscriber, Subscriber get no data + String dataId = "test-dataId-" + System.currentTimeMillis(); + String value = "test stop publish data switch"; + + LOGGER.info("dataidIn:" + dataId); + + SessionServerConfig sessionServerConfig = + sessionApplicationContext.getBean(SessionServerConfig.class); + + LOGGER.info("sessionServerConfig.isStopPushSwitch:" + sessionServerConfig.isStopPushSwitch()); + + PublisherRegistration registration = new PublisherRegistration(dataId); + registryClient1.register(registration, value); + Thread.sleep(2000L); + + SubscriberRegistration subReg = + new SubscriberRegistration( + dataId, + (dataIdOb, data) -> { + LOGGER.info("sub:" + data); + dataIdResult.set(dataIdOb); + userDataResult.set(data); + }); + subReg.setScopeEnum(ScopeEnum.dataCenter); + registryClient1.register(subReg); + Thread.sleep(2000L); + assertNull(dataIdResult.get()); + + // close stop push switch + assertTrue( + metaChannel + .getWebTarget() + .path("stopPushDataSwitch/close") + .request(APPLICATION_JSON) + .get(Result.class) + .isSuccess()); + + waitConditionUntilTimeOut(() -> dataIdResult.get() != null, 3000); + + // Subscriber get data, test data + assertEquals(dataId, dataIdResult.get()); + assertEquals(LOCAL_REGION, userDataResult.get().getLocalZone()); + assertEquals(1, userDataResult.get().getZoneData().size()); + assertEquals(1, userDataResult.get().getZoneData().values().size()); + assertEquals(true, userDataResult.get().getZoneData().containsKey(LOCAL_REGION)); + assertEquals(1, userDataResult.get().getZoneData().get(LOCAL_REGION).size()); + assertEquals(value, userDataResult.get().getZoneData().get(LOCAL_REGION).get(0)); + + // unregister Publisher & Subscriber + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/test/resource/session/ClientsOpenResourceTest.java b/test/src/test/java/com/alipay/sofa/registry/test/resource/session/ClientsOpenResourceTest.java index c9a74282e..0d0bcd16e 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/resource/session/ClientsOpenResourceTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/resource/session/ClientsOpenResourceTest.java @@ -16,37 +16,45 @@ */ package com.alipay.sofa.registry.test.resource.session; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.junit.Assert.assertTrue; + import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; import com.alipay.sofa.registry.test.BaseIntegrationTest; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringRunner; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; -import static org.junit.Assert.assertTrue; - /** * @author xuanbei * @since 2019/1/14 */ @RunWith(SpringRunner.class) public class ClientsOpenResourceTest extends BaseIntegrationTest { - @Test - public void testClientOff() throws Exception { - clientOff(); - String dataId = "test-dataId-" + System.currentTimeMillis(); - String value = "test client off"; - PublisherRegistration registration = new PublisherRegistration(dataId); - registryClient1.register(registration, value); - Thread.sleep(2000L); + @Test + public void testClientOff() throws Exception { + clientOff(); + String dataId = "test-dataId-" + System.currentTimeMillis(); + String value = "test client off"; + PublisherRegistration registration = new PublisherRegistration(dataId); + registryClient1.register(registration, value); + Thread.sleep(2000L); - String countResult = dataChannel.getWebTarget().path("digest/datum/count") - .request(APPLICATION_JSON).get(String.class); - assertTrue(countResult.contains("[Publisher] size of publisher in DefaultDataCenter is 1")); + String countResult = + dataChannel + .getWebTarget() + .path("digest/datum/count") + .request(APPLICATION_JSON) + .get(String.class); + assertTrue(countResult.contains("[Publisher] size of publisher in DefaultDataCenter is 1")); - clientOff(); - countResult = dataChannel.getWebTarget().path("digest/datum/count") - .request(APPLICATION_JSON).get(String.class); - assertTrue(countResult.contains("[Publisher] size of publisher in DefaultDataCenter is 0")); - } + clientOff(); + countResult = + dataChannel + .getWebTarget() + .path("digest/datum/count") + .request(APPLICATION_JSON) + .get(String.class); + assertTrue(countResult.contains("[Publisher] size of publisher in DefaultDataCenter is 0")); + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/test/resource/session/SessionDigestResourceTest.java b/test/src/test/java/com/alipay/sofa/registry/test/resource/session/SessionDigestResourceTest.java index c0a5a6f04..b267346b5 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/resource/session/SessionDigestResourceTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/resource/session/SessionDigestResourceTest.java @@ -16,6 +16,12 @@ */ package com.alipay.sofa.registry.test.resource.session; +import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; +import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; +import static javax.ws.rs.core.MediaType.APPLICATION_JSON; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + import com.alipay.sofa.registry.client.api.model.RegistryType; import com.alipay.sofa.registry.client.api.registration.PublisherRegistration; import com.alipay.sofa.registry.client.api.registration.SubscriberRegistration; @@ -26,174 +32,193 @@ import com.alipay.sofa.registry.core.model.ScopeEnum; import com.alipay.sofa.registry.net.NetUtil; import com.alipay.sofa.registry.test.BaseIntegrationTest; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import javax.ws.rs.client.Entity; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringRunner; -import javax.ws.rs.client.Entity; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static com.alipay.sofa.registry.client.constants.ValueConstants.DEFAULT_GROUP; -import static com.alipay.sofa.registry.common.model.constants.ValueConstants.DEFAULT_INSTANCE_ID; -import static javax.ws.rs.core.MediaType.APPLICATION_JSON; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - /** * @author xuanbei * @since 2019/1/14 */ @RunWith(SpringRunner.class) public class SessionDigestResourceTest extends BaseIntegrationTest { - private static final String dataId = "test-dataId-" + System.nanoTime(); - private static final String value = "SessionDigestResourceTest"; - private final static MySubscriberDataObserver observer = new MySubscriberDataObserver(); - - @BeforeClass - public static void beforeClass() throws Exception { - clientOff(); - - PublisherRegistration registration = new PublisherRegistration(dataId); - registryClient1.register(registration, value); - Thread.sleep(2000L); - - SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); - subReg.setScopeEnum(ScopeEnum.dataCenter); - registryClient1.register(subReg); - Thread.sleep(2000L); - - assertEquals(dataId, observer.dataId); - assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); - assertEquals(1, observer.userData.getZoneData().size()); - assertEquals(1, observer.userData.getZoneData().values().size()); - assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); - assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); - assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); - } - - @AfterClass - public static void afterClass() { - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); - registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); - } - - @Test - public void testGetSessionDataByDataInfoId() throws Exception { - Map> publisherMap = sessionChannel + private static final String dataId = "test-dataId-" + System.nanoTime(); + private static final String value = "SessionDigestResourceTest"; + private static final MySubscriberDataObserver observer = new MySubscriberDataObserver(); + + @BeforeClass + public static void beforeClass() throws Exception { + clientOff(); + + PublisherRegistration registration = new PublisherRegistration(dataId); + registryClient1.register(registration, value); + Thread.sleep(2000L); + + SubscriberRegistration subReg = new SubscriberRegistration(dataId, observer); + subReg.setScopeEnum(ScopeEnum.dataCenter); + registryClient1.register(subReg); + Thread.sleep(2000L); + + assertEquals(dataId, observer.dataId); + assertEquals(LOCAL_REGION, observer.userData.getLocalZone()); + assertEquals(1, observer.userData.getZoneData().size()); + assertEquals(1, observer.userData.getZoneData().values().size()); + assertEquals(true, observer.userData.getZoneData().containsKey(LOCAL_REGION)); + assertEquals(1, observer.userData.getZoneData().get(LOCAL_REGION).size()); + assertEquals(value, observer.userData.getZoneData().get(LOCAL_REGION).get(0)); + } + + @AfterClass + public static void afterClass() { + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.SUBSCRIBER); + registryClient1.unregister(dataId, DEFAULT_GROUP, RegistryType.PUBLISHER); + } + + @Test + public void testGetSessionDataByDataInfoId() throws Exception { + Map> publisherMap = + sessionChannel .getWebTarget() .path("digest/pub/data/query") - .queryParam("dataInfoId", - DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) - .request(APPLICATION_JSON).get(new GenericType>>() { - }); - assertEquals(1, publisherMap.size()); - assertEquals(1, publisherMap.get("PUB").size()); - assertEquals(dataId, publisherMap.get("PUB").get(0).getDataId()); - assertEquals(value, bytes2Object(publisherMap.get("PUB").get(0).getDataList().get(0) - .getBytes())); - - Map> subscriberMap = sessionChannel + .queryParam( + "dataInfoId", DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) + .request(APPLICATION_JSON) + .get(new GenericType>>() {}); + assertEquals(1, publisherMap.size()); + assertEquals(1, publisherMap.get("PUB").size()); + assertEquals(dataId, publisherMap.get("PUB").get(0).getDataId()); + assertEquals( + value, bytes2Object(publisherMap.get("PUB").get(0).getDataList().get(0).getBytes())); + + Map> subscriberMap = + sessionChannel .getWebTarget() .path("digest/sub/data/query") - .queryParam("dataInfoId", - DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) - .request(APPLICATION_JSON).get(new GenericType>>() { - }); - assertEquals(1, subscriberMap.size()); - assertEquals(1, subscriberMap.get("SUB").size()); - assertEquals(dataId, subscriberMap.get("SUB").get(0).getDataId()); - - Map map = sessionChannel + .queryParam( + "dataInfoId", DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) + .request(APPLICATION_JSON) + .get(new GenericType>>() {}); + assertEquals(1, subscriberMap.size()); + assertEquals(1, subscriberMap.get("SUB").size()); + assertEquals(dataId, subscriberMap.get("SUB").get(0).getDataId()); + + Map map = + sessionChannel .getWebTarget() .path("digest/all/data/query") - .queryParam("dataInfoId", - DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) - .request(APPLICATION_JSON).get(Map.class); - assertEquals(2, map.size()); - assertEquals(1, ((List) map.get("SUB")).size()); - assertEquals(1, ((List) map.get("PUB")).size()); - assertEquals(dataId, ((Map) ((List) map.get("SUB")).get(0)).get("dataId")); - assertEquals(dataId, ((Map) ((List) map.get("PUB")).get(0)).get("dataId")); - assertEquals(value, bytes2Object(publisherMap.get("PUB").get(0).getDataList().get(0) - .getBytes())); - } - - @Test - public void testetSessionDataByConnectId() throws Exception { - List connectIds = new ArrayList<>(); - connectIds.add(NetUtil.genHost(LOCAL_ADDRESS, getSourcePort(registryClient1)) - + ValueConstants.CONNECT_ID_SPLIT + NetUtil.genHost(LOCAL_ADDRESS, 9600)); - Map> publisherMap = sessionChannel + .queryParam( + "dataInfoId", DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP)) + .request(APPLICATION_JSON) + .get(Map.class); + assertEquals(2, map.size()); + assertEquals(1, ((List) map.get("SUB")).size()); + assertEquals(1, ((List) map.get("PUB")).size()); + assertEquals(dataId, ((Map) ((List) map.get("SUB")).get(0)).get("dataId")); + assertEquals(dataId, ((Map) ((List) map.get("PUB")).get(0)).get("dataId")); + assertEquals( + value, bytes2Object(publisherMap.get("PUB").get(0).getDataList().get(0).getBytes())); + } + + @Test + public void testetSessionDataByConnectId() throws Exception { + List connectIds = new ArrayList<>(); + connectIds.add( + NetUtil.genHost(LOCAL_ADDRESS, getSourcePort(registryClient1)) + + ValueConstants.CONNECT_ID_SPLIT + + NetUtil.genHost(LOCAL_ADDRESS, 9600)); + Map> publisherMap = + sessionChannel .getWebTarget() .path("digest/pub/connect/query") .request(APPLICATION_JSON) - .post(Entity.entity(connectIds, MediaType.APPLICATION_JSON), - new GenericType>>() { - }); - assertEquals(1, publisherMap.size()); - assertEquals(1, publisherMap.get("PUB").size()); - assertEquals(dataId, publisherMap.get("PUB").get(0).getDataId()); - assertEquals(value, bytes2Object(publisherMap.get("PUB").get(0).getDataList().get(0) - .getBytes())); - - Map> subscriberMap = sessionChannel + .post( + Entity.entity(connectIds, MediaType.APPLICATION_JSON), + new GenericType>>() {}); + assertEquals(1, publisherMap.size()); + assertEquals(1, publisherMap.get("PUB").size()); + assertEquals(dataId, publisherMap.get("PUB").get(0).getDataId()); + assertEquals( + value, bytes2Object(publisherMap.get("PUB").get(0).getDataList().get(0).getBytes())); + + Map> subscriberMap = + sessionChannel .getWebTarget() .path("digest/sub/connect/query") .request(APPLICATION_JSON) - .post(Entity.entity(connectIds, MediaType.APPLICATION_JSON), - new GenericType>>() { - }); - assertEquals(1, subscriberMap.size()); - assertEquals(1, subscriberMap.get("SUB").size()); - assertEquals(dataId, subscriberMap.get("SUB").get(0).getDataId()); - - Map map = sessionChannel.getWebTarget().path("digest/all/connect/query") + .post( + Entity.entity(connectIds, MediaType.APPLICATION_JSON), + new GenericType>>() {}); + assertEquals(1, subscriberMap.size()); + assertEquals(1, subscriberMap.get("SUB").size()); + assertEquals(dataId, subscriberMap.get("SUB").get(0).getDataId()); + + Map map = + sessionChannel + .getWebTarget() + .path("digest/all/connect/query") .request(APPLICATION_JSON) .post(Entity.entity(connectIds, MediaType.APPLICATION_JSON), Map.class); - assertEquals(2, map.size()); - assertEquals(1, ((List) map.get("SUB")).size()); - assertEquals(1, ((List) map.get("PUB")).size()); - assertEquals(dataId, ((Map) ((List) map.get("SUB")).get(0)).get("dataId")); - assertEquals(dataId, ((Map) ((List) map.get("PUB")).get(0)).get("dataId")); - assertEquals(value, bytes2Object(publisherMap.get("PUB").get(0).getDataList().get(0) - .getBytes())); - } - - @Test - public void testGetSessionDataCount() { - String result = sessionChannel.getWebTarget().path("digest/data/count") - .request(APPLICATION_JSON).get(String.class); - assertEquals("Subscriber count: 1, Publisher count: 1, Watcher count: 0", result); - } - - @Test - public void testGetPushSwitch() { - Map result = sessionChannel.getWebTarget().path("digest/pushSwitch") - .request(APPLICATION_JSON).get(Map.class); - assertEquals(1, result.size()); - assertEquals("open", result.get("pushSwitch")); - } - - @Test - public void testGetDataInfoIdList() { - Set result = sessionChannel.getWebTarget().path("digest/getDataInfoIdList") - .request(APPLICATION_JSON).get(Set.class); - - assertTrue(result.contains(DataInfo - .toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP))); - } - - @Test - public void testCheckSumDataInfoIdList() { - int result = sessionChannel.getWebTarget().path("digest/checkSumDataInfoIdList") - .request(APPLICATION_JSON).get(int.class); - assertTrue(result != 0); - } + assertEquals(2, map.size()); + assertEquals(1, ((List) map.get("SUB")).size()); + assertEquals(1, ((List) map.get("PUB")).size()); + assertEquals(dataId, ((Map) ((List) map.get("SUB")).get(0)).get("dataId")); + assertEquals(dataId, ((Map) ((List) map.get("PUB")).get(0)).get("dataId")); + assertEquals( + value, bytes2Object(publisherMap.get("PUB").get(0).getDataList().get(0).getBytes())); + } + + @Test + public void testGetSessionDataCount() { + String result = + sessionChannel + .getWebTarget() + .path("digest/data/count") + .request(APPLICATION_JSON) + .get(String.class); + assertEquals("Subscriber count: 1, Publisher count: 1, Watcher count: 0", result); + } + + @Test + public void testGetPushSwitch() { + Map result = + sessionChannel + .getWebTarget() + .path("digest/pushSwitch") + .request(APPLICATION_JSON) + .get(Map.class); + assertEquals(1, result.size()); + assertEquals("open", result.get("pushSwitch")); + } + + @Test + public void testGetDataInfoIdList() { + Set result = + sessionChannel + .getWebTarget() + .path("digest/getDataInfoIdList") + .request(APPLICATION_JSON) + .get(Set.class); + + assertTrue(result.contains(DataInfo.toDataInfoId(dataId, DEFAULT_INSTANCE_ID, DEFAULT_GROUP))); + } + + @Test + public void testCheckSumDataInfoIdList() { + int result = + sessionChannel + .getWebTarget() + .path("digest/checkSumDataInfoIdList") + .request(APPLICATION_JSON) + .get(int.class); + assertTrue(result != 0); + } } diff --git a/test/src/test/java/com/alipay/sofa/registry/test/resource/session/SessionOpenResourceTest.java b/test/src/test/java/com/alipay/sofa/registry/test/resource/session/SessionOpenResourceTest.java index dced23b2e..b217fc9cb 100644 --- a/test/src/test/java/com/alipay/sofa/registry/test/resource/session/SessionOpenResourceTest.java +++ b/test/src/test/java/com/alipay/sofa/registry/test/resource/session/SessionOpenResourceTest.java @@ -16,44 +16,51 @@ */ package com.alipay.sofa.registry.test.resource.session; +import static org.junit.Assert.assertEquals; + import com.alipay.sofa.registry.test.BaseIntegrationTest; +import java.util.List; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.junit4.SpringRunner; -import javax.ws.rs.core.GenericType; -import javax.ws.rs.core.MediaType; -import java.util.List; - -import static org.junit.Assert.assertEquals; - /** * @author xuanbei * @since 2019/1/14 */ @RunWith(SpringRunner.class) public class SessionOpenResourceTest extends BaseIntegrationTest { - @Test - public void testCheckAlive() { - String result = sessionChannel.getWebTarget().path("api/servers/alive").request() - .get(String.class); - assertEquals("OK", result); - } + @Test + public void testCheckAlive() { + String result = + sessionChannel.getWebTarget().path("api/servers/alive").request().get(String.class); + assertEquals("OK", result); + } - @Test - public void testGetSessionServerList() { - String result = sessionChannel.getWebTarget().path("api/servers/query") - .queryParam("zone", LOCAL_REGION).request().get(String.class); - assertEquals(LOCAL_ADDRESS + ":" + sessionServerPort, result); - } + @Test + public void testGetSessionServerList() { + String result = + sessionChannel + .getWebTarget() + .path("api/servers/query") + .queryParam("zone", LOCAL_REGION) + .request() + .get(String.class); + assertEquals(LOCAL_ADDRESS + ":" + sessionServerPort, result); + } - @Test - public void testGetSessionServerListJson() { - List result = sessionChannel.getWebTarget().path("api/servers/query.json") - .queryParam("zone", LOCAL_REGION).request(MediaType.APPLICATION_JSON) - .get(new GenericType>() { - }); - assertEquals(1, result.size()); - assertEquals(LOCAL_ADDRESS + ":" + sessionServerPort, result.get(0)); - } + @Test + public void testGetSessionServerListJson() { + List result = + sessionChannel + .getWebTarget() + .path("api/servers/query.json") + .queryParam("zone", LOCAL_REGION) + .request(MediaType.APPLICATION_JSON) + .get(new GenericType>() {}); + assertEquals(1, result.size()); + assertEquals(LOCAL_ADDRESS + ":" + sessionServerPort, result.get(0)); + } } diff --git a/tools/codestyle/HEADER b/tools/codestyle/HEADER index 0ed96c451..2944f9819 100644 --- a/tools/codestyle/HEADER +++ b/tools/codestyle/HEADER @@ -1,14 +1,16 @@ -Licensed to the Apache Software Foundation (ASF) under one or more -contributor license agreements. See the NOTICE file distributed with -this work for additional information regarding copyright ownership. -The ASF licenses this file to You under the Apache License, Version 2.0 -(the "License"); you may not use this file except in compliance with -the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/tools/codestyle/formatter.xml b/tools/codestyle/formatter.xml deleted file mode 100644 index 6fad4ebc4..000000000 --- a/tools/codestyle/formatter.xml +++ /dev/null @@ -1,295 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ No newline at end of file