diff --git a/client/all/pom.xml b/client/all/pom.xml
index ede8b8508..efd3d7917 100644
--- a/client/all/pom.xml
+++ b/client/all/pom.xml
@@ -6,7 +6,7 @@
com.alipay.sofa
registry-client-all
- 5.2.1
+ 5.3.0-SNAPSHOT
${project.groupId}:${project.artifactId}
http://github.com/alipay/sofa-registry
diff --git a/client/api/pom.xml b/client/api/pom.xml
index fd492459c..a546a370c 100644
--- a/client/api/pom.xml
+++ b/client/api/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-client-parent
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
diff --git a/client/impl/pom.xml b/client/impl/pom.xml
index 9b4b475e2..8631db0d6 100644
--- a/client/impl/pom.xml
+++ b/client/impl/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-client-parent
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
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 183ebb4ec..aba3677dc 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
@@ -16,6 +16,17 @@
*/
package com.alipay.sofa.registry.client.provider;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+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;
@@ -31,16 +42,6 @@
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;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.mock;
/**
* The type Default registry client test.
@@ -89,7 +90,7 @@ public void registerPublisher() throws InterruptedException {
defaultPublisher.republish("republish test");
- Thread.sleep(500L);
+ Thread.sleep(2000L);
// register success when republish
assertTrue(defaultPublisher.isRegistered());
}
@@ -111,7 +112,7 @@ public void handleData(String dataId, UserData data) {
assertNotNull(subscriber);
assertEquals(dataId, subscriber.getDataId());
- Thread.sleep(500L);
+ Thread.sleep(2000L);
RegisterCache registerCache = registryClient.getRegisterCache();
@@ -142,7 +143,7 @@ public void handleData(String dataId, ConfigData configData) {
assertNotNull(configurator);
assertEquals(dataId, configurator.getDataId());
- Thread.sleep(500L);
+ Thread.sleep(2000L);
RegisterCache registerCache = registryClient.getRegisterCache();
@@ -164,7 +165,7 @@ public void unregisterSinglePublisherTest() throws InterruptedException {
int unregisterCount = registryClient.unregister(dataId, null, RegistryType.PUBLISHER);
assertEquals(1, unregisterCount);
- Thread.sleep(500L);
+ Thread.sleep(2000L);
Publisher temp = registryClient.getRegisterCache().getPublisherByRegistId(
publisher.getRegistId());
@@ -185,7 +186,7 @@ public void unregisterSingleSubscriberTest() throws InterruptedException {
int unregisterCount = registryClient.unregister(dataId, null, RegistryType.SUBSCRIBER);
assertEquals(1, unregisterCount);
- Thread.sleep(500L);
+ Thread.sleep(2000L);
Subscriber temp = registryClient.getRegisterCache().getSubscriberByRegistId(
subscriber.getRegistId());
@@ -206,7 +207,7 @@ public void unregisterSingleConfiguratorTest() throws InterruptedException {
int unregisterCount = registryClient.unregister(dataId, null, RegistryType.CONFIGURATOR);
assertEquals(1, unregisterCount);
- Thread.sleep(500L);
+ Thread.sleep(2000L);
Subscriber temp = registryClient.getRegisterCache().getSubscriberByRegistId(
configurator.getRegistId());
@@ -236,13 +237,13 @@ public void unregisterMultiTest() throws InterruptedException {
Subscriber subscriber2 = registryClient.register(subscriberRegistration2);
- Thread.sleep(500L);
+ Thread.sleep(2000L);
// 2. unregister publisher
int unregisterCount = registryClient.unregister(dataId, null, RegistryType.PUBLISHER);
assertEquals(2, unregisterCount);
- Thread.sleep(500L);
+ Thread.sleep(2000L);
// 3. check publisher register cache
RegisterCache registerCache = registryClient.getRegisterCache();
@@ -256,7 +257,7 @@ public void unregisterMultiTest() throws InterruptedException {
unregisterCount = registryClient.unregister(dataId, null, RegistryType.SUBSCRIBER);
assertEquals(2, unregisterCount);
- Thread.sleep(500L);
+ Thread.sleep(2000L);
// 5. check subscriber register cache
Subscriber tempSub = registerCache.getSubscriberByRegistId(subscriber1.getRegistId());
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 90117a8aa..2e23dd731 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
@@ -16,6 +16,20 @@
*/
package com.alipay.sofa.registry.client.provider;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+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;
@@ -26,19 +40,6 @@
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 org.junit.After;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.List;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
/**
*
@@ -126,7 +127,7 @@ public void publishAndUnregister() throws InterruptedException {
// step 1
Publisher publisher = registryClient.register(new PublisherRegistration(dataId), data);
- Thread.sleep(500L);
+ Thread.sleep(2000L);
String registId = publisher.getRegistId();
PublisherRegister publisherRegister = mockServer.queryPubliser(registId);
@@ -137,7 +138,7 @@ public void publishAndUnregister() throws InterruptedException {
// step 2
publisher.unregister();
- Thread.sleep(500L);
+ Thread.sleep(2000L);
assertNull(mockServer.queryPubliser(registId));
@@ -151,7 +152,7 @@ public void publishAndRefused() throws InterruptedException {
// step 1
Publisher publisher = registryClient.register(new PublisherRegistration(data), data);
- Thread.sleep(500L);
+ Thread.sleep(2000L);
String registId = publisher.getRegistId();
PublisherRegister publisherRegister = mockServer.queryPubliser(registId);
@@ -182,7 +183,7 @@ public void handleData(String dataId, UserData data) {
Subscriber subscriber = registryClient.register(new SubscriberRegistration(dataId,
dataObserver));
- Thread.sleep(500L);
+ Thread.sleep(2000L);
String registId = subscriber.getRegistId();
SubscriberRegister subscriberRegister = mockServer.querySubscriber(registId);
@@ -191,7 +192,7 @@ public void handleData(String dataId, UserData data) {
// step 2
subscriber.unregister();
- Thread.sleep(500L);
+ Thread.sleep(2000L);
assertNull(mockServer.queryPubliser(registId));
@@ -211,7 +212,7 @@ public void handleData(String dataId, UserData data) {
Subscriber subscriber = registryClient.register(new SubscriberRegistration(
"subscribeAndRefused", dataObserver));
- Thread.sleep(500L);
+ Thread.sleep(2000L);
String registId = subscriber.getRegistId();
SubscriberRegister subscriberRegister = mockServer.querySubscriber(registId);
diff --git a/client/log/pom.xml b/client/log/pom.xml
index 3a4fadafe..04d11fb22 100644
--- a/client/log/pom.xml
+++ b/client/log/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-client-parent
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
diff --git a/client/pom.xml b/client/pom.xml
index 81e03c0ee..06f6a72a6 100644
--- a/client/pom.xml
+++ b/client/pom.xml
@@ -7,7 +7,7 @@
com.alipay.sofa
registry-parent
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
diff --git a/core/pom.xml b/core/pom.xml
index eb3274277..8b9bf5306 100644
--- a/core/pom.xml
+++ b/core/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-parent
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
diff --git a/pom.xml b/pom.xml
index 06131c07f..19d72061d 100644
--- a/pom.xml
+++ b/pom.xml
@@ -2,11 +2,11 @@
-
4.0.0
+
com.alipay.sofa
registry-parent
- 5.2.1
+ 5.3.0-SNAPSHOT
pom
${project.groupId}:${project.artifactId}
@@ -307,6 +307,12 @@
${metrics.version}
+
+ commons-collections
+ commons-collections
+ 3.2.2
+
+
junit
@@ -396,6 +402,9 @@
org.apache.maven.plugins
maven-surefire-plugin
2.21.0
+
+ once
+
org.jacoco
diff --git a/server/common/model/pom.xml b/server/common/model/pom.xml
index 3c1143ac3..48974de3d 100644
--- a/server/common/model/pom.xml
+++ b/server/common/model/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-common
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
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 e85455adf..72f7d5591 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
@@ -108,4 +108,16 @@ public String getMessage() {
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
diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/DatumSnapshotRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/DatumSnapshotRequest.java
new file mode 100644
index 000000000..0b517fa61
--- /dev/null
+++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/DatumSnapshotRequest.java
@@ -0,0 +1,84 @@
+/*
+ * 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.
+ */
+package com.alipay.sofa.registry.common.model;
+
+import java.io.Serializable;
+import java.util.List;
+
+import com.alipay.sofa.registry.common.model.store.Publisher;
+
+/**
+ *
+ * @author shangyu.wh
+ * @version $Id: DatumSnapshotRequest.java, v 0.1 2019-05-30 11:09 shangyu.wh Exp $
+ */
+public class DatumSnapshotRequest implements Serializable {
+
+ private static final long serialVersionUID = 2193212935059863551L;
+
+ private final String connectId;
+
+ private final String dataServerIp;
+
+ private final List publishers;
+
+ public DatumSnapshotRequest(String connectId, String dataServerIp, List publishers) {
+ this.connectId = connectId;
+ this.dataServerIp = dataServerIp;
+ this.publishers = publishers;
+ }
+
+ /**
+ * Getter method for property connectId.
+ *
+ * @return property value of connectId
+ */
+ public String getConnectId() {
+ return connectId;
+ }
+
+ /**
+ * Getter method for property dataServerIp.
+ *
+ * @return property value of dataServerIp
+ */
+ public String getDataServerIp() {
+ return dataServerIp;
+ }
+
+ /**
+ * Getter method for property publishers.
+ *
+ * @return property value of publishers
+ */
+ public List getPublishers() {
+ return publishers;
+ }
+
+ /**
+ * @see Object#toString()
+ */
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("DatumSnapshotRequest{");
+ sb.append("connectId='").append(connectId).append('\'');
+ sb.append(", dataServerIp='").append(dataServerIp).append('\'');
+ sb.append(", publishers.size=").append(publishers.size());
+ sb.append('}');
+ return sb.toString();
+ }
+}
\ No newline at end of file
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
new file mode 100644
index 000000000..67ad72236
--- /dev/null
+++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/PublisherDigestUtil.java
@@ -0,0 +1,50 @@
+/*
+ * 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.
+ */
+package com.alipay.sofa.registry.common.model;
+
+import java.util.Collection;
+
+import com.alipay.sofa.registry.common.model.store.Publisher;
+
+/**
+ *
+ * @author kezhu.wukz
+ * @author shangyu.wh
+ * @version $Id: PublisherDigestUtil.java, v 0.1 2019-05-30 20:58 shangyu.wh Exp $
+ */
+public class PublisherDigestUtil {
+
+ public static long getDigestValueSum(Collection publishers) {
+ long digest = 0L;
+ if (publishers != null && !publishers.isEmpty()) {
+ for (Publisher publisher : publishers) {
+ digest += getDigestValue(publisher);
+ }
+ }
+ return digest;
+ }
+
+ public static long getDigestValue(Publisher publisher) {
+ String registerId = publisher.getRegisterId();
+ Long version = publisher.getVersion();
+ long registerTimestamp = publisher.getRegisterTimestamp();
+ long result = registerId != null ? registerId.hashCode() : 0;
+ result = 31 * result + (version != null ? version.hashCode() : 0);
+ result = 31 * result + (int) (registerTimestamp ^ (registerTimestamp >>> 32));
+ return result;
+ }
+}
\ No newline at end of file
diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/RenewDatumRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/RenewDatumRequest.java
new file mode 100644
index 000000000..603c40fb3
--- /dev/null
+++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/RenewDatumRequest.java
@@ -0,0 +1,82 @@
+/*
+ * 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.
+ */
+package com.alipay.sofa.registry.common.model;
+
+import java.io.Serializable;
+
+/**
+ *
+ * @author shangyu.wh
+ * @author kezhu.wukz
+ * @version $Id: RenewRequest.java, v 0.1 2019-05-30 10:58 shangyu.wh Exp $
+ */
+public class RenewDatumRequest implements Serializable {
+
+ private static final long serialVersionUID = 683097441984338311L;
+
+ private final String connectId;
+
+ private final String dataServerIP;
+
+ private final String digestSum;
+
+ public RenewDatumRequest(String connectId, String dataServerIP, String digestSum) {
+ this.connectId = connectId;
+ this.dataServerIP = dataServerIP;
+ this.digestSum = digestSum;
+ }
+
+ /**
+ * Getter method for property connectId.
+ *
+ * @return property value of connectId
+ */
+ public String getConnectId() {
+ return connectId;
+ }
+
+ /**
+ * Getter method for property dataServerIP.
+ *
+ * @return property value of dataServerIP
+ */
+ public String getDataServerIP() {
+ return dataServerIP;
+ }
+
+ /**
+ * Getter method for property digestSum.
+ *
+ * @return property value of digestSum
+ */
+ public String getDigestSum() {
+ return digestSum;
+ }
+
+ /**
+ * @see Object#toString()
+ */
+ @Override
+ public String toString() {
+ final StringBuilder sb = new StringBuilder("RenewDatumRequest{");
+ sb.append("connectId='").append(connectId).append('\'');
+ sb.append(", dataServerIP='").append(dataServerIP).append('\'');
+ sb.append(", digestSum='").append(digestSum).append('\'');
+ sb.append('}');
+ return sb.toString();
+ }
+}
\ No newline at end of file
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 bd6f20409..005127563 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
@@ -56,4 +56,12 @@ public class ValueConstants {
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 ENABLE_DATA_RENEW_SNAPSHOT = "session.enable.datum.renew.switch#@#9600#@#CONFIG";
+
+ public static final String ENABLE_DATA_DATUM_EXPIRE = "data.enable.datum.expire.switch#@#9600#@#CONFIG";
+
+ public static final String LOGGER_NAME_RENEW = "RENEW-LOGGER";
+
}
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 61044ea8f..246363fa0 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,13 +16,14 @@
*/
package com.alipay.sofa.registry.common.model.dataserver;
-import com.alipay.sofa.registry.common.model.store.Publisher;
-import com.alipay.sofa.registry.common.model.store.WordCache;
-
import java.io.Serializable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
+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;
+
/**
* datum store in dataserver
*
@@ -96,7 +97,7 @@ public Datum(Publisher publisher, String dataCenter, long version) {
}
public void updateVersion() {
- this.version = System.currentTimeMillis();
+ this.version = DatumVersionUtil.nextId();
}
/**
diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/SessionServerRegisterRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/SessionServerRegisterRequest.java
index 16f00f56b..b852aa3ef 100644
--- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/SessionServerRegisterRequest.java
+++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/SessionServerRegisterRequest.java
@@ -30,16 +30,16 @@ public class SessionServerRegisterRequest implements Serializable {
private String processId;
- private Set clientHosts;
+ private Set connectIds;
/**
* constructor
* @param processId
- * @param clientHosts
+ * @param connectIds
*/
- public SessionServerRegisterRequest(String processId, Set clientHosts) {
+ public SessionServerRegisterRequest(String processId, Set connectIds) {
this.processId = processId;
- this.clientHosts = clientHosts;
+ this.connectIds = connectIds;
}
/**
@@ -61,17 +61,17 @@ public void setProcessId(String processId) {
}
/**
- * Getter method for property clientHosts.
+ * Getter method for property connectIds.
*
- * @return property value of clientHosts
+ * @return property value of connectIds
*/
- public Set getClientHosts() {
- return clientHosts;
+ public Set getConnectIds() {
+ return connectIds;
}
@Override
public String toString() {
return new StringBuilder("[SessionServerRegisterRequest] processId=")
- .append(this.processId).append(", clientHosts=").append(this.clientHosts).toString();
+ .append(this.processId).append(", connectIds=").append(this.connectIds).toString();
}
}
\ No newline at end of file
diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/UnPublishDataRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/UnPublishDataRequest.java
index cfa8554ac..33fbdbf0c 100644
--- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/UnPublishDataRequest.java
+++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/dataserver/UnPublishDataRequest.java
@@ -34,12 +34,6 @@ public class UnPublishDataRequest implements Serializable {
private long registerTimestamp;
- /**
- * constructor
- */
- public UnPublishDataRequest() {
- }
-
/**
* construtor
* @param dataInfoId
diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/NotifyProvideDataChange.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/NotifyProvideDataChange.java
index ad14df8f0..a72d16d12 100644
--- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/NotifyProvideDataChange.java
+++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/NotifyProvideDataChange.java
@@ -16,6 +16,8 @@
*/
package com.alipay.sofa.registry.common.model.metaserver;
+import com.alipay.sofa.registry.common.model.Node.NodeType;
+
import java.io.Serializable;
/**
@@ -31,6 +33,8 @@ public class NotifyProvideDataChange implements Serializable {
private DataOperator dataOperator;
+ private NodeType nodeType = NodeType.SESSION;
+
/**
* constructor
* @param dataInfoId
@@ -97,12 +101,31 @@ public void setDataOperator(DataOperator dataOperator) {
this.dataOperator = dataOperator;
}
+ /**
+ * Getter method for property nodeType.
+ *
+ * @return property value of nodeType
+ */
+ public NodeType getNodeType() {
+ return nodeType;
+ }
+
+ /**
+ * Setter method for property nodeType.
+ *
+ * @param nodeType value to be assigned to property nodeType
+ */
+ public void setNodeType(NodeType nodeType) {
+ this.nodeType = nodeType;
+ }
+
@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(", nodeType=").append(nodeType);
sb.append('}');
return sb.toString();
}
diff --git a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ReNewNodesRequest.java b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/RenewNodesRequest.java
similarity index 92%
rename from server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ReNewNodesRequest.java
rename to server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/RenewNodesRequest.java
index 50485e65c..0794e5152 100644
--- a/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/ReNewNodesRequest.java
+++ b/server/common/model/src/main/java/com/alipay/sofa/registry/common/model/metaserver/RenewNodesRequest.java
@@ -16,16 +16,16 @@
*/
package com.alipay.sofa.registry.common.model.metaserver;
-import com.alipay.sofa.registry.common.model.Node;
-
import java.io.Serializable;
+import com.alipay.sofa.registry.common.model.Node;
+
/**
*
* @author shangyu.wh
* @version $Id: RenewNodesRequest.java, v 0.1 2018-03-30 19:51 shangyu.wh Exp $
*/
-public class ReNewNodesRequest implements Serializable {
+public class RenewNodesRequest implements Serializable {
private int duration;
@@ -35,7 +35,7 @@ public class ReNewNodesRequest implements Serializable {
* constructor
* @param node
*/
- public ReNewNodesRequest(T node) {
+ public RenewNodesRequest(T node) {
this.node = node;
}
@@ -68,7 +68,7 @@ public T getNode() {
@Override
public String toString() {
- final StringBuilder sb = new StringBuilder("ReNewNodesRequest{");
+ final StringBuilder sb = new StringBuilder("RenewNodesRequest{");
sb.append("duration=").append(duration);
sb.append(", node=").append(node);
sb.append('}');
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 1ec2d9a66..5746a45f8 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
@@ -27,7 +27,7 @@ public interface StoreData {
* DataType enum
*/
enum DataType {
- SUBSCRIBER, PUBLISHER, WATCHER, UNPUBLISHER
+ SUBSCRIBER, PUBLISHER, WATCHER, UN_PUBLISHER
}
/**
diff --git a/server/common/pom.xml b/server/common/pom.xml
index 7b6197896..0c4e482e3 100644
--- a/server/common/pom.xml
+++ b/server/common/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-server-parent
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
diff --git a/server/common/util/pom.xml b/server/common/util/pom.xml
index 620f9a2cd..a41fc6708 100644
--- a/server/common/util/pom.xml
+++ b/server/common/util/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-common
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
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 fb5f24e36..7cc79bc33 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
@@ -16,12 +16,13 @@
*/
package com.alipay.sofa.registry.metrics;
+import java.util.concurrent.TimeUnit;
+
import com.alipay.sofa.registry.log.Logger;
+import com.alipay.sofa.registry.log.LoggerFactory;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Slf4jReporter;
-import java.util.concurrent.TimeUnit;
-
/**
*
* @author shangyu.wh
@@ -29,6 +30,8 @@
*/
public class ReporterUtils {
+ private static final Logger METRIC_LOGGER = LoggerFactory.getLogger("REGISTRY-METRICS");
+
/**
* start slf4j reporter
* @param period
@@ -46,4 +49,13 @@ public static void startSlf4jReporter(long period, MetricRegistry registry, Logg
}
}
+
+ /**
+ * start slf4j reporter
+ * @param period
+ * @param registry
+ */
+ public static void startSlf4jReporter(long period, MetricRegistry registry) {
+ startSlf4jReporter(period, registry, METRIC_LOGGER);
+ }
}
\ No newline at end of file
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 3e1d354a4..d081446b9 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
@@ -16,12 +16,12 @@
*/
package com.alipay.sofa.registry.task.listener;
-import com.alipay.sofa.registry.task.TaskClosure;
-
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
+import com.alipay.sofa.registry.task.TaskClosure;
+
/**
*
* @author shangyu.wh
@@ -43,9 +43,12 @@ public enum TaskType {
"SyncPublisherTask"), SYNC_SUBSCRIBER_TASK(
"SyncSubscriberTask"), SESSION_REGISTER_DATA_TASK(
"SessionRegisterDataTask"), PROVIDE_DATA_CHANGE_FETCH_TASK(
- "ProvideDataChangeFetchTask"),
-
- SUBSCRIBER_MULTI_FETCH_TASK("SubscriberMultiFetchTask"),
+ "ProvideDataChangeFetchTask"), SUBSCRIBER_MULTI_FETCH_TASK(
+ "SubscriberMultiFetchTask"), PUBLISH_DATA_TASK(
+ "PublishDataTask"), UN_PUBLISH_DATA_TASK(
+ "UnPublishDataTask"), RENEW_DATUM_TASK(
+ "RenewDatumTask"), DATUM_SNAPSHOT_TASK(
+ "DatumSnapshotTask"),
//Session Adapter task
USER_DATA_ELEMENT_PUSH_TASK("UserDataElementPushTask"), USER_DATA_ELEMENT_MULTI_PUSH_TASK(
@@ -55,7 +58,7 @@ public enum TaskType {
SESSION_NODE_CHANGE_PUSH_TASK("SessionNodeChangePushTask"), DATA_NODE_CHANGE_PUSH_TASK(
"DataNodeChangePushTask"), RECEIVE_STATUS_CONFIRM_NOTIFY_TASK(
"ReceiveStatusConfirmNotifyTask"), PERSISTENCE_DATA_CHANGE_NOTIFY_TASK(
- "PersistenceDataChangeNotifyTask");
+ "PersistenceDataChangeNotifyTask"), ;
private String name;
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 f6cd4d206..7119a88a8 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,45 +16,66 @@
*/
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;
-import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
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
*
- * @author kezhu.wukz
+ * @author kezhu.wukz
* @version $Id: AsyncHashedWheelTimer.java, v 0.1 2019-01-11 10:54 AM kezhu.wukz Exp $
*/
public class AsyncHashedWheelTimer extends HashedWheelTimer {
/** */
- private final Executor executor;
+ protected final Executor executor;
/** */
- private final TaskFailedCallback taskFailedCallback;
+ 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, ThreadFactory asyncThreadFactory,
+ int ticksPerWheel, int threadSize, int queueSize,
+ ThreadFactory asyncThreadFactory,
TaskFailedCallback taskFailedCallback) {
super(threadFactory, tickDuration, unit, ticksPerWheel);
- this.executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,
- new SynchronousQueue<>(), asyncThreadFactory);
+ 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;
}
@@ -85,14 +106,14 @@ public AsyncTimerTask(TimerTask timerTask) {
/**
*/
@Override
- public void run(Timeout timeout) throws Exception {
+ public void run(Timeout timeout) {
this.timeout = timeout;
try {
AsyncHashedWheelTimer.this.executor.execute(this);
} catch (RejectedExecutionException e) {
taskFailedCallback.executionRejected(e);
} catch (Throwable e) {
- taskFailedCallback.executionRejected(e);
+ taskFailedCallback.executionFailed(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
new file mode 100644
index 000000000..fb3a0bd63
--- /dev/null
+++ b/server/common/util/src/main/java/com/alipay/sofa/registry/timer/RecycleAsyncHashedWheelTimer.java
@@ -0,0 +1,125 @@
+/*
+ * 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.
+ */
+package com.alipay.sofa.registry.timer;
+
+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, 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;
+ }
+
+ /**
+ */
+ @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/util/DatumVersionUtil.java b/server/common/util/src/main/java/com/alipay/sofa/registry/util/DatumVersionUtil.java
new file mode 100644
index 000000000..78112433b
--- /dev/null
+++ b/server/common/util/src/main/java/com/alipay/sofa/registry/util/DatumVersionUtil.java
@@ -0,0 +1,79 @@
+/*
+ * 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.
+ */
+package com.alipay.sofa.registry.util;
+
+/**
+ * generates ID: 49 bit millisecond timestamp + 15 bit incremental ID
+ *
+ * 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 class DatumVersionUtil {
+
+ private static long sequence = 0L;
+
+ /** Tue Jan 01 00:00:00 CST 2019 */
+ private static long twepoch = 1546272000000L;
+
+ private static long sequenceBits = 15L;
+ private static long timestampLeftShift = sequenceBits;
+ private static long sequenceMask = -1L ^ (-1L << sequenceBits);
+
+ private static long lastTimestamp = -1L;
+
+ public synchronized static long nextId() {
+ long timestamp = timeGen();
+
+ if (timestamp < lastTimestamp) {
+ throw new RuntimeException(String.format(
+ "Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp
+ - timestamp));
+ }
+
+ if (lastTimestamp == timestamp) {
+ sequence = (sequence + 1) & sequenceMask;
+ if (sequence == 0) {
+ timestamp = untilNextMillis(lastTimestamp);
+ }
+ } else {
+ sequence = 0L;
+ }
+
+ lastTimestamp = timestamp;
+
+ return ((timestamp - twepoch) << timestampLeftShift) | sequence;
+ }
+
+ public static long getRealTimestamp(long id) {
+ return (id >> timestampLeftShift) + twepoch;
+ }
+
+ private static long untilNextMillis(long lastTimestamp) {
+ long timestamp = timeGen();
+ while (timestamp <= lastTimestamp) {
+ timestamp = timeGen();
+ }
+ return timestamp;
+ }
+
+ private static long timeGen() {
+ return System.currentTimeMillis();
+ }
+
+}
\ No newline at end of file
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 11b63f53b..dbabd7faf 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,13 +16,15 @@
*/
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 java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+
+import io.netty.util.Timer;
/**
* @author xuanbei
@@ -40,7 +42,7 @@ public void doTest() throws InterruptedException {
ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
threadFactoryBuilder.setDaemon(true);
final Timer timer = new AsyncHashedWheelTimer(threadFactoryBuilder.setNameFormat(
- "AsyncHashedWheelTimerTest").build(), 50, TimeUnit.MILLISECONDS, 10,
+ "AsyncHashedWheelTimerTest").build(), 50, TimeUnit.MILLISECONDS, 10, 5, 10,
threadFactoryBuilder.setNameFormat("Registry-DataNodeServiceImpl-WheelExecutor-%d")
.build(), new AsyncHashedWheelTimer.TaskFailedCallback() {
@Override
diff --git a/server/consistency/pom.xml b/server/consistency/pom.xml
index 46013874e..9c52b6b98 100644
--- a/server/consistency/pom.xml
+++ b/server/consistency/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-server-parent
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
diff --git a/server/distribution/data/pom.xml b/server/distribution/data/pom.xml
index ca808857c..444cabe65 100644
--- a/server/distribution/data/pom.xml
+++ b/server/distribution/data/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-distribution
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
diff --git a/server/distribution/integration/pom.xml b/server/distribution/integration/pom.xml
index c76f59ed8..8118951ca 100644
--- a/server/distribution/integration/pom.xml
+++ b/server/distribution/integration/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-distribution
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
diff --git a/server/distribution/meta/pom.xml b/server/distribution/meta/pom.xml
index 3cdc41546..512053820 100644
--- a/server/distribution/meta/pom.xml
+++ b/server/distribution/meta/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-distribution
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
diff --git a/server/distribution/pom.xml b/server/distribution/pom.xml
index 67cf7b9ba..ec4b3de52 100644
--- a/server/distribution/pom.xml
+++ b/server/distribution/pom.xml
@@ -6,7 +6,7 @@
com.alipay.sofa
registry-server-parent
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
diff --git a/server/distribution/session/pom.xml b/server/distribution/session/pom.xml
index 7f9fdd96d..ca9f732ec 100644
--- a/server/distribution/session/pom.xml
+++ b/server/distribution/session/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-distribution
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
diff --git a/server/pom.xml b/server/pom.xml
index c06d833c3..d2f9f1782 100644
--- a/server/pom.xml
+++ b/server/pom.xml
@@ -7,7 +7,7 @@
com.alipay.sofa
registry-parent
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
diff --git a/server/remoting/api/pom.xml b/server/remoting/api/pom.xml
index 68ef027a5..620b1f1e2 100644
--- a/server/remoting/api/pom.xml
+++ b/server/remoting/api/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-remoting
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
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 7452bb4f4..900bedbcd 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,11 +16,11 @@
*/
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
@@ -57,4 +57,6 @@ public interface Server extends Endpoint {
* @return channel
*/
Channel getChannel(URL url);
+
+ int getChannelCount();
}
\ No newline at end of file
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 3340bbf4b..6f00d8edb 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
@@ -77,14 +77,14 @@ public RequestException(Throwable cause) {
* get requestInfo from Request
* @return
*/
- public String getRequestMessage() {
+ @Override
+ public String getMessage() {
StringBuilder sb = new StringBuilder();
if (request != null) {
- sb.append("Request url:").append(request.getRequestUrl()).append(" body:")
- .append(request.getRequestBody());
- } else {
- sb.append("Request data can not be null!");
+ sb.append("request url: ").append(request.getRequestUrl()).append(", body: ")
+ .append(request.getRequestBody()).append(", ");
}
+ sb.append(super.getMessage());
return sb.toString();
}
}
\ No newline at end of file
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 7f98cc690..03c7f8526 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,11 +16,12 @@
*/
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
@@ -31,18 +32,16 @@ public class RequestExceptionTest {
public void doTest() {
RequestException exception = new RequestException("error message");
Assert.assertEquals("error message", exception.getMessage());
- Assert.assertEquals("Request data can not be null!", exception.getRequestMessage());
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("Request data can not be null!", exception.getRequestMessage());
+ 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());
- Assert.assertEquals("Request data can not be null!", exception.getRequestMessage());
Request request = new Request() {
@Override
@@ -56,11 +55,11 @@ public URL getRequestUrl() {
}
};
exception = new RequestException("error message", request);
- Assert.assertEquals("error message", exception.getMessage());
- Assert.assertEquals("Request url:null body:request body", exception.getRequestMessage());
+ Assert.assertEquals("request url: null, body: request body, error message",
+ exception.getMessage());
exception = new RequestException("error message", request, runtimeException);
- Assert.assertEquals("error message", exception.getMessage());
- Assert.assertEquals("Request url:null body:request body", exception.getRequestMessage());
+ Assert.assertEquals("request url: null, body: request body, error message",
+ exception.getMessage());
}
}
diff --git a/server/remoting/bolt/pom.xml b/server/remoting/bolt/pom.xml
index f8ce4f01b..2f7d8a849 100644
--- a/server/remoting/bolt/pom.xml
+++ b/server/remoting/bolt/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-remoting
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
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 e9fc9ed38..af2c3d71a 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,6 +16,16 @@
*/
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.Connection;
import com.alipay.remoting.ConnectionEventType;
import com.alipay.remoting.InvokeCallback;
@@ -33,16 +43,6 @@
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
@@ -342,4 +342,9 @@ public void removeChannel(Channel channel) {
public RpcServer getRpcServer() {
return boltServer;
}
+
+ @Override
+ public int getChannelCount() {
+ return channels.size();
+ }
}
\ No newline at end of file
diff --git a/server/remoting/http/pom.xml b/server/remoting/http/pom.xml
index 10ba2a2df..bff60eaf9 100644
--- a/server/remoting/http/pom.xml
+++ b/server/remoting/http/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-remoting
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
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 680384881..9907c2f31 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,15 @@
*/
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.ChannelHandler;
-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.List;
+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,13 +36,14 @@
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.spi.Container;
-import javax.ws.rs.ProcessingException;
-import java.net.InetSocketAddress;
-import java.net.URI;
-import java.util.Collection;
-import java.util.List;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.atomic.AtomicBoolean;
+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.ChannelHandler;
+import com.alipay.sofa.registry.remoting.Server;
+import com.alipay.sofa.registry.remoting.jersey.jetty.server.HttpConnectionCustomFactory;
/**
*
@@ -224,4 +226,9 @@ public URI getBaseUri() {
return baseUri;
}
+ @Override
+ public int getChannelCount() {
+ return 0;
+ }
+
}
\ No newline at end of file
diff --git a/server/remoting/pom.xml b/server/remoting/pom.xml
index 9a2d45c9c..29e168179 100644
--- a/server/remoting/pom.xml
+++ b/server/remoting/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-server-parent
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
diff --git a/server/server/data/pom.xml b/server/server/data/pom.xml
index 6eb886b28..cefa28648 100644
--- a/server/server/data/pom.xml
+++ b/server/server/data/pom.xml
@@ -5,7 +5,7 @@
com.alipay.sofa
registry-server
- 5.2.1
+ 5.3.0-SNAPSHOT
../pom.xml
4.0.0
@@ -73,6 +73,10 @@
commons-lang
commons-lang
+
+ commons-collections
+ commons-collections
+
junit
junit
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 776982906..155861aab 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
@@ -16,17 +16,35 @@
*/
package com.alipay.sofa.registry.server.data.bootstrap;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+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.beans.factory.annotation.Autowired;
+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.Import;
+
import com.alipay.sofa.registry.remoting.bolt.exchange.BoltExchange;
import com.alipay.sofa.registry.remoting.exchange.Exchange;
import com.alipay.sofa.registry.remoting.jersey.exchange.JerseyExchange;
+import com.alipay.sofa.registry.server.data.cache.CacheDigestTask;
import com.alipay.sofa.registry.server.data.cache.DataServerCache;
+import com.alipay.sofa.registry.server.data.cache.DatumCache;
import com.alipay.sofa.registry.server.data.change.DataChangeHandler;
import com.alipay.sofa.registry.server.data.change.event.DataChangeEventCenter;
import com.alipay.sofa.registry.server.data.change.notify.BackUpNotifier;
import com.alipay.sofa.registry.server.data.change.notify.IDataChangeNotifier;
import com.alipay.sofa.registry.server.data.change.notify.SessionServerNotifier;
+import com.alipay.sofa.registry.server.data.change.notify.SnapshotBackUpNotifier;
import com.alipay.sofa.registry.server.data.change.notify.TempPublisherNotifier;
-import com.alipay.sofa.registry.server.data.correction.LocalDataServerCleanHandler;
import com.alipay.sofa.registry.server.data.datasync.AcceptorStore;
import com.alipay.sofa.registry.server.data.datasync.SyncDataService;
import com.alipay.sofa.registry.server.data.datasync.sync.LocalAcceptorStore;
@@ -53,12 +71,13 @@
import com.alipay.sofa.registry.server.data.remoting.dataserver.handler.SyncDataHandler;
import com.alipay.sofa.registry.server.data.remoting.dataserver.task.AbstractTask;
import com.alipay.sofa.registry.server.data.remoting.dataserver.task.ConnectionRefreshTask;
-import com.alipay.sofa.registry.server.data.remoting.dataserver.task.ReNewNodeTask;
+import com.alipay.sofa.registry.server.data.remoting.dataserver.task.RenewNodeTask;
import com.alipay.sofa.registry.server.data.remoting.handler.AbstractClientHandler;
import com.alipay.sofa.registry.server.data.remoting.handler.AbstractServerHandler;
import com.alipay.sofa.registry.server.data.remoting.metaserver.DefaultMetaServiceImpl;
import com.alipay.sofa.registry.server.data.remoting.metaserver.IMetaServerService;
import com.alipay.sofa.registry.server.data.remoting.metaserver.MetaServerConnectionFactory;
+import com.alipay.sofa.registry.server.data.remoting.metaserver.handler.NotifyProvideDataChangeHandler;
import com.alipay.sofa.registry.server.data.remoting.metaserver.handler.ServerChangeHandler;
import com.alipay.sofa.registry.server.data.remoting.metaserver.handler.StatusConfirmHandler;
import com.alipay.sofa.registry.server.data.remoting.metaserver.task.ConnectionRefreshMetaTask;
@@ -68,26 +87,20 @@
import com.alipay.sofa.registry.server.data.remoting.sessionserver.forward.ForwardServiceImpl;
import com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.ClientOffHandler;
import com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.DataServerConnectionHandler;
+import com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.DatumSnapshotHandler;
import com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.GetDataHandler;
import com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.GetDataVersionsHandler;
import com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.PublishDataHandler;
+import com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.RenewDatumHandler;
import com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.SessionServerRegisterHandler;
import com.alipay.sofa.registry.server.data.remoting.sessionserver.handler.UnPublishDataHandler;
+import com.alipay.sofa.registry.server.data.renew.DatumLeaseManager;
+import com.alipay.sofa.registry.server.data.renew.LocalDataServerCleanHandler;
import com.alipay.sofa.registry.server.data.resource.DataDigestResource;
import com.alipay.sofa.registry.server.data.resource.HealthResource;
+import com.alipay.sofa.registry.server.data.util.ThreadPoolExecutorDataServer;
+import com.alipay.sofa.registry.util.NamedThreadFactory;
import com.alipay.sofa.registry.util.PropertySplitter;
-import org.glassfish.jersey.jackson.JacksonFeature;
-import org.glassfish.jersey.server.ResourceConfig;
-import org.springframework.beans.factory.annotation.Autowired;
-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.Import;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
/**
*
@@ -114,7 +127,8 @@ public CommonConfig commonConfig() {
}
@Bean
- public DataServerConfig dataServerBootstrapConfig(CommonConfig commonConfig) {
+ @ConditionalOnMissingBean(name = "dataServerConfig")
+ public DataServerConfig dataServerConfig(CommonConfig commonConfig) {
return new DataServerConfig(commonConfig);
}
@@ -123,10 +137,26 @@ public DataNodeStatus dataNodeStatus() {
return new DataNodeStatus();
}
+ @Bean
+ public DatumCache datumCache() {
+ return new DatumCache();
+ }
+
@Bean(name = "PropertySplitter")
public PropertySplitter propertySplitter() {
return new PropertySplitter();
}
+
+ }
+
+ @Configuration
+ public static class LogTaskConfigConfiguration {
+
+ @Bean
+ public CacheDigestTask cacheDigestTask() {
+ return new CacheDigestTask();
+ }
+
}
@Configuration
@@ -177,23 +207,25 @@ public MetaServerConnectionFactory metaServerConnectionFactory() {
}
@Bean(name = "serverHandlers")
- public Collection serverHandlers(DataServerConfig dataServerBootstrapConfig) {
+ public Collection serverHandlers(DataServerConfig dataServerConfig) {
Collection list = new ArrayList<>();
list.add(getDataHandler());
list.add(clientOffHandler());
list.add(getDataVersionsHandler());
- list.add(publishDataProcessor(dataServerBootstrapConfig));
+ list.add(publishDataProcessor());
list.add(sessionServerRegisterHandler());
list.add(unPublishDataHandler());
list.add(dataServerConnectionHandler());
+ list.add(renewDatumHandler());
+ list.add(datumSnapshotHandler());
return list;
}
@Bean(name = "serverSyncHandlers")
- public Collection serverSyncHandlers(DataServerConfig dataServerBootstrapConfig) {
+ public Collection serverSyncHandlers(DataServerConfig dataServerConfig) {
Collection list = new ArrayList<>();
list.add(getDataHandler());
- list.add(publishDataProcessor(dataServerBootstrapConfig));
+ list.add(publishDataProcessor());
list.add(unPublishDataHandler());
list.add(notifyFetchDatumHandler());
list.add(notifyOnlineHandler());
@@ -215,6 +247,7 @@ public Collection metaClientHandlers() {
Collection list = new ArrayList<>();
list.add(serverChangeHandler());
list.add(statusConfirmHandler());
+ list.add(notifyProvideDataChangeHandler());
return list;
}
@@ -244,8 +277,18 @@ public AbstractServerHandler clientOffHandler() {
}
@Bean
- public AbstractServerHandler publishDataProcessor(DataServerConfig dataServerBootstrapConfig) {
- return new PublishDataHandler(dataServerBootstrapConfig);
+ public AbstractServerHandler datumSnapshotHandler() {
+ return new DatumSnapshotHandler();
+ }
+
+ @Bean
+ public RenewDatumHandler renewDatumHandler() {
+ return new RenewDatumHandler();
+ }
+
+ @Bean
+ public AbstractServerHandler publishDataProcessor() {
+ return new PublishDataHandler();
}
@Bean
@@ -292,6 +335,11 @@ public AbstractClientHandler serverChangeHandler() {
public AbstractClientHandler statusConfirmHandler() {
return new StatusConfirmHandler();
}
+
+ @Bean
+ public NotifyProvideDataChangeHandler notifyProvideDataChangeHandler() {
+ return new NotifyProvideDataChangeHandler();
+ }
}
@Configuration
@@ -316,6 +364,11 @@ public BackUpNotifier backUpNotifier() {
return new BackUpNotifier();
}
+ @Bean
+ public SnapshotBackUpNotifier snapshotBackUpNotifier() {
+ return new SnapshotBackUpNotifier();
+ }
+
@Bean(name = "dataChangeNotifiers")
public List dataChangeNotifiers(DataServerConfig dataServerBootstrapConfig) {
List list = new ArrayList<>();
@@ -378,6 +431,11 @@ public LocalDataServerCleanHandler localDataServerCleanHandler() {
return new LocalDataServerCleanHandler();
}
+ @Bean
+ public DatumLeaseManager datumLeaseManager() {
+ return new DatumLeaseManager();
+ }
+
@Bean
public GetSyncDataHandler getSyncDataHandler() {
return new GetSyncDataHandler();
@@ -413,8 +471,8 @@ public ConnectionRefreshMetaTask connectionRefreshMetaTask() {
}
@Bean
- public ReNewNodeTask reNewNodeTask() {
- return new ReNewNodeTask();
+ public RenewNodeTask renewNodeTask() {
+ return new RenewNodeTask();
}
@Bean(name = "tasks")
@@ -422,7 +480,7 @@ public List tasks() {
List list = new ArrayList<>();
list.add(connectionRefreshTask());
list.add(connectionRefreshMetaTask());
- list.add(reNewNodeTask());
+ list.add(renewNodeTask());
return list;
}
@@ -462,9 +520,17 @@ public static class AfterWorkingProcessConfiguration {
@Autowired
AbstractClientHandler notifyDataSyncHandler;
+ @Autowired
+ RenewDatumHandler renewDatumHandler;
+
+ @Autowired
+ DatumLeaseManager datumLeaseManager;
+
@Bean(name = "afterWorkProcessors")
public List afterWorkingProcessors() {
List list = new ArrayList<>();
+ list.add(renewDatumHandler);
+ list.add(datumLeaseManager);
list.add(disconnectEventHandler);
list.add((NotifyDataSyncHandler) notifyDataSyncHandler);
return list;
@@ -476,4 +542,40 @@ public AfterWorkingProcessHandler afterWorkingProcessHandler() {
}
}
+
+ @Configuration
+ public static class ExecutorConfiguration {
+
+ @Autowired
+ DataServerConfig dataServerConfig;
+
+ @Bean(name = "publishProcessorExecutor")
+ public ThreadPoolExecutor publishProcessorExecutor() {
+ return new ThreadPoolExecutorDataServer("PublishProcessorExecutor",
+ dataServerConfig.getPublishExecutorMinPoolSize(),
+ dataServerConfig.getPublishExecutorMaxPoolSize(), 300, TimeUnit.SECONDS,
+ new ArrayBlockingQueue<>(dataServerConfig.getPublishExecutorQueueSize()),
+ new NamedThreadFactory("DataServer-PublishProcessor-executor", true));
+ }
+
+ @Bean(name = "renewDatumProcessorExecutor")
+ public ThreadPoolExecutor renewDatumProcessorExecutor() {
+ return new ThreadPoolExecutorDataServer("RenewDatumProcessorExecutor",
+ dataServerConfig.getRenewDatumExecutorMinPoolSize(),
+ dataServerConfig.getRenewDatumExecutorMaxPoolSize(), 300, TimeUnit.SECONDS,
+ new ArrayBlockingQueue<>(dataServerConfig.getRenewDatumExecutorQueueSize()),
+ new NamedThreadFactory("DataServer-RenewDatumProcessor-executor", true));
+ }
+
+ @Bean(name = "getDataProcessorExecutor")
+ public ThreadPoolExecutor getDataProcessorExecutor() {
+ return new ThreadPoolExecutorDataServer("GetDataProcessorExecutor",
+ dataServerConfig.getGetDataExecutorMinPoolSize(),
+ dataServerConfig.getGetDataExecutorMaxPoolSize(),
+ dataServerConfig.getGetDataExecutorKeepAliveTime(), TimeUnit.SECONDS,
+ new ArrayBlockingQueue<>(dataServerConfig.getGetDataExecutorQueueSize()),
+ new NamedThreadFactory("DataServer-GetDataProcessor-executor", true));
+ }
+
+ }
}
\ No newline at end of file
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 e42293b84..8cc934baf 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
@@ -16,6 +16,25 @@
*/
package com.alipay.sofa.registry.server.data.bootstrap;
+import java.lang.annotation.Annotation;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.stream.Collectors;
+
+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;
+
+import com.alipay.sofa.registry.common.model.constants.ValueConstants;
+import com.alipay.sofa.registry.common.model.metaserver.ProvideData;
import com.alipay.sofa.registry.common.model.store.URL;
import com.alipay.sofa.registry.log.Logger;
import com.alipay.sofa.registry.log.LoggerFactory;
@@ -31,21 +50,7 @@
import com.alipay.sofa.registry.server.data.event.StartTaskTypeEnum;
import com.alipay.sofa.registry.server.data.remoting.handler.AbstractServerHandler;
import com.alipay.sofa.registry.server.data.remoting.metaserver.IMetaServerService;
-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.Arrays;
-import java.util.Collection;
-import java.util.Date;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.stream.Collectors;
+import com.alipay.sofa.registry.server.data.renew.DatumLeaseManager;
/**
*
@@ -59,7 +64,7 @@ public class DataServerBootstrap {
.getLogger(DataServerBootstrap.class);
@Autowired
- private DataServerConfig dataServerBootstrapConfig;
+ private DataServerConfig dataServerConfig;
@Autowired
private IMetaServerService metaServerService;
@@ -82,12 +87,18 @@ public class DataServerBootstrap {
@Autowired
private EventCenter eventCenter;
+ @Autowired
+ private CacheDigestTask cacheDigestTask;
+
@Resource(name = "serverHandlers")
private Collection serverHandlers;
@Resource(name = "serverSyncHandlers")
private Collection serverSyncHandlers;
+ @Autowired
+ private DatumLeaseManager datumLeaseManager;
+
private Server server;
private Server dataSyncServer;
@@ -107,7 +118,9 @@ public class DataServerBootstrap {
*/
public void start() {
try {
- LOGGER.info("[DataServerBootstrap] begin start server");
+ LOGGER.info("begin start server");
+
+ LOGGER.info("the configuration items are as follows: " + dataServerConfig.toString());
openDataServer();
@@ -117,13 +130,15 @@ public void start() {
startRaftClient();
+ fetchProviderData();
+
startScheduler();
Runtime.getRuntime().addShutdownHook(new Thread(this::doStop));
- LOGGER.info("[DataServerBootstrap] start server success");
+ LOGGER.info("start server success");
} catch (Exception e) {
- throw new RuntimeException("[DataServerBootstrap] start server error", e);
+ throw new RuntimeException("start server error", e);
}
}
@@ -131,15 +146,13 @@ private void openDataServer() {
try {
if (serverForSessionStarted.compareAndSet(false, true)) {
server = boltExchange.open(new URL(NetUtil.getLocalAddress().getHostAddress(),
- dataServerBootstrapConfig.getPort()), serverHandlers
+ dataServerConfig.getPort()), serverHandlers
.toArray(new ChannelHandler[serverHandlers.size()]));
- LOGGER.info("Data server for session started! port:{}",
- dataServerBootstrapConfig.getPort());
+ LOGGER.info("Data server for session started! port:{}", dataServerConfig.getPort());
}
} catch (Exception e) {
serverForSessionStarted.set(false);
- LOGGER
- .error("Data server start error! port:{}", dataServerBootstrapConfig.getPort(), e);
+ LOGGER.error("Data server start error! port:{}", dataServerConfig.getPort(), e);
throw new RuntimeException("Data server start error!", e);
}
}
@@ -148,15 +161,15 @@ private void openDataSyncServer() {
try {
if (serverForDataSyncStarted.compareAndSet(false, true)) {
dataSyncServer = boltExchange.open(new URL(NetUtil.getLocalAddress()
- .getHostAddress(), dataServerBootstrapConfig.getSyncDataPort()),
- serverSyncHandlers.toArray(new ChannelHandler[serverSyncHandlers.size()]));
+ .getHostAddress(), dataServerConfig.getSyncDataPort()), serverSyncHandlers
+ .toArray(new ChannelHandler[serverSyncHandlers.size()]));
LOGGER.info("Data server for sync started! port:{}",
- dataServerBootstrapConfig.getSyncDataPort());
+ dataServerConfig.getSyncDataPort());
}
} catch (Exception e) {
serverForDataSyncStarted.set(false);
LOGGER.error("Data sync server start error! port:{}",
- dataServerBootstrapConfig.getSyncDataPort(), e);
+ dataServerConfig.getSyncDataPort(), e);
throw new RuntimeException("Data sync server start error!", e);
}
}
@@ -166,15 +179,15 @@ private void openHttpServer() {
if (httpServerStarted.compareAndSet(false, true)) {
bindResourceConfig();
httpServer = jerseyExchange.open(
- new URL(NetUtil.getLocalAddress().getHostAddress(), dataServerBootstrapConfig
+ new URL(NetUtil.getLocalAddress().getHostAddress(), dataServerConfig
.getHttpServerPort()), new ResourceConfig[] { jerseyResourceConfig });
LOGGER.info("Open http server port {} success!",
- dataServerBootstrapConfig.getHttpServerPort());
+ dataServerConfig.getHttpServerPort());
}
} catch (Exception e) {
httpServerStarted.set(false);
- LOGGER.error("Open http server port {} error!",
- dataServerBootstrapConfig.getHttpServerPort(), e);
+ LOGGER
+ .error("Open http server port {} error!", dataServerConfig.getHttpServerPort(), e);
throw new RuntimeException("Open http server error!", e);
}
}
@@ -182,21 +195,35 @@ private void openHttpServer() {
private void startRaftClient() {
metaServerService.startRaftClient();
eventCenter.post(new MetaServerChangeEvent(metaServerService.getMetaServerMap()));
- LOGGER.info("[DataServerBootstrap] raft client started!Leader is {}",
- metaServerService.getLeader());
+ LOGGER.info("raft client started!Leader is {}", metaServerService.getLeader());
+ }
+
+ private void fetchProviderData() {
+ ProvideData provideData = metaServerService
+ .fetchData(ValueConstants.ENABLE_DATA_DATUM_EXPIRE);
+ if (provideData == null || provideData.getProvideData() == null
+ || provideData.getProvideData().getObject() == null) {
+ LOGGER
+ .info("Fetch enableDataDatumExpire but no data existed, current config not change!");
+ return;
+ }
+ boolean enableDataDatumExpire = Boolean.parseBoolean((String) provideData.getProvideData()
+ .getObject());
+ LOGGER.info("Fetch enableDataDatumExpire {} success!", enableDataDatumExpire);
+ datumLeaseManager.setRenewEnable(enableDataDatumExpire);
}
private void startScheduler() {
try {
if (schedulerStarted.compareAndSet(false, true)) {
syncDataScheduler.startScheduler();
- // start all startTask except renew task
+ // start all startTask except correction task
eventCenter.post(new StartTaskEvent(
- Arrays.stream(StartTaskTypeEnum.values()).filter(type->type != StartTaskTypeEnum.RENEW).collect(
- Collectors.toSet())));
+ Arrays.stream(StartTaskTypeEnum.values()).filter(type -> type != StartTaskTypeEnum.RENEW)
+ .collect(Collectors.toSet())));
//start dump log
- new CacheDigestTask().start();
+ cacheDigestTask.start();
}
} catch (Exception e) {
schedulerStarted.set(false);
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 aa0d2f3aa..6b47d4717 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
@@ -16,15 +16,18 @@
*/
package com.alipay.sofa.registry.server.data.bootstrap;
-import com.alipay.sofa.registry.net.NetUtil;
-import org.springframework.boot.context.properties.ConfigurationProperties;
-
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
+import org.apache.commons.lang.builder.ToStringBuilder;
+import org.apache.commons.lang.builder.ToStringStyle;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+import com.alipay.sofa.registry.net.NetUtil;
+
/**
*
*
@@ -34,10 +37,11 @@
@ConfigurationProperties(prefix = DataServerConfig.PRE_FIX)
public class DataServerConfig {
- public static final String PRE_FIX = "data.server";
+ public static final String PRE_FIX = "data.server";
- public static final String IP = NetUtil.getLocalAddress()
- .getHostAddress();
+ public static final String IP = NetUtil
+ .getLocalAddress()
+ .getHostAddress();
private int port;
@@ -51,9 +55,9 @@ public class DataServerConfig {
private int queueSize;
- private int notifyIntervalMs = 500;
+ private int notifyIntervalMs;
- private int clientOffDelayMs = 1000;
+ private int clientOffDelayMs;
private int notifyTempDataIntervalMs;
@@ -61,41 +65,59 @@ public class DataServerConfig {
private CommonConfig commonConfig;
- private Set metaIps = null;
+ private Set metaIps = null;
+
+ private int storeNodes = 3;
+
+ private int numberOfReplicas = 1000;
+
+ private long localDataServerCleanDelay = 1000 * 60 * 30;
+
+ private int getDataExecutorMinPoolSize = 80;
+
+ private int getDataExecutorMaxPoolSize = 400;
+
+ private int getDataExecutorQueueSize = 10000;
+
+ private long getDataExecutorKeepAliveTime = 60;
- private int storeNodes = 3;
+ private int notifyDataSyncExecutorMinPoolSize = 80;
- private int numberOfReplicas = 1000;
+ private int notifyDataSyncExecutorMaxPoolSize = 400;
- private long localDataServerCleanDelay = 1000 * 60 * 30;
+ private int notifyDataSyncExecutorQueueSize = 700;
- private int getDataExecutorMinPoolSize = 80;
+ private long notifyDataSyncExecutorKeepAliveTime = 60;
- private int getDataExecutorMaxPoolSize = 400;
+ private long notifySessionRetryFirstDelay = 1000;
- private int getDataExecutorQueueSize = 10000;
+ private long notifySessionRetryIncrementDelay = 1000;
- private long getDataExecutorKeepAliveTime = 60;
+ private int notifySessionRetryTimes = 10;
- private int notifyDataSyncExecutorMinPoolSize = 80;
+ private int publishExecutorMinPoolSize = 80;
- private int notifyDataSyncExecutorMaxPoolSize = 400;
+ private int publishExecutorMaxPoolSize = 400;
- private int notifyDataSyncExecutorQueueSize = 700;
+ private int publishExecutorQueueSize = 10000;
- private long notifyDataSyncExecutorKeepAliveTime = 60;
+ private int renewDatumExecutorMinPoolSize = 50;
- private long notifySessionRetryFirstDelay = 1000;
+ private int renewDatumExecutorMaxPoolSize = 400;
- private long notifySessionRetryIncrementDelay = 1000;
+ private int renewDatumExecutorQueueSize = 100000;
- private int notifySessionRetryTimes = 10;
+ private int datumTimeToLiveSec = 900;
- private int publishExecutorMinPoolSize = 80;
+ private int datumLeaseManagerExecutorThreadSize = 1;
- private int publishExecutorMaxPoolSize = 400;
+ private int datumLeaseManagerExecutorQueueSize = 1000000;
- private int publishExecutorQueueSize = 10000;
+ private int sessionServerNotifierRetryExecutorThreadSize = 10;
+
+ private int sessionServerNotifierRetryExecutorQueueSize = 1000000;
+
+ private int renewEnableDelaySec = 30;
/**
* constructor
@@ -105,10 +127,82 @@ public DataServerConfig(CommonConfig commonConfig) {
this.commonConfig = commonConfig;
}
+ /**
+ * Getter method for property renewEnableDelaySec.
+ *
+ * @return property value of renewEnableDelaySec
+ */
+ public int getRenewEnableDelaySec() {
+ return renewEnableDelaySec;
+ }
+
+ /**
+ * Setter method for property renewEnableDelaySec .
+ *
+ * @param renewEnableDelaySec value to be assigned to property renewEnableDelaySec
+ */
+ public void setRenewEnableDelaySec(int renewEnableDelaySec) {
+ this.renewEnableDelaySec = renewEnableDelaySec;
+ }
+
public String getLocalDataCenter() {
return commonConfig.getLocalDataCenter();
}
+ /**
+ * Getter method for property renewDatumExecutorMinPoolSize.
+ *
+ * @return property value of renewDatumExecutorMinPoolSize
+ */
+ public int getRenewDatumExecutorMinPoolSize() {
+ return renewDatumExecutorMinPoolSize;
+ }
+
+ /**
+ * Setter method for property renewDatumExecutorMinPoolSize .
+ *
+ * @param renewDatumExecutorMinPoolSize value to be assigned to property renewDatumExecutorMinPoolSize
+ */
+ public void setRenewDatumExecutorMinPoolSize(int renewDatumExecutorMinPoolSize) {
+ this.renewDatumExecutorMinPoolSize = renewDatumExecutorMinPoolSize;
+ }
+
+ /**
+ * Getter method for property renewDatumExecutorMaxPoolSize.
+ *
+ * @return property value of renewDatumExecutorMaxPoolSize
+ */
+ public int getRenewDatumExecutorMaxPoolSize() {
+ return renewDatumExecutorMaxPoolSize;
+ }
+
+ /**
+ * Setter method for property renewDatumExecutorMaxPoolSize .
+ *
+ * @param renewDatumExecutorMaxPoolSize value to be assigned to property renewDatumExecutorMaxPoolSize
+ */
+ public void setRenewDatumExecutorMaxPoolSize(int renewDatumExecutorMaxPoolSize) {
+ this.renewDatumExecutorMaxPoolSize = renewDatumExecutorMaxPoolSize;
+ }
+
+ /**
+ * Getter method for property renewDatumExecutorQueueSize.
+ *
+ * @return property value of renewDatumExecutorQueueSize
+ */
+ public int getRenewDatumExecutorQueueSize() {
+ return renewDatumExecutorQueueSize;
+ }
+
+ /**
+ * Setter method for property renewDatumExecutorQueueSize .
+ *
+ * @param renewDatumExecutorQueueSize value to be assigned to property renewDatumExecutorQueueSize
+ */
+ public void setRenewDatumExecutorQueueSize(int renewDatumExecutorQueueSize) {
+ this.renewDatumExecutorQueueSize = renewDatumExecutorQueueSize;
+ }
+
/**
* Getter method for property port.
*
@@ -619,4 +713,99 @@ public int getNotifySessionRetryTimes() {
public void setNotifySessionRetryTimes(int notifySessionRetryTimes) {
this.notifySessionRetryTimes = notifySessionRetryTimes;
}
+
+ /**
+ * Getter method for property datumTimeToLiveSec.
+ *
+ * @return property value of datumTimeToLiveSec
+ */
+ public int getDatumTimeToLiveSec() {
+ return datumTimeToLiveSec;
+ }
+
+ /**
+ * Setter method for property datumTimeToLiveSec .
+ *
+ * @param datumTimeToLiveSec value to be assigned to property datumTimeToLiveSec
+ */
+ public void setDatumTimeToLiveSec(int datumTimeToLiveSec) {
+ this.datumTimeToLiveSec = datumTimeToLiveSec;
+ }
+
+ /**
+ * Getter method for property datumLeaseManagerExecutorQueueSize.
+ *
+ * @return property value of datumLeaseManagerExecutorQueueSize
+ */
+ public int getDatumLeaseManagerExecutorQueueSize() {
+ return datumLeaseManagerExecutorQueueSize;
+ }
+
+ /**
+ * Setter method for property datumLeaseManagerExecutorQueueSize .
+ *
+ * @param datumLeaseManagerExecutorQueueSize value to be assigned to property datumLeaseManagerExecutorQueueSize
+ */
+ public void setDatumLeaseManagerExecutorQueueSize(int datumLeaseManagerExecutorQueueSize) {
+ this.datumLeaseManagerExecutorQueueSize = datumLeaseManagerExecutorQueueSize;
+ }
+
+ /**
+ * Getter method for property datumLeaseManagerExecutorThreadSize.
+ *
+ * @return property value of datumLeaseManagerExecutorThreadSize
+ */
+ public int getDatumLeaseManagerExecutorThreadSize() {
+ return datumLeaseManagerExecutorThreadSize;
+ }
+
+ /**
+ * Setter method for property datumLeaseManagerExecutorThreadSize .
+ *
+ * @param datumLeaseManagerExecutorThreadSize value to be assigned to property datumLeaseManagerExecutorThreadSize
+ */
+ public void setDatumLeaseManagerExecutorThreadSize(int datumLeaseManagerExecutorThreadSize) {
+ this.datumLeaseManagerExecutorThreadSize = datumLeaseManagerExecutorThreadSize;
+ }
+
+ /**
+ * Getter method for property sessionServerNotifierRetryExecutorThreadSize.
+ *
+ * @return property value of sessionServerNotifierRetryExecutorThreadSize
+ */
+ public int getSessionServerNotifierRetryExecutorThreadSize() {
+ return sessionServerNotifierRetryExecutorThreadSize;
+ }
+
+ /**
+ * Setter method for property sessionServerNotifierRetryExecutorThreadSize .
+ *
+ * @param sessionServerNotifierRetryExecutorThreadSize value to be assigned to property sessionServerNotifierRetryExecutorThreadSize
+ */
+ public void setSessionServerNotifierRetryExecutorThreadSize(int sessionServerNotifierRetryExecutorThreadSize) {
+ this.sessionServerNotifierRetryExecutorThreadSize = sessionServerNotifierRetryExecutorThreadSize;
+ }
+
+ /**
+ * Getter method for property sessionServerNotifierRetryExecutorQueueSize.
+ *
+ * @return property value of sessionServerNotifierRetryExecutorQueueSize
+ */
+ public int getSessionServerNotifierRetryExecutorQueueSize() {
+ return sessionServerNotifierRetryExecutorQueueSize;
+ }
+
+ /**
+ * Setter method for property sessionServerNotifierRetryExecutorQueueSize .
+ *
+ * @param sessionServerNotifierRetryExecutorQueueSize value to be assigned to property sessionServerNotifierRetryExecutorQueueSize
+ */
+ public void setSessionServerNotifierRetryExecutorQueueSize(int sessionServerNotifierRetryExecutorQueueSize) {
+ this.sessionServerNotifierRetryExecutorQueueSize = sessionServerNotifierRetryExecutorQueueSize;
+ }
+
+ @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/cache/CacheDigestTask.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/CacheDigestTask.java
index 5b09ddb31..feec34a6f 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/CacheDigestTask.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/CacheDigestTask.java
@@ -16,19 +16,21 @@
*/
package com.alipay.sofa.registry.server.data.cache;
+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 org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.util.CollectionUtils;
+
import com.alipay.sofa.registry.common.model.dataserver.Datum;
import com.alipay.sofa.registry.common.model.store.Publisher;
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.util.NamedThreadFactory;
-import org.springframework.util.CollectionUtils;
-
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
/**
*
@@ -39,20 +41,23 @@ public class CacheDigestTask {
private static final Logger LOGGER = LoggerFactory.getLogger(CacheDigestTask.class);
+ @Autowired
+ private DatumCache datumCache;
+
/**
*
*/
public void start() {
- ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1, new NamedThreadFactory("CacheDigestTask"));
+ ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1,
+ new NamedThreadFactory("CacheDigestTask"));
executor.scheduleAtFixedRate(() -> {
try {
- Map> allMap = DatumCache.getAll();
+ Map> allMap = datumCache.getAll();
if (!allMap.isEmpty()) {
for (Entry> dataCenterEntry : allMap.entrySet()) {
String dataCenter = dataCenterEntry.getKey();
Map datumMap = dataCenterEntry.getValue();
- LOGGER.info("[CacheDigestTask] size of datum in {} is {}",
- dataCenter, datumMap.size());
+ LOGGER.info("[CacheDigestTask] size of datum in {} is {}", dataCenter, datumMap.size());
for (Entry dataInfoEntry : datumMap.entrySet()) {
String dataInfoId = dataInfoEntry.getKey();
Datum data = dataInfoEntry.getValue();
@@ -63,14 +68,12 @@ public void start() {
pubStr.append(logPublisher(publisher)).append(";");
}
}
- LOGGER.info(
- "[Datum] dataInfoId={}, version={}, dataCenter={}, publishers=[{}]",
- dataInfoId, data.getVersion(), dataCenter, pubStr.toString());
+ LOGGER.info("[Datum] dataInfoId={}, version={}, dataCenter={}, publishers=[{}]", dataInfoId,
+ data.getVersion(), dataCenter, pubStr.toString());
}
int pubCount = datumMap.values().stream().map(Datum::getPubMap)
.filter(map -> map != null && !map.isEmpty()).mapToInt(Map::size).sum();
- LOGGER.info("[CacheDigestTask] size of publisher in {} is {}",
- dataCenter, pubCount);
+ LOGGER.info("[CacheDigestTask] size of publisher in {} is {}", dataCenter, pubCount);
}
} else {
LOGGER.info("[CacheDigestTask] datum cache is empty");
@@ -86,9 +89,9 @@ private String logPublisher(Publisher publisher) {
if (publisher != null) {
URL url = publisher.getSourceAddress();
String urlStr = url != null ? url.getAddressString() : "null";
- return String.format("dataInfoId=%s, version=%s, host=%s, registerId=%s",
- publisher.getDataInfoId(), publisher.getVersion(), urlStr,
- publisher.getRegisterId());
+ return String.format("registerId=%s, registerTimestamp=%s, host=%s, version=%s",
+ publisher.getRegisterId(), publisher.getRegisterTimestamp(), urlStr,
+ publisher.getVersion());
}
return "";
}
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DataServerCache.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DataServerCache.java
index 5cc050ba3..df481af15 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DataServerCache.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/DataServerCache.java
@@ -21,6 +21,7 @@
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.event.DataServerChangeEvent.FromType;
import com.alipay.sofa.registry.server.data.event.handler.AfterWorkingProcessHandler;
import com.alipay.sofa.registry.server.data.node.DataNodeStatus;
import com.alipay.sofa.registry.server.data.util.LocalServerStatusEnum;
@@ -78,7 +79,7 @@ public class DataServerCache {
* @param newItem
* @return changedMap(datacenter, serverIp)
*/
- public Map> compareAndSet(DataServerChangeItem newItem) {
+ public Map> compareAndSet(DataServerChangeItem newItem, FromType fromType) {
synchronized (DataServerCache.class) {
// versionMap: datacenter -> version
Map newVersionMap = newItem.getVersionMap();
@@ -109,8 +110,8 @@ public Map> compareAndSet(DataServerChangeItem newItem) {
if (isTheSame.get()) {
LOGGER
.info(
- "current process map has a same version as change map,this change will be ignored!process version={},get version={}",
- currentNewVersionMap, newVersionMap);
+ "current process map has a same version as change map,this change will be ignored!process version={},get version={},from={}",
+ currentNewVersionMap, newVersionMap, fromType);
return new HashMap<>();
}
}
@@ -138,7 +139,8 @@ public Map> compareAndSet(DataServerChangeItem newItem) {
init(newVersionMap.get(dataServerConfig.getLocalDataCenter()));
}
if (!changedMap.isEmpty()) {
- LOGGER.info("old server map = {}", dataServerChangeItem.getServerMap());
+ LOGGER.info("old server map = {},from={}", dataServerChangeItem.getServerMap(),
+ fromType);
LOGGER.info("new server map = {}", newServerMap);
LOGGER.info("new server version map = {}", newVersionMap);
LOGGER.info("status map = {}", nodeStatusMap);
@@ -254,8 +256,9 @@ private void updateDataServerStatus() {
LOGGER
.info(
- "nodeStatusMap not contains all push list,nodeStatusMap {},push {},diff {}",
- nodeStatusMap, itemIps, Sets.difference(ips, itemIps));
+ "nodeStatusMap not contains all push list,nodeStatusMap {},push {},diff1{},diff2{}",
+ nodeStatusMap, itemIps, Sets.difference(ips, itemIps),
+ Sets.difference(itemIps, ips));
return;
}
} else {
@@ -270,6 +273,11 @@ private void updateDataServerStatus() {
dataNodeStatus.setStatus(LocalServerStatusEnum.WORKING);
+ //after working update current dataCenter list to old DataServerChangeItem
+ updateItem(
+ newDataServerChangeItem.getServerMap().get(dataServerConfig.getLocalDataCenter()),
+ newVersion, dataServerConfig.getLocalDataCenter());
+
//after working status,must clean this map,because calculate backupTriad need add not working node,see LocalDataServerChangeEventHandler getToBeSyncMap
resetStatusMapToWorking();
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 6b17f7702..2b076924c 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
@@ -16,11 +16,6 @@
*/
package com.alipay.sofa.registry.server.data.cache;
-import com.alipay.sofa.registry.common.model.dataserver.Datum;
-import com.alipay.sofa.registry.common.model.store.Publisher;
-import com.alipay.sofa.registry.server.data.change.DataChangeTypeEnum;
-import org.springframework.util.StringUtils;
-
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
@@ -28,29 +23,44 @@
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
+import org.apache.commons.lang.StringUtils;
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.alipay.sofa.registry.common.model.dataserver.Datum;
+import com.alipay.sofa.registry.common.model.store.Publisher;
+import com.alipay.sofa.registry.server.data.bootstrap.DataServerConfig;
+import com.alipay.sofa.registry.server.data.change.DataChangeTypeEnum;
+import com.alipay.sofa.registry.server.data.node.DataServerNode;
+import com.alipay.sofa.registry.server.data.remoting.dataserver.DataServerNodeFactory;
+
/**
* cache of datum, providing query function to the upper module
*
* @author qian.lqlq
- * @version $Id: DatumCache.java, v 0.1 2017-12-06 20:50 qian.lqlq Exp $
+ * @version $Id: this.java, v 0.1 2017-12-06 20:50 qian.lqlq Exp $
*/
public class DatumCache {
- public static final long ERROR_DATUM_VERSION = -2L;
+ public static final long ERROR_DATUM_VERSION = -2L;
/**
* row: dataCenter
* column: dataInfoId
* value: datum
*/
- private static final Map> DATUM_MAP = new ConcurrentHashMap<>();
+ private final Map> DATUM_MAP = new ConcurrentHashMap<>();
/**
+ * all datum index
+ *
* row: ip:port
* column: registerId
* value: publisher
*/
- private static final Map> CLIENT_PUB_MAP = new ConcurrentHashMap<>();
+ private final Map> ALL_CONNECT_ID_INDEX = new ConcurrentHashMap<>();
+
+ @Autowired
+ private DataServerConfig dataServerConfig;
/**
* get datum by specific dataCenter and dataInfoId
@@ -59,7 +69,7 @@ public class DatumCache {
* @param dataInfoId
* @return
*/
- public static Datum get(String dataCenter, String dataInfoId) {
+ public Datum get(String dataCenter, String dataInfoId) {
if (DATUM_MAP.containsKey(dataCenter)) {
Map map = DATUM_MAP.get(dataCenter);
if (map.containsKey(dataInfoId)) {
@@ -75,7 +85,7 @@ public static Datum get(String dataCenter, String dataInfoId) {
* @param dataInfoId
* @return
*/
- public static Map get(String dataInfoId) {
+ public Map get(String dataInfoId) {
Map datumMap = new HashMap<>();
DATUM_MAP.forEach((dataCenter, datums) -> {
if (datums.containsKey(dataInfoId)) {
@@ -93,12 +103,12 @@ public static Map get(String dataInfoId) {
* @param dataInfoId
* @return
*/
- public static Map getDatumGroupByDataCenter(String dataCenter, String dataInfoId) {
+ public Map getDatumGroupByDataCenter(String dataCenter, String dataInfoId) {
Map map = new HashMap<>();
if (StringUtils.isEmpty(dataCenter)) {
- map = DatumCache.get(dataInfoId);
+ map = this.get(dataInfoId);
} else {
- Datum datum = DatumCache.get(dataCenter, dataInfoId);
+ Datum datum = this.get(dataCenter, dataInfoId);
if (datum != null) {
map.put(dataCenter, datum);
}
@@ -111,18 +121,38 @@ public static Map getDatumGroupByDataCenter(String dataCenter, St
*
* @return
*/
- public static Map> getAll() {
+ public Map> getAll() {
return DATUM_MAP;
}
/**
*
*
- * @param host
+ * @param connectId
* @return
*/
- public static Map getByHost(String host) {
- return CLIENT_PUB_MAP.getOrDefault(host, null);
+ public Map getByConnectId(String connectId) {
+ return ALL_CONNECT_ID_INDEX.getOrDefault(connectId, null);
+ }
+
+ /**
+ * get own publishers by connectId
+ */
+ public Map getOwnByConnectId(String connectId) {
+ Map ownPubMap = new HashMap<>();
+ Map allPubMap = ALL_CONNECT_ID_INDEX.getOrDefault(connectId, null);
+ if (allPubMap != null) {
+ for (Map.Entry entry : allPubMap.entrySet()) {
+ String registerId = entry.getKey();
+ Publisher publisher = entry.getValue();
+ DataServerNode dataServerNode = DataServerNodeFactory.computeDataServerNode(
+ dataServerConfig.getLocalDataCenter(), publisher.getDataInfoId());
+ if (DataServerConfig.IP.equals(dataServerNode.getIp())) {
+ ownPubMap.put(registerId, publisher);
+ }
+ }
+ }
+ return ownPubMap;
}
/**
@@ -132,18 +162,11 @@ public static Map getByHost(String host) {
* @param datum
* @return the last version before datum changed, if datum is not exist, return null
*/
- public static MergeResult putDatum(DataChangeTypeEnum changeType, Datum datum) {
+ public MergeResult putDatum(DataChangeTypeEnum changeType, Datum datum) {
MergeResult mergeResult;
String dataCenter = datum.getDataCenter();
String dataInfoId = datum.getDataInfoId();
- Map map = DATUM_MAP.get(dataCenter);
- if (map == null) {
- map = new ConcurrentHashMap<>();
- Map ret = DATUM_MAP.putIfAbsent(dataCenter, map);
- if (ret != null) {
- map = ret;
- }
- }
+ Map map = getDatumMapByDataCenter(dataCenter);
//first put UnPublisher datum(dataId group instanceId is null),can not add to cache
if (datum.getDataId() == null && map.get(dataInfoId) == null) {
@@ -159,14 +182,7 @@ public static MergeResult putDatum(DataChangeTypeEnum changeType, Datum datum) {
Entry entry = iterator.next();
Publisher publisher = entry.getValue();
if (!(publisher instanceof UnPublisher)) {
- String registerId = publisher.getRegisterId();
- Map clientRegisterMap = new ConcurrentHashMap<>();
- clientRegisterMap.put(registerId, publisher);
- Map retMap = CLIENT_PUB_MAP.putIfAbsent(publisher
- .getSourceAddress().getAddressString(), clientRegisterMap);
- if (retMap != null) {
- retMap.putAll(clientRegisterMap);
- }
+ addToIndex(publisher);
} else {
//first put to cache,UnPublisher data must remove,not so got error pub data exist
iterator.remove();
@@ -184,13 +200,25 @@ public static MergeResult putDatum(DataChangeTypeEnum changeType, Datum datum) {
return mergeResult;
}
+ private Map getDatumMapByDataCenter(String dataCenter) {
+ Map map = DATUM_MAP.get(dataCenter);
+ if (map == null) {
+ map = new ConcurrentHashMap<>();
+ Map ret = DATUM_MAP.putIfAbsent(dataCenter, map);
+ if (ret != null) {
+ map = ret;
+ }
+ }
+ return map;
+ }
+
/**
* remove datum ant contains all pub data,and clean all the client map reference
* @param dataCenter
* @param dataInfoId
* @return
*/
- public static boolean cleanDatum(String dataCenter, String dataInfoId) {
+ public boolean cleanDatum(String dataCenter, String dataInfoId) {
Map datumMap = DATUM_MAP.get(dataCenter);
if (datumMap != null) {
@@ -204,8 +232,7 @@ public static boolean cleanDatum(String dataCenter, String dataInfoId) {
//remove from cache
if (cachePub != null) {
cachePubMap.remove(registerId);
- CLIENT_PUB_MAP.get(cachePub.getSourceAddress().getAddressString()).remove(
- registerId);
+ removeFromIndex(cachePub);
}
}
return true;
@@ -220,7 +247,7 @@ public static boolean cleanDatum(String dataCenter, String dataInfoId) {
* @param datum
* @return
*/
- private static MergeResult mergeDatum(Datum datum) {
+ private MergeResult mergeDatum(Datum datum) {
boolean isChanged = false;
Datum cacheDatum = DATUM_MAP.get(datum.getDataCenter()).get(datum.getDataInfoId());
Map cachePubMap = cacheDatum.getPubMap();
@@ -229,37 +256,8 @@ private static MergeResult mergeDatum(Datum datum) {
String registerId = pubEntry.getKey();
Publisher pub = pubEntry.getValue();
Publisher cachePub = cachePubMap.get(registerId);
- if (pub instanceof UnPublisher) {
- //remove from cache
- if (cachePub != null
- && pub.getRegisterTimestamp() > cachePub.getRegisterTimestamp()) {
- cachePubMap.remove(registerId);
- CLIENT_PUB_MAP.get(cachePub.getSourceAddress().getAddressString()).remove(
- registerId);
- isChanged = true;
- }
- } else {
- String pubAddr = pub.getSourceAddress().getAddressString();
- long version = pub.getVersion();
- long cacheVersion = cachePub == null ? 0L : cachePub.getVersion();
- String cachePubAddr = cachePub == null ? "" : cachePub.getSourceAddress()
- .getAddressString();
- if (cacheVersion <= version) {
- cachePubMap.put(registerId, pub);
- if (cacheVersion < version || !pubAddr.equals(cachePubAddr)) {
- // if version of both pub and cachePub are not equal, or sourceAddress of both are not equal, update
- // eg: sessionserver crash, client reconnect to other sessionserver, sourceAddress changed, version not changed
- // eg: client restart, sourceAddress and version are both changed
- if (CLIENT_PUB_MAP.containsKey(cachePubAddr)) {
- CLIENT_PUB_MAP.get(cachePubAddr).remove(registerId);
- }
- if (!CLIENT_PUB_MAP.containsKey(pubAddr)) {
- CLIENT_PUB_MAP.putIfAbsent(pubAddr, new ConcurrentHashMap<>());
- }
- CLIENT_PUB_MAP.get(pubAddr).put(registerId, pub);
- isChanged = true;
- }
- }
+ if (mergePublisher(pub, cachePubMap, cachePub)) {
+ isChanged = true;
}
}
Long lastVersion = cacheDatum.getVersion();
@@ -269,12 +267,83 @@ private static MergeResult mergeDatum(Datum datum) {
return new MergeResult(lastVersion, isChanged);
}
+ /**
+ * cover datum by snapshot
+ */
+ public Datum putSnapshot(String dataInfoId, Map toBeDeletedPubMap,
+ Map snapshotPubMap) {
+ // get cache datum
+ Map datumMap = getDatumMapByDataCenter(dataServerConfig.getLocalDataCenter());
+ Datum cacheDatum = datumMap.get(dataInfoId);
+ if (cacheDatum == null) {
+ cacheDatum = new Datum(dataInfoId, dataServerConfig.getLocalDataCenter());
+ Publisher publisher = snapshotPubMap.values().iterator().next();
+ cacheDatum.setInstanceId(publisher.getInstanceId());
+ cacheDatum.setDataId(publisher.getDataId());
+ cacheDatum.setGroup(publisher.getGroup());
+ Datum datum = datumMap.putIfAbsent(dataInfoId, cacheDatum);
+ if (datum != null) {
+ cacheDatum = datum;
+ }
+ }
+ //remove toBeDeletedPubMap from cacheDatum
+ for (Entry toBeDeletedPubEntry : toBeDeletedPubMap.entrySet()) {
+ String registerId = toBeDeletedPubEntry.getKey();
+ Publisher toBeDeletedPub = toBeDeletedPubEntry.getValue();
+ if (cacheDatum != null) {
+ cacheDatum.getPubMap().remove(registerId);
+ removeFromIndex(toBeDeletedPub);
+ }
+ }
+ // add snapshotPubMap to cacheDatum
+ for (Entry pubEntry : snapshotPubMap.entrySet()) {
+ String registerId = pubEntry.getKey();
+ Publisher snapshotPub = pubEntry.getValue();
+ Publisher cachePub = cacheDatum.getPubMap().put(registerId, snapshotPub);
+ if (cachePub != null) {
+ removeFromIndex(cachePub);
+ }
+ addToIndex(snapshotPub);
+ }
+
+ cacheDatum.updateVersion();
+
+ return cacheDatum;
+ }
+
+ private boolean mergePublisher(Publisher pub, Map cachePubMap,
+ Publisher cachePub) {
+ boolean isChanged = false;
+ String registerId = pub.getRegisterId();
+ if (pub instanceof UnPublisher) {
+ //remove from cache
+ if (cachePub != null && pub.getRegisterTimestamp() > cachePub.getRegisterTimestamp()) {
+ cachePubMap.remove(registerId);
+ removeFromIndex(cachePub);
+ isChanged = true;
+ }
+ } else {
+ long version = pub.getVersion();
+ long cacheVersion = cachePub == null ? 0L : cachePub.getVersion();
+ if (cacheVersion <= version) {
+ cachePubMap.put(registerId, pub);
+ // connectId and cacheConnectId may not be equal, so indexes need to be deleted and added, rather than overwritten directly.
+ // why connectId and cacheConnectId may not be equal?
+ // eg: sessionserver crash, client(RegistryClient but not ConfregClient) reconnect to other sessionserver, sourceAddress changed, version not changed
+ removeFromIndex(cachePub);
+ addToIndex(pub);
+ isChanged = true;
+ }
+ }
+ return isChanged;
+ }
+
/**
*
* @param datum
* @return
*/
- private static Long coverDatum(Datum datum) {
+ private Long coverDatum(Datum datum) {
String dataCenter = datum.getDataCenter();
String dataInfoId = datum.getDataInfoId();
Datum cacheDatum = DATUM_MAP.get(dataCenter).get(dataInfoId);
@@ -285,25 +354,57 @@ private static Long coverDatum(Datum datum) {
for (Entry pubEntry : pubMap.entrySet()) {
String registerId = pubEntry.getKey();
Publisher pub = pubEntry.getValue();
- String pubAddr = pub.getSourceAddress().getAddressString();
- if (!CLIENT_PUB_MAP.containsKey(pubAddr)) {
- CLIENT_PUB_MAP.putIfAbsent(pubAddr, new ConcurrentHashMap<>());
- }
- CLIENT_PUB_MAP.get(pubAddr).put(registerId, pub);
+ addToIndex(pub);
Publisher cachePub = cachePubMap.get(registerId);
- if (cachePub != null
- && pubAddr.equals(cachePub.getSourceAddress().getAddressString())) {
+ if (cachePub != null && getConnectId(pub).equals(getConnectId(cachePub))) {
cachePubMap.remove(registerId);
}
}
if (!cachePubMap.isEmpty()) {
for (Publisher cachePub : cachePubMap.values()) {
- CLIENT_PUB_MAP.get(cachePub.getSourceAddress().getAddressString()).remove(
- cachePub.getRegisterId());
+ removeFromIndex(cachePub);
}
}
}
return cacheDatum.getVersion();
}
+ private void removeFromIndex(Publisher publisher) {
+ if (publisher == null) {
+ return;
+ }
+ String connectId = getConnectId(publisher);
+
+ // remove from ALL_CONNECT_ID_INDEX
+ Map publisherMap = ALL_CONNECT_ID_INDEX.get(connectId);
+ if (publisherMap != null) {
+ publisherMap.remove(publisher.getRegisterId());
+ }
+ }
+
+ private void addToIndex(Publisher publisher) {
+ if (publisher == null) {
+ return;
+ }
+ String connectId = getConnectId(publisher);
+
+ // add to ALL_CONNECT_ID_INDEX
+ Map publisherMap = ALL_CONNECT_ID_INDEX
+ .computeIfAbsent(connectId, s -> new ConcurrentHashMap<>());
+ publisherMap.put(publisher.getRegisterId(), publisher);
+
+ }
+
+ private String getConnectId(Publisher cachePub) {
+ return cachePub.getSourceAddress().getAddressString();
+ }
+
+ /**
+ * Getter method for property OWN_CONNECT_ID_INDEX.
+ *
+ * @return property value of OWN_CONNECT_ID_INDEX
+ */
+ public Set getAllConnectIds() {
+ return ALL_CONNECT_ID_INDEX.keySet();
+ }
}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/UnPublisher.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/UnPublisher.java
index 5db5d80b9..1f3488dc8 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/UnPublisher.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/cache/UnPublisher.java
@@ -45,6 +45,6 @@ public UnPublisher(String dataInfoId, String registerId, long registerTimeStamp)
@Override
public DataType getDataType() {
- return DataType.UNPUBLISHER;
+ return DataType.UN_PUBLISHER;
}
}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/ChangeData.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/ChangeData.java
index 166f8fa48..f3e541877 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/ChangeData.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/ChangeData.java
@@ -16,11 +16,11 @@
*/
package com.alipay.sofa.registry.server.data.change;
-import com.alipay.sofa.registry.common.model.dataserver.Datum;
-
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;
+import com.alipay.sofa.registry.common.model.dataserver.Datum;
+
/**
* changed data
*
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeHandler.java
index 6f9e0104f..665095b0d 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeHandler.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataChangeHandler.java
@@ -27,9 +27,9 @@
import com.alipay.sofa.registry.server.data.change.event.DataChangeEventQueue;
import com.alipay.sofa.registry.server.data.change.notify.IDataChangeNotifier;
import com.alipay.sofa.registry.server.data.executor.ExecutorFactory;
-import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
+import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@@ -41,7 +41,7 @@
* @author qian.lqlq
* @version $Id: DataChangeHandler.java, v 0.1 2017-12-07 18:44 qian.lqlq Exp $
*/
-public class DataChangeHandler implements InitializingBean {
+public class DataChangeHandler {
private static final Logger LOGGER = LoggerFactory
.getLogger(DataChangeHandler.class);
@@ -49,31 +49,24 @@ public class DataChangeHandler implements InitializingBean {
private static final Logger LOGGER_START = LoggerFactory.getLogger("DATA-START-LOGS");
@Autowired
- private DataServerConfig dataServerBootstrapConfig;
+ private DataServerConfig dataServerConfig;
@Autowired
private DataChangeEventCenter dataChangeEventCenter;
+ @Autowired
+ private DatumCache datumCache;
+
@Resource
private List dataChangeNotifiers;
- @Override
- public void afterPropertiesSet() {
- //init DataChangeEventCenter
- dataChangeEventCenter.init(dataServerBootstrapConfig);
- start();
- }
-
- /**
- *
- */
+ @PostConstruct
public void start() {
DataChangeEventQueue[] queues = dataChangeEventCenter.getQueues();
int queueCount = queues.length;
- Executor executor = ExecutorFactory.newFixedThreadPool(queueCount,
- DataChangeHandler.class.getSimpleName());
- Executor notifyExecutor = ExecutorFactory.newFixedThreadPool(
- dataServerBootstrapConfig.getQueueCount() * 5, this.getClass().getSimpleName());
+ Executor executor = ExecutorFactory.newFixedThreadPool(queueCount, DataChangeHandler.class.getSimpleName());
+ Executor notifyExecutor = ExecutorFactory
+ .newFixedThreadPool(dataServerConfig.getQueueCount() * 5, this.getClass().getSimpleName());
for (int idx = 0; idx < queueCount; idx++) {
final DataChangeEventQueue dataChangeEventQueue = queues[idx];
final String name = dataChangeEventQueue.getName();
@@ -112,66 +105,85 @@ public ChangeNotifier(ChangeData changeData, String name) {
@Override
public void run() {
- Datum datum = changeData.getDatum();
- String dataCenter = datum.getDataCenter();
- String dataInfoId = datum.getDataInfoId();
- long version = datum.getVersion();
- DataSourceTypeEnum sourceType = changeData.getSourceType();
- DataChangeTypeEnum changeType = changeData.getChangeType();
- try {
- if (sourceType == DataSourceTypeEnum.CLEAN) {
- if (DatumCache.cleanDatum(dataCenter, dataInfoId)) {
- LOGGER
- .info(
- "[DataChangeHandler][{}] clean datum, dataCenter={}, dataInfoId={}, version={},sourceType={}, changeType={}",
- name, dataCenter, dataInfoId, version, sourceType, changeType);
- }
+ if (changeData instanceof SnapshotData) {
+ SnapshotData snapshotData = (SnapshotData) changeData;
+ String dataInfoId = snapshotData.getDataInfoId();
+ Map toBeDeletedPubMap = snapshotData.getToBeDeletedPubMap();
+ Map snapshotPubMap = snapshotData.getSnapshotPubMap();
+ Datum oldDatum = datumCache.get(dataServerConfig.getLocalDataCenter(), dataInfoId);
+ long lastVersion = oldDatum != null ? oldDatum.getVersion() : 0l;
+ Datum datum = datumCache.putSnapshot(dataInfoId, toBeDeletedPubMap, snapshotPubMap);
+ long version = datum != null ? datum.getVersion() : 0l;
+ LOGGER
+ .info(
+ "[DataChangeHandler][{}] snapshot handle,dataInfoId={}, version={}, lastVersion={}",
+ name, dataInfoId, version, lastVersion);
+ notify(datum, changeData.getSourceType(), null);
+
+ } else {
+ Datum datum = changeData.getDatum();
+
+ String dataCenter = datum.getDataCenter();
+ String dataInfoId = datum.getDataInfoId();
+ DataSourceTypeEnum sourceType = changeData.getSourceType();
+ DataChangeTypeEnum changeType = changeData.getChangeType();
+
+ if (changeType == DataChangeTypeEnum.MERGE
+ && sourceType != DataSourceTypeEnum.BACKUP
+ && sourceType != DataSourceTypeEnum.SYNC) {
+ //update version for pub or unPub merge to cache
+ //if the version product before merge to cache,it may be cause small version override big one
+ datum.updateVersion();
+ }
- } else {
- Long lastVersion = null;
+ long version = datum.getVersion();
- if (sourceType == DataSourceTypeEnum.PUB_TEMP) {
+ try {
+ if (sourceType == DataSourceTypeEnum.CLEAN) {
+ if (datumCache.cleanDatum(dataCenter, dataInfoId)) {
+ LOGGER
+ .info(
+ "[DataChangeHandler][{}] clean datum, dataCenter={}, dataInfoId={}, version={},sourceType={}, changeType={}",
+ name, dataCenter, dataInfoId, version, sourceType, changeType);
+ }
+
+ } else if (sourceType == DataSourceTypeEnum.PUB_TEMP) {
notifyTempPub(datum, sourceType, changeType);
- return;
- }
- MergeResult mergeResult = DatumCache.putDatum(changeType, datum);
- lastVersion = mergeResult.getLastVersion();
+ } else {
+ MergeResult mergeResult = datumCache.putDatum(changeType, datum);
+ Long lastVersion = mergeResult.getLastVersion();
+
+ if (lastVersion != null
+ && lastVersion.longValue() == datumCache.ERROR_DATUM_VERSION) {
+ LOGGER
+ .error(
+ "[DataChangeHandler][{}] first put unPub datum into cache error, dataCenter={}, dataInfoId={}, version={}, sourceType={},isContainsUnPub={}",
+ name, dataCenter, dataInfoId, version, sourceType,
+ datum.isContainsUnPub());
+ return;
+ }
- if (lastVersion != null
- && lastVersion.longValue() == DatumCache.ERROR_DATUM_VERSION) {
LOGGER
- .error(
- "[DataChangeHandler][{}] first put unPub datum into cache error, dataCenter={}, dataInfoId={}, version={}, sourceType={},isContainsUnPub={}",
- name, dataCenter, dataInfoId, version, sourceType,
+ .info(
+ "[DataChangeHandler][{}] datum handle,datum={},dataCenter={}, dataInfoId={}, version={}, lastVersion={}, sourceType={}, changeType={},changeFlag={},isContainsUnPub={}",
+ name, datum.hashCode(), dataCenter, dataInfoId, version,
+ lastVersion, sourceType, changeType, mergeResult.isChangeFlag(),
datum.isContainsUnPub());
- return;
- }
-
- boolean changeFlag = mergeResult.isChangeFlag();
-
- LOGGER
- .info(
- "[DataChangeHandler][{}] datum handle,datum={},dataCenter={}, dataInfoId={}, version={}, lastVersion={}, sourceType={}, changeType={},changeFlag={},isContainsUnPub={}",
- name, datum.hashCode(), dataCenter, dataInfoId, version, lastVersion,
- sourceType, changeType, changeFlag, datum.isContainsUnPub());
- //lastVersion null means first add datum
- if (lastVersion == null || version != lastVersion) {
- if (changeFlag) {
- for (IDataChangeNotifier notifier : dataChangeNotifiers) {
- if (notifier.getSuitableSource().contains(sourceType)) {
- notifier.notify(datum, lastVersion);
- }
+ //lastVersion null means first add datum
+ if (lastVersion == null || version != lastVersion) {
+ if (mergeResult.isChangeFlag()) {
+ notify(datum, sourceType, lastVersion);
}
}
}
+ } catch (Exception e) {
+ LOGGER
+ .error(
+ "[DataChangeHandler][{}] put datum into cache error, dataCenter={}, dataInfoId={}, version={}, sourceType={},isContainsUnPub={}",
+ name, dataCenter, dataInfoId, version, sourceType,
+ datum.isContainsUnPub(), e);
}
- } catch (Exception e) {
- LOGGER
- .error(
- "[DataChangeHandler][{}] put datum into cache error, dataCenter={}, dataInfoId={}, version={}, sourceType={},isContainsUnPub={}",
- name, dataCenter, dataInfoId, version, sourceType, datum.isContainsUnPub(),
- e);
}
}
@@ -183,7 +195,7 @@ private void notifyTempPub(Datum datum, DataSourceTypeEnum sourceType,
String dataInfoId = datum.getDataInfoId();
long version = datum.getVersion();
- Datum existDatum = DatumCache.get(dataCenter, dataInfoId);
+ Datum existDatum = datumCache.get(dataCenter, dataInfoId);
if (existDatum != null) {
Map cachePubMap = existDatum.getPubMap();
if (cachePubMap != null && !cachePubMap.isEmpty()) {
@@ -196,11 +208,16 @@ private void notifyTempPub(Datum datum, DataSourceTypeEnum sourceType,
"[DataChangeHandler][{}] datum handle temp pub,datum={},dataCenter={}, dataInfoId={}, version={}, sourceType={}, changeType={}",
name, datum.hashCode(), dataCenter, dataInfoId, version, sourceType, changeType);
+ notify(datum, sourceType, null);
+ }
+
+ private void notify(Datum datum, DataSourceTypeEnum sourceType, Long lastVersion) {
for (IDataChangeNotifier notifier : dataChangeNotifiers) {
if (notifier.getSuitableSource().contains(sourceType)) {
- notifier.notify(datum, null);
+ notifier.notify(datum, lastVersion);
}
}
}
}
+
}
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataSourceTypeEnum.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataSourceTypeEnum.java
index c41a14f51..b2787fbb9 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataSourceTypeEnum.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/DataSourceTypeEnum.java
@@ -46,5 +46,10 @@ public enum DataSourceTypeEnum {
/**
* local dataInfo check,not belong this node schedule remove
*/
- CLEAN
+ CLEAN,
+
+ /**
+ * Snapshot data, after renew finds data inconsistent
+ */
+ SNAPSHOT,
}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/SnapshotData.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/SnapshotData.java
new file mode 100644
index 000000000..495019d65
--- /dev/null
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/SnapshotData.java
@@ -0,0 +1,83 @@
+/*
+ * 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.
+ */
+package com.alipay.sofa.registry.server.data.change;
+
+import java.util.Map;
+import java.util.concurrent.Delayed;
+import java.util.concurrent.TimeUnit;
+
+import com.alipay.sofa.registry.common.model.store.Publisher;
+
+/**
+ * changed data
+ *
+ * @author kezhu.wukz
+ * @version $Id: ChangeData.java, v 0.1 2019-07-12 16:23 kezhu.wukz Exp $
+ */
+public class SnapshotData extends ChangeData {
+
+ private String dataInfoId;
+
+ private Map toBeDeletedPubMap;
+
+ private Map snapshotPubMap;
+
+ public SnapshotData(String dataInfoId, Map toBeDeletedPubMap,
+ Map snapshotPubMap) {
+ super(null, 0, DataSourceTypeEnum.SNAPSHOT, null);
+ this.dataInfoId = dataInfoId;
+ this.toBeDeletedPubMap = toBeDeletedPubMap;
+ this.snapshotPubMap = snapshotPubMap;
+ }
+
+ /**
+ * Getter method for property dataInfoId.
+ *
+ * @return property value of dataInfoId
+ */
+ public String getDataInfoId() {
+ return dataInfoId;
+ }
+
+ /**
+ * Getter method for property toBeDeletedPubMap.
+ *
+ * @return property value of toBeDeletedPubMap
+ */
+ public Map getToBeDeletedPubMap() {
+ return toBeDeletedPubMap;
+ }
+
+ /**
+ * Getter method for property snapshotPubMap.
+ *
+ * @return property value of snapshotPubMap
+ */
+ public Map getSnapshotPubMap() {
+ return snapshotPubMap;
+ }
+
+ @Override
+ public long getDelay(TimeUnit unit) {
+ return 0;
+ }
+
+ @Override
+ public int compareTo(Delayed o) {
+ return -1;
+ }
+}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/ClientChangeEvent.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/ClientChangeEvent.java
index c063f50d4..b2eb9f036 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/ClientChangeEvent.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/ClientChangeEvent.java
@@ -16,6 +16,8 @@
*/
package com.alipay.sofa.registry.server.data.change.event;
+import com.alipay.sofa.registry.util.DatumVersionUtil;
+
/**
*
* @author qian.lqlq
@@ -41,7 +43,7 @@ public ClientChangeEvent(String host, String dataCenter, long occurredTimestamp)
this.host = host;
this.dataCenter = dataCenter;
this.occurredTimestamp = occurredTimestamp;
- this.version = System.currentTimeMillis();
+ this.version = DatumVersionUtil.nextId();
}
@Override
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeEventCenter.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeEventCenter.java
index 58c5496e2..01b5e220d 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeEventCenter.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeEventCenter.java
@@ -16,16 +16,21 @@
*/
package com.alipay.sofa.registry.server.data.change.event;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import javax.annotation.PostConstruct;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
import com.alipay.sofa.registry.common.model.PublishType;
import com.alipay.sofa.registry.common.model.dataserver.Datum;
import com.alipay.sofa.registry.common.model.store.Publisher;
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.UnPublisher;
import com.alipay.sofa.registry.server.data.change.DataChangeTypeEnum;
import com.alipay.sofa.registry.server.data.change.DataSourceTypeEnum;
-import java.util.concurrent.atomic.AtomicBoolean;
-
/**
*
* @author qian.lqlq
@@ -44,16 +49,20 @@ public class DataChangeEventCenter {
*/
private DataChangeEventQueue[] dataChangeEventQueues;
- /**
- *
- * @param config
- */
- public void init(DataServerConfig config) {
+ @Autowired
+ private DataServerConfig dataServerConfig;
+
+ @Autowired
+ private DatumCache datumCache;
+
+ @PostConstruct
+ public void init() {
if (isInited.compareAndSet(false, true)) {
- queueCount = config.getQueueCount();
+ queueCount = dataServerConfig.getQueueCount();
dataChangeEventQueues = new DataChangeEventQueue[queueCount];
for (int idx = 0; idx < queueCount; idx++) {
- dataChangeEventQueues[idx] = new DataChangeEventQueue(idx, config);
+ dataChangeEventQueues[idx] = new DataChangeEventQueue(idx, dataServerConfig, this,
+ datumCache);
dataChangeEventQueues[idx].start();
}
}
@@ -101,6 +110,16 @@ public void onChange(ClientChangeEvent event) {
}
}
+ /**
+ *
+ * @param event
+ */
+ public void onChange(DatumSnapshotEvent event) {
+ for (DataChangeEventQueue dataChangeEventQueue : dataChangeEventQueues) {
+ dataChangeEventQueue.onChange(event);
+ }
+ }
+
/**
*
* @param changeType
@@ -118,7 +137,7 @@ public void sync(DataChangeTypeEnum changeType, DataSourceTypeEnum sourceType, D
* @param key
* @return
*/
- private int hash(String key) {
+ public int hash(String key) {
if (queueCount > 1) {
return Math.abs(key.hashCode() % queueCount);
} else {
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeEventQueue.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeEventQueue.java
index 99cd31bd3..f3b1f78cc 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeEventQueue.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeEventQueue.java
@@ -16,6 +16,16 @@
*/
package com.alipay.sofa.registry.server.data.change.event;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.DelayQueue;
+import java.util.concurrent.Executor;
+import java.util.concurrent.LinkedBlockingDeque;
+import java.util.concurrent.locks.ReentrantLock;
+
+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.log.Logger;
@@ -26,19 +36,12 @@
import com.alipay.sofa.registry.server.data.change.ChangeData;
import com.alipay.sofa.registry.server.data.change.DataChangeTypeEnum;
import com.alipay.sofa.registry.server.data.change.DataSourceTypeEnum;
+import com.alipay.sofa.registry.server.data.change.SnapshotData;
import com.alipay.sofa.registry.server.data.executor.ExecutorFactory;
import com.alipay.sofa.registry.server.data.node.DataServerNode;
import com.alipay.sofa.registry.server.data.remoting.dataserver.DataServerNodeFactory;
import com.google.common.collect.Interners;
-import java.util.Map;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.DelayQueue;
-import java.util.concurrent.Executor;
-import java.util.concurrent.LinkedBlockingDeque;
-import java.util.concurrent.locks.ReentrantLock;
-
/**
* a queue of DataChangeEvent
*
@@ -47,11 +50,16 @@
*/
public class DataChangeEventQueue {
- private static final Logger LOGGER = LoggerFactory
- .getLogger(DataChangeEventQueue.class);
+ private static final Logger LOGGER = LoggerFactory
+ .getLogger(DataChangeEventQueue.class);
- private static final Logger LOGGER_START = LoggerFactory
- .getLogger("DATA-START-LOGS");
+ private static final Logger LOGGER_START = LoggerFactory
+ .getLogger("DATA-START-LOGS");
+
+ private static final Logger RENEW_LOGGER = LoggerFactory
+ .getLogger(
+ ValueConstants.LOGGER_NAME_RENEW,
+ "[DataChangeEventQueue]");
/**
*
@@ -66,29 +74,36 @@ public class DataChangeEventQueue {
/**
*
*/
- private final Map> CHANGE_DATA_MAP = new ConcurrentHashMap<>();
+ private final Map> CHANGE_DATA_MAP_FOR_MERGE = new ConcurrentHashMap<>();
/**
*
*/
- private final DelayQueue CHANGE_QUEUE = new DelayQueue();
+ private final DelayQueue CHANGE_QUEUE = new DelayQueue();
private final int notifyIntervalMs;
private final int notifyTempDataIntervalMs;
- private final ReentrantLock lock = new ReentrantLock();
+ private final ReentrantLock lock = new ReentrantLock();
+
+ private final int queueIdx;
private DataServerConfig dataServerConfig;
+ private DataChangeEventCenter dataChangeEventCenter;
+
+ private DatumCache datumCache;
+
/**
* constructor
- * @param idx
+ * @param queueIdx
* @param dataServerConfig
*/
- public DataChangeEventQueue(int idx, DataServerConfig dataServerConfig) {
-
- this.name = String.format("%s_%s", DataChangeEventQueue.class.getSimpleName(), idx);
+ public DataChangeEventQueue(int queueIdx, DataServerConfig dataServerConfig,
+ DataChangeEventCenter dataChangeEventCenter, DatumCache datumCache) {
+ this.queueIdx = queueIdx;
+ this.name = String.format("%s_%s", DataChangeEventQueue.class.getSimpleName(), queueIdx);
this.dataServerConfig = dataServerConfig;
int queueSize = dataServerConfig.getQueueSize();
if (queueSize <= 0) {
@@ -98,6 +113,8 @@ public DataChangeEventQueue(int idx, DataServerConfig dataServerConfig) {
}
this.notifyIntervalMs = dataServerConfig.getNotifyIntervalMs();
this.notifyTempDataIntervalMs = dataServerConfig.getNotifyTempDataIntervalMs();
+ this.dataChangeEventCenter = dataChangeEventCenter;
+ this.datumCache = datumCache;
}
/**
@@ -126,16 +143,20 @@ public ChangeData take() throws InterruptedException {
ChangeData changeData = CHANGE_QUEUE.take();
lock.lock();
try {
- Datum datum = changeData.getDatum();
- if (changeData.getSourceType() != DataSourceTypeEnum.PUB_TEMP) {
- CHANGE_DATA_MAP.get(datum.getDataCenter()).remove(datum.getDataInfoId());
- }
+ removeMapForMerge(changeData);
return changeData;
} finally {
lock.unlock();
}
}
+ private void removeMapForMerge(ChangeData changeData) {
+ Datum datum = changeData.getDatum();
+ if (changeData.getSourceType() != DataSourceTypeEnum.PUB_TEMP && datum != null) {
+ CHANGE_DATA_MAP_FOR_MERGE.get(datum.getDataCenter()).remove(datum.getDataInfoId());
+ }
+ }
+
/**
*
* @param dataCenter
@@ -146,10 +167,10 @@ public ChangeData take() throws InterruptedException {
*/
private ChangeData getChangeData(String dataCenter, String dataInfoId,
DataSourceTypeEnum sourceType, DataChangeTypeEnum changeType) {
- Map map = CHANGE_DATA_MAP.get(dataCenter);
+ Map map = CHANGE_DATA_MAP_FOR_MERGE.get(dataCenter);
if (map == null) {
Map newMap = new ConcurrentHashMap<>();
- map = CHANGE_DATA_MAP.putIfAbsent(dataCenter, newMap);
+ map = CHANGE_DATA_MAP_FOR_MERGE.putIfAbsent(dataCenter, newMap);
if (map == null) {
map = newMap;
}
@@ -172,8 +193,8 @@ private ChangeData getChangeData(String dataCenter, String dataInfoId,
*
*/
public void start() {
- Executor executor = ExecutorFactory.newSingleThreadExecutor(
- String.format("%s_%s", DataChangeEventQueue.class.getSimpleName(), getName()));
+ Executor executor = ExecutorFactory
+ .newSingleThreadExecutor(String.format("%s_%s", DataChangeEventQueue.class.getSimpleName(), getName()));
executor.execute(() -> {
while (true) {
try {
@@ -182,16 +203,17 @@ public void start() {
if (scope == DataChangeScopeEnum.DATUM) {
DataChangeEvent dataChangeEvent = (DataChangeEvent) event;
//Temporary push data will be notify as soon as,and not merge to normal pub data;
- if (dataChangeEvent.getSourceType() == DataSourceTypeEnum.PUB_TEMP){
- addTempChangeData(dataChangeEvent.getDatum(),dataChangeEvent.getChangeType(),
+ if (dataChangeEvent.getSourceType() == DataSourceTypeEnum.PUB_TEMP) {
+ addTempChangeData(dataChangeEvent.getDatum(), dataChangeEvent.getChangeType(),
dataChangeEvent.getSourceType());
- }
- else {
- handleDatum(dataChangeEvent.getChangeType(),
- dataChangeEvent.getSourceType(), dataChangeEvent.getDatum());
+ } else {
+ handleDatum(dataChangeEvent.getChangeType(), dataChangeEvent.getSourceType(),
+ dataChangeEvent.getDatum());
}
} else if (scope == DataChangeScopeEnum.CLIENT) {
- handleHost((ClientChangeEvent) event);
+ handleClientOff((ClientChangeEvent) event);
+ } else if (scope == DataChangeScopeEnum.SNAPSHOT) {
+ handleSnapshot((DatumSnapshotEvent) event);
}
} catch (Throwable e) {
LOGGER.error("[{}] handle change event failed", getName(), e);
@@ -201,15 +223,21 @@ public void start() {
LOGGER_START.info("[{}] start DataChangeEventQueue success", getName());
}
- private void handleHost(ClientChangeEvent event) {
- String clientHost = event.getHost();
- synchronized (Interners.newWeakInterner().intern(clientHost)) {
- Map pubMap = DatumCache.getByHost(clientHost);
+ private void handleClientOff(ClientChangeEvent event) {
+ String connectId = event.getHost();
+ synchronized (Interners.newWeakInterner().intern(connectId)) {
+ Map pubMap = datumCache.getByConnectId(connectId);
if (pubMap != null && !pubMap.isEmpty()) {
- LOGGER.info("[{}] client off begin, host={}, occurTimestamp={},all pub size={}",
- getName(), clientHost, event.getOccurredTimestamp(), pubMap.size());
+ LOGGER.info(
+ "[{}] client off begin, connectId={}, occurTimestamp={}, all pubSize={}",
+ getName(), connectId, event.getOccurredTimestamp(), pubMap.size());
int count = 0;
for (Publisher publisher : pubMap.values()) {
+ // Only care dataInfoIds which belong to this queue
+ if (!belongTo(publisher.getDataInfoId())) {
+ continue;
+ }
+
DataServerNode dataServerNode = DataServerNodeFactory.computeDataServerNode(
dataServerConfig.getLocalDataCenter(), publisher.getDataInfoId());
//current dataCenter backup data need not unPub,it will be unPub by backup sync event
@@ -224,11 +252,11 @@ private void handleHost(ClientChangeEvent event) {
}
LOGGER
.info(
- "[{}] client off handle, host={}, occurTimestamp={},version={},handle pub size={}",
- getName(), clientHost, event.getOccurredTimestamp(), event.getVersion(),
+ "[{}] client off handle, connectId={}, occurTimestamp={}, version={}, handle pubSize={}",
+ getName(), connectId, event.getOccurredTimestamp(), event.getVersion(),
count);
} else {
- LOGGER.info("[{}] no datum to handle, host={}", getName(), clientHost);
+ LOGGER.info("[{}] no datum to handle, connectId={}", getName(), connectId);
}
}
}
@@ -259,7 +287,7 @@ private void handleDatum(DataChangeTypeEnum changeType, DataSourceTypeEnum sourc
// and version of cachePub is greater than version of pub, should be ignored
if (!(pub instanceof UnPublisher) && !(cachePub instanceof UnPublisher)
&& pub.getSourceAddress().equals(cachePub.getSourceAddress())
- && cachePub.getVersion() >= pub.getVersion()) {
+ && cachePub.getVersion() > pub.getVersion()) {
continue;
}
}
@@ -272,11 +300,76 @@ private void handleDatum(DataChangeTypeEnum changeType, DataSourceTypeEnum sourc
}
}
+ private void handleSnapshot(DatumSnapshotEvent event) {
+ String connectId = event.getConnectId();
+ Map cachePubMap = event.getCachePubMap();
+ Map snapshotPubMap = event.getPubMap();
+
+ // build SnapshotData
+ Map dataInfoId2SnapshotData = new HashMap<>();
+ synchronized (Interners.newWeakInterner().intern(connectId)) {
+ for (Map.Entry entry : snapshotPubMap.entrySet()) {
+ String registerId = entry.getKey();
+ Publisher publisher = entry.getValue();
+ String dataInfoId = publisher.getDataInfoId();
+
+ // Only care dataInfoIds which belong to this queue
+ if (!belongTo(dataInfoId)) {
+ continue;
+ }
+
+ SnapshotData snapshotData = getOrCreateSnapshotData(dataInfoId2SnapshotData,
+ dataInfoId);
+ snapshotData.getSnapshotPubMap().put(registerId, publisher);
+ }
+ for (Map.Entry entry : cachePubMap.entrySet()) {
+ String registerId = entry.getKey();
+ Publisher publisher = entry.getValue();
+ String dataInfoId = publisher.getDataInfoId();
+
+ // Only care dataInfoIds which belong to this queue
+ if (!belongTo(dataInfoId)) {
+ continue;
+ }
+
+ SnapshotData snapshotData = getOrCreateSnapshotData(dataInfoId2SnapshotData,
+ dataInfoId);
+ snapshotData.getToBeDeletedPubMap().put(registerId, publisher);
+ }
+ }
+
+ // put all SnapshotDatas to queue
+ for (SnapshotData snapshotData : dataInfoId2SnapshotData.values()) {
+ RENEW_LOGGER
+ .info(
+ "SnapshotData: connectId={}, dataInfoId={}, cachePubSize={}, snapshotPubSize={}",
+ connectId, snapshotData.getDataInfoId(), snapshotData.getToBeDeletedPubMap()
+ .size(), snapshotData.getSnapshotPubMap().size());
+ CHANGE_QUEUE.put(snapshotData);
+ }
+ }
+
+ private SnapshotData getOrCreateSnapshotData(Map dataInfoId2SnapshotData,
+ String dataInfoId) {
+ SnapshotData snapshotData = dataInfoId2SnapshotData.get(dataInfoId);
+ if (snapshotData == null) {
+ snapshotData = new SnapshotData(dataInfoId, new HashMap<>(), new HashMap<>());
+ dataInfoId2SnapshotData.put(dataInfoId, snapshotData);
+ }
+ return snapshotData;
+ }
+
private void addTempChangeData(Datum targetDatum, DataChangeTypeEnum changeType,
DataSourceTypeEnum sourceType) {
-
ChangeData tempChangeData = new ChangeData(targetDatum, this.notifyTempDataIntervalMs,
sourceType, changeType);
CHANGE_QUEUE.put(tempChangeData);
}
+
+ /**
+ * Determine whether dataInfoId belongs to the current queue
+ */
+ private boolean belongTo(String dataInfoId) {
+ return this.queueIdx == this.dataChangeEventCenter.hash(dataInfoId);
+ }
}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeScopeEnum.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeScopeEnum.java
index bfba719e5..94bbdb0d3 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeScopeEnum.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DataChangeScopeEnum.java
@@ -22,5 +22,5 @@
* @version $Id: DataChangeScopeEnum.java, v 0.1 2018-05-10 16:51 qian.lqlq Exp $
*/
public enum DataChangeScopeEnum {
- CLIENT, DATUM
+ CLIENT, DATUM, SNAPSHOT
}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DatumSnapshotEvent.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DatumSnapshotEvent.java
new file mode 100644
index 000000000..af08c25c6
--- /dev/null
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/event/DatumSnapshotEvent.java
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+package com.alipay.sofa.registry.server.data.change.event;
+
+import java.util.Map;
+
+import com.alipay.sofa.registry.common.model.store.Publisher;
+
+/**
+ *
+ * @author kezhu.wukz
+ * @version $Id: DatumSnapshotEvent.java, v 0.1 2019-05-30 18:22 kezhu.wukz Exp $
+ */
+public class DatumSnapshotEvent implements IDataChangeEvent {
+
+ /** connId, format is ip:port */
+ private String connectId;
+
+ private Map pubMap;
+
+ private Map cachePubMap;
+
+ public DatumSnapshotEvent(String connectId, Map cachePubMap,
+ Map pubMap) {
+ this.connectId = connectId;
+ this.cachePubMap = cachePubMap;
+ this.pubMap = pubMap;
+ }
+
+ /**
+ * Getter method for property connectId.
+ *
+ * @return property value of connectId
+ */
+ public String getConnectId() {
+ return connectId;
+ }
+
+ /**
+ * Getter method for property pubMap.
+ *
+ * @return property value of pubMap
+ */
+ public Map getPubMap() {
+ return pubMap;
+ }
+
+ /**
+ * Getter method for property cachePubMap.
+ *
+ * @return property value of cachePubMap
+ */
+ public Map getCachePubMap() {
+ return cachePubMap;
+ }
+
+ @Override
+ public DataChangeScopeEnum getScope() {
+ return DataChangeScopeEnum.SNAPSHOT;
+ }
+
+}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/notify/SessionServerNotifier.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/notify/SessionServerNotifier.java
index 727156d35..451f89804 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/notify/SessionServerNotifier.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/notify/SessionServerNotifier.java
@@ -16,6 +16,15 @@
*/
package com.alipay.sofa.registry.server.data.change.notify;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+import javax.annotation.PostConstruct;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
import com.alipay.remoting.Connection;
import com.alipay.sofa.registry.common.model.CommonResponse;
import com.alipay.sofa.registry.common.model.dataserver.Datum;
@@ -33,12 +42,6 @@
import com.alipay.sofa.registry.timer.AsyncHashedWheelTimer;
import com.alipay.sofa.registry.timer.AsyncHashedWheelTimer.TaskFailedCallback;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
/**
* Notify session DataChangeRequest,if fail get result callback retry
@@ -54,7 +57,7 @@ public class SessionServerNotifier implements IDataChangeNotifier {
private AsyncHashedWheelTimer asyncHashedWheelTimer;
@Autowired
- private DataServerConfig dataServerBootstrapConfig;
+ private DataServerConfig dataServerConfig;
@Autowired
private Exchange boltExchange;
@@ -62,13 +65,19 @@ public class SessionServerNotifier implements IDataChangeNotifier {
@Autowired
private SessionServerConnectionFactory sessionServerConnectionFactory;
- public SessionServerNotifier() {
+ @Autowired
+ private DatumCache datumCache;
+
+ @PostConstruct
+ public void init() {
ThreadFactoryBuilder threadFactoryBuilder = new ThreadFactoryBuilder();
threadFactoryBuilder.setDaemon(true);
asyncHashedWheelTimer = new AsyncHashedWheelTimer(threadFactoryBuilder.setNameFormat(
"Registry-SessionServerNotifier-WheelTimer").build(), 100, TimeUnit.MILLISECONDS, 1024,
- threadFactoryBuilder.setNameFormat("Registry-SessionServerNotifier-WheelExecutor-%d")
- .build(), new TaskFailedCallback() {
+ dataServerConfig.getSessionServerNotifierRetryExecutorThreadSize(),
+ dataServerConfig.getSessionServerNotifierRetryExecutorQueueSize(), threadFactoryBuilder
+ .setNameFormat("Registry-SessionServerNotifier-WheelExecutor-%d").build(),
+ new TaskFailedCallback() {
@Override
public void executionRejected(Throwable e) {
LOGGER.error("executionRejected: " + e.getMessage(), e);
@@ -86,6 +95,7 @@ public Set getSuitableSource() {
Set set = new HashSet<>();
set.add(DataSourceTypeEnum.PUB);
set.add(DataSourceTypeEnum.SYNC);
+ set.add(DataSourceTypeEnum.SNAPSHOT);
return set;
}
@@ -109,17 +119,17 @@ private void doNotify(NotifyCallback notifyCallback) {
LOGGER
.info(String
.format(
- "connection from sessionserver(%s) is not fine, so ignore notify, retryTimes=%s,request=%s",
+ "connection from sessionServer(%s) is not fine, so ignore notify, retryTimes=%s,request=%s",
connection.getRemoteAddress(), notifyCallback.retryTimes, request));
}
return;
}
- Server sessionServer = boltExchange.getServer(dataServerBootstrapConfig.getPort());
+ Server sessionServer = boltExchange.getServer(dataServerConfig.getPort());
sessionServer.sendCallback(sessionServer.getChannel(connection.getRemoteAddress()),
- request, notifyCallback, dataServerBootstrapConfig.getRpcTimeout());
+ request, notifyCallback, dataServerConfig.getRpcTimeout());
} catch (Exception e) {
LOGGER.error(String.format(
- "invokeWithCallback failed: sessionserver(%s),retryTimes=%s, request=%s",
+ "invokeWithCallback failed: sessionServer(%s),retryTimes=%s, request=%s",
connection.getRemoteAddress(), notifyCallback.retryTimes, request), e);
onFailed(notifyCallback);
}
@@ -133,14 +143,14 @@ private void onFailed(NotifyCallback notifyCallback) {
Connection connection = notifyCallback.connection;
notifyCallback.retryTimes++;
- if (notifyCallback.retryTimes <= dataServerBootstrapConfig.getNotifySessionRetryTimes()) {
+ if (notifyCallback.retryTimes <= dataServerConfig.getNotifySessionRetryTimes()) {
this.asyncHashedWheelTimer.newTimeout(timeout -> {
if (LOGGER.isInfoEnabled()) {
- LOGGER.info(String.format("retrying notify sessionserver(%s), retryTimes=%s, request=%s",
+ LOGGER.info(String.format("retrying notify sessionServer(%s), retryTimes=%s, request=%s",
connection.getRemoteAddress(), notifyCallback.retryTimes, request));
}
//check version, if it's fall behind, stop retry
- long currentVersion = DatumCache.get(request.getDataCenter(), request.getDataInfoId()).getVersion();
+ long currentVersion = datumCache.get(request.getDataCenter(), request.getDataInfoId()).getVersion();
if (request.getVersion() == currentVersion) {
doNotify(notifyCallback);
} else {
@@ -159,9 +169,9 @@ private void onFailed(NotifyCallback notifyCallback) {
}
private long getDelayTimeForRetry(int retryTimes) {
- long initialSleepTime = TimeUnit.MILLISECONDS.toMillis(dataServerBootstrapConfig
+ long initialSleepTime = TimeUnit.MILLISECONDS.toMillis(dataServerConfig
.getNotifySessionRetryFirstDelay());
- long increment = TimeUnit.MILLISECONDS.toMillis(dataServerBootstrapConfig
+ long increment = TimeUnit.MILLISECONDS.toMillis(dataServerConfig
.getNotifySessionRetryIncrementDelay());
long result = initialSleepTime + (increment * (retryTimes - 1));
return result >= 0L ? result : 0L;
@@ -185,7 +195,7 @@ public void onCallback(Channel channel, Object message) {
LOGGER
.error(String
.format(
- "response not success when notify sessionserver(%s), retryTimes=%s, request=%s, response=%s",
+ "response not success when notify sessionServer(%s), retryTimes=%s, request=%s, response=%s",
connection.getRemoteAddress(), retryTimes, request, result));
onFailed(this);
}
@@ -194,7 +204,7 @@ public void onCallback(Channel channel, Object message) {
@Override
public void onException(Channel channel, Throwable e) {
LOGGER.error(String.format(
- "exception when notify sessionserver(%s), retryTimes=%s, request=%s",
+ "exception when notify sessionServer(%s), retryTimes=%s, request=%s",
connection.getRemoteAddress(), retryTimes, request), e);
onFailed(this);
}
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/notify/SnapshotBackUpNotifier.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/notify/SnapshotBackUpNotifier.java
new file mode 100644
index 000000000..aab640fb2
--- /dev/null
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/notify/SnapshotBackUpNotifier.java
@@ -0,0 +1,51 @@
+/*
+ * 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.
+ */
+package com.alipay.sofa.registry.server.data.change.notify;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
+import com.alipay.sofa.registry.common.model.dataserver.Datum;
+import com.alipay.sofa.registry.server.data.change.DataSourceTypeEnum;
+import com.alipay.sofa.registry.server.data.datasync.SnapshotOperator;
+import com.alipay.sofa.registry.server.data.datasync.SyncDataService;
+
+/**
+ *
+ * @author kezhu.wukz
+ * @version $Id: SnapshotBackUpNotifier.java, v 0.1 2019-07-12 18:40 kezhu.wukz Exp $
+ */
+public class SnapshotBackUpNotifier implements IDataChangeNotifier {
+
+ @Autowired
+ private SyncDataService syncDataService;
+
+ @Override
+ public Set getSuitableSource() {
+ Set set = new HashSet<>();
+ set.add(DataSourceTypeEnum.SNAPSHOT);
+ return set;
+ }
+
+ @Override
+ public void notify(Datum datum, Long lastVersion) {
+ syncDataService.appendOperator(new SnapshotOperator(datum.getVersion(), lastVersion, datum,
+ DataSourceTypeEnum.BACKUP));
+ }
+}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/notify/TempPublisherNotifier.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/notify/TempPublisherNotifier.java
index b37fa7541..f4f5f5e9a 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/notify/TempPublisherNotifier.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/change/notify/TempPublisherNotifier.java
@@ -16,6 +16,13 @@
*/
package com.alipay.sofa.registry.server.data.change.notify;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Executor;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
import com.alipay.remoting.Connection;
import com.alipay.remoting.InvokeCallback;
import com.alipay.sofa.registry.common.model.CommonResponse;
@@ -31,12 +38,6 @@
import com.alipay.sofa.registry.server.data.change.DataSourceTypeEnum;
import com.alipay.sofa.registry.server.data.executor.ExecutorFactory;
import com.alipay.sofa.registry.server.data.remoting.sessionserver.SessionServerConnectionFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.Executor;
/**
*
@@ -54,7 +55,7 @@ public class TempPublisherNotifier implements IDataChangeNotifier {
.getSimpleName());
@Autowired
- private DataServerConfig dataServerBootstrapConfig;
+ private DataServerConfig dataServerConfig;
@Autowired
private Exchange boltExchange;
@@ -83,7 +84,7 @@ private void doNotify(NotifyPushDataCallback notifyPushdataCallback) {
Connection connection = notifyPushdataCallback.getConnection();
DataPushRequest request = notifyPushdataCallback.getRequest();
try {
- Server sessionServer = boltExchange.getServer(dataServerBootstrapConfig.getPort());
+ Server sessionServer = boltExchange.getServer(dataServerConfig.getPort());
sessionServer.sendCallback(sessionServer.getChannel(connection.getRemoteAddress()),
request, new CallbackHandler() {
@@ -96,7 +97,7 @@ public void onCallback(Channel channel, Object message) {
public void onException(Channel channel, Throwable exception) {
notifyPushdataCallback.onException(exception);
}
- }, dataServerBootstrapConfig.getRpcTimeout());
+ }, dataServerConfig.getRpcTimeout());
} catch (Exception e) {
LOGGER.error("[TempPublisherNotifier] notify sessionserver {} failed, {}",
connection.getRemoteIP(), request, e);
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/datasync/SnapshotOperator.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/datasync/SnapshotOperator.java
new file mode 100644
index 000000000..dd7aaf163
--- /dev/null
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/datasync/SnapshotOperator.java
@@ -0,0 +1,33 @@
+/*
+ * 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.
+ */
+package com.alipay.sofa.registry.server.data.datasync;
+
+import com.alipay.sofa.registry.common.model.dataserver.Datum;
+import com.alipay.sofa.registry.server.data.change.DataSourceTypeEnum;
+
+/**
+ *
+ * @author kezhu.wukz
+ * @version $Id: SnapshotOperator.java, v 0.1 2019-07-12 20:33 kezhu.wukz Exp $
+ */
+public class SnapshotOperator extends Operator {
+
+ public SnapshotOperator(Long version, Long sourceVersion, Datum datum,
+ DataSourceTypeEnum sourceType) {
+ super(version, sourceVersion, datum, sourceType);
+ }
+}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/datasync/sync/AbstractAcceptorStore.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/datasync/sync/AbstractAcceptorStore.java
index 70e644c0e..b07713814 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/datasync/sync/AbstractAcceptorStore.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/datasync/sync/AbstractAcceptorStore.java
@@ -16,6 +16,13 @@
*/
package com.alipay.sofa.registry.server.data.datasync.sync;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.DelayQueue;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
import com.alipay.remoting.Connection;
import com.alipay.sofa.registry.common.model.dataserver.Datum;
import com.alipay.sofa.registry.common.model.dataserver.NotifyDataSyncRequest;
@@ -26,18 +33,14 @@
import com.alipay.sofa.registry.remoting.Server;
import com.alipay.sofa.registry.remoting.exchange.Exchange;
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.datasync.AcceptorStore;
import com.alipay.sofa.registry.server.data.datasync.Operator;
+import com.alipay.sofa.registry.server.data.datasync.SnapshotOperator;
import com.alipay.sofa.registry.server.data.remoting.dataserver.DataServerConnectionFactory;
import com.alipay.sofa.registry.server.data.remoting.metaserver.IMetaServerService;
import com.alipay.sofa.registry.server.data.util.DelayItem;
import com.alipay.sofa.registry.server.data.util.TimeUtil;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.DelayQueue;
/**
*
@@ -61,11 +64,14 @@ public abstract class AbstractAcceptorStore implements AcceptorStore {
private Exchange boltExchange;
@Autowired
- private DataServerConfig dataServerBootstrapConfig;
+ private DataServerConfig dataServerConfig;
@Autowired
private DataServerConnectionFactory dataServerConnectionFactory;
+ @Autowired
+ private DatumCache datumCache;
+
private Map> acceptors = new ConcurrentHashMap<>();
private Map> notifyAcceptorsCache = new ConcurrentHashMap<>();
@@ -105,13 +111,21 @@ public void addOperator(Operator operator) {
Acceptor existAcceptor = acceptorMap.get(dataInfoId);
if (existAcceptor == null) {
- Acceptor newAcceptor = new Acceptor(DEFAULT_MAX_BUFFER_SIZE, dataInfoId, dataCenter);
+ Acceptor newAcceptor = new Acceptor(DEFAULT_MAX_BUFFER_SIZE, dataInfoId,
+ dataCenter, datumCache);
existAcceptor = acceptorMap.putIfAbsent(dataInfoId, newAcceptor);
if (existAcceptor == null) {
existAcceptor = newAcceptor;
}
}
- existAcceptor.appendOperator(operator);
+
+ if (operator instanceof SnapshotOperator) {
+ //snapshot: clear the queue, Make other data retrieve the latest memory data
+ existAcceptor.clearBefore();
+ } else {
+ existAcceptor.appendOperator(operator);
+ }
+
//put cache
putCache(existAcceptor);
} catch (Exception e) {
@@ -192,7 +206,7 @@ private void notifyChange(Acceptor acceptor) {
continue;
}
- Server syncServer = boltExchange.getServer(dataServerBootstrapConfig.getSyncDataPort());
+ Server syncServer = boltExchange.getServer(dataServerConfig.getSyncDataPort());
for (int tryCount = 0; tryCount < NOTIFY_RETRY; tryCount++) {
try {
@@ -234,6 +248,8 @@ public void changeDataCheck() {
removeCache(acceptor); // compare and remove
} catch (InterruptedException e) {
break;
+ } catch (Throwable e) {
+ LOGGER.error(e.getMessage(), e);
}
}
@@ -270,11 +286,11 @@ public SyncData getSyncData(SyncDataRequest syncDataRequest) {
}
/**
- * Getter method for property dataServerBootstrapConfig.
+ * Getter method for property dataServerConfig.
*
- * @return property value of dataServerBootstrapConfig
+ * @return property value of dataServerConfig
*/
public DataServerConfig getDataServerConfig() {
- return dataServerBootstrapConfig;
+ return dataServerConfig;
}
}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/datasync/sync/Acceptor.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/datasync/sync/Acceptor.java
index 5650ea263..b758cf6fa 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/datasync/sync/Acceptor.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/datasync/sync/Acceptor.java
@@ -16,13 +16,6 @@
*/
package com.alipay.sofa.registry.server.data.datasync.sync;
-import com.alipay.sofa.registry.common.model.dataserver.Datum;
-import com.alipay.sofa.registry.common.model.dataserver.SyncData;
-import com.alipay.sofa.registry.log.Logger;
-import com.alipay.sofa.registry.log.LoggerFactory;
-import com.alipay.sofa.registry.server.data.cache.DatumCache;
-import com.alipay.sofa.registry.server.data.datasync.Operator;
-
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collection;
@@ -36,6 +29,14 @@
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
+import com.alipay.sofa.registry.common.model.dataserver.Datum;
+import com.alipay.sofa.registry.common.model.dataserver.SyncData;
+import com.alipay.sofa.registry.log.Logger;
+import com.alipay.sofa.registry.log.LoggerFactory;
+import com.alipay.sofa.registry.server.data.cache.DatumCache;
+import com.alipay.sofa.registry.server.data.datasync.Operator;
+import com.alipay.sofa.registry.util.DatumVersionUtil;
+
/**
*
* @author shangyu.wh
@@ -57,16 +58,19 @@ public class Acceptor {
private final Lock read = readWriteLock.readLock();
private final Lock write = readWriteLock.writeLock();
+ private final DatumCache datumCache;
+
/**
* constructor
* @param maxBufferSize
* @param dataInfoId
* @param dataCenter
*/
- public Acceptor(int maxBufferSize, String dataInfoId, String dataCenter) {
+ public Acceptor(int maxBufferSize, String dataInfoId, String dataCenter, DatumCache datumCache) {
this.maxBufferSize = maxBufferSize;
this.dataInfoId = dataInfoId;
this.dataCenter = dataCenter;
+ this.datumCache = datumCache;
}
/**
@@ -146,7 +150,7 @@ public SyncData process(Long currentVersion) {
//first get all data
if (operators.isEmpty()) {
wholeDataTag = true;
- retList.add(DatumCache.get(dataCenter, dataInfoId));
+ retList.add(datumCache.get(dataCenter, dataInfoId));
LOGGER.info("Get all data!dataInfoID:{} dataCenter:{}.All data size{}:",
dataInfoId, dataCenter, retList.size());
} else {
@@ -162,7 +166,7 @@ public SyncData process(Long currentVersion) {
"Append log queue is empty,Maybe all logs record expired or no operator append!So must get all data!dataInfoID:{} dataCenter:{}.queue size{}:",
dataInfoId, dataCenter, logOperatorsOrder.size());
wholeDataTag = true;
- retList.add(DatumCache.get(dataCenter, dataInfoId));
+ retList.add(datumCache.get(dataCenter, dataInfoId));
syncData = new SyncData(dataInfoId, dataCenter, wholeDataTag, retList);
}
@@ -250,7 +254,8 @@ private boolean isFull() {
private boolean isExpired(int durationSECS, long peekVersion) {
durationSECS = (durationSECS > 0) ? durationSECS * 1000 : DEFAULT_DURATION_SECS * 1000;
- boolean ret = System.currentTimeMillis() > peekVersion + durationSECS;
+ boolean ret = System.currentTimeMillis() > DatumVersionUtil.getRealTimestamp(peekVersion)
+ + durationSECS;
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("now:" + System.currentTimeMillis() + " peek:" + peekVersion + " du:"
+ durationSECS + " result:" + ret);
@@ -258,7 +263,7 @@ private boolean isExpired(int durationSECS, long peekVersion) {
return ret;
}
- private void clearBefore() {
+ public void clearBefore() {
write.lock();
try {
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/DataServerChangeEvent.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/DataServerChangeEvent.java
index a41dfd113..447c3af8c 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/DataServerChangeEvent.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/DataServerChangeEvent.java
@@ -29,14 +29,24 @@
*/
public class DataServerChangeEvent {
+ /**
+ * node type enum
+ */
+ public enum FromType {
+ CONNECT_TASK, META_NOTIFY, REGISTER_META
+ }
+
private DataServerChangeItem dataServerChangeItem;
+ private FromType fromType;
+
/**
* constructor
* @param dataServerChangeItem
*/
- public DataServerChangeEvent(DataServerChangeItem dataServerChangeItem) {
+ public DataServerChangeEvent(DataServerChangeItem dataServerChangeItem, FromType fromType) {
this.dataServerChangeItem = dataServerChangeItem;
+ this.fromType = fromType;
}
/**
@@ -45,7 +55,7 @@ public DataServerChangeEvent(DataServerChangeItem dataServerChangeItem) {
* @param versionMap
*/
public DataServerChangeEvent(Map> serverMap,
- Map versionMap) {
+ Map versionMap, FromType fromType) {
if (serverMap == null) {
serverMap = new HashMap<>();
}
@@ -53,6 +63,8 @@ public DataServerChangeEvent(Map> serverMap,
versionMap = new HashMap<>();
}
this.dataServerChangeItem = new DataServerChangeItem(serverMap, versionMap);
+
+ this.fromType = fromType;
}
/**
@@ -63,4 +75,13 @@ public DataServerChangeEvent(Map> serverMap,
public DataServerChangeItem getDataServerChangeItem() {
return dataServerChangeItem;
}
+
+ /**
+ * Getter method for property fromType.
+ *
+ * @return property value of fromType
+ */
+ public FromType getFromType() {
+ return fromType;
+ }
}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/StartTaskTypeEnum.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/StartTaskTypeEnum.java
index a015a1f4d..49217c99f 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/StartTaskTypeEnum.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/StartTaskTypeEnum.java
@@ -34,7 +34,7 @@ public enum StartTaskTypeEnum {
CONNECT_DATA,
/**
- * ReNewNodeTask
+ * RenewNodeTask
*/
RENEW,
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/DataServerChangeEventHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/DataServerChangeEventHandler.java
index b2b1ec0a5..d9a0a3d49 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/DataServerChangeEventHandler.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/DataServerChangeEventHandler.java
@@ -55,7 +55,7 @@ public class DataServerChangeEventHandler extends AbstractEventHandler localDataServers = dataServerCache.getDataServers(
- dataServerBootstrapConfig.getLocalDataCenter()).keySet();
+ dataServerConfig.getLocalDataCenter()).keySet();
//get changed dataservers
Map> changedMap = dataServerCache
- .compareAndSet(dataServerChangeItem);
+ .compareAndSet(dataServerChangeItem,event.getFromType());
if(!changedMap.isEmpty()) {
for (Entry> changeEntry : changedMap.entrySet()) {
String dataCenter = changeEntry.getKey();
@@ -102,34 +102,34 @@ public void doHandle(DataServerChangeEvent event) {
Set ipSet = DataServerNodeFactory.getIps(dataCenter);
for (String ip : ipSet) {
if (!ips.contains(ip)) {
- DataServerNodeFactory.remove(dataCenter, ip, dataServerBootstrapConfig);
+ DataServerNodeFactory.remove(dataCenter, ip, dataServerConfig);
LOGGER.info(
- "[DataServerChangeEventHandler] remove connection, datacenter:{}, ip:{}",
- dataCenter, ip);
+ "[DataServerChangeEventHandler] remove connection, datacenter:{}, ip:{},from:{}",
+ dataCenter, ip,event.getFromType());
}
}
Long newVersion = dataServerCache.getDataCenterNewVersion(dataCenter);
Map newDataNodes = dataServerCache.getNewDataServerMap(dataCenter);
//if the datacenter is self, post LocalDataServerChangeEvent
- if (dataServerBootstrapConfig.getLocalDataCenter().equals(dataCenter)) {
+ if (dataServerConfig.getLocalDataCenter().equals(dataCenter)) {
Set newjoined = new HashSet<>(ips);
newjoined.removeAll(localDataServers);
//avoid input map reference operation DataServerNodeFactory MAP
Map map = new ConcurrentHashMap<>(newDataNodes);
- LOGGER.info("Node list change fire LocalDataServerChangeEvent,current node list={},version={}",
- map.keySet(), newVersion);
+ LOGGER.info("Node list change fire LocalDataServerChangeEvent,current node list={},version={},from:{}",
+ map.keySet(), newVersion,event.getFromType());
eventCenter.post(new LocalDataServerChangeEvent(map, newjoined,
dataServerChangeItem.getVersionMap()
- .get(dataServerBootstrapConfig.getLocalDataCenter()),
+ .get(dataServerConfig.getLocalDataCenter()),
newVersion));
} else {
dataServerCache.updateItem(newDataNodes, newVersion, dataCenter);
}
} else {
//if the datacenter which has no dataservers is not self, remove it
- if (!dataServerBootstrapConfig.getLocalDataCenter().equals(dataCenter)) {
+ if (!dataServerConfig.getLocalDataCenter().equals(dataCenter)) {
removeDataCenter(dataCenter);
}
Long newVersion = dataServerCache.getDataCenterNewVersion(dataCenter);
@@ -148,8 +148,8 @@ public void doHandle(DataServerChangeEvent event) {
if (!StringUtils.equals(ip, DataServerConfig.IP)) {
Connection connection = dataServerNode.getConnection();
if (connection != null && !connection.isFine()) {
- LOGGER.warn("[DataServerChangeEventHandler] dataServer connections is not fine,try to reconnect it,old connection={},dataCenter={}",
- connection.getRemoteAddress(), dataCenter);
+ LOGGER.warn("[DataServerChangeEventHandler] dataServer connections is not fine,try to reconnect it,old connection={},dataCenter={},from:{}",
+ connection.getRemoteAddress(), dataCenter,event.getFromType());
connectDataServer(dataCenter, ip);
}
}
@@ -170,8 +170,8 @@ private void connectDataServer(String dataCenter, String ip) {
Connection conn = null;
for (int tryCount = 0; tryCount < TRY_COUNT; tryCount++) {
try {
- conn = ((BoltChannel) dataNodeExchanger.connect(new URL(ip,
- dataServerBootstrapConfig.getSyncDataPort()))).getConnection();
+ conn = ((BoltChannel) dataNodeExchanger.connect(new URL(ip, dataServerConfig
+ .getSyncDataPort()))).getConnection();
break;
} catch (Exception e) {
LOGGER.error("[DataServerChangeEventHandler] connect dataServer {} in {} error",
@@ -189,11 +189,8 @@ private void connectDataServer(String dataCenter, String ip) {
"[DataServerChangeEventHandler] connect dataserver %s in %s failed five times,dataServer will not work,please check connect!",
ip, dataCenter));
}
- LOGGER.info("[DataServerChangeEventHandler] connect dataserver {} in {} success", ip,
- dataCenter);
//maybe get dataNode from metaServer,current has not start! register dataNode info to factory,wait for connect task next execute
- DataServerNodeFactory.register(new DataServerNode(ip, dataCenter, conn),
- dataServerBootstrapConfig);
+ DataServerNodeFactory.register(new DataServerNode(ip, dataCenter, conn), dataServerConfig);
}
/**
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/LocalDataServerChangeEventHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/LocalDataServerChangeEventHandler.java
index 9a79171e6..d303d192e 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/LocalDataServerChangeEventHandler.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/LocalDataServerChangeEventHandler.java
@@ -16,6 +16,7 @@
*/
package com.alipay.sofa.registry.server.data.event.handler;
+import com.alipay.remoting.Connection;
import com.alipay.sofa.registry.common.model.CommonResponse;
import com.alipay.sofa.registry.common.model.dataserver.Datum;
import com.alipay.sofa.registry.common.model.dataserver.NotifyFetchDatumRequest;
@@ -25,18 +26,20 @@
import com.alipay.sofa.registry.consistency.hash.ConsistentHash;
import com.alipay.sofa.registry.log.Logger;
import com.alipay.sofa.registry.log.LoggerFactory;
+import com.alipay.sofa.registry.remoting.bolt.BoltChannel;
import com.alipay.sofa.registry.remoting.exchange.message.Request;
import com.alipay.sofa.registry.server.data.bootstrap.DataServerConfig;
import com.alipay.sofa.registry.server.data.cache.BackupTriad;
import com.alipay.sofa.registry.server.data.cache.DataServerCache;
import com.alipay.sofa.registry.server.data.cache.DatumCache;
-import com.alipay.sofa.registry.server.data.correction.LocalDataServerCleanHandler;
import com.alipay.sofa.registry.server.data.event.LocalDataServerChangeEvent;
import com.alipay.sofa.registry.server.data.executor.ExecutorFactory;
import com.alipay.sofa.registry.server.data.node.DataNodeStatus;
import com.alipay.sofa.registry.server.data.node.DataServerNode;
import com.alipay.sofa.registry.server.data.remoting.DataNodeExchanger;
import com.alipay.sofa.registry.server.data.remoting.dataserver.DataServerNodeFactory;
+import com.alipay.sofa.registry.server.data.renew.DatumLeaseManager;
+import com.alipay.sofa.registry.server.data.renew.LocalDataServerCleanHandler;
import com.alipay.sofa.registry.server.data.util.LocalServerStatusEnum;
import com.alipay.sofa.registry.server.data.util.TimeUtil;
import com.google.common.collect.Lists;
@@ -46,7 +49,6 @@
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
@@ -66,7 +68,7 @@ public class LocalDataServerChangeEventHandler extends
.getLogger(LocalDataServerChangeEventHandler.class);
@Autowired
- private DataServerConfig dataServerBootstrapConfig;
+ private DataServerConfig dataServerConfig;
@Autowired
private LocalDataServerCleanHandler localDataServerCleanHandler;
@@ -80,10 +82,18 @@ public class LocalDataServerChangeEventHandler extends
@Autowired
private DataNodeStatus dataNodeStatus;
+ @Autowired
+ private DatumCache datumCache;
+
+ @Autowired
+ private DatumLeaseManager datumLeaseManager;
+
private BlockingQueue events = new LinkedBlockingDeque<>();
private AtomicBoolean isChanged = new AtomicBoolean(false);
+ private static final int TRY_COUNT = 5;
+
@Override
public Class interest() {
return LocalDataServerChangeEvent.class;
@@ -92,7 +102,11 @@ public Class interest() {
@Override
public void doHandle(LocalDataServerChangeEvent localDataServerChangeEvent) {
isChanged.set(true);
+
+ // Better change to Listener pattern
localDataServerCleanHandler.reset();
+ datumLeaseManager.reset();
+
events.offer(localDataServerChangeEvent);
}
@@ -119,11 +133,11 @@ public void run() {
try {
LocalDataServerChangeEvent event = events.take();
//if the new joined servers contains self, set status as INITIAL
- Set newJoined = event.getNewJoined();
- if (newJoined.contains(DataServerConfig.IP)
- && dataNodeStatus.getStatus() != LocalServerStatusEnum.INITIAL) {
- dataNodeStatus.setStatus(LocalServerStatusEnum.INITIAL);
- }
+ //Set newJoined = event.getNewJoined();
+ //if (newJoined.contains(DataServerConfig.IP)
+ // && dataNodeStatus.getStatus() != LocalServerStatusEnum.INITIAL) {
+ // dataNodeStatus.setStatus(LocalServerStatusEnum.INITIAL);
+ //}
//if size of events is greater than 0, not handle and continue, only handle the last one in the queue
if (events.size() > 0) {
continue;
@@ -143,7 +157,7 @@ public void run() {
dataServerCache.updateItem(event.getLocalDataServerMap(),
event.getLocalDataCenterversion(),
- dataServerBootstrapConfig.getLocalDataCenter());
+ dataServerConfig.getLocalDataCenter());
}
} catch (Throwable t) {
LOGGER.error("sync local data error", t);
@@ -162,7 +176,7 @@ private void notifyToFetch(LocalDataServerChangeEvent event, long changeVersion)
Map dataServerMapIn = event.getLocalDataServerMap();
List dataServerNodeList = Lists.newArrayList(dataServerMapIn.values());
ConsistentHash consistentHash = new ConsistentHash<>(
- dataServerBootstrapConfig.getNumberOfReplicas(), dataServerNodeList);
+ dataServerConfig.getNumberOfReplicas(), dataServerNodeList);
Map dataServerMap = new ConcurrentHashMap<>(dataServerMapIn);
Map>> toBeSyncMap = getToBeSyncMap(consistentHash);
@@ -182,7 +196,7 @@ private void notifyToFetch(LocalDataServerChangeEvent event, long changeVersion)
for (Entry dataTriadEntry : dataTriadMap
.entrySet()) {
String dataInfoId = dataTriadEntry.getKey();
- Datum datum = DatumCache.get(dataCenter, dataInfoId);
+ Datum datum = datumCache.get(dataCenter, dataInfoId);
if (datum != null) {
versionMap.put(dataInfoId, datum.getVersion());
}
@@ -212,7 +226,7 @@ private void notifyToFetch(LocalDataServerChangeEvent event, long changeVersion)
if (!isChanged.get()) {
//update server list
dataServerCache.updateItem(dataServerMapIn, event.getLocalDataCenterversion(),
- dataServerBootstrapConfig.getLocalDataCenter());
+ dataServerConfig.getLocalDataCenter());
}
}
}
@@ -229,14 +243,14 @@ private void notifyToFetch(LocalDataServerChangeEvent event, long changeVersion)
Map> triadCache = new HashMap<>();
ConsistentHash consistentHashOld = dataServerCache
- .calculateOldConsistentHash(dataServerBootstrapConfig.getLocalDataCenter());
+ .calculateOldConsistentHash(dataServerConfig.getLocalDataCenter());
if (consistentHash == null) {
LOGGER.error("Calculate Old ConsistentHash error!");
throw new RuntimeException("Calculate Old ConsistentHash error!");
}
//compute new triad for every datum in cache
- Map> allMap = DatumCache.getAll();
+ Map> allMap = datumCache.getAll();
for (Entry> dataCenterEntry : allMap.entrySet()) {
String dataCenter = dataCenterEntry.getKey();
Map datumMap = dataCenterEntry.getValue();
@@ -251,12 +265,12 @@ private void notifyToFetch(LocalDataServerChangeEvent event, long changeVersion)
backupNodes = triadCache.get(dataInfoId);
} else {
backupNodes = consistentHash.getNUniqueNodesFor(dataInfoId,
- dataServerBootstrapConfig.getStoreNodes());
+ dataServerConfig.getStoreNodes());
triadCache.put(dataInfoId, backupNodes);
}
BackupTriad backupTriad = new BackupTriad(dataInfoId,
consistentHashOld.getNUniqueNodesFor(dataInfoId,
- dataServerBootstrapConfig.getStoreNodes()));
+ dataServerConfig.getStoreNodes()));
if (backupTriad != null) {
List newJoinedNodes = backupTriad.getNewJoined(backupNodes,
dataServerCache.getNotWorking());
@@ -296,7 +310,7 @@ private boolean doNotify(String targetIp, Map> notifyV
long version) {
while (!isChanged.get()) {
DataServerNode targetNode = DataServerNodeFactory.getDataServerNode(
- dataServerBootstrapConfig.getLocalDataCenter(), targetIp);
+ dataServerConfig.getLocalDataCenter(), targetIp);
if (targetNode == null || targetNode.getConnection() == null) {
LOGGER.info(
"notify version change to sync has not connect,targetNode={}, map={}",
@@ -343,31 +357,37 @@ public URL getRequestUrl() {
*/
private void notifyOnline(long changeVersion) {
Map dataServerNodeMap = DataServerNodeFactory
- .getDataServerNodes(dataServerBootstrapConfig.getLocalDataCenter());
+ .getDataServerNodes(dataServerConfig.getLocalDataCenter());
for (Entry serverEntry : dataServerNodeMap.entrySet()) {
while (true) {
String ip = serverEntry.getKey();
- DataServerNode dataServerNode = serverEntry.getValue();
+ DataServerNode dataServerNode = DataServerNodeFactory.getDataServerNode(
+ dataServerConfig.getLocalDataCenter(), ip);
+
if (dataServerNode == null) {
+ LOGGER
+ .warn(
+ "notify Online dataserver {} has not existed in DataServerNodeFactory!version={}",
+ ip, changeVersion);
break;
}
try {
- if (dataServerNode.getConnection() == null
- || !dataServerNode.getConnection().isFine()) {
- LOGGER
- .warn(
- "notify Online dataserver connect {} not existed or not fine!version={}",
- ip, changeVersion);
- Map dataServerNodeMapCurrent = DataServerNodeFactory
- .getDataServerNodes(dataServerBootstrapConfig.getLocalDataCenter());
- DataServerNode dataServerNodeCurrent = dataServerNodeMapCurrent.get(ip);
- if (dataServerNodeCurrent == null) {
+ final Connection connection = dataServerNode.getConnection();
+ if (connection == null || !connection.isFine()) {
+ if (connection == null) {
LOGGER
.warn(
- "notify Online dataserver {} has not existed in DataServerNodeFactory!version={}",
+ "notify Online dataserver connect not existed,ip={},version={}",
ip, changeVersion);
- break;
+ } else {
+ LOGGER
+ .warn(
+ "notify Online dataserver connect not fine!remote={},local={},version={}",
+ connection.getRemoteAddress(),
+ connection.getLocalAddress(), changeVersion);
}
+ //connect now and registry connect
+ connectDataServer(dataServerConfig.getLocalDataCenter(), ip);
//maybe get dataNode from metaServer,current has not connected!wait for connect task execute
TimeUtil.randomDelay(1000);
continue;
@@ -383,8 +403,8 @@ public Object getRequestBody() {
@Override
public URL getRequestUrl() {
- return new URL(dataServerNode.getConnection().getRemoteIP(),
- dataServerNode.getConnection().getRemotePort());
+ return new URL(connection.getRemoteIP(), connection
+ .getRemotePort());
}
}).getResult();
if (response.isSuccess()) {
@@ -403,5 +423,44 @@ public URL getRequestUrl() {
}
}
+ /**
+ * connect specific dataserver
+ *
+ * @param dataCenter
+ * @param ip
+ */
+ private void connectDataServer(String dataCenter, String ip) {
+ Connection conn = null;
+ for (int tryCount = 0; tryCount < TRY_COUNT; tryCount++) {
+ try {
+ conn = ((BoltChannel) dataNodeExchanger.connect(new URL(ip, dataServerConfig
+ .getSyncDataPort()))).getConnection();
+ break;
+ } catch (Exception e) {
+ LOGGER.error(
+ "[LocalDataServerChangeEventHandler] connect dataServer {} in {} error",
+ ip, dataCenter, e);
+ TimeUtil.randomDelay(3000);
+ }
+ }
+ if (conn == null || !conn.isFine()) {
+ LOGGER
+ .error(
+ "[LocalDataServerChangeEventHandler] connect dataserver {} in {} failed five times",
+ ip, dataCenter);
+ throw new RuntimeException(
+ String
+ .format(
+ "[LocalDataServerChangeEventHandler] connect dataserver %s in %s failed five times,dataServer will not work,please check connect!",
+ ip, dataCenter));
+ }
+ LOGGER
+ .info(
+ "[LocalDataServerChangeEventHandler] connect dataserver in {} success,remote={},local={}",
+ dataCenter, conn.getRemoteAddress(), conn.getLocalAddress());
+ //maybe get dataNode from metaServer,current has not start! register dataNode info to factory,wait for connect task next execute
+ DataServerNodeFactory.register(new DataServerNode(ip, dataCenter, conn),
+ dataServerConfig);
+ }
}
}
\ No newline at end of file
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/MetaServerChangeEventHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/MetaServerChangeEventHandler.java
index 9b035c98b..1498d8947 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/MetaServerChangeEventHandler.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/event/handler/MetaServerChangeEventHandler.java
@@ -56,7 +56,7 @@ public class MetaServerChangeEventHandler extends AbstractEventHandler dataClientHandlers;
@@ -60,11 +62,11 @@ public Response request(Request request) {
if (null != request.getCallBackHandler()) {
client.sendCallback(channel, request.getRequestBody(),
request.getCallBackHandler(),
- dataServerBootstrapConfig.getRpcTimeout());
+ dataServerConfig.getRpcTimeout());
return () -> Response.ResultStatus.SUCCESSFUL;
} else {
final Object result = client.sendSync(channel, request.getRequestBody(),
- dataServerBootstrapConfig.getRpcTimeout());
+ dataServerConfig.getRpcTimeout());
return () -> result;
}
}
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/MetaNodeExchanger.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/MetaNodeExchanger.java
index 607beec97..c79b8dabf 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/MetaNodeExchanger.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/MetaNodeExchanger.java
@@ -16,6 +16,12 @@
*/
package com.alipay.sofa.registry.server.data.remoting;
+import java.util.Collection;
+
+import javax.annotation.Resource;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
import com.alipay.sofa.registry.common.model.store.URL;
import com.alipay.sofa.registry.log.Logger;
import com.alipay.sofa.registry.log.LoggerFactory;
@@ -29,10 +35,6 @@
import com.alipay.sofa.registry.server.data.bootstrap.DataServerConfig;
import com.alipay.sofa.registry.server.data.remoting.handler.AbstractClientHandler;
import com.alipay.sofa.registry.server.data.remoting.metaserver.IMetaServerService;
-import org.springframework.beans.factory.annotation.Autowired;
-
-import javax.annotation.Resource;
-import java.util.Collection;
/**
* @author xuanbei
@@ -49,7 +51,7 @@ public class MetaNodeExchanger implements NodeExchanger {
private IMetaServerService metaServerService;
@Autowired
- private DataServerConfig dataServerBootstrapConfig;
+ private DataServerConfig dataServerConfig;
@Resource(name = "metaClientHandlers")
private Collection metaClientHandlers;
@@ -63,12 +65,12 @@ public Response request(Request request) {
try {
final Object result = client.sendSync(channel, request.getRequestBody(),
- dataServerBootstrapConfig.getRpcTimeout());
+ dataServerConfig.getRpcTimeout());
return () -> result;
} catch (Exception e) {
//retry
URL url = new URL(metaServerService.refreshLeader().getIp(),
- dataServerBootstrapConfig.getMetaServerPort());
+ dataServerConfig.getMetaServerPort());
channel = client.getChannel(url);
if (channel == null) {
channel = client.connect(url);
@@ -76,7 +78,7 @@ public Response request(Request request) {
LOGGER.warn("MetaNode Exchanger request send error!It will be retry once!Request url:{}", url);
final Object result = client.sendSync(channel, request.getRequestBody(),
- dataServerBootstrapConfig.getRpcTimeout());
+ dataServerConfig.getRpcTimeout());
return () -> result;
}
}
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/DataServerNodeFactory.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/DataServerNodeFactory.java
index 53a484bea..f13e88355 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/DataServerNodeFactory.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/DataServerNodeFactory.java
@@ -59,14 +59,18 @@ public class DataServerNodeFactory {
*
* @param dataServerNode
*/
- public static void register(DataServerNode dataServerNode,
- DataServerConfig dataServerBootstrapConfig) {
+ public static void register(DataServerNode dataServerNode, DataServerConfig dataServerConfig) {
String dataCenter = dataServerNode.getDataCenter();
- if (!MAP.containsKey(dataCenter)) {
- MAP.put(dataCenter, new ConcurrentHashMap<>());
+ Map dataMap = MAP.get(dataCenter);
+ if (dataMap == null) {
+ Map newMap = new ConcurrentHashMap<>();
+ dataMap = MAP.putIfAbsent(dataCenter, newMap);
+ if (dataMap == null) {
+ dataMap = newMap;
+ }
}
- MAP.get(dataCenter).put(dataServerNode.getIp(), dataServerNode);
- refreshConsistent(dataCenter, dataServerBootstrapConfig);
+ dataMap.put(dataServerNode.getIp(), dataServerNode);
+ refreshConsistent(dataCenter, dataServerConfig);
}
/**
@@ -74,31 +78,29 @@ public static void register(DataServerNode dataServerNode,
*
* @param dataCenter
*/
- public static void refreshConsistent(String dataCenter,
- DataServerConfig dataServerBootstrapConfig) {
+ public static void refreshConsistent(String dataCenter, DataServerConfig dataServerConfig) {
List dataServerNodes = Lists.newArrayList(MAP.get(dataCenter).values());
- if (dataServerBootstrapConfig.getLocalDataCenter().equals(dataCenter)) {
+ if (dataServerConfig.getLocalDataCenter().equals(dataCenter)) {
if (!MAP.get(dataCenter).keySet().contains(DataServerConfig.IP)) {
- dataServerNodes.add(new DataServerNode(DataServerConfig.IP,
- dataServerBootstrapConfig.getLocalDataCenter(), null));
+ dataServerNodes.add(new DataServerNode(DataServerConfig.IP, dataServerConfig
+ .getLocalDataCenter(), null));
}
}
CONSISTENT_HASH_MAP.put(dataCenter,
- new ConsistentHash<>(dataServerBootstrapConfig.getNumberOfReplicas(), dataServerNodes));
+ new ConsistentHash<>(dataServerConfig.getNumberOfReplicas(), dataServerNodes));
}
/**
* for single node consistentHash
- * @param dataServerBootstrapConfig
+ * @param dataServerConfig
*/
- public static void initConsistent(DataServerConfig dataServerBootstrapConfig) {
+ public static void initConsistent(DataServerConfig dataServerConfig) {
if (init.compareAndSet(false, true)) {
List dataServerNodes = Lists.newArrayList();
- dataServerNodes.add(new DataServerNode(DataServerConfig.IP, dataServerBootstrapConfig
+ dataServerNodes.add(new DataServerNode(DataServerConfig.IP, dataServerConfig
.getLocalDataCenter(), null));
- CONSISTENT_HASH_MAP.put(dataServerBootstrapConfig.getLocalDataCenter(),
- new ConsistentHash<>(dataServerBootstrapConfig.getNumberOfReplicas(),
- dataServerNodes));
+ CONSISTENT_HASH_MAP.put(dataServerConfig.getLocalDataCenter(), new ConsistentHash<>(
+ dataServerConfig.getNumberOfReplicas(), dataServerNodes));
}
}
@@ -155,8 +157,7 @@ public static Set getIps(String dataCenter) {
* @param dataCenter
* @param ip
*/
- public static void remove(String dataCenter, String ip,
- DataServerConfig dataServerBootstrapConfig) {
+ public static void remove(String dataCenter, String ip, DataServerConfig dataServerConfig) {
if (MAP.containsKey(dataCenter)) {
Map map = MAP.get(dataCenter);
if (map != null) {
@@ -168,7 +169,7 @@ public static void remove(String dataCenter, String ip,
map.remove(ip);
}
}
- refreshConsistent(dataCenter, dataServerBootstrapConfig);
+ refreshConsistent(dataCenter, dataServerConfig);
}
/**
diff --git a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/FetchDataHandler.java b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/FetchDataHandler.java
index 76c9c0b33..0ebcab135 100644
--- a/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/FetchDataHandler.java
+++ b/server/server/data/src/main/java/com/alipay/sofa/registry/server/data/remoting/dataserver/handler/FetchDataHandler.java
@@ -16,6 +16,10 @@
*/
package com.alipay.sofa.registry.server.data.remoting.dataserver.handler;
+import java.util.Map;
+
+import org.springframework.beans.factory.annotation.Autowired;
+
import com.alipay.sofa.registry.common.model.GenericResponse;
import com.alipay.sofa.registry.common.model.Node;
import com.alipay.sofa.registry.common.model.dataserver.Datum;
@@ -25,8 +29,6 @@
import com.alipay.sofa.registry.server.data.remoting.handler.AbstractClientHandler;
import com.alipay.sofa.registry.util.ParaCheckUtil;
-import java.util.Map;
-
/**
* processor to get specific data
*
@@ -35,6 +37,9 @@
*/
public class FetchDataHandler extends AbstractClientHandler {
+ @Autowired
+ private DatumCache datumCache;
+
@Override
public void checkParam(GetDataRequest request) throws RuntimeException {
ParaCheckUtil.checkNotBlank(request.getDataInfoId(), "GetDataRequest.dataInfoId");
@@ -42,7 +47,7 @@ public void checkParam(GetDataRequest request) throws RuntimeException {
@Override
public Object doHandle(Channel channel, GetDataRequest request) {
- return new GenericResponse