diff --git a/consistency/pom.xml b/consistency/pom.xml index 2d47dcfb195..a7368be2d16 100644 --- a/consistency/pom.xml +++ b/consistency/pom.xml @@ -14,24 +14,12 @@ ~ See the License for the specific language governing permissions and ~ limitations under the License. --> - - - - com.alibaba.nacos - nacos-all - 1.3.0 - ../pom.xml - - - 4.0.0 - + + nacos-consistency - jar - - nacos-consistency ${project.version} - http://nacos.io + @@ -41,40 +29,36 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - UTF-8 - - + ${project.groupId} @@ -93,5 +77,21 @@ protobuf-java + 4.0.0 + + nacos-consistency ${project.version} + jar + + com.alibaba.nacos + nacos-all + ../pom.xml + 1.3.0 + + + + UTF-8 + + + http://nacos.io diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/CommandOperations.java b/consistency/src/main/java/com/alibaba/nacos/consistency/CommandOperations.java index 0df182b39d0..b08d65551fa 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/CommandOperations.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/CommandOperations.java @@ -22,18 +22,20 @@ import java.util.Map; /** + * Operation and maintenance command interface. + * * @author liaochuntao */ public interface CommandOperations { - - /** - * Operation and maintenance interface operation entry - * - * @param commands commands - * @return execute success - */ - default RestResult execute(Map commands) { - return RestResultUtils.success(); - } - + + /** + * Operation and maintenance interface operation entry. + * + * @param commands commands + * @return execute success + */ + default RestResult execute(Map commands) { + return RestResultUtils.success(); + } + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/Config.java b/consistency/src/main/java/com/alibaba/nacos/consistency/Config.java index ca48615aec5..fd47c56335f 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/Config.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/Config.java @@ -17,83 +17,80 @@ package com.alibaba.nacos.consistency; import java.io.Serializable; -import java.util.Collection; -import java.util.List; import java.util.Set; /** - * Consistent protocol related configuration objects + * Consistent protocol related configuration objects. * - * {@link LogProcessor} : The consistency protocol provides services for all businesses, - * but each business only cares about the transaction information belonging to that business, - * and the transaction processing between the various services should not block each other. Therefore, - * the LogProcessor is abstracted to implement the parallel processing of transactions of different services. - * Corresponding LogProcessor sub-interface: LogProcessor4AP or LogProcessor4CP, different consistency - * protocols will actively discover the corresponding LogProcessor + *

{@link LogProcessor} : The consistency protocol provides services for all businesses, but each business only cares + * about the transaction information belonging to that business, and the transaction processing between the various + * services should not block each other. Therefore, the LogProcessor is abstracted to implement the parallel processing + * of transactions of different services. Corresponding LogProcessor sub-interface: LogProcessor4AP or LogProcessor4CP, + * different consistency protocols will actively discover the corresponding LogProcessor * * @author liaochuntao */ public interface Config extends Serializable { - + /** - * Set the cluster node information to initialize,like [ip:port, ip:port, ip:port] + * Set the cluster node information to initialize,like [ip:port, ip:port, ip:port]. * - * @param self local node address information, ip:port - * @param members {@link Set} + * @param self local node address information, ip:port + * @param members {@link Set} */ void setMembers(String self, Set members); - + /** - * members join + * members join. * - * @param members {@link Set} + * @param members {@link Set} */ void addMembers(Set members); - + /** - * members leave + * members leave. * - * @param members {@link Set} + * @param members {@link Set} */ void removeMembers(Set members); - + /** - * get local node address info + * get local node address info. * * @return address */ String getSelfMember(); - + /** - * get the cluster node information + * get the cluster node information. * * @return members info, like [ip:port, ip:port, ip:port] */ Set getMembers(); - + /** - * Add configuration content + * Add configuration content. * * @param key config key * @param value config value */ void setVal(String key, String value); - + /** - * get configuration content by key + * get configuration content by key. * * @param key config key * @return config value */ String getVal(String key); - + /** - * get configuration content by key, if not found, use default-val + * get configuration content by key, if not found, use default-val. * * @param key config key * @param defaultVal default value * @return config value */ String getValOfDefault(String key, String defaultVal); - + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/ConsistencyProtocol.java b/consistency/src/main/java/com/alibaba/nacos/consistency/ConsistencyProtocol.java index 26a65342d3a..e03134b6e59 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/ConsistencyProtocol.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/ConsistencyProtocol.java @@ -16,7 +16,6 @@ package com.alibaba.nacos.consistency; - import com.alibaba.nacos.consistency.entity.GetRequest; import com.alibaba.nacos.consistency.entity.Log; import com.alibaba.nacos.consistency.entity.Response; @@ -26,8 +25,7 @@ import java.util.concurrent.CompletableFuture; /** - * Has nothing to do with the specific implementation of the consistency protocol - * Initialization sequence: init(Config) + * Has nothing to do with the specific implementation of the consistency protocol Initialization sequence: init(Config). * *

    *
  • {@link Config} : Relevant configuration information required by the consistency protocol, @@ -40,79 +38,79 @@ * @author liaochuntao */ public interface ConsistencyProtocol extends CommandOperations { - + /** - * Consistency protocol initialization: perform initialization operations based on the incoming Config - * 一致性协议初始化,根据 Config 实现类 + * Consistency protocol initialization: perform initialization operations based on the incoming. + * Config 一致性协议初始化,根据Config 实现类 * * @param config {@link Config} */ void init(T config); - + /** - * Add a log handler + * Add a log handler. * * @param processors {@link LogProcessor} */ void addLogProcessors(Collection

    processors); - + /** - * Copy of metadata information for this consensus protocol + * Copy of metadata information for this consensus protocol. * 该一致性协议的元数据信息 * * @return metaData {@link ProtocolMetaData} */ ProtocolMetaData protocolMetaData(); - + /** - * Obtain data according to the request + * Obtain data according to the request. * * @param request request * @return data {@link Response} - * @throws Exception + * @throws Exception {@link Exception} */ Response getData(GetRequest request) throws Exception; - + /** - * Get data asynchronously + * Get data asynchronously. * * @param request request - * @return data {@link CompletableFuture} + * @return data {@link CompletableFuture} */ CompletableFuture aGetData(GetRequest request); - + /** - * Data operation, returning submission results synchronously + * Data operation, returning submission results synchronously. * 同步数据提交,在 Datum 中已携带相应的数据操作信息 * * @param data {@link Log} * @return submit operation result {@link Response} - * @throws Exception + * @throws Exception {@link Exception} */ Response submit(Log data) throws Exception; - + /** - * Data submission operation, returning submission results asynchronously - * 异步数据提交,在 Datum 中已携带相应的数据操作信息,返回一个Future,自行操作,提交发生的异常会在CompleteFuture中 + * Data submission operation, returning submission results asynchronously. + * 异步数据提交,在 Datum中已携带相应的数据操作信息,返回一个Future,自行操作,提交发生的异常会在CompleteFuture中 * * @param data {@link Log} - * @return {@link CompletableFuture} submit result + * @return {@link CompletableFuture} submit result * @throws Exception when submit throw Exception */ CompletableFuture submitAsync(Log data); - + /** - * New member list + * New member list . * 新的成员节点列表,一致性协议自行处理相应的成员节点是加入还是离开 * * @param addresses [ip:port, ip:port, ...] */ void memberChange(Set addresses); - + /** - * Consistency agreement service shut down + * Consistency agreement service shut down . * 一致性协议服务关闭 */ void shutdown(); - + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/IdGenerator.java b/consistency/src/main/java/com/alibaba/nacos/consistency/IdGenerator.java index 90713ea9710..29abfdefb6d 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/IdGenerator.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/IdGenerator.java @@ -19,34 +19,36 @@ import java.util.Map; /** + * Id generator. + * * @author liaochuntao */ public interface IdGenerator { - + /** - * Perform the corresponding initialization operation + * Perform the corresponding initialization operation. */ void init(); - + /** - * current id info + * current id info. * * @return current id */ long currentId(); - + /** - * Get next id + * Get next id. * * @return next id */ long nextId(); - + /** - * Returns information for the current IDGenerator + * Returns information for the current IDGenerator. * - * @return {@link Map} + * @return {@link Map} */ Map info(); - + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/LogProcessor.java b/consistency/src/main/java/com/alibaba/nacos/consistency/LogProcessor.java index 8f568259bc6..8cf8b5e6b3e 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/LogProcessor.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/LogProcessor.java @@ -21,46 +21,44 @@ import com.alibaba.nacos.consistency.entity.Response; /** - * Can be discovered through SPI or Spring, - * This interface is just a function definition interface. Different consistency protocols - * have their own LogDispatcher. It is not recommended to directly implement this interface. + * Can be discovered through SPI or Spring, This interface is just a function definition interface. Different + * consistency protocols have their own LogDispatcher. It is not recommended to directly implement this interface. * * @author liaochuntao */ @SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule") public abstract class LogProcessor { - + /** - * get data by key + * get data by key. * * @param request request {@link GetRequest} * @return target type data */ public abstract Response onRequest(GetRequest request); - + /** - * Process Submitted Log + * Process Submitted Log. * * @param log {@link Log} * @return {@link boolean} */ public abstract Response onApply(Log log); - + /** - * Irremediable errors that need to trigger business price cuts + * Irremediable errors that need to trigger business price cuts. * * @param error {@link Throwable} */ public void onError(Throwable error) { } - + /** - * In order for the state machine that handles the transaction to be able to route - * the Log to the correct LogProcessor, the LogProcessor needs to have an identity - * information + * In order for the state machine that handles the transaction to be able to route the Log to the correct + * LogProcessor, the LogProcessor needs to have an identity information. * * @return Business unique identification name */ public abstract String group(); - + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/ProtocolMetaData.java b/consistency/src/main/java/com/alibaba/nacos/consistency/ProtocolMetaData.java index 57520e16075..5b46d73f19a 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/ProtocolMetaData.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/ProtocolMetaData.java @@ -32,35 +32,35 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; /** - * Consistent protocol metadata information, > structure - * Listeners that can register to listen to changes in value + * Consistent protocol metadata information, <Key, <Key, Value >> structure Listeners that can register to listen to + * changes in value. * * @author liaochuntao */ @SuppressWarnings("PMD.Rule:CollectionInitShouldAssignCapacityRule") public final class ProtocolMetaData { - - private static final Executor EXECUTOR = ExecutorFactory.Managed.newFixedExecutorService( - ProtocolMetaData.class.getCanonicalName(), - 4, - new NameThreadFactory("com.alibaba.nacos.consistency.protocol.metadata")); - + + private static final Executor EXECUTOR = ExecutorFactory.Managed + .newFixedExecutorService(ProtocolMetaData.class.getCanonicalName(), 4, + new NameThreadFactory("com.alibaba.nacos.consistency.protocol.metadata")); + private Map metaDataMap = new ConcurrentHashMap<>(4); - + public Map> getMetaDataMap() { - return metaDataMap.entrySet() - .stream() - .map(entry -> { - return Pair.with(entry.getKey(), entry.getValue().getItemMap() - .entrySet().stream() - .collect(TreeMap::new, (m, e) -> m.put(e.getKey(), e.getValue().getData()), TreeMap::putAll)); - }) + return metaDataMap.entrySet().stream().map(entry -> Pair.with(entry.getKey(), + entry.getValue().getItemMap().entrySet().stream() + .collect(TreeMap::new, (m, e) -> m.put(e.getKey(), e.getValue().getData()), TreeMap::putAll))) .collect(TreeMap::new, (m, e) -> m.put(e.getValue0(), e.getValue1()), TreeMap::putAll); } - + // Does not guarantee thread safety, there may be two updates of // time-1 and time-2 (time-1 > mapMap) { mapMap.forEach((s, map) -> { metaDataMap.computeIfAbsent(s, MetaData::new); @@ -68,7 +68,14 @@ public void load(final Map> mapMap) { map.forEach(data::put); }); } - + + /** + * get protocol metadata by group and key. + * + * @param group group name + * @param subKey key + * @return target value + */ public Object get(String group, String subKey) { if (StringUtils.isBlank(subKey)) { return metaDataMap.get(group); @@ -79,60 +86,52 @@ public Object get(String group, String subKey) { return null; } } - + // If MetaData does not exist, actively create a MetaData - + public void subscribe(final String group, final String key, final Observer observer) { metaDataMap.computeIfAbsent(group, s -> new MetaData(group)); - metaDataMap.get(group) - .subscribe(key, observer); + metaDataMap.get(group).subscribe(key, observer); } - + public void unSubscribe(final String group, final String key, final Observer observer) { metaDataMap.computeIfAbsent(group, s -> new MetaData(group)); - metaDataMap.get(group) - .unSubscribe(key, observer); + metaDataMap.get(group).unSubscribe(key, observer); } - + @SuppressWarnings("PMD.ThreadPoolCreationRule") - public final class MetaData { - + public static final class MetaData { + private final Map itemMap = new ConcurrentHashMap<>(8); - - private transient final String group; - + + private final transient String group; + public MetaData(String group) { this.group = group; } - + public Map getItemMap() { return itemMap; } - + void put(String key, Object value) { - itemMap.computeIfAbsent(key, s -> { - ValueItem item = new ValueItem(group + "/" + key); - return item; - }); + itemMap.computeIfAbsent(key, s -> new ValueItem(group + "/" + key)); ValueItem item = itemMap.get(key); item.setData(value); } - + public ValueItem get(String key) { return itemMap.get(key); } - + // If ValueItem does not exist, actively create a ValueItem - + void subscribe(final String key, final Observer observer) { - itemMap.computeIfAbsent(key, s -> { - ValueItem item = new ValueItem(group + "/" + key); - return item; - }); + itemMap.computeIfAbsent(key, s -> new ValueItem(group + "/" + key)); final ValueItem item = itemMap.get(key); item.addObserver(observer); } - + void unSubscribe(final String key, final Observer observer) { final ValueItem item = itemMap.get(key); if (item == null) { @@ -140,22 +139,27 @@ void unSubscribe(final String key, final Observer observer) { } item.deleteObserver(observer); } - + } - - public final class ValueItem extends Observable { - - private transient final String path; - private transient final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); - private transient final ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); - private transient final ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); + + public static final class ValueItem extends Observable { + + private final transient String path; + + private final transient ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + + private final transient ReentrantReadWriteLock.ReadLock readLock = lock.readLock(); + + private final transient ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock(); + private volatile Object data; + private transient BlockingQueue deferObject = new LinkedBlockingQueue<>(); - + public ValueItem(String path) { this.path = path; } - + public Object getData() { readLock.lock(); try { @@ -164,14 +168,14 @@ public Object getData() { readLock.unlock(); } } - + void setData(Object data) { writeLock.lock(); try { this.data = data; deferObject.offer(data); setChanged(); - + EXECUTOR.execute(() -> { try { notifyObservers(deferObject.take()); @@ -184,4 +188,4 @@ void setData(Object data) { } } } -} +} \ No newline at end of file diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/SerializeFactory.java b/consistency/src/main/java/com/alibaba/nacos/consistency/SerializeFactory.java index 4c2ea7c877f..f15e4ea5323 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/SerializeFactory.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/SerializeFactory.java @@ -23,28 +23,30 @@ import java.util.ServiceLoader; /** + * Serialization factory. + * * @author liaochuntao */ public class SerializeFactory { - - public static final String HESSIAN_INDEX = "Kryo".toLowerCase(); - - private static final Map SERIALIZER_MAP = new HashMap( - 4); - - public static String DEFAULT_SERIALIZER = HESSIAN_INDEX; - - static { - Serializer serializer = new HessianSerializer(); - SERIALIZER_MAP.put(HESSIAN_INDEX, serializer); - ServiceLoader loader = ServiceLoader.load(Serializer.class); - for (Serializer item : loader) { - SERIALIZER_MAP.put(item.name().toLowerCase(), item); - } - } - - public static Serializer getDefault() { - return SERIALIZER_MAP.get(DEFAULT_SERIALIZER); - } - + + public static final String HESSIAN_INDEX = "Hessian".toLowerCase(); + + private static final Map SERIALIZER_MAP = new HashMap(4); + + @SuppressWarnings("checkstyle:StaticVariableName") + public static String DEFAULT_SERIALIZER = HESSIAN_INDEX; + + static { + Serializer serializer = new HessianSerializer(); + SERIALIZER_MAP.put(HESSIAN_INDEX, serializer); + ServiceLoader loader = ServiceLoader.load(Serializer.class); + for (Serializer item : loader) { + SERIALIZER_MAP.put(item.name().toLowerCase(), item); + } + } + + public static Serializer getDefault() { + return SERIALIZER_MAP.get(DEFAULT_SERIALIZER); + } + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/Serializer.java b/consistency/src/main/java/com/alibaba/nacos/consistency/Serializer.java index a9e9d557662..76f439d825f 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/Serializer.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/Serializer.java @@ -16,34 +16,34 @@ package com.alibaba.nacos.consistency; -import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** + * Serialization interface. + * * @author liaochuntao */ public interface Serializer { - + Map> CLASS_CACHE = new ConcurrentHashMap<>(8); - + /** - * Deserialize the data + * Deserialize the data. * * @param data byte[] - * @param cls class - * @param class type + * @param cls class + * @param class type * @return target object instance */ T deserialize(byte[] data, Class cls); - + /** - * Deserialize the data + * Deserialize the data. * - * @param data byte[] + * @param data byte[] * @param classFullName class full name - * @param class type + * @param class type * @return target object instance */ default T deserialize(byte[] data, String classFullName) { @@ -52,8 +52,7 @@ default T deserialize(byte[] data, String classFullName) { CLASS_CACHE.computeIfAbsent(classFullName, name -> { try { return Class.forName(classFullName); - } - catch (ClassNotFoundException e) { + } catch (ClassNotFoundException e) { throw new RuntimeException(e); } }); @@ -63,20 +62,20 @@ default T deserialize(byte[] data, String classFullName) { return null; } } - + /** - * Serialize the object + * Serialize the object. * * @param obj target obj * @return byte[] */ byte[] serialize(T obj); - + /** - * The name of the serializer implementer + * The name of the serializer implementer. * * @return name */ String name(); - + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/ap/APProtocol.java b/consistency/src/main/java/com/alibaba/nacos/consistency/ap/APProtocol.java index 336df6a6b70..9197e53f806 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/ap/APProtocol.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/ap/APProtocol.java @@ -20,6 +20,8 @@ import com.alibaba.nacos.consistency.ConsistencyProtocol; /** + * ap protocol. + * * @author liaochuntao */ @SuppressWarnings("all") diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/ap/LogProcessor4AP.java b/consistency/src/main/java/com/alibaba/nacos/consistency/ap/LogProcessor4AP.java index 6079eb9ab9e..397a0d17583 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/ap/LogProcessor4AP.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/ap/LogProcessor4AP.java @@ -19,8 +19,11 @@ import com.alibaba.nacos.consistency.LogProcessor; /** + * log processor for ap. + * * @author liaochuntao */ @SuppressWarnings("all") public abstract class LogProcessor4AP extends LogProcessor { + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/cp/CPProtocol.java b/consistency/src/main/java/com/alibaba/nacos/consistency/cp/CPProtocol.java index bde4d720db4..6fc0d2468de 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/cp/CPProtocol.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/cp/CPProtocol.java @@ -20,17 +20,19 @@ import com.alibaba.nacos.consistency.ConsistencyProtocol; /** + * cp protocol. + * * @author liaochuntao */ @SuppressWarnings("all") public interface CPProtocol extends ConsistencyProtocol { - - /** - * Returns whether this node is a leader node - * - * @param group business module info - * @return is leader - */ - boolean isLeader(String group); - + + /** + * Returns whether this node is a leader node + * + * @param group business module info + * @return is leader + */ + boolean isLeader(String group); + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/cp/LogProcessor4CP.java b/consistency/src/main/java/com/alibaba/nacos/consistency/cp/LogProcessor4CP.java index 89f3267e319..49ef8cd31fc 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/cp/LogProcessor4CP.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/cp/LogProcessor4CP.java @@ -18,24 +18,27 @@ import com.alibaba.nacos.consistency.LogProcessor; import com.alibaba.nacos.consistency.snapshot.SnapshotOperation; + import java.util.Collections; import java.util.List; /** + * log processor for cp. + * * @author liaochuntao */ @SuppressWarnings("all") public abstract class LogProcessor4CP extends LogProcessor { - - + + /** - * Discovery snapshot handler - * It is up to LogProcessor to decide which SnapshotOperate should be loaded and saved by itself + * Discovery snapshot handler It is up to LogProcessor to decide which SnapshotOperate should be loaded and saved by + * itself. * * @return {@link List } */ public List loadSnapshotOperate() { return Collections.emptyList(); } - + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/cp/MetadataKey.java b/consistency/src/main/java/com/alibaba/nacos/consistency/cp/MetadataKey.java index 3b9c79a79a9..1fd8dfa201f 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/cp/MetadataKey.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/cp/MetadataKey.java @@ -17,14 +17,16 @@ package com.alibaba.nacos.consistency.cp; /** + * Key value of metadata information of CP protocol. + * * @author liaochuntao */ public class MetadataKey { - + public static final String LEADER_META_DATA = "leader"; - + public static final String TERM_META_DATA = "term"; - + public static final String RAFT_GROUP_MEMBER = "raftGroupMember"; - + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Data.java b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Data.java index f95df7d5fe4..f1701104d6c 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Data.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Data.java @@ -19,99 +19,77 @@ package com.alibaba.nacos.consistency.entity; +@SuppressWarnings("all") public final class Data { - private Data() {} - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistryLite registry) { - } - - public static void registerAllExtensions( - com.google.protobuf.ExtensionRegistry registry) { - registerAllExtensions( - (com.google.protobuf.ExtensionRegistryLite) registry); - } - static final com.google.protobuf.Descriptors.Descriptor - internal_static_Log_descriptor; - static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_Log_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor - internal_static_Log_ExtendInfoEntry_descriptor; - static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_Log_ExtendInfoEntry_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor - internal_static_GetRequest_descriptor; - static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_GetRequest_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor - internal_static_GetRequest_ExtendInfoEntry_descriptor; - static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_GetRequest_ExtendInfoEntry_fieldAccessorTable; - static final com.google.protobuf.Descriptors.Descriptor - internal_static_Response_descriptor; - static final - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable - internal_static_Response_fieldAccessorTable; - - public static com.google.protobuf.Descriptors.FileDescriptor - getDescriptor() { - return descriptor; - } - private static com.google.protobuf.Descriptors.FileDescriptor - descriptor; - static { - String[] descriptorData = { - "\n\nData.proto\"\255\001\n\003Log\022\r\n\005group\030\001 \001(\t\022\013\n\003k" + - "ey\030\002 \001(\t\022\014\n\004data\030\003 \001(\014\022\014\n\004type\030\004 \001(\t\022\021\n\t" + - "operation\030\005 \001(\t\022(\n\nextendInfo\030\006 \003(\0132\024.Lo" + - "g.ExtendInfoEntry\0321\n\017ExtendInfoEntry\022\013\n\003" + - "key\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001\"\215\001\n\nGetRequ" + - "est\022\r\n\005group\030\001 \001(\t\022\014\n\004data\030\002 \001(\014\022/\n\nexte" + - "ndInfo\030\003 \003(\0132\033.GetRequest.ExtendInfoEntr" + - "y\0321\n\017ExtendInfoEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005val" + - "ue\030\002 \001(\t:\0028\001\"9\n\010Response\022\014\n\004data\030\001 \001(\014\022\016" + - "\n\006errMsg\030\002 \001(\t\022\017\n\007success\030\003 \001(\010B(\n$com.a" + - "libaba.nacos.consistency.entityP\001b\006proto" + - "3" - }; - descriptor = com.google.protobuf.Descriptors.FileDescriptor - .internalBuildGeneratedFileFrom(descriptorData, - new com.google.protobuf.Descriptors.FileDescriptor[] { - }); - internal_static_Log_descriptor = - getDescriptor().getMessageTypes().get(0); - internal_static_Log_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_Log_descriptor, - new String[] { "Group", "Key", "Data", "Type", "Operation", "ExtendInfo", }); - internal_static_Log_ExtendInfoEntry_descriptor = - internal_static_Log_descriptor.getNestedTypes().get(0); - internal_static_Log_ExtendInfoEntry_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_Log_ExtendInfoEntry_descriptor, - new String[] { "Key", "Value", }); - internal_static_GetRequest_descriptor = - getDescriptor().getMessageTypes().get(1); - internal_static_GetRequest_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_GetRequest_descriptor, - new String[] { "Group", "Data", "ExtendInfo", }); - internal_static_GetRequest_ExtendInfoEntry_descriptor = - internal_static_GetRequest_descriptor.getNestedTypes().get(0); - internal_static_GetRequest_ExtendInfoEntry_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_GetRequest_ExtendInfoEntry_descriptor, - new String[] { "Key", "Value", }); - internal_static_Response_descriptor = - getDescriptor().getMessageTypes().get(2); - internal_static_Response_fieldAccessorTable = new - com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( - internal_static_Response_descriptor, - new String[] { "Data", "ErrMsg", "Success", }); - } - - // @@protoc_insertion_point(outer_class_scope) + + static final com.google.protobuf.Descriptors.Descriptor internal_static_Log_descriptor; + + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Log_fieldAccessorTable; + + static final com.google.protobuf.Descriptors.Descriptor internal_static_Log_ExtendInfoEntry_descriptor; + + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Log_ExtendInfoEntry_fieldAccessorTable; + + static final com.google.protobuf.Descriptors.Descriptor internal_static_GetRequest_descriptor; + + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_GetRequest_fieldAccessorTable; + + static final com.google.protobuf.Descriptors.Descriptor internal_static_GetRequest_ExtendInfoEntry_descriptor; + + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_GetRequest_ExtendInfoEntry_fieldAccessorTable; + + static final com.google.protobuf.Descriptors.Descriptor internal_static_Response_descriptor; + + static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Response_fieldAccessorTable; + + private static com.google.protobuf.Descriptors.FileDescriptor descriptor; + + static { + String[] descriptorData = {"\n\nData.proto\"\255\001\n\003Log\022\r\n\005group\030\001 \001(\t\022\013\n\003k" + + "ey\030\002 \001(\t\022\014\n\004data\030\003 \001(\014\022\014\n\004type\030\004 \001(\t\022\021\n\t" + + "operation\030\005 \001(\t\022(\n\nextendInfo\030\006 \003(\0132\024.Lo" + + "g.ExtendInfoEntry\0321\n\017ExtendInfoEntry\022\013\n\003" + + "key\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001\"\215\001\n\nGetRequ" + + "est\022\r\n\005group\030\001 \001(\t\022\014\n\004data\030\002 \001(\014\022/\n\nexte" + + "ndInfo\030\003 \003(\0132\033.GetRequest.ExtendInfoEntr" + + "y\0321\n\017ExtendInfoEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005val" + + "ue\030\002 \001(\t:\0028\001\"9\n\010Response\022\014\n\004data\030\001 \001(\014\022\016" + + "\n\006errMsg\030\002 \001(\t\022\017\n\007success\030\003 \001(\010B(\n$com.a" + + "libaba.nacos.consistency.entityP\001b\006proto" + "3"}; + descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, + new com.google.protobuf.Descriptors.FileDescriptor[] {}); + internal_static_Log_descriptor = getDescriptor().getMessageTypes().get(0); + internal_static_Log_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_Log_descriptor, + new String[] {"Group", "Key", "Data", "Type", "Operation", "ExtendInfo",}); + internal_static_Log_ExtendInfoEntry_descriptor = internal_static_Log_descriptor.getNestedTypes().get(0); + internal_static_Log_ExtendInfoEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_Log_ExtendInfoEntry_descriptor, new String[] {"Key", "Value",}); + internal_static_GetRequest_descriptor = getDescriptor().getMessageTypes().get(1); + internal_static_GetRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_GetRequest_descriptor, new String[] {"Group", "Data", "ExtendInfo",}); + internal_static_GetRequest_ExtendInfoEntry_descriptor = internal_static_GetRequest_descriptor.getNestedTypes() + .get(0); + internal_static_GetRequest_ExtendInfoEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_GetRequest_ExtendInfoEntry_descriptor, new String[] {"Key", "Value",}); + internal_static_Response_descriptor = getDescriptor().getMessageTypes().get(2); + internal_static_Response_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( + internal_static_Response_descriptor, new String[] {"Data", "ErrMsg", "Success",}); + } + + private Data() { + } + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) { + } + + public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) { + registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry); + } + + public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { + return descriptor; + } + + // @@protoc_insertion_point(outer_class_scope) } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/GetRequest.java b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/GetRequest.java index e582b326799..e11c5c33c7c 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/GetRequest.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/GetRequest.java @@ -20,880 +20,865 @@ package com.alibaba.nacos.consistency.entity; /** - * Protobuf type {@code GetRequest} + * Protobuf type {@code GetRequest}. */ -public final class GetRequest extends - com.google.protobuf.GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:GetRequest) - GetRequestOrBuilder { -private static final long serialVersionUID = 0L; - // Use GetRequest.newBuilder() to construct. - private GetRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - private GetRequest() { - group_ = ""; - data_ = com.google.protobuf.ByteString.EMPTY; - } - - @Override - @SuppressWarnings({"unused"}) - protected Object newInstance( - UnusedPrivateParameter unused) { - return new GetRequest(); - } - - @Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private GetRequest( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 10: { - String s = input.readStringRequireUtf8(); - - group_ = s; - break; - } - case 18: { - - data_ = input.readBytes(); - break; - } - case 26: { - if (!((mutable_bitField0_ & 0x00000001) != 0)) { - extendInfo_ = com.google.protobuf.MapField.newMapField( - ExtendInfoDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000001; - } - com.google.protobuf.MapEntry - extendInfo__ = input.readMessage( - ExtendInfoDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); - extendInfo_.getMutableMap().put( - extendInfo__.getKey(), extendInfo__.getValue()); - break; - } - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; +@SuppressWarnings("all") +public final class GetRequest extends com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:GetRequest) + GetRequestOrBuilder { + + public static final int GROUP_FIELD_NUMBER = 1; + + public static final int DATA_FIELD_NUMBER = 2; + + public static final int EXTENDINFO_FIELD_NUMBER = 3; + + private static final long serialVersionUID = 0L; + + // @@protoc_insertion_point(class_scope:GetRequest) + private static final GetRequest DEFAULT_INSTANCE; + + private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { + @Override + public GetRequest parsePartialFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new GetRequest(input, extensionRegistry); + } + }; + + static { + DEFAULT_INSTANCE = new GetRequest(); + } + + private volatile Object group_; + + private com.google.protobuf.ByteString data_; + + private com.google.protobuf.MapField extendInfo_; + + private byte memoizedIsInitialized = -1; + + // Use GetRequest.newBuilder() to construct. + private GetRequest(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private GetRequest() { + group_ = ""; + data_ = com.google.protobuf.ByteString.EMPTY; + } + + private GetRequest(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 10: { + String s = input.readStringRequireUtf8(); + + group_ = s; + break; + } + case 18: { + + data_ = input.readBytes(); + break; + } + case 26: { + if (!((mutable_bitField0_ & 0x00000001) != 0)) { + extendInfo_ = com.google.protobuf.MapField + .newMapField(ExtendInfoDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000001; + } + com.google.protobuf.MapEntry extendInfo__ = input + .readMessage(ExtendInfoDefaultEntryHolder.defaultEntry.getParserForType(), + extensionRegistry); + extendInfo_.getMutableMap().put(extendInfo__.getKey(), extendInfo__.getValue()); + break; + } + default: { + if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + } } - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return Data.internal_static_GetRequest_descriptor; - } - - @SuppressWarnings({"rawtypes"}) - @Override - protected com.google.protobuf.MapField internalGetMapField( - int number) { - switch (number) { - case 3: - return internalGetExtendInfo(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); - } - } - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return Data.internal_static_GetRequest_fieldAccessorTable - .ensureFieldAccessorsInitialized( - GetRequest.class, GetRequest.Builder.class); - } - - public static final int GROUP_FIELD_NUMBER = 1; - private volatile Object group_; - /** - * string group = 1; - */ - public String getGroup() { - Object ref = group_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - group_ = s; - return s; - } - } - /** - * string group = 1; - */ - public com.google.protobuf.ByteString - getGroupBytes() { - Object ref = group_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - group_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - public static final int DATA_FIELD_NUMBER = 2; - private com.google.protobuf.ByteString data_; - /** - * bytes data = 2; - */ - public com.google.protobuf.ByteString getData() { - return data_; - } - - public static final int EXTENDINFO_FIELD_NUMBER = 3; - private static final class ExtendInfoDefaultEntryHolder { - static final com.google.protobuf.MapEntry< - String, String> defaultEntry = - com.google.protobuf.MapEntry - .newDefaultInstance( - Data.internal_static_GetRequest_ExtendInfoEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.STRING, - ""); - } - private com.google.protobuf.MapField< - String, String> extendInfo_; - private com.google.protobuf.MapField - internalGetExtendInfo() { - if (extendInfo_ == null) { - return com.google.protobuf.MapField.emptyMapField( - ExtendInfoDefaultEntryHolder.defaultEntry); - } - return extendInfo_; - } - - public int getExtendInfoCount() { - return internalGetExtendInfo().getMap().size(); - } - /** - * map<string, string> extendInfo = 3; - */ - - public boolean containsExtendInfo( - String key) { - if (key == null) { throw new NullPointerException(); } - return internalGetExtendInfo().getMap().containsKey(key); - } - /** - * Use {@link #getExtendInfoMap()} instead. - */ - @Deprecated - public java.util.Map getExtendInfo() { - return getExtendInfoMap(); - } - /** - * map<string, string> extendInfo = 3; - */ - - public java.util.Map getExtendInfoMap() { - return internalGetExtendInfo().getMap(); - } - /** - * map<string, string> extendInfo = 3; - */ - - public String getExtendInfoOrDefault( - String key, - String defaultValue) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetExtendInfo().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<string, string> extendInfo = 3; - */ - - public String getExtendInfoOrThrow( - String key) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetExtendInfo().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); - } - - private byte memoizedIsInitialized = -1; - @Override - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - @Override - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - if (!getGroupBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, group_); - } - if (!data_.isEmpty()) { - output.writeBytes(2, data_); - } - com.google.protobuf.GeneratedMessageV3 - .serializeStringMapTo( - output, - internalGetExtendInfo(), - ExtendInfoDefaultEntryHolder.defaultEntry, - 3); - unknownFields.writeTo(output); - } - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (!getGroupBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, group_); - } - if (!data_.isEmpty()) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(2, data_); - } - for (java.util.Map.Entry entry - : internalGetExtendInfo().getMap().entrySet()) { - com.google.protobuf.MapEntry - extendInfo__ = ExtendInfoDefaultEntryHolder.defaultEntry.newBuilderForType() - .setKey(entry.getKey()) - .setValue(entry.getValue()) - .build(); - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(3, extendInfo__); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof GetRequest)) { - return super.equals(obj); - } - GetRequest other = (GetRequest) obj; - - if (!getGroup() - .equals(other.getGroup())) return false; - if (!getData() - .equals(other.getData())) return false; - if (!internalGetExtendInfo().equals( - other.internalGetExtendInfo())) return false; - if (!unknownFields.equals(other.unknownFields)) return false; - return true; - } - - @Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + GROUP_FIELD_NUMBER; - hash = (53 * hash) + getGroup().hashCode(); - hash = (37 * hash) + DATA_FIELD_NUMBER; - hash = (53 * hash) + getData().hashCode(); - if (!internalGetExtendInfo().getMap().isEmpty()) { - hash = (37 * hash) + EXTENDINFO_FIELD_NUMBER; - hash = (53 * hash) + internalGetExtendInfo().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static GetRequest parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static GetRequest parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static GetRequest parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static GetRequest parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static GetRequest parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static GetRequest parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static GetRequest parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static GetRequest parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static GetRequest parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static GetRequest parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static GetRequest parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static GetRequest parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - @Override - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(GetRequest prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - @Override - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } - - @Override - protected Builder newBuilderForType( - BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code GetRequest} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:GetRequest) - GetRequestOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return Data.internal_static_GetRequest_descriptor; - } - - @SuppressWarnings({"rawtypes"}) - protected com.google.protobuf.MapField internalGetMapField( - int number) { - switch (number) { - case 3: - return internalGetExtendInfo(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); - } - } - @SuppressWarnings({"rawtypes"}) - protected com.google.protobuf.MapField internalGetMutableMapField( - int number) { - switch (number) { - case 3: - return internalGetMutableExtendInfo(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); - } - } - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return Data.internal_static_GetRequest_fieldAccessorTable - .ensureFieldAccessorsInitialized( - GetRequest.class, GetRequest.Builder.class); - } - - // Construct using com.alibaba.nacos.consistency.entity.GetRequest.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3 - .alwaysUseFieldBuilders) { - } - } - @Override - public Builder clear() { - super.clear(); - group_ = ""; - - data_ = com.google.protobuf.ByteString.EMPTY; - - internalGetMutableExtendInfo().clear(); - return this; - } - - @Override - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return Data.internal_static_GetRequest_descriptor; - } - - @Override - public GetRequest getDefaultInstanceForType() { - return GetRequest.getDefaultInstance(); - } - - @Override - public GetRequest build() { - GetRequest result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - @Override - public GetRequest buildPartial() { - GetRequest result = new GetRequest(this); - int from_bitField0_ = bitField0_; - result.group_ = group_; - result.data_ = data_; - result.extendInfo_ = internalGetExtendInfo(); - result.extendInfo_.makeImmutable(); - onBuilt(); - return result; - } - - @Override - public Builder clone() { - return super.clone(); - } - @Override - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.setField(field, value); - } - @Override - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return super.clearField(field); - } - @Override - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return super.clearOneof(oneof); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return Data.internal_static_GetRequest_descriptor; + } + + public static GetRequest parseFrom(java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static GetRequest parseFrom(java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static GetRequest parseFrom(com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static GetRequest parseFrom(com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static GetRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static GetRequest parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static GetRequest parseFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static GetRequest parseFrom(java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static GetRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static GetRequest parseDelimitedFrom(java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + + public static GetRequest parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static GetRequest parseFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder(GetRequest prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public static GetRequest getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + @Override - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, Object value) { - return super.setRepeatedField(field, index, value); + @SuppressWarnings({"unused"}) + protected Object newInstance(UnusedPrivateParameter unused) { + return new GetRequest(); } + @Override - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.addRepeatedField(field, value); + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; } + + @SuppressWarnings({"rawtypes"}) @Override - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof GetRequest) { - return mergeFrom((GetRequest)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(GetRequest other) { - if (other == GetRequest.getDefaultInstance()) return this; - if (!other.getGroup().isEmpty()) { - group_ = other.group_; - onChanged(); - } - if (other.getData() != com.google.protobuf.ByteString.EMPTY) { - setData(other.getData()); - } - internalGetMutableExtendInfo().mergeFrom( - other.internalGetExtendInfo()); - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 3: + return internalGetExtendInfo(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - + @Override - public final boolean isInitialized() { - return true; + protected FieldAccessorTable internalGetFieldAccessorTable() { + return Data.internal_static_GetRequest_fieldAccessorTable + .ensureFieldAccessorsInitialized(GetRequest.class, GetRequest.Builder.class); } - - @Override - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - GetRequest parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (GetRequest) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; - } - private int bitField0_; - - private Object group_ = ""; + /** * string group = 1; */ public String getGroup() { - Object ref = group_; - if (!(ref instanceof String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - group_ = s; - return s; - } else { - return (String) ref; - } - } - /** - * string group = 1; - */ - public com.google.protobuf.ByteString - getGroupBytes() { - Object ref = group_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - group_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * string group = 1; - */ - public Builder setGroup( - String value) { - if (value == null) { - throw new NullPointerException(); - } - - group_ = value; - onChanged(); - return this; - } - /** - * string group = 1; - */ - public Builder clearGroup() { - - group_ = getDefaultInstance().getGroup(); - onChanged(); - return this; + Object ref = group_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + group_ = s; + return s; + } } + /** * string group = 1; */ - public Builder setGroupBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - group_ = value; - onChanged(); - return this; + public com.google.protobuf.ByteString getGroupBytes() { + Object ref = group_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + group_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - - private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; + /** * bytes data = 2; */ public com.google.protobuf.ByteString getData() { - return data_; - } - /** - * bytes data = 2; - */ - public Builder setData(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - - data_ = value; - onChanged(); - return this; - } - /** - * bytes data = 2; - */ - public Builder clearData() { - - data_ = getDefaultInstance().getData(); - onChanged(); - return this; + return data_; } - - private com.google.protobuf.MapField< - String, String> extendInfo_; - private com.google.protobuf.MapField - internalGetExtendInfo() { - if (extendInfo_ == null) { - return com.google.protobuf.MapField.emptyMapField( - ExtendInfoDefaultEntryHolder.defaultEntry); - } - return extendInfo_; - } - private com.google.protobuf.MapField - internalGetMutableExtendInfo() { - onChanged();; - if (extendInfo_ == null) { - extendInfo_ = com.google.protobuf.MapField.newMapField( - ExtendInfoDefaultEntryHolder.defaultEntry); - } - if (!extendInfo_.isMutable()) { - extendInfo_ = extendInfo_.copy(); - } - return extendInfo_; + + private com.google.protobuf.MapField internalGetExtendInfo() { + if (extendInfo_ == null) { + return com.google.protobuf.MapField.emptyMapField(ExtendInfoDefaultEntryHolder.defaultEntry); + } + return extendInfo_; } - + public int getExtendInfoCount() { - return internalGetExtendInfo().getMap().size(); + return internalGetExtendInfo().getMap().size(); } + /** * map<string, string> extendInfo = 3; */ - - public boolean containsExtendInfo( - String key) { - if (key == null) { throw new NullPointerException(); } - return internalGetExtendInfo().getMap().containsKey(key); + + public boolean containsExtendInfo(String key) { + if (key == null) { + throw new NullPointerException(); + } + return internalGetExtendInfo().getMap().containsKey(key); } + /** * Use {@link #getExtendInfoMap()} instead. */ @Deprecated public java.util.Map getExtendInfo() { - return getExtendInfoMap(); + return getExtendInfoMap(); } + /** * map<string, string> extendInfo = 3; */ - + public java.util.Map getExtendInfoMap() { - return internalGetExtendInfo().getMap(); + return internalGetExtendInfo().getMap(); } + /** * map<string, string> extendInfo = 3; */ - - public String getExtendInfoOrDefault( - String key, - String defaultValue) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetExtendInfo().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; + + public String getExtendInfoOrDefault(String key, String defaultValue) { + if (key == null) { + throw new NullPointerException(); + } + java.util.Map map = internalGetExtendInfo().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; } + /** * map<string, string> extendInfo = 3; */ - - public String getExtendInfoOrThrow( - String key) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetExtendInfo().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); + + public String getExtendInfoOrThrow(String key) { + if (key == null) { + throw new NullPointerException(); + } + java.util.Map map = internalGetExtendInfo().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); } - - public Builder clearExtendInfo() { - internalGetMutableExtendInfo().getMutableMap() - .clear(); - return this; + + @Override + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) { + return true; + } + if (isInitialized == 0) { + return false; + } + + memoizedIsInitialized = 1; + return true; } - /** - * map<string, string> extendInfo = 3; - */ - - public Builder removeExtendInfo( - String key) { - if (key == null) { throw new NullPointerException(); } - internalGetMutableExtendInfo().getMutableMap() - .remove(key); - return this; + + @Override + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getGroupBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, group_); + } + if (!data_.isEmpty()) { + output.writeBytes(2, data_); + } + com.google.protobuf.GeneratedMessageV3 + .serializeStringMapTo(output, internalGetExtendInfo(), ExtendInfoDefaultEntryHolder.defaultEntry, 3); + unknownFields.writeTo(output); } - /** - * Use alternate mutation accessors instead. - */ - @Deprecated - public java.util.Map - getMutableExtendInfo() { - return internalGetMutableExtendInfo().getMutableMap(); + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) { + return size; + } + + size = 0; + if (!getGroupBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, group_); + } + if (!data_.isEmpty()) { + size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, data_); + } + for (java.util.Map.Entry entry : internalGetExtendInfo().getMap().entrySet()) { + com.google.protobuf.MapEntry extendInfo__ = ExtendInfoDefaultEntryHolder.defaultEntry + .newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build(); + size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, extendInfo__); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; } - /** - * map<string, string> extendInfo = 3; - */ - public Builder putExtendInfo( - String key, - String value) { - if (key == null) { throw new NullPointerException(); } - if (value == null) { throw new NullPointerException(); } - internalGetMutableExtendInfo().getMutableMap() - .put(key, value); - return this; + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof GetRequest)) { + return super.equals(obj); + } + GetRequest other = (GetRequest) obj; + + if (!getGroup().equals(other.getGroup())) { + return false; + } + if (!getData().equals(other.getData())) { + return false; + } + if (!internalGetExtendInfo().equals(other.internalGetExtendInfo())) { + return false; + } + if (!unknownFields.equals(other.unknownFields)) { + return false; + } + return true; } - /** - * map<string, string> extendInfo = 3; - */ - - public Builder putAllExtendInfo( - java.util.Map values) { - internalGetMutableExtendInfo().getMutableMap() - .putAll(values); - return this; + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + GROUP_FIELD_NUMBER; + hash = (53 * hash) + getGroup().hashCode(); + hash = (37 * hash) + DATA_FIELD_NUMBER; + hash = (53 * hash) + getData().hashCode(); + if (!internalGetExtendInfo().getMap().isEmpty()) { + hash = (37 * hash) + EXTENDINFO_FIELD_NUMBER; + hash = (53 * hash) + internalGetExtendInfo().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; } + @Override - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); + public Builder newBuilderForType() { + return newBuilder(); } - + @Override - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } - - - // @@protoc_insertion_point(builder_scope:GetRequest) - } - - // @@protoc_insertion_point(class_scope:GetRequest) - private static final GetRequest DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new GetRequest(); - } - - public static GetRequest getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { + @Override - public GetRequest parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new GetRequest(input, extensionRegistry); + protected Builder newBuilderForType(BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - @Override - public GetRequest getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + @Override + public GetRequest getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + private static final class ExtendInfoDefaultEntryHolder { + + static final com.google.protobuf.MapEntry defaultEntry = com.google.protobuf.MapEntry.newDefaultInstance( + Data.internal_static_GetRequest_ExtendInfoEntry_descriptor, + com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.STRING, + ""); + } + + /** + * Protobuf type {@code GetRequest} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:GetRequest) + GetRequestOrBuilder { + + private int bitField0_; + + private Object group_ = ""; + + private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; + + private com.google.protobuf.MapField extendInfo_; + + // Construct using com.alibaba.nacos.consistency.entity.GetRequest.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return Data.internal_static_GetRequest_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 3: + return internalGetExtendInfo(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField(int number) { + switch (number) { + case 3: + return internalGetMutableExtendInfo(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } + } + + @Override + protected FieldAccessorTable internalGetFieldAccessorTable() { + return Data.internal_static_GetRequest_fieldAccessorTable + .ensureFieldAccessorsInitialized(GetRequest.class, GetRequest.Builder.class); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { + } + } + + @Override + public Builder clear() { + super.clear(); + group_ = ""; + + data_ = com.google.protobuf.ByteString.EMPTY; + + internalGetMutableExtendInfo().clear(); + return this; + } + + @Override + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return Data.internal_static_GetRequest_descriptor; + } + + @Override + public GetRequest getDefaultInstanceForType() { + return GetRequest.getDefaultInstance(); + } + + @Override + public GetRequest build() { + GetRequest result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + @Override + public GetRequest buildPartial() { + GetRequest result = new GetRequest(this); + int from_bitField0_ = bitField0_; + result.group_ = group_; + result.data_ = data_; + result.extendInfo_ = internalGetExtendInfo(); + result.extendInfo_.makeImmutable(); + onBuilt(); + return result; + } + + @Override + public Builder clone() { + return super.clone(); + } + + @Override + public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { + return super.setField(field, value); + } + + @Override + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return super.clearField(field); + } + + @Override + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return super.clearOneof(oneof); + } + + @Override + public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, int index, + Object value) { + return super.setRepeatedField(field, index, value); + } + + @Override + public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { + return super.addRepeatedField(field, value); + } + + @Override + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof GetRequest) { + return mergeFrom((GetRequest) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(GetRequest other) { + if (other == GetRequest.getDefaultInstance()) { + return this; + } + if (!other.getGroup().isEmpty()) { + group_ = other.group_; + onChanged(); + } + if (other.getData() != com.google.protobuf.ByteString.EMPTY) { + setData(other.getData()); + } + internalGetMutableExtendInfo().mergeFrom(other.internalGetExtendInfo()); + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + @Override + public final boolean isInitialized() { + return true; + } + + @Override + public Builder mergeFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + GetRequest parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (GetRequest) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + /** + * string group = 1; + */ + public String getGroup() { + Object ref = group_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + group_ = s; + return s; + } else { + return (String) ref; + } + } + + /** + * string group = 1; + */ + public Builder setGroup(String value) { + if (value == null) { + throw new NullPointerException(); + } + + group_ = value; + onChanged(); + return this; + } + + /** + * string group = 1; + */ + public com.google.protobuf.ByteString getGroupBytes() { + Object ref = group_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + group_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * string group = 1; + */ + public Builder setGroupBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + group_ = value; + onChanged(); + return this; + } + + /** + * string group = 1; + */ + public Builder clearGroup() { + + group_ = getDefaultInstance().getGroup(); + onChanged(); + return this; + } + + /** + * bytes data = 2; + */ + public com.google.protobuf.ByteString getData() { + return data_; + } + + /** + * bytes data = 2; + */ + public Builder setData(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + + data_ = value; + onChanged(); + return this; + } + + /** + * bytes data = 2; + */ + public Builder clearData() { + + data_ = getDefaultInstance().getData(); + onChanged(); + return this; + } + + private com.google.protobuf.MapField internalGetExtendInfo() { + if (extendInfo_ == null) { + return com.google.protobuf.MapField.emptyMapField(ExtendInfoDefaultEntryHolder.defaultEntry); + } + return extendInfo_; + } + + private com.google.protobuf.MapField internalGetMutableExtendInfo() { + onChanged(); + ; + if (extendInfo_ == null) { + extendInfo_ = com.google.protobuf.MapField.newMapField(ExtendInfoDefaultEntryHolder.defaultEntry); + } + if (!extendInfo_.isMutable()) { + extendInfo_ = extendInfo_.copy(); + } + return extendInfo_; + } + + public int getExtendInfoCount() { + return internalGetExtendInfo().getMap().size(); + } + + /** + * map<string, string> extendInfo = 3; + */ + + public boolean containsExtendInfo(String key) { + if (key == null) { + throw new NullPointerException(); + } + return internalGetExtendInfo().getMap().containsKey(key); + } + + /** + * Use {@link #getExtendInfoMap()} instead. + */ + @Deprecated + public java.util.Map getExtendInfo() { + return getExtendInfoMap(); + } + + /** + * map<string, string> extendInfo = 3; + */ + + public java.util.Map getExtendInfoMap() { + return internalGetExtendInfo().getMap(); + } + + /** + * map<string, string> extendInfo = 3; + */ + + public String getExtendInfoOrDefault(String key, String defaultValue) { + if (key == null) { + throw new NullPointerException(); + } + java.util.Map map = internalGetExtendInfo().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + + /** + * map<string, string> extendInfo = 3; + */ + + public String getExtendInfoOrThrow(String key) { + if (key == null) { + throw new NullPointerException(); + } + java.util.Map map = internalGetExtendInfo().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearExtendInfo() { + internalGetMutableExtendInfo().getMutableMap().clear(); + return this; + } + + /** + * map<string, string> extendInfo = 3; + */ + + public Builder removeExtendInfo(String key) { + if (key == null) { + throw new NullPointerException(); + } + internalGetMutableExtendInfo().getMutableMap().remove(key); + return this; + } + + /** + * Use alternate mutation accessors instead. + */ + @Deprecated + public java.util.Map getMutableExtendInfo() { + return internalGetMutableExtendInfo().getMutableMap(); + } + + /** + * map<string, string> extendInfo = 3; + */ + public Builder putExtendInfo(String key, String value) { + if (key == null) { + throw new NullPointerException(); + } + if (value == null) { + throw new NullPointerException(); + } + internalGetMutableExtendInfo().getMutableMap().put(key, value); + return this; + } + + /** + * map<string, string> extendInfo = 3; + */ + + public Builder putAllExtendInfo(java.util.Map values) { + internalGetMutableExtendInfo().getMutableMap().putAll(values); + return this; + } + + @Override + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + @Override + public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:GetRequest) + } + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/GetRequestOrBuilder.java b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/GetRequestOrBuilder.java index 172c0abd1a8..8e7886df32c 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/GetRequestOrBuilder.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/GetRequestOrBuilder.java @@ -19,52 +19,56 @@ package com.alibaba.nacos.consistency.entity; +@SuppressWarnings("all") public interface GetRequestOrBuilder extends - // @@protoc_insertion_point(interface_extends:GetRequest) - com.google.protobuf.MessageOrBuilder { - - /** - * string group = 1; - */ - String getGroup(); - /** - * string group = 1; - */ - com.google.protobuf.ByteString - getGroupBytes(); - - /** - * bytes data = 2; - */ - com.google.protobuf.ByteString getData(); - - /** - * map<string, string> extendInfo = 3; - */ - int getExtendInfoCount(); - /** - * map<string, string> extendInfo = 3; - */ - boolean containsExtendInfo(String key); - /** - * Use {@link #getExtendInfoMap()} instead. - */ - @Deprecated - java.util.Map - getExtendInfo(); - /** - * map<string, string> extendInfo = 3; - */ - java.util.Map - getExtendInfoMap(); - /** - * map<string, string> extendInfo = 3; - */ - - String getExtendInfoOrDefault(String key, String defaultValue); - /** - * map<string, string> extendInfo = 3; - */ - - String getExtendInfoOrThrow(String key); + // @@protoc_insertion_point(interface_extends:GetRequest) + com.google.protobuf.MessageOrBuilder { + + /** + * string group = 1; + */ + String getGroup(); + + /** + * string group = 1; + */ + com.google.protobuf.ByteString getGroupBytes(); + + /** + * bytes data = 2; + */ + com.google.protobuf.ByteString getData(); + + /** + * map<string, string> extendInfo = 3; + */ + int getExtendInfoCount(); + + /** + * map<string, string> extendInfo = 3; + */ + boolean containsExtendInfo(String key); + + /** + * Use {@link #getExtendInfoMap()} instead. + */ + @Deprecated + java.util.Map getExtendInfo(); + + /** + * map<string, string> extendInfo = 3; + */ + java.util.Map getExtendInfoMap(); + + /** + * map<string, string> extendInfo = 3; + */ + + String getExtendInfoOrDefault(String key, String defaultValue); + + /** + * map<string, string> extendInfo = 3; + */ + + String getExtendInfoOrThrow(String key); } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Log.java b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Log.java index f54d5fdf189..452e7374401 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Log.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Log.java @@ -20,1261 +20,1239 @@ package com.alibaba.nacos.consistency.entity; /** - * Protobuf type {@code Log} + * Protobuf type {@code Log}. */ -public final class Log extends - com.google.protobuf.GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:Log) - LogOrBuilder { -private static final long serialVersionUID = 0L; - // Use Log.newBuilder() to construct. - private Log(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - private Log() { - group_ = ""; - key_ = ""; - data_ = com.google.protobuf.ByteString.EMPTY; - type_ = ""; - operation_ = ""; - } - - @Override - @SuppressWarnings({"unused"}) - protected Object newInstance( - UnusedPrivateParameter unused) { - return new Log(); - } - - @Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private Log( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new NullPointerException(); - } - int mutable_bitField0_ = 0; - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 10: { - String s = input.readStringRequireUtf8(); - - group_ = s; - break; - } - case 18: { - String s = input.readStringRequireUtf8(); - - key_ = s; - break; - } - case 26: { - - data_ = input.readBytes(); - break; - } - case 34: { - String s = input.readStringRequireUtf8(); - - type_ = s; - break; - } - case 42: { - String s = input.readStringRequireUtf8(); - - operation_ = s; - break; - } - case 50: { - if (!((mutable_bitField0_ & 0x00000001) != 0)) { - extendInfo_ = com.google.protobuf.MapField.newMapField( - ExtendInfoDefaultEntryHolder.defaultEntry); - mutable_bitField0_ |= 0x00000001; - } - com.google.protobuf.MapEntry - extendInfo__ = input.readMessage( - ExtendInfoDefaultEntryHolder.defaultEntry.getParserForType(), extensionRegistry); - extendInfo_.getMutableMap().put( - extendInfo__.getKey(), extendInfo__.getValue()); - break; - } - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; +@SuppressWarnings("all") +public final class Log extends com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:Log) + LogOrBuilder { + + public static final int GROUP_FIELD_NUMBER = 1; + + public static final int KEY_FIELD_NUMBER = 2; + + public static final int DATA_FIELD_NUMBER = 3; + + public static final int TYPE_FIELD_NUMBER = 4; + + public static final int OPERATION_FIELD_NUMBER = 5; + + public static final int EXTENDINFO_FIELD_NUMBER = 6; + + private static final long serialVersionUID = 0L; + + // @@protoc_insertion_point(class_scope:Log) + private static final Log DEFAULT_INSTANCE; + + private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { + @Override + public Log parsePartialFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Log(input, extensionRegistry); + } + }; + + static { + DEFAULT_INSTANCE = new Log(); + } + + private volatile Object group_; + + private volatile Object key_; + + private com.google.protobuf.ByteString data_; + + private volatile Object type_; + + private volatile Object operation_; + + private com.google.protobuf.MapField extendInfo_; + + private byte memoizedIsInitialized = -1; + + // Use Log.newBuilder() to construct. + private Log(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private Log() { + group_ = ""; + key_ = ""; + data_ = com.google.protobuf.ByteString.EMPTY; + type_ = ""; + operation_ = ""; + } + + private Log(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new NullPointerException(); + } + int mutable_bitField0_ = 0; + com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 10: { + String s = input.readStringRequireUtf8(); + + group_ = s; + break; + } + case 18: { + String s = input.readStringRequireUtf8(); + + key_ = s; + break; + } + case 26: { + + data_ = input.readBytes(); + break; + } + case 34: { + String s = input.readStringRequireUtf8(); + + type_ = s; + break; + } + case 42: { + String s = input.readStringRequireUtf8(); + + operation_ = s; + break; + } + case 50: { + if (!((mutable_bitField0_ & 0x00000001) != 0)) { + extendInfo_ = com.google.protobuf.MapField + .newMapField(ExtendInfoDefaultEntryHolder.defaultEntry); + mutable_bitField0_ |= 0x00000001; + } + com.google.protobuf.MapEntry extendInfo__ = input + .readMessage(ExtendInfoDefaultEntryHolder.defaultEntry.getParserForType(), + extensionRegistry); + extendInfo_.getMutableMap().put(extendInfo__.getKey(), extendInfo__.getValue()); + break; + } + default: { + if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + } } - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return Data.internal_static_Log_descriptor; - } - - @SuppressWarnings({"rawtypes"}) - @Override - protected com.google.protobuf.MapField internalGetMapField( - int number) { - switch (number) { - case 6: - return internalGetExtendInfo(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); - } - } - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return Data.internal_static_Log_fieldAccessorTable - .ensureFieldAccessorsInitialized( - Log.class, Log.Builder.class); - } - - public static final int GROUP_FIELD_NUMBER = 1; - private volatile Object group_; - /** - * string group = 1; - */ - public String getGroup() { - Object ref = group_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - group_ = s; - return s; - } - } - /** - * string group = 1; - */ - public com.google.protobuf.ByteString - getGroupBytes() { - Object ref = group_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - group_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - public static final int KEY_FIELD_NUMBER = 2; - private volatile Object key_; - /** - * string key = 2; - */ - public String getKey() { - Object ref = key_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - key_ = s; - return s; - } - } - /** - * string key = 2; - */ - public com.google.protobuf.ByteString - getKeyBytes() { - Object ref = key_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - key_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - public static final int DATA_FIELD_NUMBER = 3; - private com.google.protobuf.ByteString data_; - /** - * bytes data = 3; - */ - public com.google.protobuf.ByteString getData() { - return data_; - } - - public static final int TYPE_FIELD_NUMBER = 4; - private volatile Object type_; - /** - * string type = 4; - */ - public String getType() { - Object ref = type_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - type_ = s; - return s; - } - } - /** - * string type = 4; - */ - public com.google.protobuf.ByteString - getTypeBytes() { - Object ref = type_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - type_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - public static final int OPERATION_FIELD_NUMBER = 5; - private volatile Object operation_; - /** - * string operation = 5; - */ - public String getOperation() { - Object ref = operation_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - operation_ = s; - return s; - } - } - /** - * string operation = 5; - */ - public com.google.protobuf.ByteString - getOperationBytes() { - Object ref = operation_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - operation_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - public static final int EXTENDINFO_FIELD_NUMBER = 6; - private static final class ExtendInfoDefaultEntryHolder { - static final com.google.protobuf.MapEntry< - String, String> defaultEntry = - com.google.protobuf.MapEntry - .newDefaultInstance( - Data.internal_static_Log_ExtendInfoEntry_descriptor, - com.google.protobuf.WireFormat.FieldType.STRING, - "", - com.google.protobuf.WireFormat.FieldType.STRING, - ""); - } - private com.google.protobuf.MapField< - String, String> extendInfo_; - private com.google.protobuf.MapField - internalGetExtendInfo() { - if (extendInfo_ == null) { - return com.google.protobuf.MapField.emptyMapField( - ExtendInfoDefaultEntryHolder.defaultEntry); - } - return extendInfo_; - } - - public int getExtendInfoCount() { - return internalGetExtendInfo().getMap().size(); - } - /** - * map<string, string> extendInfo = 6; - */ - - public boolean containsExtendInfo( - String key) { - if (key == null) { throw new NullPointerException(); } - return internalGetExtendInfo().getMap().containsKey(key); - } - /** - * Use {@link #getExtendInfoMap()} instead. - */ - @Deprecated - public java.util.Map getExtendInfo() { - return getExtendInfoMap(); - } - /** - * map<string, string> extendInfo = 6; - */ - - public java.util.Map getExtendInfoMap() { - return internalGetExtendInfo().getMap(); - } - /** - * map<string, string> extendInfo = 6; - */ - - public String getExtendInfoOrDefault( - String key, - String defaultValue) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetExtendInfo().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; - } - /** - * map<string, string> extendInfo = 6; - */ - - public String getExtendInfoOrThrow( - String key) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetExtendInfo().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); - } - - private byte memoizedIsInitialized = -1; - @Override - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - @Override - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - if (!getGroupBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 1, group_); - } - if (!getKeyBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, key_); - } - if (!data_.isEmpty()) { - output.writeBytes(3, data_); - } - if (!getTypeBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 4, type_); - } - if (!getOperationBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 5, operation_); - } - com.google.protobuf.GeneratedMessageV3 - .serializeStringMapTo( - output, - internalGetExtendInfo(), - ExtendInfoDefaultEntryHolder.defaultEntry, - 6); - unknownFields.writeTo(output); - } - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (!getGroupBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, group_); - } - if (!getKeyBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, key_); - } - if (!data_.isEmpty()) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(3, data_); - } - if (!getTypeBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, type_); - } - if (!getOperationBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, operation_); - } - for (java.util.Map.Entry entry - : internalGetExtendInfo().getMap().entrySet()) { - com.google.protobuf.MapEntry - extendInfo__ = ExtendInfoDefaultEntryHolder.defaultEntry.newBuilderForType() - .setKey(entry.getKey()) - .setValue(entry.getValue()) - .build(); - size += com.google.protobuf.CodedOutputStream - .computeMessageSize(6, extendInfo__); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof Log)) { - return super.equals(obj); - } - Log other = (Log) obj; - - if (!getGroup() - .equals(other.getGroup())) return false; - if (!getKey() - .equals(other.getKey())) return false; - if (!getData() - .equals(other.getData())) return false; - if (!getType() - .equals(other.getType())) return false; - if (!getOperation() - .equals(other.getOperation())) return false; - if (!internalGetExtendInfo().equals( - other.internalGetExtendInfo())) return false; - if (!unknownFields.equals(other.unknownFields)) return false; - return true; - } - - @Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + GROUP_FIELD_NUMBER; - hash = (53 * hash) + getGroup().hashCode(); - hash = (37 * hash) + KEY_FIELD_NUMBER; - hash = (53 * hash) + getKey().hashCode(); - hash = (37 * hash) + DATA_FIELD_NUMBER; - hash = (53 * hash) + getData().hashCode(); - hash = (37 * hash) + TYPE_FIELD_NUMBER; - hash = (53 * hash) + getType().hashCode(); - hash = (37 * hash) + OPERATION_FIELD_NUMBER; - hash = (53 * hash) + getOperation().hashCode(); - if (!internalGetExtendInfo().getMap().isEmpty()) { - hash = (37 * hash) + EXTENDINFO_FIELD_NUMBER; - hash = (53 * hash) + internalGetExtendInfo().hashCode(); - } - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static Log parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static Log parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static Log parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static Log parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static Log parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static Log parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static Log parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static Log parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static Log parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static Log parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static Log parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static Log parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - @Override - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(Log prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - @Override - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } - - @Override - protected Builder newBuilderForType( - BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code Log} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:Log) - LogOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return Data.internal_static_Log_descriptor; - } - - @SuppressWarnings({"rawtypes"}) - protected com.google.protobuf.MapField internalGetMapField( - int number) { - switch (number) { - case 6: - return internalGetExtendInfo(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); - } - } - @SuppressWarnings({"rawtypes"}) - protected com.google.protobuf.MapField internalGetMutableMapField( - int number) { - switch (number) { - case 6: - return internalGetMutableExtendInfo(); - default: - throw new RuntimeException( - "Invalid map field number: " + number); - } - } - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return Data.internal_static_Log_fieldAccessorTable - .ensureFieldAccessorsInitialized( - Log.class, Log.Builder.class); - } - - // Construct using com.alibaba.nacos.consistency.entity.Log.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3 - .alwaysUseFieldBuilders) { - } - } - @Override - public Builder clear() { - super.clear(); - group_ = ""; - - key_ = ""; - - data_ = com.google.protobuf.ByteString.EMPTY; - - type_ = ""; - - operation_ = ""; - - internalGetMutableExtendInfo().clear(); - return this; - } - - @Override - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return Data.internal_static_Log_descriptor; - } - - @Override - public Log getDefaultInstanceForType() { - return Log.getDefaultInstance(); - } - - @Override - public Log build() { - Log result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - @Override - public Log buildPartial() { - Log result = new Log(this); - int from_bitField0_ = bitField0_; - result.group_ = group_; - result.key_ = key_; - result.data_ = data_; - result.type_ = type_; - result.operation_ = operation_; - result.extendInfo_ = internalGetExtendInfo(); - result.extendInfo_.makeImmutable(); - onBuilt(); - return result; - } - - @Override - public Builder clone() { - return super.clone(); - } - @Override - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.setField(field, value); - } - @Override - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return super.clearField(field); - } - @Override - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return super.clearOneof(oneof); - } - @Override - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, Object value) { - return super.setRepeatedField(field, index, value); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return Data.internal_static_Log_descriptor; + } + + public static Log parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Log parseFrom(java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Log parseFrom(com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Log parseFrom(com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Log parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Log parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Log parseFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static Log parseFrom(java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static Log parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static Log parseDelimitedFrom(java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + + public static Log parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static Log parseFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder(Log prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public static Log getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + @Override - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.addRepeatedField(field, value); + @SuppressWarnings({"unused"}) + protected Object newInstance(UnusedPrivateParameter unused) { + return new Log(); } + @Override - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof Log) { - return mergeFrom((Log)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(Log other) { - if (other == Log.getDefaultInstance()) return this; - if (!other.getGroup().isEmpty()) { - group_ = other.group_; - onChanged(); - } - if (!other.getKey().isEmpty()) { - key_ = other.key_; - onChanged(); - } - if (other.getData() != com.google.protobuf.ByteString.EMPTY) { - setData(other.getData()); - } - if (!other.getType().isEmpty()) { - type_ = other.type_; - onChanged(); - } - if (!other.getOperation().isEmpty()) { - operation_ = other.operation_; - onChanged(); - } - internalGetMutableExtendInfo().mergeFrom( - other.internalGetExtendInfo()); - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; } - + + @SuppressWarnings({"rawtypes"}) @Override - public final boolean isInitialized() { - return true; + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 6: + return internalGetExtendInfo(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } } - + @Override - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - Log parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (Log) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; + protected FieldAccessorTable internalGetFieldAccessorTable() { + return Data.internal_static_Log_fieldAccessorTable + .ensureFieldAccessorsInitialized(Log.class, Log.Builder.class); } - private int bitField0_; - - private Object group_ = ""; + /** * string group = 1; */ public String getGroup() { - Object ref = group_; - if (!(ref instanceof String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - group_ = s; - return s; - } else { - return (String) ref; - } - } - /** - * string group = 1; - */ - public com.google.protobuf.ByteString - getGroupBytes() { - Object ref = group_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - group_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * string group = 1; - */ - public Builder setGroup( - String value) { - if (value == null) { - throw new NullPointerException(); - } - - group_ = value; - onChanged(); - return this; - } - /** - * string group = 1; - */ - public Builder clearGroup() { - - group_ = getDefaultInstance().getGroup(); - onChanged(); - return this; + Object ref = group_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + group_ = s; + return s; + } } + /** * string group = 1; */ - public Builder setGroupBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - group_ = value; - onChanged(); - return this; + public com.google.protobuf.ByteString getGroupBytes() { + Object ref = group_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + group_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - - private Object key_ = ""; + /** * string key = 2; */ public String getKey() { - Object ref = key_; - if (!(ref instanceof String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - key_ = s; - return s; - } else { - return (String) ref; - } - } - /** - * string key = 2; - */ - public com.google.protobuf.ByteString - getKeyBytes() { - Object ref = key_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - key_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * string key = 2; - */ - public Builder setKey( - String value) { - if (value == null) { - throw new NullPointerException(); - } - - key_ = value; - onChanged(); - return this; - } - /** - * string key = 2; - */ - public Builder clearKey() { - - key_ = getDefaultInstance().getKey(); - onChanged(); - return this; + Object ref = key_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + key_ = s; + return s; + } } + /** * string key = 2; */ - public Builder setKeyBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - key_ = value; - onChanged(); - return this; + public com.google.protobuf.ByteString getKeyBytes() { + Object ref = key_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + key_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - - private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; + /** * bytes data = 3; */ public com.google.protobuf.ByteString getData() { - return data_; + return data_; } - /** - * bytes data = 3; - */ - public Builder setData(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - - data_ = value; - onChanged(); - return this; - } - /** - * bytes data = 3; - */ - public Builder clearData() { - - data_ = getDefaultInstance().getData(); - onChanged(); - return this; - } - - private Object type_ = ""; + /** * string type = 4; */ public String getType() { - Object ref = type_; - if (!(ref instanceof String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - type_ = s; - return s; - } else { - return (String) ref; - } - } - /** - * string type = 4; - */ - public com.google.protobuf.ByteString - getTypeBytes() { - Object ref = type_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - type_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * string type = 4; - */ - public Builder setType( - String value) { - if (value == null) { - throw new NullPointerException(); - } - - type_ = value; - onChanged(); - return this; - } - /** - * string type = 4; - */ - public Builder clearType() { - - type_ = getDefaultInstance().getType(); - onChanged(); - return this; + Object ref = type_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + type_ = s; + return s; + } } + /** * string type = 4; */ - public Builder setTypeBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - type_ = value; - onChanged(); - return this; + public com.google.protobuf.ByteString getTypeBytes() { + Object ref = type_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + type_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - - private Object operation_ = ""; + /** * string operation = 5; */ public String getOperation() { - Object ref = operation_; - if (!(ref instanceof String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - operation_ = s; - return s; - } else { - return (String) ref; - } - } - /** - * string operation = 5; - */ - public com.google.protobuf.ByteString - getOperationBytes() { - Object ref = operation_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - operation_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - /** - * string operation = 5; - */ - public Builder setOperation( - String value) { - if (value == null) { - throw new NullPointerException(); - } - - operation_ = value; - onChanged(); - return this; - } - /** - * string operation = 5; - */ - public Builder clearOperation() { - - operation_ = getDefaultInstance().getOperation(); - onChanged(); - return this; + Object ref = operation_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + operation_ = s; + return s; + } } + /** * string operation = 5; */ - public Builder setOperationBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - operation_ = value; - onChanged(); - return this; - } - - private com.google.protobuf.MapField< - String, String> extendInfo_; - private com.google.protobuf.MapField - internalGetExtendInfo() { - if (extendInfo_ == null) { - return com.google.protobuf.MapField.emptyMapField( - ExtendInfoDefaultEntryHolder.defaultEntry); - } - return extendInfo_; + public com.google.protobuf.ByteString getOperationBytes() { + Object ref = operation_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + operation_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } - private com.google.protobuf.MapField - internalGetMutableExtendInfo() { - onChanged();; - if (extendInfo_ == null) { - extendInfo_ = com.google.protobuf.MapField.newMapField( - ExtendInfoDefaultEntryHolder.defaultEntry); - } - if (!extendInfo_.isMutable()) { - extendInfo_ = extendInfo_.copy(); - } - return extendInfo_; + + private com.google.protobuf.MapField internalGetExtendInfo() { + if (extendInfo_ == null) { + return com.google.protobuf.MapField.emptyMapField(ExtendInfoDefaultEntryHolder.defaultEntry); + } + return extendInfo_; } - + public int getExtendInfoCount() { - return internalGetExtendInfo().getMap().size(); + return internalGetExtendInfo().getMap().size(); } + /** * map<string, string> extendInfo = 6; */ - - public boolean containsExtendInfo( - String key) { - if (key == null) { throw new NullPointerException(); } - return internalGetExtendInfo().getMap().containsKey(key); + + public boolean containsExtendInfo(String key) { + if (key == null) { + throw new NullPointerException(); + } + return internalGetExtendInfo().getMap().containsKey(key); } + /** * Use {@link #getExtendInfoMap()} instead. */ @Deprecated public java.util.Map getExtendInfo() { - return getExtendInfoMap(); + return getExtendInfoMap(); } + /** * map<string, string> extendInfo = 6; */ - + public java.util.Map getExtendInfoMap() { - return internalGetExtendInfo().getMap(); + return internalGetExtendInfo().getMap(); } + /** * map<string, string> extendInfo = 6; */ - - public String getExtendInfoOrDefault( - String key, - String defaultValue) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetExtendInfo().getMap(); - return map.containsKey(key) ? map.get(key) : defaultValue; + + public String getExtendInfoOrDefault(String key, String defaultValue) { + if (key == null) { + throw new NullPointerException(); + } + java.util.Map map = internalGetExtendInfo().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; } + /** * map<string, string> extendInfo = 6; */ - - public String getExtendInfoOrThrow( - String key) { - if (key == null) { throw new NullPointerException(); } - java.util.Map map = - internalGetExtendInfo().getMap(); - if (!map.containsKey(key)) { - throw new IllegalArgumentException(); - } - return map.get(key); + + public String getExtendInfoOrThrow(String key) { + if (key == null) { + throw new NullPointerException(); + } + java.util.Map map = internalGetExtendInfo().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); } - - public Builder clearExtendInfo() { - internalGetMutableExtendInfo().getMutableMap() - .clear(); - return this; + + @Override + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) { + return true; + } + if (isInitialized == 0) { + return false; + } + + memoizedIsInitialized = 1; + return true; } - /** - * map<string, string> extendInfo = 6; - */ - - public Builder removeExtendInfo( - String key) { - if (key == null) { throw new NullPointerException(); } - internalGetMutableExtendInfo().getMutableMap() - .remove(key); - return this; + + @Override + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!getGroupBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 1, group_); + } + if (!getKeyBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, key_); + } + if (!data_.isEmpty()) { + output.writeBytes(3, data_); + } + if (!getTypeBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 4, type_); + } + if (!getOperationBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 5, operation_); + } + com.google.protobuf.GeneratedMessageV3 + .serializeStringMapTo(output, internalGetExtendInfo(), ExtendInfoDefaultEntryHolder.defaultEntry, 6); + unknownFields.writeTo(output); } - /** - * Use alternate mutation accessors instead. - */ - @Deprecated - public java.util.Map - getMutableExtendInfo() { - return internalGetMutableExtendInfo().getMutableMap(); + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) { + return size; + } + + size = 0; + if (!getGroupBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, group_); + } + if (!getKeyBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, key_); + } + if (!data_.isEmpty()) { + size += com.google.protobuf.CodedOutputStream.computeBytesSize(3, data_); + } + if (!getTypeBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, type_); + } + if (!getOperationBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, operation_); + } + for (java.util.Map.Entry entry : internalGetExtendInfo().getMap().entrySet()) { + com.google.protobuf.MapEntry extendInfo__ = ExtendInfoDefaultEntryHolder.defaultEntry + .newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build(); + size += com.google.protobuf.CodedOutputStream.computeMessageSize(6, extendInfo__); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; } - /** - * map<string, string> extendInfo = 6; - */ - public Builder putExtendInfo( - String key, - String value) { - if (key == null) { throw new NullPointerException(); } - if (value == null) { throw new NullPointerException(); } - internalGetMutableExtendInfo().getMutableMap() - .put(key, value); - return this; + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof Log)) { + return super.equals(obj); + } + Log other = (Log) obj; + + if (!getGroup().equals(other.getGroup())) { + return false; + } + if (!getKey().equals(other.getKey())) { + return false; + } + if (!getData().equals(other.getData())) { + return false; + } + if (!getType().equals(other.getType())) { + return false; + } + if (!getOperation().equals(other.getOperation())) { + return false; + } + if (!internalGetExtendInfo().equals(other.internalGetExtendInfo())) { + return false; + } + if (!unknownFields.equals(other.unknownFields)) { + return false; + } + return true; } - /** - * map<string, string> extendInfo = 6; - */ - - public Builder putAllExtendInfo( - java.util.Map values) { - internalGetMutableExtendInfo().getMutableMap() - .putAll(values); - return this; + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + GROUP_FIELD_NUMBER; + hash = (53 * hash) + getGroup().hashCode(); + hash = (37 * hash) + KEY_FIELD_NUMBER; + hash = (53 * hash) + getKey().hashCode(); + hash = (37 * hash) + DATA_FIELD_NUMBER; + hash = (53 * hash) + getData().hashCode(); + hash = (37 * hash) + TYPE_FIELD_NUMBER; + hash = (53 * hash) + getType().hashCode(); + hash = (37 * hash) + OPERATION_FIELD_NUMBER; + hash = (53 * hash) + getOperation().hashCode(); + if (!internalGetExtendInfo().getMap().isEmpty()) { + hash = (37 * hash) + EXTENDINFO_FIELD_NUMBER; + hash = (53 * hash) + internalGetExtendInfo().hashCode(); + } + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; } + @Override - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); + public Builder newBuilderForType() { + return newBuilder(); } - + @Override - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } - - - // @@protoc_insertion_point(builder_scope:Log) - } - - // @@protoc_insertion_point(class_scope:Log) - private static final Log DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new Log(); - } - - public static Log getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { + @Override - public Log parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new Log(input, extensionRegistry); + protected Builder newBuilderForType(BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - @Override - public Log getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - + + @Override + public com.google.protobuf.Parser getParserForType() { + return PARSER; + } + + @Override + public Log getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + private static final class ExtendInfoDefaultEntryHolder { + + static final com.google.protobuf.MapEntry defaultEntry = com.google.protobuf.MapEntry.newDefaultInstance( + Data.internal_static_Log_ExtendInfoEntry_descriptor, com.google.protobuf.WireFormat.FieldType.STRING, + "", com.google.protobuf.WireFormat.FieldType.STRING, ""); + } + + /** + * Protobuf type {@code Log} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:Log) + LogOrBuilder { + + private int bitField0_; + + private Object group_ = ""; + + private Object key_ = ""; + + private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; + + private Object type_ = ""; + + private Object operation_ = ""; + + private com.google.protobuf.MapField extendInfo_; + + // Construct using com.alibaba.nacos.consistency.entity.Log.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return Data.internal_static_Log_descriptor; + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMapField(int number) { + switch (number) { + case 6: + return internalGetExtendInfo(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } + } + + @SuppressWarnings({"rawtypes"}) + protected com.google.protobuf.MapField internalGetMutableMapField(int number) { + switch (number) { + case 6: + return internalGetMutableExtendInfo(); + default: + throw new RuntimeException("Invalid map field number: " + number); + } + } + + @Override + protected FieldAccessorTable internalGetFieldAccessorTable() { + return Data.internal_static_Log_fieldAccessorTable + .ensureFieldAccessorsInitialized(Log.class, Log.Builder.class); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { + } + } + + @Override + public Builder clear() { + super.clear(); + group_ = ""; + + key_ = ""; + + data_ = com.google.protobuf.ByteString.EMPTY; + + type_ = ""; + + operation_ = ""; + + internalGetMutableExtendInfo().clear(); + return this; + } + + @Override + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return Data.internal_static_Log_descriptor; + } + + @Override + public Log getDefaultInstanceForType() { + return Log.getDefaultInstance(); + } + + @Override + public Log build() { + Log result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + @Override + public Log buildPartial() { + Log result = new Log(this); + int from_bitField0_ = bitField0_; + result.group_ = group_; + result.key_ = key_; + result.data_ = data_; + result.type_ = type_; + result.operation_ = operation_; + result.extendInfo_ = internalGetExtendInfo(); + result.extendInfo_.makeImmutable(); + onBuilt(); + return result; + } + + @Override + public Builder clone() { + return super.clone(); + } + + @Override + public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { + return super.setField(field, value); + } + + @Override + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return super.clearField(field); + } + + @Override + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return super.clearOneof(oneof); + } + + @Override + public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, int index, + Object value) { + return super.setRepeatedField(field, index, value); + } + + @Override + public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { + return super.addRepeatedField(field, value); + } + + @Override + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof Log) { + return mergeFrom((Log) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(Log other) { + if (other == Log.getDefaultInstance()) { + return this; + } + if (!other.getGroup().isEmpty()) { + group_ = other.group_; + onChanged(); + } + if (!other.getKey().isEmpty()) { + key_ = other.key_; + onChanged(); + } + if (other.getData() != com.google.protobuf.ByteString.EMPTY) { + setData(other.getData()); + } + if (!other.getType().isEmpty()) { + type_ = other.type_; + onChanged(); + } + if (!other.getOperation().isEmpty()) { + operation_ = other.operation_; + onChanged(); + } + internalGetMutableExtendInfo().mergeFrom(other.internalGetExtendInfo()); + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + @Override + public final boolean isInitialized() { + return true; + } + + @Override + public Builder mergeFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + Log parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (Log) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + /** + * string group = 1; + */ + public String getGroup() { + Object ref = group_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + group_ = s; + return s; + } else { + return (String) ref; + } + } + + /** + * string group = 1; + */ + public Builder setGroup(String value) { + if (value == null) { + throw new NullPointerException(); + } + + group_ = value; + onChanged(); + return this; + } + + /** + * string group = 1; + */ + public com.google.protobuf.ByteString getGroupBytes() { + Object ref = group_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + group_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * string group = 1; + */ + public Builder setGroupBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + group_ = value; + onChanged(); + return this; + } + + /** + * string group = 1; + */ + public Builder clearGroup() { + + group_ = getDefaultInstance().getGroup(); + onChanged(); + return this; + } + + /** + * string key = 2; + */ + public String getKey() { + Object ref = key_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + key_ = s; + return s; + } else { + return (String) ref; + } + } + + /** + * string key = 2; + */ + public Builder setKey(String value) { + if (value == null) { + throw new NullPointerException(); + } + + key_ = value; + onChanged(); + return this; + } + + /** + * string key = 2; + */ + public com.google.protobuf.ByteString getKeyBytes() { + Object ref = key_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + key_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * string key = 2; + */ + public Builder setKeyBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + key_ = value; + onChanged(); + return this; + } + + /** + * string key = 2; + */ + public Builder clearKey() { + + key_ = getDefaultInstance().getKey(); + onChanged(); + return this; + } + + /** + * bytes data = 3; + */ + public com.google.protobuf.ByteString getData() { + return data_; + } + + /** + * bytes data = 3; + */ + public Builder setData(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + + data_ = value; + onChanged(); + return this; + } + + /** + * bytes data = 3; + */ + public Builder clearData() { + + data_ = getDefaultInstance().getData(); + onChanged(); + return this; + } + + /** + * string type = 4; + */ + public String getType() { + Object ref = type_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + type_ = s; + return s; + } else { + return (String) ref; + } + } + + /** + * string type = 4; + */ + public Builder setType(String value) { + if (value == null) { + throw new NullPointerException(); + } + + type_ = value; + onChanged(); + return this; + } + + /** + * string type = 4; + */ + public com.google.protobuf.ByteString getTypeBytes() { + Object ref = type_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + type_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * string type = 4; + */ + public Builder setTypeBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + type_ = value; + onChanged(); + return this; + } + + /** + * string type = 4; + */ + public Builder clearType() { + + type_ = getDefaultInstance().getType(); + onChanged(); + return this; + } + + /** + * string operation = 5; + */ + public String getOperation() { + Object ref = operation_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + operation_ = s; + return s; + } else { + return (String) ref; + } + } + + /** + * string operation = 5; + */ + public Builder setOperation(String value) { + if (value == null) { + throw new NullPointerException(); + } + + operation_ = value; + onChanged(); + return this; + } + + /** + * string operation = 5; + */ + public com.google.protobuf.ByteString getOperationBytes() { + Object ref = operation_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + operation_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * string operation = 5; + */ + public Builder setOperationBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + operation_ = value; + onChanged(); + return this; + } + + /** + * string operation = 5; + */ + public Builder clearOperation() { + + operation_ = getDefaultInstance().getOperation(); + onChanged(); + return this; + } + + private com.google.protobuf.MapField internalGetExtendInfo() { + if (extendInfo_ == null) { + return com.google.protobuf.MapField.emptyMapField(ExtendInfoDefaultEntryHolder.defaultEntry); + } + return extendInfo_; + } + + private com.google.protobuf.MapField internalGetMutableExtendInfo() { + onChanged(); + ; + if (extendInfo_ == null) { + extendInfo_ = com.google.protobuf.MapField.newMapField(ExtendInfoDefaultEntryHolder.defaultEntry); + } + if (!extendInfo_.isMutable()) { + extendInfo_ = extendInfo_.copy(); + } + return extendInfo_; + } + + public int getExtendInfoCount() { + return internalGetExtendInfo().getMap().size(); + } + + /** + * map<string, string> extendInfo = 6; + */ + + public boolean containsExtendInfo(String key) { + if (key == null) { + throw new NullPointerException(); + } + return internalGetExtendInfo().getMap().containsKey(key); + } + + /** + * Use {@link #getExtendInfoMap()} instead. + */ + @Deprecated + public java.util.Map getExtendInfo() { + return getExtendInfoMap(); + } + + /** + * map<string, string> extendInfo = 6; + */ + + public java.util.Map getExtendInfoMap() { + return internalGetExtendInfo().getMap(); + } + + /** + * map<string, string> extendInfo = 6; + */ + + public String getExtendInfoOrDefault(String key, String defaultValue) { + if (key == null) { + throw new NullPointerException(); + } + java.util.Map map = internalGetExtendInfo().getMap(); + return map.containsKey(key) ? map.get(key) : defaultValue; + } + + /** + * map<string, string> extendInfo = 6; + */ + + public String getExtendInfoOrThrow(String key) { + if (key == null) { + throw new NullPointerException(); + } + java.util.Map map = internalGetExtendInfo().getMap(); + if (!map.containsKey(key)) { + throw new IllegalArgumentException(); + } + return map.get(key); + } + + public Builder clearExtendInfo() { + internalGetMutableExtendInfo().getMutableMap().clear(); + return this; + } + + /** + * map<string, string> extendInfo = 6; + */ + + public Builder removeExtendInfo(String key) { + if (key == null) { + throw new NullPointerException(); + } + internalGetMutableExtendInfo().getMutableMap().remove(key); + return this; + } + + /** + * Use alternate mutation accessors instead. + */ + @Deprecated + public java.util.Map getMutableExtendInfo() { + return internalGetMutableExtendInfo().getMutableMap(); + } + + /** + * map<string, string> extendInfo = 6; + */ + public Builder putExtendInfo(String key, String value) { + if (key == null) { + throw new NullPointerException(); + } + if (value == null) { + throw new NullPointerException(); + } + internalGetMutableExtendInfo().getMutableMap().put(key, value); + return this; + } + + /** + * map<string, string> extendInfo = 6; + */ + + public Builder putAllExtendInfo(java.util.Map values) { + internalGetMutableExtendInfo().getMutableMap().putAll(values); + return this; + } + + @Override + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + @Override + public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:Log) + } + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/LogOrBuilder.java b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/LogOrBuilder.java index 9a8cfa159ed..d1bfb48b641 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/LogOrBuilder.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/LogOrBuilder.java @@ -19,82 +19,86 @@ package com.alibaba.nacos.consistency.entity; +@SuppressWarnings("all") public interface LogOrBuilder extends - // @@protoc_insertion_point(interface_extends:Log) - com.google.protobuf.MessageOrBuilder { - - /** - * string group = 1; - */ - String getGroup(); - /** - * string group = 1; - */ - com.google.protobuf.ByteString - getGroupBytes(); - - /** - * string key = 2; - */ - String getKey(); - /** - * string key = 2; - */ - com.google.protobuf.ByteString - getKeyBytes(); - - /** - * bytes data = 3; - */ - com.google.protobuf.ByteString getData(); - - /** - * string type = 4; - */ - String getType(); - /** - * string type = 4; - */ - com.google.protobuf.ByteString - getTypeBytes(); - - /** - * string operation = 5; - */ - String getOperation(); - /** - * string operation = 5; - */ - com.google.protobuf.ByteString - getOperationBytes(); - - /** - * map<string, string> extendInfo = 6; - */ - int getExtendInfoCount(); - /** - * map<string, string> extendInfo = 6; - */ - boolean containsExtendInfo(String key); - /** - * Use {@link #getExtendInfoMap()} instead. - */ - @Deprecated - java.util.Map - getExtendInfo(); - /** - * map<string, string> extendInfo = 6; - */ - java.util.Map - getExtendInfoMap(); - /** - * map<string, string> extendInfo = 6; - */ - - String getExtendInfoOrDefault(String key, String defaultValue); - /** - * map<string, string> extendInfo = 6; - */ - - String getExtendInfoOrThrow(String key); + // @@protoc_insertion_point(interface_extends:Log) + com.google.protobuf.MessageOrBuilder { + + /** + * string group = 1; + */ + String getGroup(); + + /** + * string group = 1; + */ + com.google.protobuf.ByteString getGroupBytes(); + + /** + * string key = 2; + */ + String getKey(); + + /** + * string key = 2; + */ + com.google.protobuf.ByteString getKeyBytes(); + + /** + * bytes data = 3; + */ + com.google.protobuf.ByteString getData(); + + /** + * string type = 4; + */ + String getType(); + + /** + * string type = 4; + */ + com.google.protobuf.ByteString getTypeBytes(); + + /** + * string operation = 5; + */ + String getOperation(); + + /** + * string operation = 5; + */ + com.google.protobuf.ByteString getOperationBytes(); + + /** + * map<string, string> extendInfo = 6; + */ + int getExtendInfoCount(); + + /** + * map<string, string> extendInfo = 6; + */ + boolean containsExtendInfo(String key); + + /** + * Use {@link #getExtendInfoMap()} instead. + */ + @Deprecated + java.util.Map getExtendInfo(); + + /** + * map<string, string> extendInfo = 6; + */ + java.util.Map getExtendInfoMap(); + + /** + * map<string, string> extendInfo = 6; + */ + + String getExtendInfoOrDefault(String key, String defaultValue); + + /** + * map<string, string> extendInfo = 6; + */ + + String getExtendInfoOrThrow(String key); } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Response.java b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Response.java index eff188d6f8a..e5784f55ca6 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Response.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/Response.java @@ -20,662 +20,658 @@ package com.alibaba.nacos.consistency.entity; /** - * Protobuf type {@code Response} + * Protobuf type {@code Response}. */ -public final class Response extends - com.google.protobuf.GeneratedMessageV3 implements - // @@protoc_insertion_point(message_implements:Response) - ResponseOrBuilder { -private static final long serialVersionUID = 0L; - // Use Response.newBuilder() to construct. - private Response(com.google.protobuf.GeneratedMessageV3.Builder builder) { - super(builder); - } - private Response() { - data_ = com.google.protobuf.ByteString.EMPTY; - errMsg_ = ""; - } - - @Override - @SuppressWarnings({"unused"}) - protected Object newInstance( - UnusedPrivateParameter unused) { - return new Response(); - } - - @Override - public final com.google.protobuf.UnknownFieldSet - getUnknownFields() { - return this.unknownFields; - } - private Response( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - this(); - if (extensionRegistry == null) { - throw new NullPointerException(); - } - com.google.protobuf.UnknownFieldSet.Builder unknownFields = - com.google.protobuf.UnknownFieldSet.newBuilder(); - try { - boolean done = false; - while (!done) { - int tag = input.readTag(); - switch (tag) { - case 0: - done = true; - break; - case 10: { - - data_ = input.readBytes(); - break; - } - case 18: { - String s = input.readStringRequireUtf8(); - - errMsg_ = s; - break; - } - case 24: { - - success_ = input.readBool(); - break; - } - default: { - if (!parseUnknownField( - input, unknownFields, extensionRegistry, tag)) { - done = true; +@SuppressWarnings("all") +public final class Response extends com.google.protobuf.GeneratedMessageV3 implements + // @@protoc_insertion_point(message_implements:Response) + ResponseOrBuilder { + + public static final int DATA_FIELD_NUMBER = 1; + + public static final int ERRMSG_FIELD_NUMBER = 2; + + public static final int SUCCESS_FIELD_NUMBER = 3; + + private static final long serialVersionUID = 0L; + + // @@protoc_insertion_point(class_scope:Response) + private static final Response DEFAULT_INSTANCE; + + private static final com.google.protobuf.Parser PARSER = new com.google.protobuf.AbstractParser() { + @Override + public Response parsePartialFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return new Response(input, extensionRegistry); + } + }; + + static { + DEFAULT_INSTANCE = new Response(); + } + + private com.google.protobuf.ByteString data_; + + private volatile Object errMsg_; + + private boolean success_; + + private byte memoizedIsInitialized = -1; + + // Use Response.newBuilder() to construct. + private Response(com.google.protobuf.GeneratedMessageV3.Builder builder) { + super(builder); + } + + private Response() { + data_ = com.google.protobuf.ByteString.EMPTY; + errMsg_ = ""; + } + + private Response(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + this(); + if (extensionRegistry == null) { + throw new NullPointerException(); + } + com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); + try { + boolean done = false; + while (!done) { + int tag = input.readTag(); + switch (tag) { + case 0: + done = true; + break; + case 10: { + + data_ = input.readBytes(); + break; + } + case 18: { + String s = input.readStringRequireUtf8(); + + errMsg_ = s; + break; + } + case 24: { + + success_ = input.readBool(); + break; + } + default: { + if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { + done = true; + } + break; + } + } } - break; - } - } - } - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - throw e.setUnfinishedMessage(this); - } catch (java.io.IOException e) { - throw new com.google.protobuf.InvalidProtocolBufferException( - e).setUnfinishedMessage(this); - } finally { - this.unknownFields = unknownFields.build(); - makeExtensionsImmutable(); - } - } - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return Data.internal_static_Response_descriptor; - } - - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return Data.internal_static_Response_fieldAccessorTable - .ensureFieldAccessorsInitialized( - Response.class, Response.Builder.class); - } - - public static final int DATA_FIELD_NUMBER = 1; - private com.google.protobuf.ByteString data_; - /** - * bytes data = 1; - */ - public com.google.protobuf.ByteString getData() { - return data_; - } - - public static final int ERRMSG_FIELD_NUMBER = 2; - private volatile Object errMsg_; - /** - * string errMsg = 2; - */ - public String getErrMsg() { - Object ref = errMsg_; - if (ref instanceof String) { - return (String) ref; - } else { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - errMsg_ = s; - return s; - } - } - /** - * string errMsg = 2; - */ - public com.google.protobuf.ByteString - getErrMsgBytes() { - Object ref = errMsg_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - errMsg_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } - } - - public static final int SUCCESS_FIELD_NUMBER = 3; - private boolean success_; - /** - * bool success = 3; - */ - public boolean getSuccess() { - return success_; - } - - private byte memoizedIsInitialized = -1; - @Override - public final boolean isInitialized() { - byte isInitialized = memoizedIsInitialized; - if (isInitialized == 1) return true; - if (isInitialized == 0) return false; - - memoizedIsInitialized = 1; - return true; - } - - @Override - public void writeTo(com.google.protobuf.CodedOutputStream output) - throws java.io.IOException { - if (!data_.isEmpty()) { - output.writeBytes(1, data_); - } - if (!getErrMsgBytes().isEmpty()) { - com.google.protobuf.GeneratedMessageV3.writeString(output, 2, errMsg_); - } - if (success_ != false) { - output.writeBool(3, success_); - } - unknownFields.writeTo(output); - } - - @Override - public int getSerializedSize() { - int size = memoizedSize; - if (size != -1) return size; - - size = 0; - if (!data_.isEmpty()) { - size += com.google.protobuf.CodedOutputStream - .computeBytesSize(1, data_); - } - if (!getErrMsgBytes().isEmpty()) { - size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, errMsg_); - } - if (success_ != false) { - size += com.google.protobuf.CodedOutputStream - .computeBoolSize(3, success_); - } - size += unknownFields.getSerializedSize(); - memoizedSize = size; - return size; - } - - @Override - public boolean equals(final Object obj) { - if (obj == this) { - return true; - } - if (!(obj instanceof Response)) { - return super.equals(obj); - } - Response other = (Response) obj; - - if (!getData() - .equals(other.getData())) return false; - if (!getErrMsg() - .equals(other.getErrMsg())) return false; - if (getSuccess() - != other.getSuccess()) return false; - if (!unknownFields.equals(other.unknownFields)) return false; - return true; - } - - @Override - public int hashCode() { - if (memoizedHashCode != 0) { - return memoizedHashCode; - } - int hash = 41; - hash = (19 * hash) + getDescriptor().hashCode(); - hash = (37 * hash) + DATA_FIELD_NUMBER; - hash = (53 * hash) + getData().hashCode(); - hash = (37 * hash) + ERRMSG_FIELD_NUMBER; - hash = (53 * hash) + getErrMsg().hashCode(); - hash = (37 * hash) + SUCCESS_FIELD_NUMBER; - hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean( - getSuccess()); - hash = (29 * hash) + unknownFields.hashCode(); - memoizedHashCode = hash; - return hash; - } - - public static Response parseFrom( - java.nio.ByteBuffer data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static Response parseFrom( - java.nio.ByteBuffer data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static Response parseFrom( - com.google.protobuf.ByteString data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static Response parseFrom( - com.google.protobuf.ByteString data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static Response parseFrom(byte[] data) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data); - } - public static Response parseFrom( - byte[] data, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return PARSER.parseFrom(data, extensionRegistry); - } - public static Response parseFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static Response parseFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - public static Response parseDelimitedFrom(java.io.InputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input); - } - public static Response parseDelimitedFrom( - java.io.InputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseDelimitedWithIOException(PARSER, input, extensionRegistry); - } - public static Response parseFrom( - com.google.protobuf.CodedInputStream input) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input); - } - public static Response parseFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - return com.google.protobuf.GeneratedMessageV3 - .parseWithIOException(PARSER, input, extensionRegistry); - } - - @Override - public Builder newBuilderForType() { return newBuilder(); } - public static Builder newBuilder() { - return DEFAULT_INSTANCE.toBuilder(); - } - public static Builder newBuilder(Response prototype) { - return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); - } - @Override - public Builder toBuilder() { - return this == DEFAULT_INSTANCE - ? new Builder() : new Builder().mergeFrom(this); - } - - @Override - protected Builder newBuilderForType( - BuilderParent parent) { - Builder builder = new Builder(parent); - return builder; - } - /** - * Protobuf type {@code Response} - */ - public static final class Builder extends - com.google.protobuf.GeneratedMessageV3.Builder implements - // @@protoc_insertion_point(builder_implements:Response) - ResponseOrBuilder { - public static final com.google.protobuf.Descriptors.Descriptor - getDescriptor() { - return Data.internal_static_Response_descriptor; - } - - @Override - protected FieldAccessorTable - internalGetFieldAccessorTable() { - return Data.internal_static_Response_fieldAccessorTable - .ensureFieldAccessorsInitialized( - Response.class, Response.Builder.class); - } - - // Construct using com.alibaba.nacos.consistency.entity.Response.newBuilder() - private Builder() { - maybeForceBuilderInitialization(); - } - - private Builder( - BuilderParent parent) { - super(parent); - maybeForceBuilderInitialization(); - } - private void maybeForceBuilderInitialization() { - if (com.google.protobuf.GeneratedMessageV3 - .alwaysUseFieldBuilders) { - } - } - @Override - public Builder clear() { - super.clear(); - data_ = com.google.protobuf.ByteString.EMPTY; - - errMsg_ = ""; - - success_ = false; - - return this; - } - - @Override - public com.google.protobuf.Descriptors.Descriptor - getDescriptorForType() { - return Data.internal_static_Response_descriptor; - } - - @Override - public Response getDefaultInstanceForType() { - return Response.getDefaultInstance(); - } - - @Override - public Response build() { - Response result = buildPartial(); - if (!result.isInitialized()) { - throw newUninitializedMessageException(result); - } - return result; - } - - @Override - public Response buildPartial() { - Response result = new Response(this); - result.data_ = data_; - result.errMsg_ = errMsg_; - result.success_ = success_; - onBuilt(); - return result; - } - - @Override - public Builder clone() { - return super.clone(); - } - @Override - public Builder setField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.setField(field, value); - } - @Override - public Builder clearField( - com.google.protobuf.Descriptors.FieldDescriptor field) { - return super.clearField(field); - } - @Override - public Builder clearOneof( - com.google.protobuf.Descriptors.OneofDescriptor oneof) { - return super.clearOneof(oneof); - } - @Override - public Builder setRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - int index, Object value) { - return super.setRepeatedField(field, index, value); - } - @Override - public Builder addRepeatedField( - com.google.protobuf.Descriptors.FieldDescriptor field, - Object value) { - return super.addRepeatedField(field, value); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + throw e.setUnfinishedMessage(this); + } catch (java.io.IOException e) { + throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); + } finally { + this.unknownFields = unknownFields.build(); + makeExtensionsImmutable(); + } } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return Data.internal_static_Response_descriptor; + } + + public static Response parseFrom(java.nio.ByteBuffer data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Response parseFrom(java.nio.ByteBuffer data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Response parseFrom(com.google.protobuf.ByteString data) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Response parseFrom(com.google.protobuf.ByteString data, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Response parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data); + } + + public static Response parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) + throws com.google.protobuf.InvalidProtocolBufferException { + return PARSER.parseFrom(data, extensionRegistry); + } + + public static Response parseFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static Response parseFrom(java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static Response parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); + } + + public static Response parseDelimitedFrom(java.io.InputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry); + } + + public static Response parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); + } + + public static Response parseFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry); + } + + public static Builder newBuilder() { + return DEFAULT_INSTANCE.toBuilder(); + } + + public static Builder newBuilder(Response prototype) { + return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); + } + + public static Response getDefaultInstance() { + return DEFAULT_INSTANCE; + } + + public static com.google.protobuf.Parser parser() { + return PARSER; + } + @Override - public Builder mergeFrom(com.google.protobuf.Message other) { - if (other instanceof Response) { - return mergeFrom((Response)other); - } else { - super.mergeFrom(other); - return this; - } - } - - public Builder mergeFrom(Response other) { - if (other == Response.getDefaultInstance()) return this; - if (other.getData() != com.google.protobuf.ByteString.EMPTY) { - setData(other.getData()); - } - if (!other.getErrMsg().isEmpty()) { - errMsg_ = other.errMsg_; - onChanged(); - } - if (other.getSuccess() != false) { - setSuccess(other.getSuccess()); - } - this.mergeUnknownFields(other.unknownFields); - onChanged(); - return this; + @SuppressWarnings({"unused"}) + protected Object newInstance(UnusedPrivateParameter unused) { + return new Response(); } - + @Override - public final boolean isInitialized() { - return true; + public final com.google.protobuf.UnknownFieldSet getUnknownFields() { + return this.unknownFields; } - + @Override - public Builder mergeFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws java.io.IOException { - Response parsedMessage = null; - try { - parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); - } catch (com.google.protobuf.InvalidProtocolBufferException e) { - parsedMessage = (Response) e.getUnfinishedMessage(); - throw e.unwrapIOException(); - } finally { - if (parsedMessage != null) { - mergeFrom(parsedMessage); - } - } - return this; + protected FieldAccessorTable internalGetFieldAccessorTable() { + return Data.internal_static_Response_fieldAccessorTable + .ensureFieldAccessorsInitialized(Response.class, Response.Builder.class); } - - private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; + /** * bytes data = 1; */ public com.google.protobuf.ByteString getData() { - return data_; + return data_; } - /** - * bytes data = 1; - */ - public Builder setData(com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - - data_ = value; - onChanged(); - return this; - } - /** - * bytes data = 1; - */ - public Builder clearData() { - - data_ = getDefaultInstance().getData(); - onChanged(); - return this; - } - - private Object errMsg_ = ""; + /** * string errMsg = 2; */ public String getErrMsg() { - Object ref = errMsg_; - if (!(ref instanceof String)) { - com.google.protobuf.ByteString bs = - (com.google.protobuf.ByteString) ref; - String s = bs.toStringUtf8(); - errMsg_ = s; - return s; - } else { - return (String) ref; - } + Object ref = errMsg_; + if (ref instanceof String) { + return (String) ref; + } else { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + errMsg_ = s; + return s; + } } + /** * string errMsg = 2; */ - public com.google.protobuf.ByteString - getErrMsgBytes() { - Object ref = errMsg_; - if (ref instanceof String) { - com.google.protobuf.ByteString b = - com.google.protobuf.ByteString.copyFromUtf8( - (String) ref); - errMsg_ = b; - return b; - } else { - return (com.google.protobuf.ByteString) ref; - } + public com.google.protobuf.ByteString getErrMsgBytes() { + Object ref = errMsg_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + errMsg_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } } + /** - * string errMsg = 2; + * bool success = 3; */ - public Builder setErrMsg( - String value) { - if (value == null) { - throw new NullPointerException(); - } - - errMsg_ = value; - onChanged(); - return this; + public boolean getSuccess() { + return success_; } - /** - * string errMsg = 2; - */ - public Builder clearErrMsg() { - - errMsg_ = getDefaultInstance().getErrMsg(); - onChanged(); - return this; + + @Override + public final boolean isInitialized() { + byte isInitialized = memoizedIsInitialized; + if (isInitialized == 1) { + return true; + } + if (isInitialized == 0) { + return false; + } + + memoizedIsInitialized = 1; + return true; } - /** - * string errMsg = 2; - */ - public Builder setErrMsgBytes( - com.google.protobuf.ByteString value) { - if (value == null) { - throw new NullPointerException(); - } - checkByteStringIsUtf8(value); - - errMsg_ = value; - onChanged(); - return this; + + @Override + public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { + if (!data_.isEmpty()) { + output.writeBytes(1, data_); + } + if (!getErrMsgBytes().isEmpty()) { + com.google.protobuf.GeneratedMessageV3.writeString(output, 2, errMsg_); + } + if (success_ != false) { + output.writeBool(3, success_); + } + unknownFields.writeTo(output); } - - private boolean success_ ; - /** - * bool success = 3; - */ - public boolean getSuccess() { - return success_; + + @Override + public int getSerializedSize() { + int size = memoizedSize; + if (size != -1) { + return size; + } + + size = 0; + if (!data_.isEmpty()) { + size += com.google.protobuf.CodedOutputStream.computeBytesSize(1, data_); + } + if (!getErrMsgBytes().isEmpty()) { + size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, errMsg_); + } + if (success_ != false) { + size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, success_); + } + size += unknownFields.getSerializedSize(); + memoizedSize = size; + return size; } - /** - * bool success = 3; - */ - public Builder setSuccess(boolean value) { - - success_ = value; - onChanged(); - return this; + + @Override + public boolean equals(final Object obj) { + if (obj == this) { + return true; + } + if (!(obj instanceof Response)) { + return super.equals(obj); + } + Response other = (Response) obj; + + if (!getData().equals(other.getData())) { + return false; + } + if (!getErrMsg().equals(other.getErrMsg())) { + return false; + } + if (getSuccess() != other.getSuccess()) { + return false; + } + if (!unknownFields.equals(other.unknownFields)) { + return false; + } + return true; } - /** - * bool success = 3; - */ - public Builder clearSuccess() { - - success_ = false; - onChanged(); - return this; + + @Override + public int hashCode() { + if (memoizedHashCode != 0) { + return memoizedHashCode; + } + int hash = 41; + hash = (19 * hash) + getDescriptor().hashCode(); + hash = (37 * hash) + DATA_FIELD_NUMBER; + hash = (53 * hash) + getData().hashCode(); + hash = (37 * hash) + ERRMSG_FIELD_NUMBER; + hash = (53 * hash) + getErrMsg().hashCode(); + hash = (37 * hash) + SUCCESS_FIELD_NUMBER; + hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSuccess()); + hash = (29 * hash) + unknownFields.hashCode(); + memoizedHashCode = hash; + return hash; + } + + @Override + public Builder newBuilderForType() { + return newBuilder(); } + @Override - public final Builder setUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.setUnknownFields(unknownFields); + public Builder toBuilder() { + return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } - + @Override - public final Builder mergeUnknownFields( - final com.google.protobuf.UnknownFieldSet unknownFields) { - return super.mergeUnknownFields(unknownFields); + protected Builder newBuilderForType(BuilderParent parent) { + Builder builder = new Builder(parent); + return builder; } - - - // @@protoc_insertion_point(builder_scope:Response) - } - - // @@protoc_insertion_point(class_scope:Response) - private static final Response DEFAULT_INSTANCE; - static { - DEFAULT_INSTANCE = new Response(); - } - - public static Response getDefaultInstance() { - return DEFAULT_INSTANCE; - } - - private static final com.google.protobuf.Parser - PARSER = new com.google.protobuf.AbstractParser() { + @Override - public Response parsePartialFrom( - com.google.protobuf.CodedInputStream input, - com.google.protobuf.ExtensionRegistryLite extensionRegistry) - throws com.google.protobuf.InvalidProtocolBufferException { - return new Response(input, extensionRegistry); + public com.google.protobuf.Parser getParserForType() { + return PARSER; } - }; - - public static com.google.protobuf.Parser parser() { - return PARSER; - } - - @Override - public com.google.protobuf.Parser getParserForType() { - return PARSER; - } - - @Override - public Response getDefaultInstanceForType() { - return DEFAULT_INSTANCE; - } - + + @Override + public Response getDefaultInstanceForType() { + return DEFAULT_INSTANCE; + } + + /** + * Protobuf type {@code Response} + */ + public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder implements + // @@protoc_insertion_point(builder_implements:Response) + ResponseOrBuilder { + + private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY; + + private Object errMsg_ = ""; + + private boolean success_; + + // Construct using com.alibaba.nacos.consistency.entity.Response.newBuilder() + private Builder() { + maybeForceBuilderInitialization(); + } + + private Builder(BuilderParent parent) { + super(parent); + maybeForceBuilderInitialization(); + } + + public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { + return Data.internal_static_Response_descriptor; + } + + @Override + protected FieldAccessorTable internalGetFieldAccessorTable() { + return Data.internal_static_Response_fieldAccessorTable + .ensureFieldAccessorsInitialized(Response.class, Response.Builder.class); + } + + private void maybeForceBuilderInitialization() { + if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) { + } + } + + @Override + public Builder clear() { + super.clear(); + data_ = com.google.protobuf.ByteString.EMPTY; + + errMsg_ = ""; + + success_ = false; + + return this; + } + + @Override + public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { + return Data.internal_static_Response_descriptor; + } + + @Override + public Response getDefaultInstanceForType() { + return Response.getDefaultInstance(); + } + + @Override + public Response build() { + Response result = buildPartial(); + if (!result.isInitialized()) { + throw newUninitializedMessageException(result); + } + return result; + } + + @Override + public Response buildPartial() { + Response result = new Response(this); + result.data_ = data_; + result.errMsg_ = errMsg_; + result.success_ = success_; + onBuilt(); + return result; + } + + @Override + public Builder clone() { + return super.clone(); + } + + @Override + public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { + return super.setField(field, value); + } + + @Override + public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { + return super.clearField(field); + } + + @Override + public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { + return super.clearOneof(oneof); + } + + @Override + public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, int index, + Object value) { + return super.setRepeatedField(field, index, value); + } + + @Override + public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) { + return super.addRepeatedField(field, value); + } + + @Override + public Builder mergeFrom(com.google.protobuf.Message other) { + if (other instanceof Response) { + return mergeFrom((Response) other); + } else { + super.mergeFrom(other); + return this; + } + } + + public Builder mergeFrom(Response other) { + if (other == Response.getDefaultInstance()) { + return this; + } + if (other.getData() != com.google.protobuf.ByteString.EMPTY) { + setData(other.getData()); + } + if (!other.getErrMsg().isEmpty()) { + errMsg_ = other.errMsg_; + onChanged(); + } + if (other.getSuccess() != false) { + setSuccess(other.getSuccess()); + } + this.mergeUnknownFields(other.unknownFields); + onChanged(); + return this; + } + + @Override + public final boolean isInitialized() { + return true; + } + + @Override + public Builder mergeFrom(com.google.protobuf.CodedInputStream input, + com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { + Response parsedMessage = null; + try { + parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); + } catch (com.google.protobuf.InvalidProtocolBufferException e) { + parsedMessage = (Response) e.getUnfinishedMessage(); + throw e.unwrapIOException(); + } finally { + if (parsedMessage != null) { + mergeFrom(parsedMessage); + } + } + return this; + } + + /** + * bytes data = 1; + */ + public com.google.protobuf.ByteString getData() { + return data_; + } + + /** + * bytes data = 1; + */ + public Builder setData(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + + data_ = value; + onChanged(); + return this; + } + + /** + * bytes data = 1; + */ + public Builder clearData() { + + data_ = getDefaultInstance().getData(); + onChanged(); + return this; + } + + /** + * string errMsg = 2; + */ + public String getErrMsg() { + Object ref = errMsg_; + if (!(ref instanceof String)) { + com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; + String s = bs.toStringUtf8(); + errMsg_ = s; + return s; + } else { + return (String) ref; + } + } + + /** + * string errMsg = 2; + */ + public Builder setErrMsg(String value) { + if (value == null) { + throw new NullPointerException(); + } + + errMsg_ = value; + onChanged(); + return this; + } + + /** + * string errMsg = 2; + */ + public com.google.protobuf.ByteString getErrMsgBytes() { + Object ref = errMsg_; + if (ref instanceof String) { + com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref); + errMsg_ = b; + return b; + } else { + return (com.google.protobuf.ByteString) ref; + } + } + + /** + * string errMsg = 2; + */ + public Builder setErrMsgBytes(com.google.protobuf.ByteString value) { + if (value == null) { + throw new NullPointerException(); + } + checkByteStringIsUtf8(value); + + errMsg_ = value; + onChanged(); + return this; + } + + /** + * string errMsg = 2; + */ + public Builder clearErrMsg() { + + errMsg_ = getDefaultInstance().getErrMsg(); + onChanged(); + return this; + } + + /** + * bool success = 3; + */ + public boolean getSuccess() { + return success_; + } + + /** + * bool success = 3; + */ + public Builder setSuccess(boolean value) { + + success_ = value; + onChanged(); + return this; + } + + /** + * bool success = 3; + */ + public Builder clearSuccess() { + + success_ = false; + onChanged(); + return this; + } + + @Override + public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.setUnknownFields(unknownFields); + } + + @Override + public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { + return super.mergeUnknownFields(unknownFields); + } + + // @@protoc_insertion_point(builder_scope:Response) + } + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/ResponseOrBuilder.java b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/ResponseOrBuilder.java index 20c3c58eaf2..c0050499747 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/entity/ResponseOrBuilder.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/entity/ResponseOrBuilder.java @@ -19,27 +19,28 @@ package com.alibaba.nacos.consistency.entity; +@SuppressWarnings("all") public interface ResponseOrBuilder extends - // @@protoc_insertion_point(interface_extends:Response) - com.google.protobuf.MessageOrBuilder { - - /** - * bytes data = 1; - */ - com.google.protobuf.ByteString getData(); - - /** - * string errMsg = 2; - */ - String getErrMsg(); - /** - * string errMsg = 2; - */ - com.google.protobuf.ByteString - getErrMsgBytes(); - - /** - * bool success = 3; - */ - boolean getSuccess(); + // @@protoc_insertion_point(interface_extends:Response) + com.google.protobuf.MessageOrBuilder { + + /** + * bytes data = 1; + */ + com.google.protobuf.ByteString getData(); + + /** + * string errMsg = 2; + */ + String getErrMsg(); + + /** + * string errMsg = 2; + */ + com.google.protobuf.ByteString getErrMsgBytes(); + + /** + * bool success = 3; + */ + boolean getSuccess(); } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/exception/ConsistencyException.java b/consistency/src/main/java/com/alibaba/nacos/consistency/exception/ConsistencyException.java index 3f1abd1646e..7fcd5814d5f 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/exception/ConsistencyException.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/exception/ConsistencyException.java @@ -17,29 +17,33 @@ package com.alibaba.nacos.consistency.exception; /** + * Conformance protocol internal exceptions. + * * @author liaochuntao */ public class ConsistencyException extends RuntimeException { + private static final long serialVersionUID = 1935132712388069418L; - + public ConsistencyException() { super(); } - + public ConsistencyException(String message) { super(message); } - + public ConsistencyException(String message, Throwable cause) { super(message, cause); } - + public ConsistencyException(Throwable cause) { super(cause); } - - protected ConsistencyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + + protected ConsistencyException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } - + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/exception/NoSuchLogProcessorException.java b/consistency/src/main/java/com/alibaba/nacos/consistency/exception/NoSuchLogProcessorException.java index e6446f137e9..a5522f1d2ce 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/exception/NoSuchLogProcessorException.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/exception/NoSuchLogProcessorException.java @@ -17,26 +17,29 @@ package com.alibaba.nacos.consistency.exception; /** + * There is no log processing group corresponding to the group. + * * @author liaochuntao */ public class NoSuchLogProcessorException extends RuntimeException { - + public NoSuchLogProcessorException() { } - + public NoSuchLogProcessorException(String message) { super(message); } - + public NoSuchLogProcessorException(String message, Throwable cause) { super(message, cause); } - + public NoSuchLogProcessorException(Throwable cause) { super(cause); } - - public NoSuchLogProcessorException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + + public NoSuchLogProcessorException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/serialize/HessianSerializer.java b/consistency/src/main/java/com/alibaba/nacos/consistency/serialize/HessianSerializer.java index a7174f5eb2e..a2df7a49aaa 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/serialize/HessianSerializer.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/serialize/HessianSerializer.java @@ -27,53 +27,55 @@ import java.io.IOException; /** + * hessian serializer. + * * @author liaochuntao */ @SuppressWarnings("all") public class HessianSerializer implements Serializer { - - private SerializerFactory serializerFactory = new SerializerFactory(); - - public HessianSerializer() { - } - - @Override - public T deserialize(byte[] data, Class cls) { - - if (ByteUtils.isEmpty(data)) { - return null; - } - - Hessian2Input input = new Hessian2Input(new ByteArrayInputStream(data)); - input.setSerializerFactory(serializerFactory); - Object resultObject; - try { - resultObject = input.readObject(); - input.close(); - } catch (IOException e) { - throw new RuntimeException("IOException occurred when Hessian serializer decode!", e); - } - return (T) resultObject; - } - - @Override - public byte[] serialize(T obj) { - ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); - Hessian2Output output = new Hessian2Output(byteArray); - output.setSerializerFactory(serializerFactory); - try { - output.writeObject(obj); - output.close(); - } catch (IOException e) { - throw new RuntimeException("IOException occurred when Hessian serializer encode!", e); - } - - return byteArray.toByteArray(); - } - - @Override - public String name() { - return "Hessian"; - } - + + private SerializerFactory serializerFactory = new SerializerFactory(); + + public HessianSerializer() { + } + + @Override + public T deserialize(byte[] data, Class cls) { + + if (ByteUtils.isEmpty(data)) { + return null; + } + + Hessian2Input input = new Hessian2Input(new ByteArrayInputStream(data)); + input.setSerializerFactory(serializerFactory); + Object resultObject; + try { + resultObject = input.readObject(); + input.close(); + } catch (IOException e) { + throw new RuntimeException("IOException occurred when Hessian serializer decode!", e); + } + return (T) resultObject; + } + + @Override + public byte[] serialize(T obj) { + ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); + Hessian2Output output = new Hessian2Output(byteArray); + output.setSerializerFactory(serializerFactory); + try { + output.writeObject(obj); + output.close(); + } catch (IOException e) { + throw new RuntimeException("IOException occurred when Hessian serializer encode!", e); + } + + return byteArray.toByteArray(); + } + + @Override + public String name() { + return "Hessian"; + } + } \ No newline at end of file diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/LocalFileMeta.java b/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/LocalFileMeta.java index a94f5ee1584..f1494c4f82b 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/LocalFileMeta.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/LocalFileMeta.java @@ -19,37 +19,37 @@ import java.util.Properties; /** + * Meta information for the snapshot file. + * * @author liaochuntao */ public class LocalFileMeta { - + private final Properties fileMeta; - + public LocalFileMeta() { this.fileMeta = new Properties(); } - + public LocalFileMeta(Properties properties) { this.fileMeta = properties; } - + public LocalFileMeta append(Object key, Object value) { fileMeta.put(key, value); return this; } - + public Object get(String key) { return fileMeta.getProperty(key); } - + public Properties getFileMeta() { return fileMeta; } - + @Override public String toString() { - return "LocalFileMeta{" + - "fileMeta=" + fileMeta + - '}'; + return "LocalFileMeta{" + "fileMeta=" + fileMeta + '}'; } } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/Reader.java b/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/Reader.java index 185c15a7446..e2600ec5f05 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/Reader.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/Reader.java @@ -20,27 +20,29 @@ import java.util.Map; /** + * Read the snapshot file interface. + * * @author liaochuntao */ public class Reader { - + private final String path; - + private final Map allFiles; - + public Reader(String path, Map allFiles) { this.path = path; this.allFiles = Collections.unmodifiableMap(allFiles); } - + public String getPath() { return path; } - + public Map listFiles() { return allFiles; } - + public LocalFileMeta getFileMeta(String fileName) { return allFiles.get(fileName); } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/SnapshotOperation.java b/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/SnapshotOperation.java index eccb59a9ab0..245cacaae72 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/SnapshotOperation.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/SnapshotOperation.java @@ -19,27 +19,26 @@ import java.util.function.BiConsumer; /** - * Custom snapshot operation interface - * Discovery via SPI + * Custom snapshot operation interface Discovery via SPI. * * @author liaochuntao */ public interface SnapshotOperation { - + /** - * do snapshot save operation + * do snapshot save operation. * * @param writer {@link Writer} - * @param callFinally Callback {@link BiConsumer} when the snapshot operation is complete + * @param callFinally Callback {@link BiConsumer} when the snapshot operation is complete */ void onSnapshotSave(Writer writer, BiConsumer callFinally); - + /** - * do snapshot load operation + * do snapshot load operation. * * @param reader {@link Reader} * @return operation label */ boolean onSnapshotLoad(Reader reader); - + } diff --git a/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/Writer.java b/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/Writer.java index 157c8a6109e..bef012cdbcc 100644 --- a/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/Writer.java +++ b/consistency/src/main/java/com/alibaba/nacos/consistency/snapshot/Writer.java @@ -21,21 +21,24 @@ import java.util.Map; /** + * Snapshot write interface. + * * @author liaochuntao */ public class Writer { - + private final Map files = new HashMap<>(); + private String path; - + public Writer(String path) { this.path = path; } - + public String getPath() { return path; } - + /** * Adds a snapshot file without metadata. * @@ -46,7 +49,7 @@ public boolean addFile(final String fileName) { files.put(fileName, new LocalFileMeta().append("file-name", fileName)); return true; } - + /** * Adds a snapshot file with metadata. * @@ -57,7 +60,7 @@ public boolean addFile(final String fileName, final LocalFileMeta meta) { files.put(fileName, meta); return true; } - + /** * Remove a snapshot file. * @@ -68,9 +71,9 @@ public boolean removeFile(final String fileName) { files.remove(fileName); return true; } - + public Map listFiles() { return Collections.unmodifiableMap(files); } - + } diff --git a/consistency/src/main/proto/Data.proto b/consistency/src/main/proto/Data.proto index 083501a1323..32f19af052d 100644 --- a/consistency/src/main/proto/Data.proto +++ b/consistency/src/main/proto/Data.proto @@ -20,23 +20,23 @@ option java_multiple_files = true; option java_package = "com.alibaba.nacos.consistency.entity"; message Log { - string group = 1; - string key = 2; - bytes data = 3; - string type = 4; - string operation = 5; - map extendInfo = 6; + string group = 1; + string key = 2; + bytes data = 3; + string type = 4; + string operation = 5; + map extendInfo = 6; } message GetRequest { - string group = 1; - bytes data = 2; - map extendInfo = 3; + string group = 1; + bytes data = 2; + map extendInfo = 3; } message Response { - bytes data = 1; - string errMsg = 2; - bool success = 3; + bytes data = 1; + string errMsg = 2; + bool success = 3; } diff --git a/consistency/src/test/java/com/alibaba/nacos/consistency/ProtocolMetaDataTest.java b/consistency/src/test/java/com/alibaba/nacos/consistency/ProtocolMetaDataTest.java index 353501f4cb7..f77eb38ce38 100644 --- a/consistency/src/test/java/com/alibaba/nacos/consistency/ProtocolMetaDataTest.java +++ b/consistency/src/test/java/com/alibaba/nacos/consistency/ProtocolMetaDataTest.java @@ -16,6 +16,10 @@ package com.alibaba.nacos.consistency; +import com.alibaba.nacos.common.utils.JacksonUtils; +import org.junit.Assert; +import org.junit.Test; + import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; @@ -23,52 +27,48 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; -import com.alibaba.nacos.common.utils.JacksonUtils; -import org.junit.Assert; -import org.junit.Test; - public class ProtocolMetaDataTest { - + @Test - public void test_protocol_meta_data() throws Exception { + public void testProtocolMetaData() throws Exception { Map> map = new HashMap<>(); Map data = new HashMap<>(); data.put("test-1", LocalDateTime.now()); data.put("test_2", LocalDateTime.now()); map.put("global", data); - + ProtocolMetaData metaData = new ProtocolMetaData(); - + metaData.load(map); - + String json = JacksonUtils.toJson(metaData); AtomicInteger count = new AtomicInteger(0); - + CountDownLatch latch = new CountDownLatch(2); - + metaData.subscribe("global", "test-1", (o, arg) -> { System.out.println(arg); count.incrementAndGet(); latch.countDown(); }); - + System.out.println(json); - + map = new HashMap<>(); data = new HashMap<>(); data.put("test-1", LocalDateTime.now()); data.put("test_2", LocalDateTime.now()); map.put("global", data); - + metaData.load(map); - + json = JacksonUtils.toJson(metaData); System.out.println(json); - + latch.await(10_000L, TimeUnit.MILLISECONDS); - + Assert.assertEquals(2, count.get()); - + } - + } diff --git a/consistency/src/test/java/com/alibaba/nacos/consistency/SerializeFactoryTest.java b/consistency/src/test/java/com/alibaba/nacos/consistency/SerializeFactoryTest.java index 39a8c43d3df..acb16597cd9 100644 --- a/consistency/src/test/java/com/alibaba/nacos/consistency/SerializeFactoryTest.java +++ b/consistency/src/test/java/com/alibaba/nacos/consistency/SerializeFactoryTest.java @@ -28,52 +28,51 @@ import java.util.concurrent.CopyOnWriteArraySet; public class SerializeFactoryTest { - - - @Test - public void test_list_serialize() throws Exception { - byte[] data = new byte[0]; - Serializer serializer = SerializeFactory.getDefault(); - - List logsList = new ArrayList<>(); - for (int i = 0; i < 4; i ++) { - logsList.add(i); - } - - data = serializer.serialize(logsList); - Assert.assertNotEquals(0, data.length); - - ArrayList list = serializer.deserialize(data, ArrayList.class); - System.out.println(list); - } - - @Test - public void test_map_serialize() { - byte[] data = new byte[0]; - Serializer serializer = SerializeFactory.getDefault(); - Map logsMap = new HashMap<>(); - for (int i = 0; i < 4; i ++) { - logsMap.put(i, i); - } - data = serializer.serialize(logsMap); - Assert.assertNotEquals(0, data.length); - Map result = serializer.deserialize(data, HashMap.class); - System.out.println(result); - } - - @Test - public void test_set_serialize() { - byte[] data = new byte[0]; - Serializer serializer = SerializeFactory.getDefault(); - Set logsMap = new CopyOnWriteArraySet<>(); - for (int i = 0; i < 4; i ++) { - logsMap.add(i); - } - - data = serializer.serialize(logsMap); - Assert.assertNotEquals(0, data.length); - Set result = serializer.deserialize(data, HashSet.class); - System.out.println(result); - } - + + @Test + public void testListSerialize() throws Exception { + byte[] data = new byte[0]; + Serializer serializer = SerializeFactory.getDefault(); + + List logsList = new ArrayList<>(); + for (int i = 0; i < 4; i++) { + logsList.add(i); + } + + data = serializer.serialize(logsList); + Assert.assertNotEquals(0, data.length); + + ArrayList list = serializer.deserialize(data, ArrayList.class); + System.out.println(list); + } + + @Test + public void testMapSerialize() { + byte[] data = new byte[0]; + Serializer serializer = SerializeFactory.getDefault(); + Map logsMap = new HashMap<>(); + for (int i = 0; i < 4; i++) { + logsMap.put(i, i); + } + data = serializer.serialize(logsMap); + Assert.assertNotEquals(0, data.length); + Map result = serializer.deserialize(data, HashMap.class); + System.out.println(result); + } + + @Test + public void testSetSerialize() { + byte[] data = new byte[0]; + Serializer serializer = SerializeFactory.getDefault(); + Set logsMap = new CopyOnWriteArraySet<>(); + for (int i = 0; i < 4; i++) { + logsMap.add(i); + } + + data = serializer.serialize(logsMap); + Assert.assertNotEquals(0, data.length); + Set result = serializer.deserialize(data, HashSet.class); + System.out.println(result); + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/AccessException.java b/core/src/main/java/com/alibaba/nacos/core/auth/AccessException.java index 06e2c1c23c1..50b5b581f36 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/AccessException.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/AccessException.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.auth; import com.alibaba.nacos.api.exception.NacosException; @@ -24,19 +25,19 @@ * @since 1.2.0 */ public class AccessException extends NacosException { - + private static final long serialVersionUID = -2926344920552803270L; - - public AccessException(){ - + + public AccessException() { + } - + public AccessException(int code) { this.setErrCode(code); } - + public AccessException(String msg) { this.setErrMsg(msg); } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/ActionTypes.java b/core/src/main/java/com/alibaba/nacos/core/auth/ActionTypes.java index 8455c423d00..4cace580b17 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/ActionTypes.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/ActionTypes.java @@ -13,30 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.auth; /** - * Resource action type definitions + * Resource action type definitions. * * @author nkorange * @since 1.2.0 */ public enum ActionTypes { /** - * Read + * Read. */ READ("r"), /** - * Write + * Write. */ WRITE("w"); - + private String action; - + ActionTypes(String action) { this.action = action; } - + @Override public String toString() { return action; diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/AuthConfigs.java b/core/src/main/java/com/alibaba/nacos/core/auth/AuthConfigs.java index 0ef8fd7ad74..a8b92871269 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/AuthConfigs.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/AuthConfigs.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.auth; import com.alibaba.nacos.common.JustForTest; @@ -29,7 +30,7 @@ import java.util.Objects; /** - * Auth related configurations + * Auth related configurations. * * @author nkorange * @since 1.2.0 @@ -37,66 +38,76 @@ @Component @Configuration public class AuthConfigs { - + + @JustForTest + private static Boolean cachingEnabled = null; + @Autowired private ReloadableConfigs reloadableConfigs; - + /** - * secret key + * secret key. */ @Value("${nacos.core.auth.default.token.secret.key:}") private String secretKey; - + /** - * Token validity time(seconds) + * Token validity time(seconds). */ @Value("${nacos.core.auth.default.token.expire.seconds:1800}") private long tokenValidityInSeconds; - + /** - * Which auth system is in use + * Which auth system is in use. */ @Value("${nacos.core.auth.system.type:}") private String nacosAuthSystemType; - - @JustForTest - private static Boolean cachingEnabled = null; - + public String getSecretKey() { return secretKey; } - + public long getTokenValidityInSeconds() { return tokenValidityInSeconds; } - + public String getNacosAuthSystemType() { return nacosAuthSystemType; } - + + /** + * auth function is open. + * + * @return auth function is open + */ public boolean isAuthEnabled() { // Runtime -D parameter has higher priority: String enabled = System.getProperty("nacos.core.auth.enabled"); if (StringUtils.isNotBlank(enabled)) { return BooleanUtils.toBoolean(enabled); } - return BooleanUtils.toBoolean(reloadableConfigs.getProperties() - .getProperty("nacos.core.auth.enabled", "false")); + return BooleanUtils + .toBoolean(reloadableConfigs.getProperties().getProperty("nacos.core.auth.enabled", "false")); } - + + /** + * Whether permission information can be cached. + * + * @return bool + */ public boolean isCachingEnabled() { if (Objects.nonNull(AuthConfigs.cachingEnabled)) { return cachingEnabled; } - return BooleanUtils.toBoolean(reloadableConfigs.getProperties() - .getProperty("nacos.core.auth.caching.enabled", "true")); + return BooleanUtils + .toBoolean(reloadableConfigs.getProperties().getProperty("nacos.core.auth.caching.enabled", "true")); } - + @JustForTest public static void setCachingEnabled(boolean cachingEnabled) { AuthConfigs.cachingEnabled = cachingEnabled; } - + @Bean public FilterRegistrationBean authFilterRegistration() { FilterRegistrationBean registration = new FilterRegistrationBean<>(); @@ -104,13 +115,13 @@ public FilterRegistrationBean authFilterRegistration() { registration.addUrlPatterns("/*"); registration.setName("authFilter"); registration.setOrder(6); - + return registration; } - + @Bean public AuthFilter authFilter() { return new AuthFilter(); } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java b/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java index c23bc86bf63..a37d93fe03b 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/AuthFilter.java @@ -13,17 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.auth; +import com.alibaba.nacos.common.utils.ExceptionUtil; import com.alibaba.nacos.core.code.ControllerMethodsCache; import com.alibaba.nacos.core.utils.Constants; -import com.alibaba.nacos.common.utils.ExceptionUtil; import com.alibaba.nacos.core.utils.Loggers; import com.alibaba.nacos.core.utils.WebUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.*; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @@ -31,78 +36,79 @@ import java.net.URI; /** - * Unified filter to handle authentication and authorization + * Unified filter to handle authentication and authorization. * * @author nkorange * @since 1.2.0 */ public class AuthFilter implements Filter { - + @Autowired private AuthConfigs authConfigs; - + @Autowired private AuthManager authManager; - + @Autowired private ControllerMethodsCache methodsCache; - + @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) - throws IOException, ServletException { - + throws IOException, ServletException { + if (!authConfigs.isAuthEnabled()) { chain.doFilter(request, response); return; } - + HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; - + String userAgent = WebUtils.getUserAgent(req); - + if (StringUtils.startsWith(userAgent, Constants.NACOS_SERVER_HEADER)) { chain.doFilter(request, response); return; } - + try { - + String path = new URI(req.getRequestURI()).getPath(); Method method = methodsCache.getMethod(req.getMethod(), path); - + if (method == null) { chain.doFilter(request, response); return; } - + if (method.isAnnotationPresent(Secured.class) && authConfigs.isAuthEnabled()) { - + if (Loggers.AUTH.isDebugEnabled()) { Loggers.AUTH.debug("auth start, request: {} {}", req.getMethod(), req.getRequestURI()); } - + Secured secured = method.getAnnotation(Secured.class); String action = secured.action().toString(); String resource = secured.resource(); - + if (StringUtils.isBlank(resource)) { ResourceParser parser = secured.parser().newInstance(); resource = parser.parseName(req); } - + if (StringUtils.isBlank(resource)) { // deny if we don't find any resource: throw new AccessException("resource name invalid!"); } - + authManager.auth(new Permission(resource, action), authManager.login(req)); - + } chain.doFilter(request, response); } catch (AccessException e) { if (Loggers.AUTH.isDebugEnabled()) { - Loggers.AUTH.debug("access denied, request: {} {}, reason: {}", req.getMethod(), req.getRequestURI(), e.getErrMsg()); + Loggers.AUTH.debug("access denied, request: {} {}, reason: {}", req.getMethod(), req.getRequestURI(), + e.getErrMsg()); } resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getErrMsg()); return; diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/AuthManager.java b/core/src/main/java/com/alibaba/nacos/core/auth/AuthManager.java index d3c0012cdf9..b1cfaeea8cd 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/AuthManager.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/AuthManager.java @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.nacos.core.auth; +package com.alibaba.nacos.core.auth; /** * Access control entry. Can be extended by 3rd party implementations. @@ -23,7 +23,7 @@ * @since 1.2.0 */ public interface AuthManager { - + /** * Authentication of request, identify the user who request the resource. * @@ -32,12 +32,12 @@ public interface AuthManager { * @throws AccessException if authentication is failed */ User login(Object request) throws AccessException; - + /** * Authorization of request, constituted with resource and user. * * @param permission permission to auth - * @param user user who wants to access the resource. + * @param user user who wants to access the resource. * @throws AccessException if authorization is failed */ void auth(Permission permission, User user) throws AccessException; diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/AuthSystemTypes.java b/core/src/main/java/com/alibaba/nacos/core/auth/AuthSystemTypes.java index 905359a88cf..2517b5bbc94 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/AuthSystemTypes.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/AuthSystemTypes.java @@ -17,15 +17,15 @@ package com.alibaba.nacos.core.auth; /** - * Types of all auth implementations + * Types of all auth implementations. * * @author nkorange * @since 1.2.0 */ public enum AuthSystemTypes { - + /** - * Nacos builtin auth system + * Nacos builtin auth system. */ NACOS } diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/DefaultResourceParser.java b/core/src/main/java/com/alibaba/nacos/core/auth/DefaultResourceParser.java index a331a46c89c..86d36645ac6 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/DefaultResourceParser.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/DefaultResourceParser.java @@ -13,18 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.auth; import org.apache.commons.lang3.StringUtils; /** - * Default resource parser + * Default resource parser. * * @author nkorange * @since 1.2.0 */ public class DefaultResourceParser implements ResourceParser { - + @Override public String parseName(Object request) { return StringUtils.EMPTY; diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/Permission.java b/core/src/main/java/com/alibaba/nacos/core/auth/Permission.java index 0e513c7de4b..9e3ca334707 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/Permission.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/Permission.java @@ -13,60 +13,58 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.auth; import java.io.Serializable; /** - * Permission to auth + * Permission to auth. * * @author nkorange * @since 1.2.0 */ public class Permission implements Serializable { - + private static final long serialVersionUID = -3583076254743606551L; - - public Permission() { - - } - - public Permission(String resource, String action) { - this.resource = resource; - this.action = action; - } - + /** - * An unique key of resource + * An unique key of resource. */ private String resource; - + /** - * Action on resource, refer to class ActionTypes + * Action on resource, refer to class ActionTypes. */ private String action; - + + public Permission() { + + } + + public Permission(String resource, String action) { + this.resource = resource; + this.action = action; + } + public String getResource() { return resource; } - + public void setResource(String resource) { this.resource = resource; } - + public String getAction() { return action; } - + public void setAction(String action) { this.action = action; } - + @Override public String toString() { - return "Permission{" + - "resource='" + resource + '\'' + - ", action='" + action + '\'' + - '}'; + return "Permission{" + "resource='" + resource + '\'' + ", action='" + action + '\'' + '}'; } } diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/Resource.java b/core/src/main/java/com/alibaba/nacos/core/auth/Resource.java index 7f1915575c3..74a9bb5d95d 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/Resource.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/Resource.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.auth; import java.io.Serializable; @@ -24,32 +25,32 @@ * @since 1.2.0 */ public class Resource implements Serializable { - + public static final String SPLITTER = ":"; + public static final String ANY = "*"; + private static final long serialVersionUID = 925971662931204553L; - + /** * The unique key of resource. */ private String key; - + public Resource(String key) { this.key = key; } - + public String getKey() { return key; } - + public String parseName() { return key.substring(0, key.lastIndexOf(SPLITTER)); } - + @Override public String toString() { - return "Resource{" + - "key='" + key + '\'' + - '}'; + return "Resource{" + "key='" + key + '\'' + '}'; } } diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/ResourceParser.java b/core/src/main/java/com/alibaba/nacos/core/auth/ResourceParser.java index b519647081d..b86a1e0894f 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/ResourceParser.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/ResourceParser.java @@ -13,22 +13,22 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.nacos.core.auth; +package com.alibaba.nacos.core.auth; /** - * Resource parser + * Resource parser. * * @author nkorange * @since 1.2.0 */ public interface ResourceParser { - + /** - * Parse a unique name of the resource from the request + * Parse a unique name of the resource from the request. * - * @param request where we can find the resource info. Given it may vary from Http request to gRPC request, - * we use a Object type for future accommodation. + * @param request where we can find the resource info. Given it may vary from Http request to gRPC request, we use a + * Object type for future accommodation. * @return resource name */ String parseName(Object request); diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/Secured.java b/core/src/main/java/com/alibaba/nacos/core/auth/Secured.java index b6db37eecce..2b129f05517 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/Secured.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/Secured.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.auth; import org.apache.commons.lang3.StringUtils; @@ -28,23 +29,23 @@ */ @Retention(RetentionPolicy.RUNTIME) public @interface Secured { - + /** - * The action type of the request + * The action type of the request. * * @return action type, default READ */ ActionTypes action() default ActionTypes.READ; - + /** - * The name of resource related to the request + * The name of resource related to the request. * * @return resource name */ String resource() default StringUtils.EMPTY; - + /** - * Resource name parser. Should have lower priority than resource() + * Resource name parser. Should have lower priority than resource(). * * @return class type of resource parser */ diff --git a/core/src/main/java/com/alibaba/nacos/core/auth/User.java b/core/src/main/java/com/alibaba/nacos/core/auth/User.java index 8bf2a9ddac9..806cb8bee0a 100644 --- a/core/src/main/java/com/alibaba/nacos/core/auth/User.java +++ b/core/src/main/java/com/alibaba/nacos/core/auth/User.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.auth; import java.io.Serializable; @@ -24,17 +25,18 @@ * @since 1.2.0 */ public class User implements Serializable { - + private static final long serialVersionUID = -8002966873087151367L; + /** - * Unique string representing user + * Unique string representing user. */ private String userName; - + public String getUserName() { return userName; } - + public void setUserName(String userName) { this.userName = userName; } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/AbstractMemberLookup.java b/core/src/main/java/com/alibaba/nacos/core/cluster/AbstractMemberLookup.java index 8c176b5ec90..2b5e70865cc 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/AbstractMemberLookup.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/AbstractMemberLookup.java @@ -22,25 +22,28 @@ import java.util.concurrent.atomic.AtomicBoolean; /** + * Addressable pattern base class. + * * @author liaochuntao */ public abstract class AbstractMemberLookup implements MemberLookup { - - protected ServerMemberManager memberManager; - protected AtomicBoolean start = new AtomicBoolean(false); - - @Override - public void injectMemberManager(ServerMemberManager memberManager) { - this.memberManager = memberManager; - } - - @Override - public void afterLookup(Collection members) { - this.memberManager.memberChange(members); - } - - @Override - public void destroy() throws NacosException { - - } + + protected ServerMemberManager memberManager; + + protected AtomicBoolean start = new AtomicBoolean(false); + + @Override + public void injectMemberManager(ServerMemberManager memberManager) { + this.memberManager = memberManager; + } + + @Override + public void afterLookup(Collection members) { + this.memberManager.memberChange(members); + } + + @Override + public void destroy() throws NacosException { + + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/Member.java b/core/src/main/java/com/alibaba/nacos/core/cluster/Member.java index a0d9760a73b..98a9837b056 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/Member.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/Member.java @@ -25,170 +25,180 @@ import java.util.TreeMap; /** + * Cluster member node. + * * @author liaochuntao */ public class Member implements Comparable, Cloneable { - + private String ip; - - private int port = -1; - - private volatile NodeState state = NodeState.UP; - - private Map extendInfo = Collections.synchronizedMap(new TreeMap<>()); - - private String address = ""; - - private transient int failAccessCnt = 0; - - public Member() { + + private int port = -1; + + private volatile NodeState state = NodeState.UP; + + private Map extendInfo = Collections.synchronizedMap(new TreeMap<>()); + + private String address = ""; + + private transient int failAccessCnt = 0; + + public Member() { String prefix = "nacos.core.member.meta."; - extendInfo.put(MemberMetaDataConstants.SITE_KEY, ApplicationUtils - .getProperty(prefix + MemberMetaDataConstants.SITE_KEY, "unknow")); - extendInfo.put(MemberMetaDataConstants.AD_WEIGHT, ApplicationUtils - .getProperty(prefix + MemberMetaDataConstants.AD_WEIGHT, "0")); - extendInfo.put(MemberMetaDataConstants.WEIGHT, ApplicationUtils - .getProperty(prefix + MemberMetaDataConstants.WEIGHT, "1")); - } - - public static MemberBuilder builder() { - return new MemberBuilder(); - } - - public void setIp(String ip) { - this.ip = ip; - } - - public int getPort() { - return port; - } - - public void setPort(int port) { - this.port = port; - } - - public NodeState getState() { - return state; - } - - public void setState(NodeState state) { - this.state = state; - } - - public Map getExtendInfo() { - return extendInfo; - } - - public void setExtendInfo(Map extendInfo) { - this.extendInfo.putAll(extendInfo); - } - - public void setAddress(String address) { - this.address = address; - } - - public String getIp() { - return ip; - } - - public String getAddress() { - if (StringUtils.isBlank(address)) { - address = ip + ":" + port; - } - return address; - } - - public Object getExtendVal(String key) { - return extendInfo.get(key); - } - - public void setExtendVal(String key, Object value) { - extendInfo.put(key, value); - } - - public boolean check() { - return StringUtils.isNoneBlank(ip, address) && port != -1; - } - - public int getFailAccessCnt() { - return failAccessCnt; - } - - public void setFailAccessCnt(int failAccessCnt) { - this.failAccessCnt = failAccessCnt; - } - - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - Member that = (Member) o; - if (StringUtils.isAnyBlank(address, that.address)) { - return port == that.port && StringUtils.equals(ip, that.ip); - } - return StringUtils.equals(address, that.address); - } - - @Override - public String toString() { - return "Member{" + "address='" + getAddress() + '\'' + '}'; - } - - @Override - public int hashCode() { - return Objects.hash(ip, port); - } - - @Override - public int compareTo(Member o) { - return getAddress().compareTo(o.getAddress()); - } - - public static final class MemberBuilder { - private String ip; - private int port; - private NodeState state; - private Map extendInfo = Collections - .synchronizedMap(new TreeMap<>()); - - private MemberBuilder() { - } - - public MemberBuilder ip(String ip) { - this.ip = ip; - return this; - } - - public MemberBuilder port(int port) { - this.port = port; - return this; - } - - public MemberBuilder state(NodeState state) { - this.state = state; - return this; - } - - public MemberBuilder extendInfo(Map extendInfo) { - this.extendInfo.putAll(extendInfo); - return this; - } - - public Member build() { - Member serverNode = new Member(); - if (Objects.nonNull(this.extendInfo)) { - serverNode.extendInfo.putAll(this.extendInfo); - } - serverNode.state = this.state; - serverNode.ip = this.ip; - serverNode.port = this.port; - serverNode.address = this.ip + ":" + this.port; - return serverNode; - } - } - + extendInfo.put(MemberMetaDataConstants.SITE_KEY, + ApplicationUtils.getProperty(prefix + MemberMetaDataConstants.SITE_KEY, "unknow")); + extendInfo.put(MemberMetaDataConstants.AD_WEIGHT, + ApplicationUtils.getProperty(prefix + MemberMetaDataConstants.AD_WEIGHT, "0")); + extendInfo.put(MemberMetaDataConstants.WEIGHT, + ApplicationUtils.getProperty(prefix + MemberMetaDataConstants.WEIGHT, "1")); + } + + public static MemberBuilder builder() { + return new MemberBuilder(); + } + + public int getPort() { + return port; + } + + public void setPort(int port) { + this.port = port; + } + + public NodeState getState() { + return state; + } + + public void setState(NodeState state) { + this.state = state; + } + + public Map getExtendInfo() { + return extendInfo; + } + + public void setExtendInfo(Map extendInfo) { + this.extendInfo.putAll(extendInfo); + } + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public String getAddress() { + if (StringUtils.isBlank(address)) { + address = ip + ":" + port; + } + return address; + } + + public void setAddress(String address) { + this.address = address; + } + + public Object getExtendVal(String key) { + return extendInfo.get(key); + } + + public void setExtendVal(String key, Object value) { + extendInfo.put(key, value); + } + + public boolean check() { + return StringUtils.isNoneBlank(ip, address) && port != -1; + } + + public int getFailAccessCnt() { + return failAccessCnt; + } + + public void setFailAccessCnt(int failAccessCnt) { + this.failAccessCnt = failAccessCnt; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Member that = (Member) o; + if (StringUtils.isAnyBlank(address, that.address)) { + return port == that.port && StringUtils.equals(ip, that.ip); + } + return StringUtils.equals(address, that.address); + } + + @Override + public String toString() { + return "Member{" + "address='" + getAddress() + '\'' + '}'; + } + + @Override + public int hashCode() { + return Objects.hash(ip, port); + } + + @Override + public int compareTo(Member o) { + return getAddress().compareTo(o.getAddress()); + } + + public static final class MemberBuilder { + + private String ip; + + private int port; + + private NodeState state; + + private Map extendInfo = Collections.synchronizedMap(new TreeMap<>()); + + private MemberBuilder() { + } + + public MemberBuilder ip(String ip) { + this.ip = ip; + return this; + } + + public MemberBuilder port(int port) { + this.port = port; + return this; + } + + public MemberBuilder state(NodeState state) { + this.state = state; + return this; + } + + public MemberBuilder extendInfo(Map extendInfo) { + this.extendInfo.putAll(extendInfo); + return this; + } + + /** + * build Member. + * + * @return {@link Member} + */ + public Member build() { + Member serverNode = new Member(); + if (Objects.nonNull(this.extendInfo)) { + serverNode.extendInfo.putAll(this.extendInfo); + } + serverNode.state = this.state; + serverNode.ip = this.ip; + serverNode.port = this.port; + serverNode.address = this.ip + ":" + this.port; + return serverNode; + } + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberChangeEvent.java b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberChangeEvent.java index 06bf9567cb0..3f7e13ea731 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberChangeEvent.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberChangeEvent.java @@ -17,12 +17,12 @@ package com.alibaba.nacos.core.cluster; import com.alibaba.nacos.core.notify.Event; + import java.util.Collection; import java.util.concurrent.atomic.AtomicLong; /** - * Publish this event when the node list changes,All interested in the node list change - * event can listen to this event + * Publish this event when the node list changes,All interested in the node list change event can listen to this event. * *
      *
    • {@link com.alibaba.nacos.core.distributed.ProtocolManager}
    • @@ -33,43 +33,49 @@ * @author liaochuntao */ public class MemberChangeEvent implements Event { - + private static final AtomicLong SEQUENCE = new AtomicLong(0); - + private static final long serialVersionUID = 7308126651076668976L; - + private Collection members; - + private long no = SEQUENCE.getAndIncrement(); - + public static MemberChangeEventBuilder builder() { return new MemberChangeEventBuilder(); } - + public Collection getMembers() { return members; } - + public void setMembers(Collection members) { this.members = members; } - + @Override public long sequence() { return no; } - + public static final class MemberChangeEventBuilder { + private Collection allMembers; - + private MemberChangeEventBuilder() { } - + public MemberChangeEventBuilder members(Collection allMembers) { this.allMembers = allMembers; return this; } - + + /** + * build MemberChangeEvent. + * + * @return {@link MemberChangeEvent} + */ public MemberChangeEvent build() { MemberChangeEvent memberChangeEvent = new MemberChangeEvent(); memberChangeEvent.setMembers(allMembers); diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberChangeListener.java b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberChangeListener.java index b1303c5bda1..0b401441eab 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberChangeListener.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberChangeListener.java @@ -20,12 +20,14 @@ import com.alibaba.nacos.core.notify.listener.Subscribe; /** + * Node change listeners. + * * @author liaochuntao */ public interface MemberChangeListener extends Subscribe { - + /** - * return NodeChangeEvent.class info + * return NodeChangeEvent.class info. * * @return {@link MemberChangeEvent#getClass()} */ @@ -33,9 +35,9 @@ public interface MemberChangeListener extends Subscribe { default Class subscribeType() { return MemberChangeEvent.class; } - + /** - * Whether to ignore expired events + * Whether to ignore expired events. * * @return default value is {@link Boolean#TRUE} */ diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberLookup.java b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberLookup.java index dc32636b055..4d6f4078572 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberLookup.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberLookup.java @@ -17,55 +17,53 @@ package com.alibaba.nacos.core.cluster; import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.core.cluster.Member; -import com.alibaba.nacos.core.cluster.ServerMemberManager; import java.util.Collection; import java.util.Collections; import java.util.Map; /** - * Member node addressing mode + * Member node addressing mode. * * @author liaochuntao */ public interface MemberLookup { - - /** - * start - * - * @throws NacosException - */ - void start() throws NacosException; - - /** - * Inject the ServerMemberManager property - * - * @param memberManager {@link ServerMemberManager} - */ - void injectMemberManager(ServerMemberManager memberManager); - - /** - * The addressing pattern finds cluster nodes - * - * @param members {@link Collection} - */ - void afterLookup(Collection members); - - /** - * Addressing mode closed - * - * @throws NacosException - */ - void destroy() throws NacosException; - - /** - * Some data information about the addressing pattern - * - * @return {@link Map} - */ - default Map info() { - return Collections.emptyMap(); - } - + + /** + * start. + * + * @throws NacosException NacosException + */ + void start() throws NacosException; + + /** + * Inject the ServerMemberManager property. + * + * @param memberManager {@link ServerMemberManager} + */ + void injectMemberManager(ServerMemberManager memberManager); + + /** + * The addressing pattern finds cluster nodes. + * + * @param members {@link Collection} + */ + void afterLookup(Collection members); + + /** + * Addressing mode closed. + * + * @throws NacosException NacosException + */ + void destroy() throws NacosException; + + /** + * Some data information about the addressing pattern. + * + * @return {@link Map} + */ + default Map info() { + return Collections.emptyMap(); + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberMetaDataConstants.java b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberMetaDataConstants.java index c15f1c6e6bb..7ed2a9fe792 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberMetaDataConstants.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberMetaDataConstants.java @@ -13,37 +13,32 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.cluster; /** - * The necessary metadata information for the node + * The necessary metadata information for the node. * * @author liaochuntao */ public class MemberMetaDataConstants { - - /** - * Raft port,This parameter is dropped when GRPC is used as a whole - */ - public static final String RAFT_PORT = "raftPort"; - - public static final String SITE_KEY = "site"; - - public static final String AD_WEIGHT = "adWeight"; - - public static final String WEIGHT = "weight"; - - public static final String LAST_REFRESH_TIME = "lastRefreshTime"; - - public static final String VERSION = "version"; - - public static final String[] META_KEY_LIST = new String[]{ - RAFT_PORT, - SITE_KEY, - AD_WEIGHT, - WEIGHT, - LAST_REFRESH_TIME, - VERSION, - }; - + + /** + * Raft port,This parameter is dropped when GRPC is used as a whole. + */ + public static final String RAFT_PORT = "raftPort"; + + public static final String SITE_KEY = "site"; + + public static final String AD_WEIGHT = "adWeight"; + + public static final String WEIGHT = "weight"; + + public static final String LAST_REFRESH_TIME = "lastRefreshTime"; + + public static final String VERSION = "version"; + + public static final String[] META_KEY_LIST = new String[] {SITE_KEY, AD_WEIGHT, RAFT_PORT, WEIGHT, + LAST_REFRESH_TIME, VERSION}; + } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java index 449f0d68709..a0f77ea7f30 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/MemberUtils.java @@ -19,7 +19,6 @@ import com.alibaba.nacos.common.utils.ExceptionUtil; import com.alibaba.nacos.core.utils.ApplicationUtils; import com.alibaba.nacos.core.utils.Loggers; -import java.util.concurrent.ThreadLocalRandom; import org.apache.commons.lang3.StringUtils; import java.time.LocalDateTime; @@ -30,114 +29,156 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; import java.util.function.Predicate; /** + * Member node tool class. + * * @author liaochuntao */ public class MemberUtils { - - private static final String SEMICOLON = ":"; - private static final String TARGET_MEMBER_CONNECT_REFUSE_ERRMSG = "Connection refused"; - - private static ServerMemberManager manager; - - public static void setManager(ServerMemberManager manager) { - MemberUtils.manager = manager; - } - - public static void copy(Member newMember, Member oldMember) { - oldMember.setIp(newMember.getIp()); - oldMember.setPort(newMember.getPort()); - oldMember.setState(newMember.getState()); - oldMember.setExtendInfo(newMember.getExtendInfo()); - oldMember.setAddress(newMember.getAddress()); - } - - @SuppressWarnings("PMD.UndefineMagicConstantRule") - public static Member singleParse(String member) { - // Nacos default port is 8848 - int defaultPort = 8848; - // Set the default Raft port information for securit - - String address = member; - int port = defaultPort; - if (address.contains(SEMICOLON)) { - String[] info = address.split(SEMICOLON); - address = info[0]; - port = Integer.parseInt(info[1]); - } - - Member target = Member.builder().ip(address).port(port) - .state(NodeState.UP).build(); - - Map extendInfo = new HashMap<>(4); - // The Raft Port information needs to be set by default - extendInfo.put(MemberMetaDataConstants.RAFT_PORT, String.valueOf(calculateRaftPort(target))); - target.setExtendInfo(extendInfo); - return target; - } - - public static int calculateRaftPort(Member member) { - return member.getPort() - 1000; - } - - public static Collection multiParse(Collection addresses) { - List members = new ArrayList<>(addresses.size()); - for (String address : addresses) { - Member member = singleParse(address); - members.add(member); - } - return members; - } - - public static void onSuccess(Member member) { - manager.getMemberAddressInfos().add(member.getAddress()); - member.setState(NodeState.UP); - member.setFailAccessCnt(0); - manager.update(member); - } - - public static void onFail(Member member) { - onFail(member, null); - } - - public static void onFail(Member member, Throwable ex) { - manager.getMemberAddressInfos().remove(member.getAddress()); - member.setState(NodeState.SUSPICIOUS); - member.setFailAccessCnt(member.getFailAccessCnt() + 1); - int maxFailAccessCnt = ApplicationUtils - .getProperty("nacos.core.member.fail-access-cnt", Integer.class, 3); - - // If the number of consecutive failures to access the target node reaches - // a maximum, or the link request is rejected, the state is directly down - if (member.getFailAccessCnt() > maxFailAccessCnt || StringUtils.containsIgnoreCase(ex.getMessage(), TARGET_MEMBER_CONNECT_REFUSE_ERRMSG)) { - member.setState(NodeState.DOWN); - } - manager.update(member); - } - - public static void syncToFile(Collection members) { - try { - StringBuilder builder = new StringBuilder(); - builder.append("#").append(LocalDateTime.now()).append(StringUtils.LF); - for (String member : simpleMembers(members)) { - builder.append(member).append(StringUtils.LF); - } - ApplicationUtils.writeClusterConf(builder.toString()); - } - catch (Throwable ex) { - Loggers.CLUSTER.error("cluster member node persistence failed : {}", - ExceptionUtil.getAllExceptionMsg(ex)); - } - } - - @SuppressWarnings("PMD.UndefineMagicConstantRule") - public static Collection kRandom(Collection members, - Predicate filter, int k) { - + + private static final String SEMICOLON = ":"; + + private static final String TARGET_MEMBER_CONNECT_REFUSE_ERRMSG = "Connection refused"; + + private static ServerMemberManager manager; + + public static void setManager(ServerMemberManager manager) { + MemberUtils.manager = manager; + } + + /** + * Information copy. + * + * @param newMember {@link Member} + * @param oldMember {@link Member} + */ + public static void copy(Member newMember, Member oldMember) { + oldMember.setIp(newMember.getIp()); + oldMember.setPort(newMember.getPort()); + oldMember.setState(newMember.getState()); + oldMember.setExtendInfo(newMember.getExtendInfo()); + oldMember.setAddress(newMember.getAddress()); + } + + /** + * parse ip:port to member. + * + * @param member ip:port + * @return {@link Member} + */ + @SuppressWarnings("PMD.UndefineMagicConstantRule") + public static Member singleParse(String member) { + // Nacos default port is 8848 + int defaultPort = 8848; + // Set the default Raft port information for securit + + String address = member; + int port = defaultPort; + if (address.contains(SEMICOLON)) { + String[] info = address.split(SEMICOLON); + address = info[0]; + port = Integer.parseInt(info[1]); + } + + Member target = Member.builder().ip(address).port(port).state(NodeState.UP).build(); + + Map extendInfo = new HashMap<>(4); + // The Raft Port information needs to be set by default + extendInfo.put(MemberMetaDataConstants.RAFT_PORT, String.valueOf(calculateRaftPort(target))); + target.setExtendInfo(extendInfo); + return target; + } + + public static int calculateRaftPort(Member member) { + return member.getPort() - 1000; + } + + /** + * Resolves to Member list. + * + * @param addresses ip list, example [127.0.0.1:8847,127.0.0.1:8848,127.0.0.1:8849] + * @return member list + */ + public static Collection multiParse(Collection addresses) { + List members = new ArrayList<>(addresses.size()); + for (String address : addresses) { + Member member = singleParse(address); + members.add(member); + } + return members; + } + + /** + * Successful processing of the operation on the node. + * + * @param member {@link Member} + */ + public static void onSuccess(Member member) { + manager.getMemberAddressInfos().add(member.getAddress()); + member.setState(NodeState.UP); + member.setFailAccessCnt(0); + manager.update(member); + } + + public static void onFail(Member member) { + onFail(member, null); + } + + /** + * Failure processing of the operation on the node. + * + * @param member {@link Member} + * @param ex {@link Throwable} + */ + public static void onFail(Member member, Throwable ex) { + manager.getMemberAddressInfos().remove(member.getAddress()); + member.setState(NodeState.SUSPICIOUS); + member.setFailAccessCnt(member.getFailAccessCnt() + 1); + int maxFailAccessCnt = ApplicationUtils.getProperty("nacos.core.member.fail-access-cnt", Integer.class, 3); + + // If the number of consecutive failures to access the target node reaches + // a maximum, or the link request is rejected, the state is directly down + if (member.getFailAccessCnt() > maxFailAccessCnt || StringUtils + .containsIgnoreCase(ex.getMessage(), TARGET_MEMBER_CONNECT_REFUSE_ERRMSG)) { + member.setState(NodeState.DOWN); + } + manager.update(member); + } + + /** + * Node list information persistence. + * + * @param members member list + */ + public static void syncToFile(Collection members) { + try { + StringBuilder builder = new StringBuilder(); + builder.append("#").append(LocalDateTime.now()).append(StringUtils.LF); + for (String member : simpleMembers(members)) { + builder.append(member).append(StringUtils.LF); + } + ApplicationUtils.writeClusterConf(builder.toString()); + } catch (Throwable ex) { + Loggers.CLUSTER.error("cluster member node persistence failed : {}", ExceptionUtil.getAllExceptionMsg(ex)); + } + } + + /** + * We randomly pick k nodes. + * + * @param members member list + * @param filter filter {@link Predicate} + * @param k node number + * @return target members + */ + @SuppressWarnings("PMD.UndefineMagicConstantRule") + public static Collection kRandom(Collection members, Predicate filter, int k) { + Set kMembers = new HashSet<>(); - + // Here thinking similar consul gossip protocols random k node int totalSize = members.size(); Member[] membersArray = members.toArray(new Member[totalSize]); @@ -149,27 +190,27 @@ public static Collection kRandom(Collection members, kMembers.add(member); } } - + return kMembers; - } - - // 默认配置格式解析,只有nacos-server的ip or ip:port or hostname:port 信息 - - public static Collection readServerConf(Collection members) { - Set nodes = new HashSet<>(); - - for (String member : members) { - Member target = singleParse(member); - nodes.add(target); - } - - return nodes; - } - - public static List simpleMembers(Collection members) { - return members.stream().map(Member::getAddress) - .sorted() - .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); - } - + } + + /** + * Default configuration format resolution, only NACos-Server IP or IP :port or hostname: Port information. + */ + public static Collection readServerConf(Collection members) { + Set nodes = new HashSet<>(); + + for (String member : members) { + Member target = singleParse(member); + nodes.add(target); + } + + return nodes; + } + + public static List simpleMembers(Collection members) { + return members.stream().map(Member::getAddress).sorted() + .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/NodeState.java b/core/src/main/java/com/alibaba/nacos/core/cluster/NodeState.java index 0df406668e4..93f6adcad3f 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/NodeState.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/NodeState.java @@ -17,7 +17,7 @@ package com.alibaba.nacos.core.cluster; /** - * The life cycle state of a node plays an important role + * The life cycle state of a node plays an important role. * *

      1.3.0 The unified sinking operation should be done first, and the node state * should be radiated out later, mainly for whether the request can be processed and so on

      @@ -25,30 +25,30 @@ * @author liaochuntao */ public enum NodeState { - + /** - * Node is starting + * Node is starting. */ STARTING, - + /** - * Node is up and ready for request + * Node is up and ready for request. */ UP, - + /** - * Node may Crash + * Node may Crash. */ SUSPICIOUS, - + /** - * Node is out of service, something abnormal happened + * Node is out of service, something abnormal happened. */ DOWN, - + /** - * The Node is isolated + * The Node is isolated. */ ISOLATION, - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java b/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java index 57efebc3a1e..a0bfa53d745 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/ServerMemberManager.java @@ -59,399 +59,393 @@ import java.util.function.BiFunction; /** - * Cluster node management in Nacos - *

      - * {@link ServerMemberManager#init()} Cluster node manager initialization - * {@link ServerMemberManager#shutdown()} The cluster node manager is down - * {@link ServerMemberManager#getSelf()} Gets local node information - * {@link ServerMemberManager#getServerList()} Gets the cluster node dictionary - * {@link ServerMemberManager#getMemberAddressInfos()} Gets the address information of the healthy member node - * {@link ServerMemberManager#allMembers()} Gets a list of member information objects - * {@link ServerMemberManager#allMembersWithoutSelf()} Gets a list of cluster member nodes with the exception of this node - * {@link ServerMemberManager#hasMember(String)} Is there a node - * {@link ServerMemberManager#memberChange(Collection)} The final node list changes the method, making the full size more - * {@link ServerMemberManager#memberJoin(Collection)} Node join, can automatically trigger - * {@link ServerMemberManager#memberLeave(Collection)} When the node leaves, only the interface call can be manually triggered - * {@link ServerMemberManager#update(Member)} Update the target node information - * {@link ServerMemberManager#isUnHealth(String)} Whether the target node is healthy - * {@link ServerMemberManager#initAndStartLookup()} Initializes the addressing mode + * Cluster node management in Nacos. + * + *

      {@link ServerMemberManager#init()} Cluster node manager initialization {@link ServerMemberManager#shutdown()} The + * cluster node manager is down {@link ServerMemberManager#getSelf()} Gets local node information {@link + * ServerMemberManager#getServerList()} Gets the cluster node dictionary {@link ServerMemberManager#getMemberAddressInfos()} + * Gets the address information of the healthy member node {@link ServerMemberManager#allMembers()} Gets a list of + * member information objects {@link ServerMemberManager#allMembersWithoutSelf()} Gets a list of cluster member nodes + * with the exception of this node {@link ServerMemberManager#hasMember(String)} Is there a node {@link + * ServerMemberManager#memberChange(Collection)} The final node list changes the method, making the full size more + * {@link ServerMemberManager#memberJoin(Collection)} Node join, can automatically trigger {@link + * ServerMemberManager#memberLeave(Collection)} When the node leaves, only the interface call can be manually triggered + * {@link ServerMemberManager#update(Member)} Update the target node information {@link + * ServerMemberManager#isUnHealth(String)} Whether the target node is healthy {@link + * ServerMemberManager#initAndStartLookup()} Initializes the addressing mode * * @author liaochuntao */ @Component(value = "serverMemberManager") @SuppressWarnings("all") -public class ServerMemberManager - implements ApplicationListener { - - private final NAsyncHttpClient asyncHttpClient = HttpClientManager.getAsyncHttpClient(); - - /** - * Cluster node list - */ - private volatile ConcurrentSkipListMap serverList; - - /** - * Is this node in the cluster list - */ - private volatile boolean isInIpList = true; - - /** - * port - */ - private int port; - - /** - * Address information for the local node - */ - private String localAddress; - - /** - * Addressing pattern instances - */ - private MemberLookup lookup; - - /** - * self member obj - */ - private volatile Member self; - - /** - * here is always the node information of the "UP" state - */ - private volatile Set memberAddressInfos = new ConcurrentHashSet<>(); - - /** - * Broadcast this node element information task - */ - private final MemberInfoReportTask infoReportTask = new MemberInfoReportTask(); - - public ServerMemberManager(ServletContext servletContext) throws Exception { - this.serverList = new ConcurrentSkipListMap(); - ApplicationUtils.setContextPath(servletContext.getContextPath()); - MemberUtils.setManager(this); - - init(); - } - - protected void init() throws NacosException { - Loggers.CORE.info("Nacos-related cluster resource initialization"); - this.port = ApplicationUtils.getProperty("server.port", Integer.class, 8848); - this.localAddress = InetUtils.getSelfIp() + ":" + port; - this.self = MemberUtils.singleParse(this.localAddress); - this.self.setExtendVal(MemberMetaDataConstants.VERSION, VersionUtils.version); - serverList.put(self.getAddress(), self); - - // register NodeChangeEvent publisher to NotifyManager - registerClusterEvent(); - - // Initializes the lookup mode - initAndStartLookup(); - - if (serverList.isEmpty()) { - throw new NacosException(NacosException.SERVER_ERROR, - "cannot get serverlist, so exit."); - } - - Loggers.CORE.info("The cluster resource is initialized"); - } - - private void initAndStartLookup() throws NacosException { - this.lookup = LookupFactory.createLookUp(this); - this.lookup.start(); - } - - public void swithLookup(String name) throws NacosException { - this.lookup = LookupFactory.switchLookup(name, this); - this.lookup.start(); - } - - private void registerClusterEvent() { - // Register node change events - NotifyCenter.registerToPublisher(MemberChangeEvent.class, - ApplicationUtils.getProperty("nacos.member-change-event.queue.size", - Integer.class, 128)); - - // The address information of this node needs to be dynamically modified - // when registering the IP change of this node - NotifyCenter.registerSubscribe(new Subscribe() { - @Override - public void onEvent(InetUtils.IPChangeEvent event) { - String oldAddress = event.getOldIp() + ":" + port; - String newAddress = event.getNewIp() + ":" + port; - ServerMemberManager.this.localAddress = newAddress; - ApplicationUtils.setLocalAddress(localAddress); - - Member self = ServerMemberManager.this.self; - self.setIp(event.getNewIp()); - - ServerMemberManager.this.serverList.remove(oldAddress); - ServerMemberManager.this.serverList.put(newAddress, self); - - ServerMemberManager.this.memberAddressInfos.remove(oldAddress); - ServerMemberManager.this.memberAddressInfos.add(newAddress); - } - - @Override - public Class subscribeType() { - return InetUtils.IPChangeEvent.class; - } - }); - } - - public boolean update(Member newMember) { - Loggers.CLUSTER.debug("Node information update : {}", newMember); - - String address = newMember.getAddress(); - newMember.setExtendVal(MemberMetaDataConstants.LAST_REFRESH_TIME, System.currentTimeMillis()); - - if (!serverList.containsKey(address)) { - return false; - } - serverList.computeIfPresent(address, new BiFunction() { - @Override - public Member apply(String s, Member member) { - if (!NodeState.UP.equals(newMember.getState())) { - memberAddressInfos.remove(newMember.getAddress()); - } - MemberUtils.copy(newMember, member); - return member; - } - }); - return true; - } - - public boolean hasMember(String address) { - boolean result = serverList.containsKey(address); - if (!result) { - // If only IP information is passed in, a fuzzy match is required - for (Map.Entry entry : serverList.entrySet()) { - if (StringUtils.contains(entry.getKey(), address)) { - result = true; - break; - } - } - } - return result; - } - - public Member getSelf() { - return this.self; - } - - public Member find(String address) { - return serverList.get(address); - } - - public Collection allMembers() { - // We need to do a copy to avoid affecting the real data - HashSet set = new HashSet<>(serverList.values()); - set.add(self); - return set; - } - - public List allMembersWithoutSelf() { - List members = new ArrayList<>(serverList.values()); - members.remove(self); - return members; - } - - synchronized boolean memberChange(Collection members) { - - if (members == null || members.isEmpty()) { - return false; - } - - boolean isContainSelfIp = members.stream().anyMatch( - ipPortTmp -> Objects.equals(localAddress, ipPortTmp.getAddress())); - - if (isContainSelfIp) { - isInIpList = true; - } - else { - isInIpList = false; - members.add(this.self); - Loggers.CLUSTER - .warn("[serverlist] self ip {} not in serverlist {}", self, members); - } - - // If the number of old and new clusters is different, the cluster information - // must have changed; if the number of clusters is the same, then compare whether - // there is a difference; if there is a difference, then the cluster node changes - // are involved and all recipients need to be notified of the node change event - - boolean hasChange = members.size() != serverList.size(); - ConcurrentSkipListMap tmpMap = new ConcurrentSkipListMap(); - Set tmpAddressInfo = new ConcurrentHashSet<>(); - for (Member member : members) { - final String address = member.getAddress(); - - if (!serverList.containsKey(address)) { - hasChange = true; - } - - // Ensure that the node is created only once - tmpMap.put(address, member); - tmpAddressInfo.add(address); - } - - Map oldList = serverList; - Set oldSet = memberAddressInfos; - - serverList = tmpMap; - memberAddressInfos = tmpAddressInfo; - - Collection finalMembers = allMembers(); - - Loggers.CLUSTER.warn("[serverlist] updated to : {}", finalMembers); - - oldList.clear(); - oldSet.clear(); - - // Persist the current cluster node information to cluster.conf - // need to put the event publication into a synchronized block to ensure - // that the event publication is sequential - if (hasChange) { - MemberUtils.syncToFile(finalMembers); - Event event = MemberChangeEvent.builder().members(finalMembers).build(); - NotifyCenter.publishEvent(event); - } - - return hasChange; - } - - public synchronized boolean memberJoin(Collection members) { - Set set = new HashSet<>(members); - set.addAll(allMembers()); - return memberChange(set); - } - - public synchronized boolean memberLeave(Collection members) { - Set set = new HashSet<>(allMembers()); - set.removeAll(members); - return memberChange(set); - } - - public boolean isUnHealth(String address) { - Member member = serverList.get(address); - if (member == null) { - return false; - } - return !NodeState.UP.equals(member.getState()); - } - - public boolean isFirstIp() { - return Objects.equals(serverList.firstKey(), this.localAddress); - } - - @Override - public void onApplicationEvent(WebServerInitializedEvent event) { - getSelf().setState(NodeState.UP); - if (!ApplicationUtils.getStandaloneMode()) { - GlobalExecutor.scheduleByCommon(this.infoReportTask, 5_000L); - } - ApplicationUtils.setPort(event.getWebServer().getPort()); - ApplicationUtils.setLocalAddress(this.localAddress); - Loggers.CLUSTER.info("This node is ready to provide external services"); - } - - @PreDestroy - public void shutdown() throws NacosException { - serverList.clear(); - memberAddressInfos.clear(); - infoReportTask.shutdown(); - LookupFactory.destroy(); - } - - public Set getMemberAddressInfos() { - return memberAddressInfos; - } - - @JustForTest - public void updateMember(Member member) { - serverList.put(member.getAddress(), member); - } - - @JustForTest - public void setMemberAddressInfos(Set memberAddressInfos) { - this.memberAddressInfos = memberAddressInfos; - } - - public Map getServerList() { - return Collections.unmodifiableMap(serverList); - } - - public boolean isInIpList() { - return isInIpList; - } - - // Synchronize the metadata information of a node - // A health check of the target node is also attached - - class MemberInfoReportTask extends Task { - - private final GenericType> reference = new GenericType>() { - }; - - private int cursor = 0; - - @Override - protected void executeBody() { - List members = ServerMemberManager.this.allMembersWithoutSelf(); - - if (members.isEmpty()) { - return; - } - - this.cursor = (this.cursor + 1) % members.size(); - Member target = members.get(cursor); - - Loggers.CLUSTER.debug("report the metadata to the node : {}", target.getAddress()); - - final String url = HttpUtils.buildUrl(false, target.getAddress(), - ApplicationUtils.getContextPath(), Commons.NACOS_CORE_CONTEXT, - "/cluster/report"); - - try { - asyncHttpClient.post(url, Header.newInstance().addParam(Constants.NACOS_SERVER_HEADER, - VersionUtils.version), Query.EMPTY, getSelf(), - reference.getType(), new Callback() { - @Override - public void onReceive(RestResult result) { - if (result.getCode() == HttpStatus.NOT_IMPLEMENTED.value() || result.getCode() == HttpStatus.NOT_FOUND.value()) { - Loggers.CLUSTER.warn("{} version is too low, it is recommended to upgrade the version : {}", target, VersionUtils.version); - return; - } - if (result.ok()) { - MemberUtils.onSuccess(target); - } - else { - Loggers.CLUSTER - .warn("failed to report new info to target node : {}, result : {}", - target.getAddress(), result); - MemberUtils.onFail(target); - } - } - - @Override - public void onError(Throwable throwable) { - Loggers.CLUSTER - .error("failed to report new info to target node : {}, error : {}", - target.getAddress(), ExceptionUtil.getAllExceptionMsg(throwable)); - MemberUtils.onFail(target, throwable); - } - }); - } - catch (Throwable ex) { - Loggers.CLUSTER - .error("failed to report new info to target node : {}, error : {}", - target.getAddress(), ExceptionUtil.getAllExceptionMsg(ex)); - } - } - - @Override - protected void after() { - GlobalExecutor.scheduleByCommon(this, 2_000L); - } - } - +public class ServerMemberManager implements ApplicationListener { + + private final NAsyncHttpClient asyncHttpClient = HttpClientManager.getAsyncHttpClient(); + + /** + * Cluster node list + */ + private volatile ConcurrentSkipListMap serverList; + + /** + * Is this node in the cluster list + */ + private volatile boolean isInIpList = true; + + /** + * port + */ + private int port; + + /** + * Address information for the local node + */ + private String localAddress; + + /** + * Addressing pattern instances + */ + private MemberLookup lookup; + + /** + * self member obj + */ + private volatile Member self; + + /** + * here is always the node information of the "UP" state + */ + private volatile Set memberAddressInfos = new ConcurrentHashSet<>(); + + /** + * Broadcast this node element information task + */ + private final MemberInfoReportTask infoReportTask = new MemberInfoReportTask(); + + public ServerMemberManager(ServletContext servletContext) throws Exception { + this.serverList = new ConcurrentSkipListMap(); + ApplicationUtils.setContextPath(servletContext.getContextPath()); + MemberUtils.setManager(this); + + init(); + } + + protected void init() throws NacosException { + Loggers.CORE.info("Nacos-related cluster resource initialization"); + this.port = ApplicationUtils.getProperty("server.port", Integer.class, 8848); + this.localAddress = InetUtils.getSelfIp() + ":" + port; + this.self = MemberUtils.singleParse(this.localAddress); + this.self.setExtendVal(MemberMetaDataConstants.VERSION, VersionUtils.version); + serverList.put(self.getAddress(), self); + + // register NodeChangeEvent publisher to NotifyManager + registerClusterEvent(); + + // Initializes the lookup mode + initAndStartLookup(); + + if (serverList.isEmpty()) { + throw new NacosException(NacosException.SERVER_ERROR, "cannot get serverlist, so exit."); + } + + Loggers.CORE.info("The cluster resource is initialized"); + } + + private void initAndStartLookup() throws NacosException { + this.lookup = LookupFactory.createLookUp(this); + this.lookup.start(); + } + + public void swithLookup(String name) throws NacosException { + this.lookup = LookupFactory.switchLookup(name, this); + this.lookup.start(); + } + + private void registerClusterEvent() { + // Register node change events + NotifyCenter.registerToPublisher(MemberChangeEvent.class, + ApplicationUtils.getProperty("nacos.member-change-event.queue.size", Integer.class, 128)); + + // The address information of this node needs to be dynamically modified + // when registering the IP change of this node + NotifyCenter.registerSubscribe(new Subscribe() { + @Override + public void onEvent(InetUtils.IPChangeEvent event) { + String oldAddress = event.getOldIp() + ":" + port; + String newAddress = event.getNewIp() + ":" + port; + ServerMemberManager.this.localAddress = newAddress; + ApplicationUtils.setLocalAddress(localAddress); + + Member self = ServerMemberManager.this.self; + self.setIp(event.getNewIp()); + + ServerMemberManager.this.serverList.remove(oldAddress); + ServerMemberManager.this.serverList.put(newAddress, self); + + ServerMemberManager.this.memberAddressInfos.remove(oldAddress); + ServerMemberManager.this.memberAddressInfos.add(newAddress); + } + + @Override + public Class subscribeType() { + return InetUtils.IPChangeEvent.class; + } + }); + } + + public boolean update(Member newMember) { + Loggers.CLUSTER.debug("Node information update : {}", newMember); + + String address = newMember.getAddress(); + newMember.setExtendVal(MemberMetaDataConstants.LAST_REFRESH_TIME, System.currentTimeMillis()); + + if (!serverList.containsKey(address)) { + return false; + } + serverList.computeIfPresent(address, new BiFunction() { + @Override + public Member apply(String s, Member member) { + if (!NodeState.UP.equals(newMember.getState())) { + memberAddressInfos.remove(newMember.getAddress()); + } + MemberUtils.copy(newMember, member); + return member; + } + }); + return true; + } + + public boolean hasMember(String address) { + boolean result = serverList.containsKey(address); + if (!result) { + // If only IP information is passed in, a fuzzy match is required + for (Map.Entry entry : serverList.entrySet()) { + if (StringUtils.contains(entry.getKey(), address)) { + result = true; + break; + } + } + } + return result; + } + + public Member getSelf() { + return this.self; + } + + public Member find(String address) { + return serverList.get(address); + } + + public Collection allMembers() { + // We need to do a copy to avoid affecting the real data + HashSet set = new HashSet<>(serverList.values()); + set.add(self); + return set; + } + + public List allMembersWithoutSelf() { + List members = new ArrayList<>(serverList.values()); + members.remove(self); + return members; + } + + synchronized boolean memberChange(Collection members) { + + if (members == null || members.isEmpty()) { + return false; + } + + boolean isContainSelfIp = members.stream() + .anyMatch(ipPortTmp -> Objects.equals(localAddress, ipPortTmp.getAddress())); + + if (isContainSelfIp) { + isInIpList = true; + } else { + isInIpList = false; + members.add(this.self); + Loggers.CLUSTER.warn("[serverlist] self ip {} not in serverlist {}", self, members); + } + + // If the number of old and new clusters is different, the cluster information + // must have changed; if the number of clusters is the same, then compare whether + // there is a difference; if there is a difference, then the cluster node changes + // are involved and all recipients need to be notified of the node change event + + boolean hasChange = members.size() != serverList.size(); + ConcurrentSkipListMap tmpMap = new ConcurrentSkipListMap(); + Set tmpAddressInfo = new ConcurrentHashSet<>(); + for (Member member : members) { + final String address = member.getAddress(); + + if (!serverList.containsKey(address)) { + hasChange = true; + } + + // Ensure that the node is created only once + tmpMap.put(address, member); + tmpAddressInfo.add(address); + } + + Map oldList = serverList; + Set oldSet = memberAddressInfos; + + serverList = tmpMap; + memberAddressInfos = tmpAddressInfo; + + Collection finalMembers = allMembers(); + + Loggers.CLUSTER.warn("[serverlist] updated to : {}", finalMembers); + + oldList.clear(); + oldSet.clear(); + + // Persist the current cluster node information to cluster.conf + // need to put the event publication into a synchronized block to ensure + // that the event publication is sequential + if (hasChange) { + MemberUtils.syncToFile(finalMembers); + Event event = MemberChangeEvent.builder().members(finalMembers).build(); + NotifyCenter.publishEvent(event); + } + + return hasChange; + } + + public synchronized boolean memberJoin(Collection members) { + Set set = new HashSet<>(members); + set.addAll(allMembers()); + return memberChange(set); + } + + public synchronized boolean memberLeave(Collection members) { + Set set = new HashSet<>(allMembers()); + set.removeAll(members); + return memberChange(set); + } + + public boolean isUnHealth(String address) { + Member member = serverList.get(address); + if (member == null) { + return false; + } + return !NodeState.UP.equals(member.getState()); + } + + public boolean isFirstIp() { + return Objects.equals(serverList.firstKey(), this.localAddress); + } + + @Override + public void onApplicationEvent(WebServerInitializedEvent event) { + getSelf().setState(NodeState.UP); + if (!ApplicationUtils.getStandaloneMode()) { + GlobalExecutor.scheduleByCommon(this.infoReportTask, 5_000L); + } + ApplicationUtils.setPort(event.getWebServer().getPort()); + ApplicationUtils.setLocalAddress(this.localAddress); + Loggers.CLUSTER.info("This node is ready to provide external services"); + } + + @PreDestroy + public void shutdown() throws NacosException { + serverList.clear(); + memberAddressInfos.clear(); + infoReportTask.shutdown(); + LookupFactory.destroy(); + } + + public Set getMemberAddressInfos() { + return memberAddressInfos; + } + + @JustForTest + public void updateMember(Member member) { + serverList.put(member.getAddress(), member); + } + + @JustForTest + public void setMemberAddressInfos(Set memberAddressInfos) { + this.memberAddressInfos = memberAddressInfos; + } + + public Map getServerList() { + return Collections.unmodifiableMap(serverList); + } + + public boolean isInIpList() { + return isInIpList; + } + + // Synchronize the metadata information of a node + // A health check of the target node is also attached + + class MemberInfoReportTask extends Task { + + private final GenericType> reference = new GenericType>() { + }; + + private int cursor = 0; + + @Override + protected void executeBody() { + List members = ServerMemberManager.this.allMembersWithoutSelf(); + + if (members.isEmpty()) { + return; + } + + this.cursor = (this.cursor + 1) % members.size(); + Member target = members.get(cursor); + + Loggers.CLUSTER.debug("report the metadata to the node : {}", target.getAddress()); + + final String url = HttpUtils + .buildUrl(false, target.getAddress(), ApplicationUtils.getContextPath(), Commons.NACOS_CORE_CONTEXT, + "/cluster/report"); + + try { + asyncHttpClient + .post(url, Header.newInstance().addParam(Constants.NACOS_SERVER_HEADER, VersionUtils.version), + Query.EMPTY, getSelf(), reference.getType(), new Callback() { + @Override + public void onReceive(RestResult result) { + if (result.getCode() == HttpStatus.NOT_IMPLEMENTED.value() + || result.getCode() == HttpStatus.NOT_FOUND.value()) { + Loggers.CLUSTER + .warn("{} version is too low, it is recommended to upgrade the version : {}", + target, VersionUtils.version); + return; + } + if (result.ok()) { + MemberUtils.onSuccess(target); + } else { + Loggers.CLUSTER + .warn("failed to report new info to target node : {}, result : {}", + target.getAddress(), result); + MemberUtils.onFail(target); + } + } + + @Override + public void onError(Throwable throwable) { + Loggers.CLUSTER + .error("failed to report new info to target node : {}, error : {}", + target.getAddress(), + ExceptionUtil.getAllExceptionMsg(throwable)); + MemberUtils.onFail(target, throwable); + } + }); + } catch (Throwable ex) { + Loggers.CLUSTER.error("failed to report new info to target node : {}, error : {}", target.getAddress(), + ExceptionUtil.getAllExceptionMsg(ex)); + } + } + + @Override + protected void after() { + GlobalExecutor.scheduleByCommon(this, 2_000L); + } + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/Task.java b/core/src/main/java/com/alibaba/nacos/core/cluster/Task.java index 91ff68948d6..9b7ee8f3f47 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/Task.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/Task.java @@ -16,16 +16,19 @@ package com.alibaba.nacos.core.cluster; +import com.alibaba.nacos.common.utils.ExceptionUtil; import com.alibaba.nacos.core.utils.Loggers; /** + * task. + * * @author liaochuntao */ @SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule") public abstract class Task implements Runnable { - + protected volatile boolean shutdown = false; - + @Override public void run() { if (shutdown) { @@ -34,28 +37,28 @@ public void run() { try { executeBody(); } catch (Throwable t) { - Loggers.CORE.error("this task execute has error : {}", t); + Loggers.CORE.error("this task execute has error : {}", ExceptionUtil.getStackTrace(t)); } finally { if (!shutdown) { after(); } } } - + /** - * Task executive + * Task executive. */ protected abstract void executeBody(); - + /** - * after executeBody should do + * after executeBody should do. */ protected void after() { - + } - + public void shutdown() { shutdown = true; } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/AddressServerMemberLookup.java b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/AddressServerMemberLookup.java index 37ac43667ca..6028d3337b6 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/AddressServerMemberLookup.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/AddressServerMemberLookup.java @@ -38,143 +38,145 @@ import java.util.Map; /** - * Cluster member addressing mode for the address server + * Cluster member addressing mode for the address server. * * @author liaochuntao */ public class AddressServerMemberLookup extends AbstractMemberLookup { - - private final GenericType> genericType = new GenericType>() { - }; - - public String domainName; - public String addressPort; - public String addressUrl; - public String envIdUrl; - public String addressServerUrl; - private volatile boolean isAddressServerHealth = true; - private int addressServerFailCount = 0; - private int maxFailCount = 12; - private NSyncHttpClient syncHttpClient = HttpClientManager.getSyncHttpClient(); - private volatile boolean shutdown = false; - - @Override - public void start() throws NacosException { - if (start.compareAndSet(false, true)) { - this.maxFailCount = Integer.parseInt(ApplicationUtils.getProperty("maxHealthCheckFailCount", "12")); - initAddressSys(); - run(); - } - } - - private void initAddressSys() { - String envDomainName = System.getenv("address_server_domain"); - if (StringUtils.isBlank(envDomainName)) { - domainName = System.getProperty("address.server.domain", "jmenv.tbsite.net"); - } else { - domainName = envDomainName; - } - String envAddressPort = System.getenv("address_server_port"); - if (StringUtils.isBlank(envAddressPort)) { - addressPort = System.getProperty("address.server.port", "8080"); - } else { - addressPort = envAddressPort; - } - addressUrl = System.getProperty("address.server.url", - ApplicationUtils.getContextPath() + "/" + "serverlist"); - addressServerUrl = "http://" + domainName + ":" + addressPort + addressUrl; - envIdUrl = "http://" + domainName + ":" + addressPort + "/env"; - - Loggers.CORE.info("ServerListService address-server port:" + addressPort); - Loggers.CORE.info("ADDRESS_SERVER_URL:" + addressServerUrl); - } - - @SuppressWarnings("PMD.UndefineMagicConstantRule") - private void run() throws NacosException { - // With the address server, you need to perform a synchronous member node pull at startup - // Repeat three times, successfully jump out - boolean success = false; - Throwable ex = null; - int maxRetry = ApplicationUtils.getProperty("nacos.core.address-server.retry", Integer.class, 5); - for (int i = 0; i < maxRetry; i ++) { - try { - syncFromAddressUrl(); - success = true; - break; - } catch (Throwable e) { - ex = e; - Loggers.CLUSTER.error("[serverlist] exception, error : {}", ExceptionUtil.getAllExceptionMsg(ex)); - } - } - if (!success) { - throw new NacosException(NacosException.SERVER_ERROR, ex); - } - - GlobalExecutor.scheduleByCommon(new AddressServerSyncTask(), 5_000L); - } - - @Override - public void destroy() throws NacosException { - shutdown = true; - } - - @Override - public Map info() { - Map info = new HashMap<>(4); - info.put("addressServerHealth", isAddressServerHealth); - info.put("addressServerUrl", addressServerUrl); - info.put("envIdUrl", envIdUrl); - info.put("addressServerFailCount", addressServerFailCount); - return info; - } - - class AddressServerSyncTask implements Runnable { - - @Override - public void run() { - if (shutdown) { - return; - } - try { - syncFromAddressUrl(); - } - catch (Throwable ex) { - addressServerFailCount++; - if (addressServerFailCount >= maxFailCount) { - isAddressServerHealth = false; - } - Loggers.CLUSTER.error("[serverlist] exception, error : {}", ExceptionUtil.getAllExceptionMsg(ex)); - } finally { - GlobalExecutor.scheduleByCommon(this, 5_000L); - } - } - } - - private void syncFromAddressUrl() throws Exception { - RestResult result = syncHttpClient - .get(addressServerUrl, Header.EMPTY, Query.EMPTY, - genericType.getType()); - if (HttpStatus.OK.value() == result.getCode()) { - isAddressServerHealth = true; - Reader reader = new StringReader(result.getData()); - try { - afterLookup(MemberUtils.readServerConf(ApplicationUtils.analyzeClusterConf(reader))); - } - catch (Throwable e) { - Loggers.CLUSTER - .error("[serverlist] exception for analyzeClusterConf, error : {}", - ExceptionUtil.getAllExceptionMsg(e)); - } - addressServerFailCount = 0; - isAddressServerHealth = false; - } - else { - addressServerFailCount++; - if (addressServerFailCount >= maxFailCount) { - isAddressServerHealth = false; - } - Loggers.CLUSTER.error("[serverlist] failed to get serverlist, error code {}", - result.getCode()); - } - } + + private final GenericType> genericType = new GenericType>() { + }; + + public String domainName; + + public String addressPort; + + public String addressUrl; + + public String envIdUrl; + + public String addressServerUrl; + + private volatile boolean isAddressServerHealth = true; + + private int addressServerFailCount = 0; + + private int maxFailCount = 12; + + private NSyncHttpClient syncHttpClient = HttpClientManager.getSyncHttpClient(); + + private volatile boolean shutdown = false; + + @Override + public void start() throws NacosException { + if (start.compareAndSet(false, true)) { + this.maxFailCount = Integer.parseInt(ApplicationUtils.getProperty("maxHealthCheckFailCount", "12")); + initAddressSys(); + run(); + } + } + + private void initAddressSys() { + String envDomainName = System.getenv("address_server_domain"); + if (StringUtils.isBlank(envDomainName)) { + domainName = System.getProperty("address.server.domain", "jmenv.tbsite.net"); + } else { + domainName = envDomainName; + } + String envAddressPort = System.getenv("address_server_port"); + if (StringUtils.isBlank(envAddressPort)) { + addressPort = System.getProperty("address.server.port", "8080"); + } else { + addressPort = envAddressPort; + } + addressUrl = System.getProperty("address.server.url", ApplicationUtils.getContextPath() + "/" + "serverlist"); + addressServerUrl = "http://" + domainName + ":" + addressPort + addressUrl; + envIdUrl = "http://" + domainName + ":" + addressPort + "/env"; + + Loggers.CORE.info("ServerListService address-server port:" + addressPort); + Loggers.CORE.info("ADDRESS_SERVER_URL:" + addressServerUrl); + } + + @SuppressWarnings("PMD.UndefineMagicConstantRule") + private void run() throws NacosException { + // With the address server, you need to perform a synchronous member node pull at startup + // Repeat three times, successfully jump out + boolean success = false; + Throwable ex = null; + int maxRetry = ApplicationUtils.getProperty("nacos.core.address-server.retry", Integer.class, 5); + for (int i = 0; i < maxRetry; i++) { + try { + syncFromAddressUrl(); + success = true; + break; + } catch (Throwable e) { + ex = e; + Loggers.CLUSTER.error("[serverlist] exception, error : {}", ExceptionUtil.getAllExceptionMsg(ex)); + } + } + if (!success) { + throw new NacosException(NacosException.SERVER_ERROR, ex); + } + + GlobalExecutor.scheduleByCommon(new AddressServerSyncTask(), 5_000L); + } + + @Override + public void destroy() throws NacosException { + shutdown = true; + } + + @Override + public Map info() { + Map info = new HashMap<>(4); + info.put("addressServerHealth", isAddressServerHealth); + info.put("addressServerUrl", addressServerUrl); + info.put("envIdUrl", envIdUrl); + info.put("addressServerFailCount", addressServerFailCount); + return info; + } + + private void syncFromAddressUrl() throws Exception { + RestResult result = syncHttpClient + .get(addressServerUrl, Header.EMPTY, Query.EMPTY, genericType.getType()); + if (HttpStatus.OK.value() == result.getCode()) { + isAddressServerHealth = true; + Reader reader = new StringReader(result.getData()); + try { + afterLookup(MemberUtils.readServerConf(ApplicationUtils.analyzeClusterConf(reader))); + } catch (Throwable e) { + Loggers.CLUSTER.error("[serverlist] exception for analyzeClusterConf, error : {}", + ExceptionUtil.getAllExceptionMsg(e)); + } + addressServerFailCount = 0; + isAddressServerHealth = false; + } else { + addressServerFailCount++; + if (addressServerFailCount >= maxFailCount) { + isAddressServerHealth = false; + } + Loggers.CLUSTER.error("[serverlist] failed to get serverlist, error code {}", result.getCode()); + } + } + + class AddressServerSyncTask implements Runnable { + + @Override + public void run() { + if (shutdown) { + return; + } + try { + syncFromAddressUrl(); + } catch (Throwable ex) { + addressServerFailCount++; + if (addressServerFailCount >= maxFailCount) { + isAddressServerHealth = false; + } + Loggers.CLUSTER.error("[serverlist] exception, error : {}", ExceptionUtil.getAllExceptionMsg(ex)); + } finally { + GlobalExecutor.scheduleByCommon(this, 5_000L); + } + } + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/FileConfigMemberLookup.java b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/FileConfigMemberLookup.java index 8ac0dbbe68c..f51294db085 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/FileConfigMemberLookup.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/FileConfigMemberLookup.java @@ -17,12 +17,12 @@ package com.alibaba.nacos.core.cluster.lookup; import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.core.file.FileChangeEvent; -import com.alibaba.nacos.core.file.FileWatcher; -import com.alibaba.nacos.core.file.WatchFileCenter; import com.alibaba.nacos.core.cluster.AbstractMemberLookup; import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.MemberUtils; +import com.alibaba.nacos.core.file.FileChangeEvent; +import com.alibaba.nacos.core.file.FileWatcher; +import com.alibaba.nacos.core.file.WatchFileCenter; import com.alibaba.nacos.core.utils.ApplicationUtils; import com.alibaba.nacos.core.utils.Loggers; import org.apache.commons.lang3.StringUtils; @@ -32,58 +32,54 @@ import java.util.List; /** - * Cluster.conf file managed cluster member node addressing pattern + * Cluster.conf file managed cluster member node addressing pattern. * * @author liaochuntao */ public class FileConfigMemberLookup extends AbstractMemberLookup { - - private FileWatcher watcher = new FileWatcher() { - @Override - public void onChange(FileChangeEvent event) { - readClusterConfFromDisk(); - } - - @Override - public boolean interest(String context) { - return StringUtils.contains(context, "cluster.conf"); - } - }; - - @Override - public void start() throws NacosException { - if (start.compareAndSet(false, true)) { - readClusterConfFromDisk(); - - // Use the inotify mechanism to monitor file changes and automatically - // trigger the reading of cluster.conf - try { - WatchFileCenter.registerWatcher(ApplicationUtils.getConfFilePath(), watcher); - } - catch (Throwable e) { - Loggers.CLUSTER - .error("An exception occurred in the launch file monitor : {}", e.getMessage()); - } - } - } - - @Override - public void destroy() throws NacosException { - WatchFileCenter.deregisterWatcher(ApplicationUtils.getConfFilePath(), watcher); - } - - private void readClusterConfFromDisk() { - Collection tmpMembers = new ArrayList<>(); - try { - List tmp = ApplicationUtils.readClusterConf(); - tmpMembers = MemberUtils.readServerConf(tmp); - } - catch (Throwable e) { - Loggers.CLUSTER - .error("nacos-XXXX [serverlist] failed to get serverlist from disk!, error : {}", - e.getMessage()); - } - - afterLookup(tmpMembers); - } + + private FileWatcher watcher = new FileWatcher() { + @Override + public void onChange(FileChangeEvent event) { + readClusterConfFromDisk(); + } + + @Override + public boolean interest(String context) { + return StringUtils.contains(context, "cluster.conf"); + } + }; + + @Override + public void start() throws NacosException { + if (start.compareAndSet(false, true)) { + readClusterConfFromDisk(); + + // Use the inotify mechanism to monitor file changes and automatically + // trigger the reading of cluster.conf + try { + WatchFileCenter.registerWatcher(ApplicationUtils.getConfFilePath(), watcher); + } catch (Throwable e) { + Loggers.CLUSTER.error("An exception occurred in the launch file monitor : {}", e.getMessage()); + } + } + } + + @Override + public void destroy() throws NacosException { + WatchFileCenter.deregisterWatcher(ApplicationUtils.getConfFilePath(), watcher); + } + + private void readClusterConfFromDisk() { + Collection tmpMembers = new ArrayList<>(); + try { + List tmp = ApplicationUtils.readClusterConf(); + tmpMembers = MemberUtils.readServerConf(tmp); + } catch (Throwable e) { + Loggers.CLUSTER + .error("nacos-XXXX [serverlist] failed to get serverlist from disk!, error : {}", e.getMessage()); + } + + afterLookup(tmpMembers); + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/LookupFactory.java b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/LookupFactory.java index 785dd945cca..710ee598bf3 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/LookupFactory.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/LookupFactory.java @@ -28,136 +28,154 @@ import java.util.Objects; /** + * An addressing pattern factory, responsible for the creation of all addressing patterns. + * * @author liaochuntao */ public final class LookupFactory { - - static final String LOOKUP_MODE_TYPE = "nacos.core.member.lookup.type"; - - static MemberLookup LOOK_UP = null; - - static LookupType currentLookupType = null; - - public enum LookupType { - - /** - * File addressing mode - */ - FILE_CONFIG(1, "file"), - - /** - * Address server addressing mode - */ - ADDRESS_SERVER(2, "address-server"), - - ; - - private final int code; - private final String name; - - LookupType(int code, String name) { - this.code = code; - this.name = name; - } - - public int getCode() { - return code; - } - - public String getName() { - return name; - } - - @Override - public String toString() { - return name; - } - - public static LookupType sourceOf(String name) { - for (LookupType type : values()) { - if (Objects.equals(type.name, name)) { - return type; - } - } - return null; - } - } - - public static MemberLookup createLookUp(ServerMemberManager memberManager) - throws NacosException { - if (!ApplicationUtils.getStandaloneMode()) { - String lookupType = ApplicationUtils.getProperty(LOOKUP_MODE_TYPE); - LookupType type = chooseLookup(lookupType); - LOOK_UP = find(type); - currentLookupType = type; - } - else { - LOOK_UP = new StandaloneMemberLookup(); - } - LOOK_UP.injectMemberManager(memberManager); - Loggers.CLUSTER.info("Current addressing mode selection : {}", - LOOK_UP.getClass().getSimpleName()); - return LOOK_UP; - } - - public static MemberLookup switchLookup(String name, - ServerMemberManager memberManager) throws NacosException { - LookupType lookupType = LookupType.sourceOf(name); - - if (Objects.isNull(lookupType)) { - throw new IllegalArgumentException( - "The addressing mode exists : " + name + ", just support : [" + Arrays - .toString(LookupType.values()) + "]"); - } - - if (Objects.equals(currentLookupType, lookupType)) { - return LOOK_UP; - } - MemberLookup newLookup = find(lookupType); - currentLookupType = lookupType; - if (Objects.nonNull(LOOK_UP)) { - LOOK_UP.destroy(); - } - LOOK_UP = newLookup; - LOOK_UP.injectMemberManager(memberManager); - Loggers.CLUSTER.info("Current addressing mode selection : {}", - LOOK_UP.getClass().getSimpleName()); - return LOOK_UP; - } - - private static MemberLookup find(LookupType type) { - if (LookupType.FILE_CONFIG.equals(type)) { - LOOK_UP = new FileConfigMemberLookup(); - return LOOK_UP; - } - if (LookupType.ADDRESS_SERVER.equals(type)) { - LOOK_UP = new AddressServerMemberLookup(); - return LOOK_UP; - } - // unpossible to run here - throw new IllegalArgumentException(); - } - - private static LookupType chooseLookup(String lookupType) { - if (StringUtils.isNotBlank(lookupType)) { - LookupType type = LookupType.sourceOf(lookupType); - if (Objects.nonNull(type)) { - return type; - } - } - File file = new File(ApplicationUtils.getClusterConfFilePath()); - if (file.exists() || StringUtils.isNotBlank(ApplicationUtils.getMemberList())) { - return LookupType.FILE_CONFIG; - } - return LookupType.ADDRESS_SERVER; - } - - public static MemberLookup getLookUp() { - return LOOK_UP; - } - - public static void destroy() throws NacosException { - Objects.requireNonNull(LOOK_UP).destroy(); - } - + + private static final String LOOKUP_MODE_TYPE = "nacos.core.member.lookup.type"; + + @SuppressWarnings("checkstyle:StaticVariableName") + private static MemberLookup LOOK_UP = null; + + private static LookupType currentLookupType = null; + + /** + * Create the target addressing pattern. + * + * @param memberManager {@link ServerMemberManager} + * @return {@link MemberLookup} + * @throws NacosException NacosException + */ + public static MemberLookup createLookUp(ServerMemberManager memberManager) throws NacosException { + if (!ApplicationUtils.getStandaloneMode()) { + String lookupType = ApplicationUtils.getProperty(LOOKUP_MODE_TYPE); + LookupType type = chooseLookup(lookupType); + LOOK_UP = find(type); + currentLookupType = type; + } else { + LOOK_UP = new StandaloneMemberLookup(); + } + LOOK_UP.injectMemberManager(memberManager); + Loggers.CLUSTER.info("Current addressing mode selection : {}", LOOK_UP.getClass().getSimpleName()); + return LOOK_UP; + } + + /** + * Switch to target addressing mode. + * + * @param name target member-lookup name + * @param memberManager {@link ServerMemberManager} + * @return {@link MemberLookup} + * @throws NacosException {@link NacosException} + */ + public static MemberLookup switchLookup(String name, ServerMemberManager memberManager) throws NacosException { + LookupType lookupType = LookupType.sourceOf(name); + + if (Objects.isNull(lookupType)) { + throw new IllegalArgumentException( + "The addressing mode exists : " + name + ", just support : [" + Arrays.toString(LookupType.values()) + + "]"); + } + + if (Objects.equals(currentLookupType, lookupType)) { + return LOOK_UP; + } + MemberLookup newLookup = find(lookupType); + currentLookupType = lookupType; + if (Objects.nonNull(LOOK_UP)) { + LOOK_UP.destroy(); + } + LOOK_UP = newLookup; + LOOK_UP.injectMemberManager(memberManager); + Loggers.CLUSTER.info("Current addressing mode selection : {}", LOOK_UP.getClass().getSimpleName()); + return LOOK_UP; + } + + private static MemberLookup find(LookupType type) { + if (LookupType.FILE_CONFIG.equals(type)) { + LOOK_UP = new FileConfigMemberLookup(); + return LOOK_UP; + } + if (LookupType.ADDRESS_SERVER.equals(type)) { + LOOK_UP = new AddressServerMemberLookup(); + return LOOK_UP; + } + // unpossible to run here + throw new IllegalArgumentException(); + } + + private static LookupType chooseLookup(String lookupType) { + if (StringUtils.isNotBlank(lookupType)) { + LookupType type = LookupType.sourceOf(lookupType); + if (Objects.nonNull(type)) { + return type; + } + } + File file = new File(ApplicationUtils.getClusterConfFilePath()); + if (file.exists() || StringUtils.isNotBlank(ApplicationUtils.getMemberList())) { + return LookupType.FILE_CONFIG; + } + return LookupType.ADDRESS_SERVER; + } + + public static MemberLookup getLookUp() { + return LOOK_UP; + } + + public static void destroy() throws NacosException { + Objects.requireNonNull(LOOK_UP).destroy(); + } + + public enum LookupType { + + /** + * File addressing mode. + */ + FILE_CONFIG(1, "file"), + + /** + * Address server addressing mode. + */ + ADDRESS_SERVER(2, "address-server"); + + private final int code; + + private final String name; + + LookupType(int code, String name) { + this.code = code; + this.name = name; + } + + /** + * find one {@link LookupType} by name, if not found, return null. + * + * @param name name + * @return {@link LookupType} + */ + public static LookupType sourceOf(String name) { + for (LookupType type : values()) { + if (Objects.equals(type.name, name)) { + return type; + } + } + return null; + } + + public int getCode() { + return code; + } + + public String getName() { + return name; + } + + @Override + public String toString() { + return name; + } + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/StandaloneMemberLookup.java b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/StandaloneMemberLookup.java index 222a4d555bd..65ffecab6b2 100644 --- a/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/StandaloneMemberLookup.java +++ b/core/src/main/java/com/alibaba/nacos/core/cluster/lookup/StandaloneMemberLookup.java @@ -24,17 +24,17 @@ import java.util.Collections; /** - * Member node addressing mode in stand-alone mode + * Member node addressing mode in stand-alone mode. * * @author liaochuntao */ public class StandaloneMemberLookup extends AbstractMemberLookup { - - @Override - public void start() { - if (start.compareAndSet(false, true)) { - String url = InetUtils.getSelfIp() + ":" + ApplicationUtils.getPort(); - afterLookup(MemberUtils.readServerConf(Collections.singletonList(url))); - } - } + + @Override + public void start() { + if (start.compareAndSet(false, true)) { + String url = InetUtils.getSelfIp() + ":" + ApplicationUtils.getPort(); + afterLookup(MemberUtils.readServerConf(Collections.singletonList(url))); + } + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/code/ControllerMethodsCache.java b/core/src/main/java/com/alibaba/nacos/core/code/ControllerMethodsCache.java index 7c4ea9d7741..9433878e599 100644 --- a/core/src/main/java/com/alibaba/nacos/core/code/ControllerMethodsCache.java +++ b/core/src/main/java/com/alibaba/nacos/core/code/ControllerMethodsCache.java @@ -13,14 +13,20 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.nacos.core.code; +package com.alibaba.nacos.core.code; import org.apache.commons.lang3.ArrayUtils; import org.reflections.Reflections; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; -import org.springframework.web.bind.annotation.*; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PatchMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; import java.lang.reflect.Method; import java.util.Set; @@ -28,44 +34,58 @@ import java.util.concurrent.ConcurrentMap; /** - * Method cache + * Method cache. * * @author nkorange * @since 1.2.0 */ @Component public class ControllerMethodsCache { - + @Value("${server.servlet.contextPath:/nacos}") private String contextPath; - - private ConcurrentMap methods = new - ConcurrentHashMap<>(); - + + private ConcurrentMap methods = new ConcurrentHashMap<>(); + public ConcurrentMap getMethods() { return methods; } - + public Method getMethod(String httpMethod, String path) { String key = httpMethod + "-->" + path.replace(contextPath, ""); return methods.get(key); } - + + /** + * find target method from this package. + * + * @param packageName package name + */ public void initClassMethod(String packageName) { Reflections reflections = new Reflections(packageName); Set> classesList = reflections.getTypesAnnotatedWith(RequestMapping.class); - + for (Class clazz : classesList) { initClassMethod(clazz); } } - + + /** + * find target method from class list. + * + * @param classesList class list + */ public void initClassMethod(Set> classesList) { for (Class clazz : classesList) { initClassMethod(clazz); } } - + + /** + * find target method from target class. + * + * @param clazz {@link Class} + */ public void initClassMethod(Class clazz) { RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class); for (String classPath : requestMapping.value()) { @@ -86,37 +106,37 @@ public void initClassMethod(Class clazz) { } } } - + private void parseSubAnnotations(Method method, String classPath) { - + final GetMapping getMapping = method.getAnnotation(GetMapping.class); final PostMapping postMapping = method.getAnnotation(PostMapping.class); final PutMapping putMapping = method.getAnnotation(PutMapping.class); final DeleteMapping deleteMapping = method.getAnnotation(DeleteMapping.class); final PatchMapping patchMapping = method.getAnnotation(PatchMapping.class); - + if (getMapping != null) { put(RequestMethod.GET, classPath, getMapping.value(), method); } - + if (postMapping != null) { put(RequestMethod.POST, classPath, postMapping.value(), method); } - + if (putMapping != null) { put(RequestMethod.PUT, classPath, putMapping.value(), method); } - + if (deleteMapping != null) { put(RequestMethod.DELETE, classPath, deleteMapping.value(), method); } - + if (patchMapping != null) { put(RequestMethod.PATCH, classPath, patchMapping.value(), method); } - + } - + private void put(RequestMethod requestMethod, String classPath, String[] requestPaths, Method method) { if (ArrayUtils.isEmpty(requestPaths)) { methods.put(requestMethod.name() + "-->" + classPath, method); diff --git a/core/src/main/java/com/alibaba/nacos/core/code/LoggingSpringApplicationRunListener.java b/core/src/main/java/com/alibaba/nacos/core/code/LoggingSpringApplicationRunListener.java index 6ab23c6494d..37b052f87ed 100644 --- a/core/src/main/java/com/alibaba/nacos/core/code/LoggingSpringApplicationRunListener.java +++ b/core/src/main/java/com/alibaba/nacos/core/code/LoggingSpringApplicationRunListener.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.code; import com.alibaba.nacos.core.utils.ApplicationUtils; @@ -29,70 +30,70 @@ import static org.springframework.core.io.ResourceLoader.CLASSPATH_URL_PREFIX; /** - * Logging {@link SpringApplicationRunListener} before {@link EventPublishingRunListener} execution + * Logging {@link SpringApplicationRunListener} before {@link EventPublishingRunListener} execution. * * @author Mercy * @since 0.2.2 */ public class LoggingSpringApplicationRunListener implements SpringApplicationRunListener, Ordered { - + private static final String DEFAULT_NACOS_LOGBACK_LOCATION = CLASSPATH_URL_PREFIX + "META-INF/logback/nacos.xml"; - - private static final Logger logger = LoggerFactory.getLogger(LoggingSpringApplicationRunListener.class); - + + private static final Logger LOGGER = LoggerFactory.getLogger(LoggingSpringApplicationRunListener.class); + private final SpringApplication application; - + private final String[] args; - + public LoggingSpringApplicationRunListener(SpringApplication application, String[] args) { this.application = application; this.args = args; } - + @Override public void starting() { } - + @Override public void environmentPrepared(ConfigurableEnvironment environment) { ApplicationUtils.injectEnvironment(environment); if (!environment.containsProperty(CONFIG_PROPERTY)) { System.setProperty(CONFIG_PROPERTY, DEFAULT_NACOS_LOGBACK_LOCATION); - if (logger.isInfoEnabled()) { - logger.info("There is no property named \"{}\" in Spring Boot Environment, " + - "and whose value is {} will be set into System's Properties", CONFIG_PROPERTY, + if (LOGGER.isInfoEnabled()) { + LOGGER.info("There is no property named \"{}\" in Spring Boot Environment, " + + "and whose value is {} will be set into System's Properties", CONFIG_PROPERTY, DEFAULT_NACOS_LOGBACK_LOCATION); } } } - + @Override public void contextPrepared(ConfigurableApplicationContext context) { - + } - + @Override public void contextLoaded(ConfigurableApplicationContext context) { - + } - + @Override public void started(ConfigurableApplicationContext context) { - + } - + @Override public void running(ConfigurableApplicationContext context) { - + } - + @Override public void failed(ConfigurableApplicationContext context, Throwable exception) { - + } - + /** - * Before {@link EventPublishingRunListener} + * Before {@link EventPublishingRunListener}. * * @return HIGHEST_PRECEDENCE */ diff --git a/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java b/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java index 88efc13e1be..10d7338947a 100644 --- a/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java +++ b/core/src/main/java/com/alibaba/nacos/core/code/StandaloneProfileApplicationListener.java @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.nacos.core.code; -import java.util.Arrays; +package com.alibaba.nacos.core.code; import com.alibaba.nacos.core.utils.ApplicationUtils; import org.slf4j.Logger; @@ -26,40 +25,40 @@ import org.springframework.core.PriorityOrdered; import org.springframework.core.env.ConfigurableEnvironment; +import java.util.Arrays; + import static com.alibaba.nacos.core.utils.Constants.STANDALONE_MODE_PROPERTY_NAME; import static com.alibaba.nacos.core.utils.Constants.STANDALONE_SPRING_PROFILE; /** - * Standalone {@link Profile} {@link ApplicationListener} for {@link ApplicationEnvironmentPreparedEvent} + * Standalone {@link Profile} {@link ApplicationListener} for {@link ApplicationEnvironmentPreparedEvent}. * * @author Mercy * @see ConfigurableEnvironment#addActiveProfile(String) * @since 0.2.2 */ -public class StandaloneProfileApplicationListener implements ApplicationListener, - PriorityOrdered { - - private static final Logger logger = LoggerFactory.getLogger(StandaloneProfileApplicationListener.class); - +public class StandaloneProfileApplicationListener + implements ApplicationListener, PriorityOrdered { + + private static final Logger LOGGER = LoggerFactory.getLogger(StandaloneProfileApplicationListener.class); + @Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { - + ConfigurableEnvironment environment = event.getEnvironment(); ApplicationUtils.injectEnvironment(environment); - + if (environment.getProperty(STANDALONE_MODE_PROPERTY_NAME, boolean.class, false)) { environment.addActiveProfile(STANDALONE_SPRING_PROFILE); } - - if (logger.isInfoEnabled()) { - logger.info("Spring Environment's active profiles : {} in standalone mode : {}", - Arrays.asList(environment.getActiveProfiles()), - ApplicationUtils.getStandaloneMode() - ); + + if (LOGGER.isInfoEnabled()) { + LOGGER.info("Spring Environment's active profiles : {} in standalone mode : {}", + Arrays.asList(environment.getActiveProfiles()), ApplicationUtils.getStandaloneMode()); } - + } - + @Override public int getOrder() { return HIGHEST_PRECEDENCE; diff --git a/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java b/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java index c9208287495..19a30dd73e8 100644 --- a/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java +++ b/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java @@ -13,16 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.code; import com.alibaba.nacos.common.executor.ExecutorFactory; import com.alibaba.nacos.common.executor.NameThreadFactory; import com.alibaba.nacos.common.executor.ThreadPoolManager; -import com.alibaba.nacos.core.file.WatchFileCenter; import com.alibaba.nacos.common.http.HttpClientManager; -import com.alibaba.nacos.core.utils.DiskUtils; +import com.alibaba.nacos.core.file.WatchFileCenter; import com.alibaba.nacos.core.notify.NotifyCenter; import com.alibaba.nacos.core.utils.ApplicationUtils; +import com.alibaba.nacos.core.utils.DiskUtils; import com.alibaba.nacos.core.utils.InetUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -41,185 +42,170 @@ import java.util.concurrent.TimeUnit; /** - * Logging starting message {@link SpringApplicationRunListener} before {@link EventPublishingRunListener} execution + * Logging starting message {@link SpringApplicationRunListener} before {@link EventPublishingRunListener} execution. * * @author hxy1991 * @since 0.5.0 */ -public class StartingSpringApplicationRunListener - implements SpringApplicationRunListener, Ordered { - - private static final Logger LOGGER = LoggerFactory - .getLogger(StartingSpringApplicationRunListener.class); - - private static final String MODE_PROPERTY_KEY_STAND_MODE = "nacos.mode"; - - private static final String MODE_PROPERTY_KEY_FUNCTION_MODE = "nacos.function.mode"; - - private static final String LOCAL_IP_PROPERTY_KEY = "nacos.local.ip"; - - private ScheduledExecutorService scheduledExecutorService; - - private volatile boolean starting; - - public StartingSpringApplicationRunListener(SpringApplication application, - String[] args) { - - } - - @Override - public void starting() { - starting = true; - } - - @Override - public void environmentPrepared(ConfigurableEnvironment environment) { - ApplicationUtils.injectEnvironment(environment); - if (ApplicationUtils.getStandaloneMode()) { - System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "stand alone"); - } - else { - System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "cluster"); - } - if (ApplicationUtils.getFunctionMode() == null) { - System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, "All"); - } - else if (ApplicationUtils.FUNCTION_MODE_CONFIG - .equals(ApplicationUtils.getFunctionMode())) { - System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, - ApplicationUtils.FUNCTION_MODE_CONFIG); - } - else if (ApplicationUtils.FUNCTION_MODE_NAMING - .equals(ApplicationUtils.getFunctionMode())) { - System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, - ApplicationUtils.FUNCTION_MODE_NAMING); - } - - System.setProperty(LOCAL_IP_PROPERTY_KEY, InetUtils.getSelfIp()); - } - - @Override - public void contextPrepared(ConfigurableApplicationContext context) { - logClusterConf(); - logStarting(); - } - - @Override - public void contextLoaded(ConfigurableApplicationContext context) { - - } - - @Override - public void started(ConfigurableApplicationContext context) { - starting = false; - ConfigurableEnvironment env = context.getEnvironment(); - - closeExecutor(); - - logFilePath(); - - // External data sources are used by default in cluster mode - boolean useExternalStorage = ("mysql".equalsIgnoreCase(env.getProperty("spring.datasource.platform", ""))); - - // must initialize after setUseExternalDB - // This value is true in stand-alone mode and false in cluster mode - // If this value is set to true in cluster mode, nacos's distributed storage engine is turned on - // default value is depend on ${nacos.standalone} - - if (!useExternalStorage) { - boolean embeddedStorage = ApplicationUtils.getStandaloneMode() || Boolean.getBoolean("embeddedStorage"); - // If the embedded data source storage is not turned on, it is automatically - // upgraded to the external data source storage, as before - if (!embeddedStorage) { - useExternalStorage = true; - } - } - - LOGGER.info("Nacos started successfully in {} mode. use {} storage", - System.getProperty(MODE_PROPERTY_KEY_STAND_MODE), useExternalStorage ? "external" : "embedded"); - } - - @Override - public void running(ConfigurableApplicationContext context) { - - } - - @Override - public void failed(ConfigurableApplicationContext context, Throwable exception) { - starting = false; - - logFilePath(); - - LOGGER.error("Startup errors : {}", exception); - - HttpClientManager.shutdown(); - ThreadPoolManager.shutdown(); - WatchFileCenter.shutdown(); - NotifyCenter.shutdown(); - - closeExecutor(); - - context.close(); - - LOGGER.error("Nacos failed to start, please see {} for more details.", - Paths.get(ApplicationUtils.getNacosHome(), "logs/nacos.log")); - } - - /** - * Before {@link EventPublishingRunListener} - * - * @return HIGHEST_PRECEDENCE - */ - @Override - public int getOrder() { - return HIGHEST_PRECEDENCE; - } - - private void logClusterConf() { - if (!ApplicationUtils.getStandaloneMode()) { - try { - List clusterConf = ApplicationUtils.readClusterConf(); - LOGGER.info("The server IP list of Nacos is {}", clusterConf); - } - catch (IOException e) { - LOGGER.error("read cluster conf fail", e); - } - } - } - - private void logFilePath() { - String[] dirNames = new String[] { "logs", "conf", "data" }; - for (String dirName : dirNames) { - LOGGER.info("Nacos Log files: {}", - Paths.get(ApplicationUtils.getNacosHome(), dirName).toString()); - try { - DiskUtils.forceMkdir(new File( - Paths.get(ApplicationUtils.getNacosHome(), dirName).toUri())); - } - catch (Exception e) { - throw new RuntimeException(e); - } - } - } - - private void closeExecutor() { - if (scheduledExecutorService != null) { - scheduledExecutorService.shutdownNow(); - } - } - - private void logStarting() { - if (!ApplicationUtils.getStandaloneMode()) { - +public class StartingSpringApplicationRunListener implements SpringApplicationRunListener, Ordered { + + private static final Logger LOGGER = LoggerFactory.getLogger(StartingSpringApplicationRunListener.class); + + private static final String MODE_PROPERTY_KEY_STAND_MODE = "nacos.mode"; + + private static final String MODE_PROPERTY_KEY_FUNCTION_MODE = "nacos.function.mode"; + + private static final String LOCAL_IP_PROPERTY_KEY = "nacos.local.ip"; + + private ScheduledExecutorService scheduledExecutorService; + + private volatile boolean starting; + + public StartingSpringApplicationRunListener(SpringApplication application, String[] args) { + + } + + @Override + public void starting() { + starting = true; + } + + @Override + public void environmentPrepared(ConfigurableEnvironment environment) { + ApplicationUtils.injectEnvironment(environment); + if (ApplicationUtils.getStandaloneMode()) { + System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "stand alone"); + } else { + System.setProperty(MODE_PROPERTY_KEY_STAND_MODE, "cluster"); + } + if (ApplicationUtils.getFunctionMode() == null) { + System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, "All"); + } else if (ApplicationUtils.FUNCTION_MODE_CONFIG.equals(ApplicationUtils.getFunctionMode())) { + System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, ApplicationUtils.FUNCTION_MODE_CONFIG); + } else if (ApplicationUtils.FUNCTION_MODE_NAMING.equals(ApplicationUtils.getFunctionMode())) { + System.setProperty(MODE_PROPERTY_KEY_FUNCTION_MODE, ApplicationUtils.FUNCTION_MODE_NAMING); + } + + System.setProperty(LOCAL_IP_PROPERTY_KEY, InetUtils.getSelfIp()); + } + + @Override + public void contextPrepared(ConfigurableApplicationContext context) { + logClusterConf(); + logStarting(); + } + + @Override + public void contextLoaded(ConfigurableApplicationContext context) { + + } + + @Override + public void started(ConfigurableApplicationContext context) { + starting = false; + ConfigurableEnvironment env = context.getEnvironment(); + + closeExecutor(); + + logFilePath(); + + // External data sources are used by default in cluster mode + boolean useExternalStorage = ("mysql".equalsIgnoreCase(env.getProperty("spring.datasource.platform", ""))); + + // must initialize after setUseExternalDB + // This value is true in stand-alone mode and false in cluster mode + // If this value is set to true in cluster mode, nacos's distributed storage engine is turned on + // default value is depend on ${nacos.standalone} + + if (!useExternalStorage) { + boolean embeddedStorage = ApplicationUtils.getStandaloneMode() || Boolean.getBoolean("embeddedStorage"); + // If the embedded data source storage is not turned on, it is automatically + // upgraded to the external data source storage, as before + if (!embeddedStorage) { + useExternalStorage = true; + } + } + + LOGGER.info("Nacos started successfully in {} mode. use {} storage", + System.getProperty(MODE_PROPERTY_KEY_STAND_MODE), useExternalStorage ? "external" : "embedded"); + } + + @Override + public void running(ConfigurableApplicationContext context) { + + } + + @Override + public void failed(ConfigurableApplicationContext context, Throwable exception) { + starting = false; + + logFilePath(); + + LOGGER.error("Startup errors : {}", exception); + + HttpClientManager.shutdown(); + ThreadPoolManager.shutdown(); + WatchFileCenter.shutdown(); + NotifyCenter.shutdown(); + + closeExecutor(); + + context.close(); + + LOGGER.error("Nacos failed to start, please see {} for more details.", + Paths.get(ApplicationUtils.getNacosHome(), "logs/nacos.log")); + } + + /** + * Before {@link EventPublishingRunListener}. + * + * @return HIGHEST_PRECEDENCE + */ + @Override + public int getOrder() { + return HIGHEST_PRECEDENCE; + } + + private void logClusterConf() { + if (!ApplicationUtils.getStandaloneMode()) { + try { + List clusterConf = ApplicationUtils.readClusterConf(); + LOGGER.info("The server IP list of Nacos is {}", clusterConf); + } catch (IOException e) { + LOGGER.error("read cluster conf fail", e); + } + } + } + + private void logFilePath() { + String[] dirNames = new String[] {"logs", "conf", "data"}; + for (String dirName : dirNames) { + LOGGER.info("Nacos Log files: {}", Paths.get(ApplicationUtils.getNacosHome(), dirName).toString()); + try { + DiskUtils.forceMkdir(new File(Paths.get(ApplicationUtils.getNacosHome(), dirName).toUri())); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + } + + private void closeExecutor() { + if (scheduledExecutorService != null) { + scheduledExecutorService.shutdownNow(); + } + } + + private void logStarting() { + if (!ApplicationUtils.getStandaloneMode()) { + scheduledExecutorService = ExecutorFactory - .newSingleScheduledExecutorService( - new NameThreadFactory("com.alibaba.nacos.core.nacos-starting")); - - scheduledExecutorService.scheduleWithFixedDelay(() -> { - if (starting) { - LOGGER.info("Nacos is starting..."); - } - }, 1, 1, TimeUnit.SECONDS); - } - } -} + .newSingleScheduledExecutorService(new NameThreadFactory("com.alibaba.nacos.core.nacos-starting")); + + scheduledExecutorService.scheduleWithFixedDelay(() -> { + if (starting) { + LOGGER.info("Nacos is starting..."); + } + }, 1, 1, TimeUnit.SECONDS); + } + } +} \ No newline at end of file diff --git a/core/src/main/java/com/alibaba/nacos/core/controller/CoreOpsController.java b/core/src/main/java/com/alibaba/nacos/core/controller/CoreOpsController.java index d5a368d2497..b6450c78c78 100644 --- a/core/src/main/java/com/alibaba/nacos/core/controller/CoreOpsController.java +++ b/core/src/main/java/com/alibaba/nacos/core/controller/CoreOpsController.java @@ -17,10 +17,10 @@ package com.alibaba.nacos.core.controller; import com.alibaba.nacos.common.model.RestResult; -import com.alibaba.nacos.core.distributed.ProtocolManager; -import com.alibaba.nacos.core.utils.Commons; import com.alibaba.nacos.common.model.RestResultUtils; +import com.alibaba.nacos.core.distributed.ProtocolManager; import com.alibaba.nacos.core.distributed.id.IdGeneratorManager; +import com.alibaba.nacos.core.utils.Commons; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; @@ -31,40 +31,45 @@ import java.util.Map; /** + * Kernel modules operate and maintain HTTP interfaces. + * * @author liaochuntao */ @RestController @RequestMapping(Commons.NACOS_CORE_CONTEXT + "/ops") public class CoreOpsController { - - private final ProtocolManager protocolManager; - private final IdGeneratorManager idGeneratorManager; - - public CoreOpsController(ProtocolManager protocolManager, - IdGeneratorManager idGeneratorManager) { - this.protocolManager = protocolManager; - this.idGeneratorManager = idGeneratorManager; - } - - // Temporarily overpassed the raft operations interface - // { - // "groupId": "xxx", - // "command": "transferLeader or doSnapshot or resetRaftCluster or removePeer" - // "value": "ip:{raft_port}" - // } - - @PostMapping(value = "/raft") - public RestResult raftOps(@RequestBody Map commands) { - return protocolManager.getCpProtocol().execute(commands); - } - - @GetMapping(value = "/idInfo") - public RestResult>> idInfo() { - Map> info = new HashMap<>(10); - idGeneratorManager.getGeneratorMap() - .forEach( - (resource, idGenerator) -> info.put(resource, idGenerator.info())); - return RestResultUtils.success(info); - } - + + private final ProtocolManager protocolManager; + + private final IdGeneratorManager idGeneratorManager; + + public CoreOpsController(ProtocolManager protocolManager, IdGeneratorManager idGeneratorManager) { + this.protocolManager = protocolManager; + this.idGeneratorManager = idGeneratorManager; + } + + // Temporarily overpassed the raft operations interface + // { + // "groupId": "xxx", + // "command": "transferLeader or doSnapshot or resetRaftCluster or removePeer" + // "value": "ip:{raft_port}" + // } + + @PostMapping(value = "/raft") + public RestResult raftOps(@RequestBody Map commands) { + return protocolManager.getCpProtocol().execute(commands); + } + + /** + * Gets the current health of the ID generator. + * + * @return {@link RestResult} + */ + @GetMapping(value = "/idInfo") + public RestResult>> idInfo() { + Map> info = new HashMap<>(10); + idGeneratorManager.getGeneratorMap().forEach((resource, idGenerator) -> info.put(resource, idGenerator.info())); + return RestResultUtils.success(info); + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java b/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java index e43b22d4a75..16c810195ea 100644 --- a/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java +++ b/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java @@ -47,145 +47,158 @@ import java.util.concurrent.TimeUnit; /** + * Cluster communication interface. + * * @author liaochuntao */ @RestController @RequestMapping(Commons.NACOS_CORE_CONTEXT + "/cluster") public class NacosClusterController { - - private final ServerMemberManager memberManager; - - public NacosClusterController(ServerMemberManager memberManager) { - this.memberManager = memberManager; - } - - @GetMapping(value = "/self") - public RestResult self() { - return RestResultUtils.success(memberManager.getSelf()); - } - - @GetMapping(value = "/nodes") - public RestResult> listNodes( - @RequestParam(value = "keyword", required = false) String ipKeyWord) { - Collection members = memberManager.allMembers(); - Collection result = new ArrayList<>(); - - members.stream().sorted().forEach(member -> { - if (StringUtils.isBlank(ipKeyWord)) { - result.add(member); - return; - } - final String address = member.getAddress(); - if (StringUtils.equals(address, ipKeyWord) || StringUtils - .startsWith(address, ipKeyWord)) { - result.add(member); - } - }); - - return RestResultUtils.success(result); - } - - // The client can get all the nacos node information in the current - // cluster according to this interface - - @GetMapping(value = "/simple/nodes") - public RestResult> listSimpleNodes() { - return RestResultUtils.success(memberManager.getMemberAddressInfos()); - } - - @GetMapping("/health") - public RestResult getHealth() { - return RestResultUtils.success(memberManager.getSelf().getState().name()); - } - - @PostMapping(value = { "/report" }) - public RestResult report(@RequestBody Member node) { - if (!node.check()) { - return RestResultUtils.failedWithMsg(400, "Node information is illegal"); - } - LoggerUtils.printIfDebugEnabled(Loggers.CLUSTER, - "node state report, receive info : {}", node); - node.setState(NodeState.UP); - node.setFailAccessCnt(0); - - boolean result = memberManager.update(node); - - return RestResultUtils.success(Boolean.toString(result)); - } - - @PostMapping(value = "/switch/lookup") - public RestResult switchLookup(@RequestParam(name = "type") String type) { - try { - memberManager.swithLookup(type); - return RestResultUtils.success(); - } - catch (Throwable ex) { - return RestResultUtils.failed(ex.getMessage()); - } - } - - @PostMapping("/server/leave") - public RestResult leave(@RequestBody Collection params) - throws Exception { - Collection memberList = MemberUtils.multiParse(params); - memberManager.memberLeave(memberList); - final NAsyncHttpClient asyncHttpClient = HttpClientManager.getAsyncHttpClient(); - final GenericType> genericType = new GenericType>() { - }; - final Collection notifyList = memberManager.allMembersWithoutSelf(); - notifyList.removeAll(memberList); - CountDownLatch latch = new CountDownLatch(notifyList.size()); - for (Member member : notifyList) { - final String url = HttpUtils.buildUrl(false, member.getAddress(), - ApplicationUtils.getContextPath(), Commons.NACOS_CORE_CONTEXT, - "/cluster/server/leave"); - asyncHttpClient - .post(url, Header.EMPTY, Query.EMPTY, params, genericType.getType(), - new Callback() { - @Override - public void onReceive(RestResult result) { - try { - if (result.ok()) { - LoggerUtils - .printIfDebugEnabled(Loggers.CLUSTER, - "The node : [{}] success to process the request", - member); - MemberUtils.onSuccess(member); - } - else { - Loggers.CLUSTER - .warn("The node : [{}] failed to process the request, response is : {}", - member, result); - MemberUtils.onFail(member); - } - } - finally { - latch.countDown(); - } - } - - @Override - public void onError(Throwable throwable) { - try { - Loggers.CLUSTER - .error("Failed to communicate with the node : {}", - member); - MemberUtils.onFail(member); - } - finally { - latch.countDown(); - } - } - }); - } - - try { - latch.await(10_000, TimeUnit.MILLISECONDS); - return RestResultUtils.success("ok"); - } - catch (Throwable ex) { - return RestResultUtils.failed(ex.getMessage()); - } - } - + + private final ServerMemberManager memberManager; + + public NacosClusterController(ServerMemberManager memberManager) { + this.memberManager = memberManager; + } + + @GetMapping(value = "/self") + public RestResult self() { + return RestResultUtils.success(memberManager.getSelf()); + } + + /** + * The console displays the list of cluster members. + * + * @param ipKeyWord search keyWord + * @return all members + */ + @GetMapping(value = "/nodes") + public RestResult> listNodes( + @RequestParam(value = "keyword", required = false) String ipKeyWord) { + Collection members = memberManager.allMembers(); + Collection result = new ArrayList<>(); + + members.stream().sorted().forEach(member -> { + if (StringUtils.isBlank(ipKeyWord)) { + result.add(member); + return; + } + final String address = member.getAddress(); + if (StringUtils.equals(address, ipKeyWord) || StringUtils.startsWith(address, ipKeyWord)) { + result.add(member); + } + }); + + return RestResultUtils.success(result); + } + + // The client can get all the nacos node information in the current + // cluster according to this interface + + @GetMapping(value = "/simple/nodes") + public RestResult> listSimpleNodes() { + return RestResultUtils.success(memberManager.getMemberAddressInfos()); + } + + @GetMapping("/health") + public RestResult getHealth() { + return RestResultUtils.success(memberManager.getSelf().getState().name()); + } + + /** + * Other nodes return their own metadata information. + * + * @param node {@link Member} + * @return {@link RestResult} + */ + @PostMapping(value = {"/report"}) + public RestResult report(@RequestBody Member node) { + if (!node.check()) { + return RestResultUtils.failedWithMsg(400, "Node information is illegal"); + } + LoggerUtils.printIfDebugEnabled(Loggers.CLUSTER, "node state report, receive info : {}", node); + node.setState(NodeState.UP); + node.setFailAccessCnt(0); + + boolean result = memberManager.update(node); + + return RestResultUtils.success(Boolean.toString(result)); + } + + /** + * Addressing mode switch. + * + * @param type member-lookup name + * @return {@link RestResult} + */ + @PostMapping(value = "/switch/lookup") + public RestResult switchLookup(@RequestParam(name = "type") String type) { + try { + memberManager.swithLookup(type); + return RestResultUtils.success(); + } catch (Throwable ex) { + return RestResultUtils.failed(ex.getMessage()); + } + } + + /** + * member leave. + * + * @param params member ip list, example [ip1:port1,ip2:port2,...] + * @return {@link RestResult} + * @throws Exception {@link Exception} + */ + @PostMapping("/server/leave") + public RestResult leave(@RequestBody Collection params) throws Exception { + Collection memberList = MemberUtils.multiParse(params); + memberManager.memberLeave(memberList); + final NAsyncHttpClient asyncHttpClient = HttpClientManager.getAsyncHttpClient(); + final GenericType> genericType = new GenericType>() { + }; + final Collection notifyList = memberManager.allMembersWithoutSelf(); + notifyList.removeAll(memberList); + CountDownLatch latch = new CountDownLatch(notifyList.size()); + for (Member member : notifyList) { + final String url = HttpUtils + .buildUrl(false, member.getAddress(), ApplicationUtils.getContextPath(), Commons.NACOS_CORE_CONTEXT, + "/cluster/server/leave"); + asyncHttpClient.post(url, Header.EMPTY, Query.EMPTY, params, genericType.getType(), new Callback() { + @Override + public void onReceive(RestResult result) { + try { + if (result.ok()) { + LoggerUtils.printIfDebugEnabled(Loggers.CLUSTER, + "The node : [{}] success to process the request", member); + MemberUtils.onSuccess(member); + } else { + Loggers.CLUSTER + .warn("The node : [{}] failed to process the request, response is : {}", member, + result); + MemberUtils.onFail(member); + } + } finally { + latch.countDown(); + } + } + + @Override + public void onError(Throwable throwable) { + try { + Loggers.CLUSTER.error("Failed to communicate with the node : {}", member); + MemberUtils.onFail(member); + } finally { + latch.countDown(); + } + } + }); + } + + try { + latch.await(10_000, TimeUnit.MILLISECONDS); + return RestResultUtils.success("ok"); + } catch (Throwable ex) { + return RestResultUtils.failed(ex.getMessage()); + } + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/AbstractConsistencyProtocol.java b/core/src/main/java/com/alibaba/nacos/core/distributed/AbstractConsistencyProtocol.java index e4f7785abe7..8cf1183343e 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/AbstractConsistencyProtocol.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/AbstractConsistencyProtocol.java @@ -20,32 +20,36 @@ import com.alibaba.nacos.consistency.ConsistencyProtocol; import com.alibaba.nacos.consistency.LogProcessor; import com.alibaba.nacos.consistency.ProtocolMetaData; + import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** + * Consistent protocol base class. + * * @author liaochuntao */ -public abstract class AbstractConsistencyProtocol implements ConsistencyProtocol { - +@SuppressWarnings("all") +public abstract class AbstractConsistencyProtocol + implements ConsistencyProtocol { + protected final ProtocolMetaData metaData = new ProtocolMetaData(); - + protected Map processorMap = Collections.synchronizedMap(new HashMap<>()); - + public void loadLogProcessor(List logProcessors) { - logProcessors.forEach(logDispatcher -> processorMap - .put(logDispatcher.group(), logDispatcher)); + logProcessors.forEach(logDispatcher -> processorMap.put(logDispatcher.group(), logDispatcher)); } - + protected Map allProcessor() { return processorMap; } - + @Override public ProtocolMetaData protocolMetaData() { return this.metaData; } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/ConsistencyConfiguration.java b/core/src/main/java/com/alibaba/nacos/core/distributed/ConsistencyConfiguration.java index 0119d6cceb0..38cacdcd1ca 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/ConsistencyConfiguration.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/ConsistencyConfiguration.java @@ -19,32 +19,33 @@ import com.alibaba.nacos.consistency.cp.CPProtocol; import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.core.distributed.raft.JRaftProtocol; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + import java.util.Iterator; import java.util.ServiceLoader; import java.util.concurrent.Callable; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - /** + * consistency configuration. + * * @author liaochuntao */ @SuppressWarnings("all") @Configuration public class ConsistencyConfiguration { - + @Bean(value = "strongAgreementProtocol") public CPProtocol strongAgreementProtocol(ServerMemberManager memberManager) throws Exception { final CPProtocol protocol = getProtocol(CPProtocol.class, () -> new JRaftProtocol(memberManager)); return protocol; } - + private T getProtocol(Class cls, Callable builder) throws Exception { - ServiceLoader protocols = ServiceLoader - .load(cls); - + ServiceLoader protocols = ServiceLoader.load(cls); + // Select only the first implementation - + Iterator iterator = protocols.iterator(); if (iterator.hasNext()) { return iterator.next(); @@ -52,5 +53,5 @@ private T getProtocol(Class cls, Callable builder) throws Exception { return builder.call(); } } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/ProtocolExecutor.java b/core/src/main/java/com/alibaba/nacos/core/distributed/ProtocolExecutor.java index 02c829b8201..db0bb4e0c17 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/ProtocolExecutor.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/ProtocolExecutor.java @@ -17,27 +17,29 @@ package com.alibaba.nacos.core.distributed; import com.alibaba.nacos.common.executor.ExecutorFactory; - import com.alibaba.nacos.core.utils.ClassUtils; + import java.util.concurrent.ExecutorService; /** + * ProtocolExecutor. + * * @author liaochuntao */ public final class ProtocolExecutor { - - private static final ExecutorService CP_MEMBER_CHANGE_EXECUTOR = ExecutorFactory.Managed.newSingleExecutorService( - ClassUtils.getCanonicalName(ProtocolManager.class)); - - private static final ExecutorService AP_MEMBER_CHANGE_EXECUTOR = ExecutorFactory.Managed.newSingleExecutorService( - ClassUtils.getCanonicalName(ProtocolManager.class)); - - public static void cpMemberChange(Runnable runnable) { - CP_MEMBER_CHANGE_EXECUTOR.execute(runnable); - } - - public static void apMemberChange(Runnable runnable) { - AP_MEMBER_CHANGE_EXECUTOR.execute(runnable); - } - -} + + private static final ExecutorService CP_MEMBER_CHANGE_EXECUTOR = ExecutorFactory.Managed + .newSingleExecutorService(ClassUtils.getCanonicalName(ProtocolManager.class)); + + private static final ExecutorService AP_MEMBER_CHANGE_EXECUTOR = ExecutorFactory.Managed + .newSingleExecutorService(ClassUtils.getCanonicalName(ProtocolManager.class)); + + public static void cpMemberChange(Runnable runnable) { + CP_MEMBER_CHANGE_EXECUTOR.execute(runnable); + } + + public static void apMemberChange(Runnable runnable) { + AP_MEMBER_CHANGE_EXECUTOR.execute(runnable); + } + +} \ No newline at end of file diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/ProtocolManager.java b/core/src/main/java/com/alibaba/nacos/core/distributed/ProtocolManager.java index aece6a53bcf..0126a97d3fc 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/ProtocolManager.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/ProtocolManager.java @@ -42,136 +42,135 @@ import java.util.Set; /** - * Conformance protocol management, responsible for managing the lifecycle - * of conformance protocols in Nacos + * Conformance protocol management, responsible for managing the lifecycle of conformance protocols in Nacos. * * @author liaochuntao */ @SuppressWarnings("all") @Component(value = "ProtocolManager") @DependsOn("serverMemberManager") -public class ProtocolManager - implements ApplicationListener, DisposableBean, - MemberChangeListener { - - private CPProtocol cpProtocol; - private APProtocol apProtocol; - - @Autowired - private ServerMemberManager memberManager; - - private boolean apInit = false; - private boolean cpInit = false; - - @PostConstruct - public void init() { - this.memberManager = memberManager; - NotifyCenter.registerSubscribe(this); - } - - // delay init protocol - - public CPProtocol getCpProtocol() { - synchronized (this) { - if (!cpInit) { - initCPProtocol(); +public class ProtocolManager implements ApplicationListener, DisposableBean, MemberChangeListener { + + private CPProtocol cpProtocol; + + private APProtocol apProtocol; + + @Autowired + private ServerMemberManager memberManager; + + private boolean apInit = false; + + private boolean cpInit = false; + + private static Set toAPMembersInfo(Collection members) { + Set nodes = new HashSet<>(); + members.forEach(member -> nodes.add(member.getAddress())); + return nodes; + } + + // delay init protocol + + private static Set toCPMembersInfo(Collection members) { + Set nodes = new HashSet<>(); + members.forEach(member -> { + final String ip = member.getIp(); + final int raftPort = MemberUtils.calculateRaftPort(member); + nodes.add(ip + ":" + raftPort); + }); + return nodes; + } + + @PostConstruct + public void init() { + this.memberManager = memberManager; + NotifyCenter.registerSubscribe(this); + } + + public CPProtocol getCpProtocol() { + synchronized (this) { + if (!cpInit) { + initCPProtocol(); cpInit = true; } - } - return cpProtocol; - } - - public APProtocol getApProtocol() { - synchronized (this) { - if (!apInit) { - initAPProtocol(); + } + return cpProtocol; + } + + public APProtocol getApProtocol() { + synchronized (this) { + if (!apInit) { + initAPProtocol(); apInit = true; } - } - return apProtocol; - } - - public void destroy() { - if (Objects.nonNull(apProtocol)) { - apProtocol.shutdown(); - } - if (Objects.nonNull(cpProtocol)) { - cpProtocol.shutdown(); - } - } - - @Override - public void onApplicationEvent(ContextStartedEvent event) { - } - - private void initAPProtocol() { - ApplicationUtils.getBeanIfExist(APProtocol.class, protocol -> { - Class configType = ClassUtils.resolveGenericType(protocol.getClass()); - Config config = (Config) ApplicationUtils.getBean(configType); - injectMembers4AP(config); - protocol.init((config)); - ProtocolManager.this.apProtocol = protocol; - }); - } - - private void initCPProtocol() { - ApplicationUtils.getBeanIfExist(CPProtocol.class, protocol -> { - Class configType = ClassUtils.resolveGenericType(protocol.getClass()); - Config config = (Config) ApplicationUtils.getBean(configType); - injectMembers4CP(config); - protocol.init((config)); - ProtocolManager.this.cpProtocol = protocol; - }); - } - - private void injectMembers4CP(Config config) { - final Member selfMember = memberManager.getSelf(); - final String self = selfMember.getIp() + ":" + Integer.parseInt(String.valueOf( - selfMember.getExtendVal(MemberMetaDataConstants.RAFT_PORT))); - Set others = toCPMembersInfo(memberManager.allMembers()); - config.setMembers(self, others); - } - - private void injectMembers4AP(Config config) { - final String self = memberManager.getSelf().getAddress(); - Set others = toAPMembersInfo(memberManager.allMembers()); - config.setMembers(self, others); - } - - @Override - public void onEvent(MemberChangeEvent event) { - // Here, the sequence of node change events is very important. For example, - // node change event A occurs at time T1, and node change event B occurs at - // time T2 after a period of time. - // (T1 < T2) - - Set copy = new HashSet<>(event.getMembers()); - - // Node change events between different protocols should not block each other. - // and we use a single thread pool to inform the consistency layer of node changes, - // to avoid multiple tasks simultaneously carrying out the consistency layer of - // node changes operation - if (Objects.nonNull(apProtocol)) { - ProtocolExecutor.apMemberChange(() -> apProtocol.memberChange(toAPMembersInfo(copy))); - } - if (Objects.nonNull(cpProtocol)) { - ProtocolExecutor.cpMemberChange(() -> cpProtocol.memberChange(toCPMembersInfo(copy))); - } - } - - private static Set toAPMembersInfo(Collection members) { - Set nodes = new HashSet<>(); - members.forEach(member -> nodes.add(member.getAddress())); - return nodes; - } - - private static Set toCPMembersInfo(Collection members) { - Set nodes = new HashSet<>(); - members.forEach(member -> { - final String ip = member.getIp(); - final int raftPort = MemberUtils.calculateRaftPort(member); - nodes.add(ip + ":" + raftPort); - }); - return nodes; - } + } + return apProtocol; + } + + public void destroy() { + if (Objects.nonNull(apProtocol)) { + apProtocol.shutdown(); + } + if (Objects.nonNull(cpProtocol)) { + cpProtocol.shutdown(); + } + } + + @Override + public void onApplicationEvent(ContextStartedEvent event) { + } + + private void initAPProtocol() { + ApplicationUtils.getBeanIfExist(APProtocol.class, protocol -> { + Class configType = ClassUtils.resolveGenericType(protocol.getClass()); + Config config = (Config) ApplicationUtils.getBean(configType); + injectMembers4AP(config); + protocol.init((config)); + ProtocolManager.this.apProtocol = protocol; + }); + } + + private void initCPProtocol() { + ApplicationUtils.getBeanIfExist(CPProtocol.class, protocol -> { + Class configType = ClassUtils.resolveGenericType(protocol.getClass()); + Config config = (Config) ApplicationUtils.getBean(configType); + injectMembers4CP(config); + protocol.init((config)); + ProtocolManager.this.cpProtocol = protocol; + }); + } + + private void injectMembers4CP(Config config) { + final Member selfMember = memberManager.getSelf(); + final String self = selfMember.getIp() + ":" + Integer + .parseInt(String.valueOf(selfMember.getExtendVal(MemberMetaDataConstants.RAFT_PORT))); + Set others = toCPMembersInfo(memberManager.allMembers()); + config.setMembers(self, others); + } + + private void injectMembers4AP(Config config) { + final String self = memberManager.getSelf().getAddress(); + Set others = toAPMembersInfo(memberManager.allMembers()); + config.setMembers(self, others); + } + + @Override + public void onEvent(MemberChangeEvent event) { + // Here, the sequence of node change events is very important. For example, + // node change event A occurs at time T1, and node change event B occurs at + // time T2 after a period of time. + // (T1 < T2) + + Set copy = new HashSet<>(event.getMembers()); + + // Node change events between different protocols should not block each other. + // and we use a single thread pool to inform the consistency layer of node changes, + // to avoid multiple tasks simultaneously carrying out the consistency layer of + // node changes operation + if (Objects.nonNull(apProtocol)) { + ProtocolExecutor.apMemberChange(() -> apProtocol.memberChange(toAPMembersInfo(copy))); + } + if (Objects.nonNull(cpProtocol)) { + ProtocolExecutor.cpMemberChange(() -> cpProtocol.memberChange(toCPMembersInfo(copy))); + } + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/id/IdGeneratorManager.java b/core/src/main/java/com/alibaba/nacos/core/distributed/id/IdGeneratorManager.java index d8d783a6d87..abe0a86326e 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/id/IdGeneratorManager.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/id/IdGeneratorManager.java @@ -17,6 +17,7 @@ package com.alibaba.nacos.core.distributed.id; import com.alibaba.nacos.consistency.IdGenerator; +import org.springframework.stereotype.Component; import java.util.Iterator; import java.util.Map; @@ -25,18 +26,19 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; -import org.springframework.stereotype.Component; - /** + * Id generator manager. + * * @author liaochuntao */ @SuppressWarnings("PMD.UndefineMagicConstantRule") @Component public class IdGeneratorManager { - + private final Map generatorMap = new ConcurrentHashMap<>(); + private final Function supplier; - + public IdGeneratorManager() { this.supplier = s -> { IdGenerator generator; @@ -51,25 +53,36 @@ public IdGeneratorManager() { return generator; }; } - + public void register(String resource) { generatorMap.computeIfAbsent(resource, s -> supplier.apply(resource)); } - + + /** + * Register resources that need to use the ID generator. + * + * @param resources resource name list + */ public void register(String... resources) { for (String resource : resources) { generatorMap.computeIfAbsent(resource, s -> supplier.apply(resource)); } } - + + /** + * request next id by resource name. + * + * @param resource resource name + * @return id + */ public long nextId(String resource) { if (generatorMap.containsKey(resource)) { return generatorMap.get(resource).nextId(); } - throw new NoSuchElementException("The resource is not registered with the distributed " + - "ID resource for the time being."); + throw new NoSuchElementException( + "The resource is not registered with the distributed " + "ID resource for the time being."); } - + public Map getGeneratorMap() { return generatorMap; } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/id/SnowFlowerIdGenerator.java b/core/src/main/java/com/alibaba/nacos/core/distributed/id/SnowFlowerIdGenerator.java index 064918581b6..f8db27cb564 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/id/SnowFlowerIdGenerator.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/id/SnowFlowerIdGenerator.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.distributed.id; import com.alibaba.nacos.consistency.IdGenerator; @@ -29,141 +30,143 @@ import java.util.Map; /** - * copy from http://www.cluozy.com/home/hexo/2018/08/11/shariding-JDBC-snowflake/ + * copy from http://www.cluozy.com/home/hexo/2018/08/11/shariding-JDBC-snowflake/. * * WorkerId generation policy: Calculate the InetAddress hashcode - *

      - * The repeat rate of the dataCenterId, the value of the maximum dataCenterId times the - * time of each Raft election. The time for raft to select the master is generally measured - * in seconds. If the interval of an election is 5 seconds, it will take 150 seconds for - * the DataCenterId to be repeated. This is still based on the situation that the new master + * + *

      The repeat rate of the dataCenterId, the value of the maximum dataCenterId times the time of each Raft election. + * The + * time for raft to select the master is generally measured in seconds. If the interval of an election is 5 seconds, it + * will take 150 seconds for the DataCenterId to be repeated. This is still based on the situation that the new master * needs to be selected after each election of the Leader * * @author liaochuntao */ @SuppressWarnings("all") public class SnowFlowerIdGenerator implements IdGenerator { - - private static final Logger logger = LoggerFactory - .getLogger(SnowFlowerIdGenerator.class); - - /** - * Start time intercept (2018-08-05 08:34) - */ - public static final long EPOCH = 1533429240000L; - // 序列所占位数 - private static final long SEQUENCE_BITS = 12L; - // workerId所占位数 - private static final long WORKER_ID_BITS = 10L; - // 序列掩码(111111111111B = 4095) - private static final long SEQUENCE_MASK = 4095L; - // workerId左边共12位(序列号) - private static final long WORKER_ID_LEFT_SHIFT_BITS = 12L; - // 时间戳左边共22位(序列号+workerId) - private static final long TIMESTAMP_LEFT_SHIFT_BITS = 22L; - // 工作机器ID最大值1024 - private static final long WORKER_ID_MAX_VALUE = 1024L; - private long workerId; - private long sequence; - private long lastTime; - private long currentId; - - { - long workerId = ApplicationUtils - .getProperty("nacos.core.snowflake.worker-id", Integer.class, -1); - - if (workerId != -1) { - this.workerId = workerId; - } - else { - InetAddress address; - try { - address = InetAddress.getLocalHost(); - } - catch (final UnknownHostException e) { - throw new IllegalStateException( - "Cannot get LocalHost InetAddress, please check your network!"); - } - byte[] ipAddressByteArray = address.getAddress(); - this.workerId = ( - ((ipAddressByteArray[ipAddressByteArray.length - 2] & 0B11) - << Byte.SIZE) + ( - ipAddressByteArray[ipAddressByteArray.length - 1] & 0xFF)); - } - } - - @Override - public void init() { - initialize(workerId); - } - - @Override - public long currentId() { - return currentId; - } - - @Override - public synchronized long nextId() { - long currentMillis = System.currentTimeMillis(); - Preconditions.checkState(this.lastTime <= currentMillis, - "Clock is moving backwards, last time is %d milliseconds, current time is %d milliseconds", - new Object[] { this.lastTime, currentMillis }); - if (this.lastTime == currentMillis) { - if (0L == (this.sequence = ++this.sequence & 4095L)) { - currentMillis = this.waitUntilNextTime(currentMillis); - } - } - else { - this.sequence = 0L; - } - - this.lastTime = currentMillis; - logger.debug("{}-{}-{}", (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")) - .format(new Date(this.lastTime)), workerId, this.sequence); - - currentId = currentMillis - EPOCH << 22 | workerId << 12 | this.sequence; - return currentId; - } - - @Override - public Map info() { - Map info = new HashMap<>(4); - info.put("currentId", currentId); - info.put("workerId", workerId); - return info; - } - - // ==============================Constructors===================================== - - /** - * init - * - * @param workerId worker id (0~1024) - */ - public void initialize(long workerId) { - if (workerId > WORKER_ID_MAX_VALUE || workerId < 0) { - throw new IllegalArgumentException(String.format( - "worker Id can't be greater than %d or less than 0, current workId %d", - WORKER_ID_MAX_VALUE, workerId)); - } - this.workerId = workerId; - } - - /** - * Block to the next millisecond until a new timestamp is obtained - * - * @param lastTimestamp The time intercept of the last ID generated - * @return Current timestamp - */ - private long waitUntilNextTime(long lastTimestamp) { - long time; - time = System.currentTimeMillis(); - while (time <= lastTimestamp) { - ; - time = System.currentTimeMillis(); - } - - return time; - } - + + /** + * Start time intercept (2018-08-05 08:34) + */ + public static final long EPOCH = 1533429240000L; + + private static final Logger logger = LoggerFactory.getLogger(SnowFlowerIdGenerator.class); + + // 序列所占位数 + private static final long SEQUENCE_BITS = 12L; + + // workerId所占位数 + private static final long WORKER_ID_BITS = 10L; + + // 序列掩码(111111111111B = 4095) + private static final long SEQUENCE_MASK = 4095L; + + // workerId左边共12位(序列号) + private static final long WORKER_ID_LEFT_SHIFT_BITS = 12L; + + // 时间戳左边共22位(序列号+workerId) + private static final long TIMESTAMP_LEFT_SHIFT_BITS = 22L; + + // 工作机器ID最大值1024 + private static final long WORKER_ID_MAX_VALUE = 1024L; + + private long workerId; + + private long sequence; + + private long lastTime; + + private long currentId; + + { + long workerId = ApplicationUtils.getProperty("nacos.core.snowflake.worker-id", Integer.class, -1); + + if (workerId != -1) { + this.workerId = workerId; + } else { + InetAddress address; + try { + address = InetAddress.getLocalHost(); + } catch (final UnknownHostException e) { + throw new IllegalStateException("Cannot get LocalHost InetAddress, please check your network!"); + } + byte[] ipAddressByteArray = address.getAddress(); + this.workerId = (((ipAddressByteArray[ipAddressByteArray.length - 2] & 0B11) << Byte.SIZE) + ( + ipAddressByteArray[ipAddressByteArray.length - 1] & 0xFF)); + } + } + + @Override + public void init() { + initialize(workerId); + } + + @Override + public long currentId() { + return currentId; + } + + @Override + public synchronized long nextId() { + long currentMillis = System.currentTimeMillis(); + Preconditions.checkState(this.lastTime <= currentMillis, + "Clock is moving backwards, last time is %d milliseconds, current time is %d milliseconds", + new Object[] {this.lastTime, currentMillis}); + if (this.lastTime == currentMillis) { + if (0L == (this.sequence = ++this.sequence & 4095L)) { + currentMillis = this.waitUntilNextTime(currentMillis); + } + } else { + this.sequence = 0L; + } + + this.lastTime = currentMillis; + logger.debug("{}-{}-{}", (new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")).format(new Date(this.lastTime)), + workerId, this.sequence); + + currentId = currentMillis - EPOCH << 22 | workerId << 12 | this.sequence; + return currentId; + } + + @Override + public Map info() { + Map info = new HashMap<>(4); + info.put("currentId", currentId); + info.put("workerId", workerId); + return info; + } + + // ==============================Constructors===================================== + + /** + * init + * + * @param workerId worker id (0~1024) + */ + public void initialize(long workerId) { + if (workerId > WORKER_ID_MAX_VALUE || workerId < 0) { + throw new IllegalArgumentException( + String.format("worker Id can't be greater than %d or less than 0, current workId %d", + WORKER_ID_MAX_VALUE, workerId)); + } + this.workerId = workerId; + } + + /** + * Block to the next millisecond until a new timestamp is obtained + * + * @param lastTimestamp The time intercept of the last ID generated + * @return Current timestamp + */ + private long waitUntilNextTime(long lastTimestamp) { + long time; + time = System.currentTimeMillis(); + while (time <= lastTimestamp) { + ; + time = System.currentTimeMillis(); + } + + return time; + } + } \ No newline at end of file diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftMaintainService.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftMaintainService.java index 83223e9693c..3adfa0d5376 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftMaintainService.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftMaintainService.java @@ -18,68 +18,71 @@ import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.common.model.RestResultUtils; -import com.alibaba.nacos.core.distributed.raft.utils.JRaftOps; import com.alibaba.nacos.core.distributed.raft.utils.JRaftConstants; +import com.alibaba.nacos.core.distributed.raft.utils.JRaftOps; import com.alipay.sofa.jraft.CliService; import com.alipay.sofa.jraft.Node; -import com.alipay.sofa.jraft.conf.Configuration; import java.util.Map; import java.util.Objects; /** - * JRaft operations interface + * JRaft operations interface. * * @author liaochuntao */ @SuppressWarnings("PMD.ClassNamingShouldBeCamelRule") public class JRaftMaintainService { - - private final JRaftServer raftServer; - - public JRaftMaintainService(JRaftServer raftServer) { - this.raftServer = raftServer; - } - - public RestResult execute(String[] args) { - return RestResultUtils.failed("not support yet"); - } - - public RestResult execute(Map args) { - final CliService cliService = raftServer.getCliService(); - if (args.containsKey(JRaftConstants.GROUP_ID)) { - final String groupId = args.get(JRaftConstants.GROUP_ID); - final Node node = raftServer.findNodeByGroup(groupId); - return single(cliService, groupId, node, args); - } - Map tupleMap = raftServer.getMultiRaftGroup(); - for (Map.Entry entry : tupleMap.entrySet()) { - final String group = entry.getKey(); - final Node node = entry.getValue().getNode(); - RestResult result = single(cliService, group, node, args); - if (!result.ok()) { - return result; - } - } - return RestResultUtils.success(); - } - - private RestResult single(CliService cliService, String groupId, Node node, - Map args) { - try { - if (node == null) { - return RestResultUtils.failed("not this raft group : " + groupId); - } - final String command = args.get(JRaftConstants.COMMAND_NAME); - JRaftOps ops = JRaftOps.sourceOf(command); - if (Objects.isNull(ops)) { - return RestResultUtils.failed("Not support command : " + command); - } - return ops.execute(cliService, groupId, node, args); - } - catch (Throwable ex) { - return RestResultUtils.failed(ex.getMessage()); - } - } - + + private final JRaftServer raftServer; + + public JRaftMaintainService(JRaftServer raftServer) { + this.raftServer = raftServer; + } + + public RestResult execute(String[] args) { + return RestResultUtils.failed("not support yet"); + } + + /** + * Execute relevant commands. + * + * @param args {@link Map} + * @return {@link RestResult} + */ + public RestResult execute(Map args) { + final CliService cliService = raftServer.getCliService(); + if (args.containsKey(JRaftConstants.GROUP_ID)) { + final String groupId = args.get(JRaftConstants.GROUP_ID); + final Node node = raftServer.findNodeByGroup(groupId); + return single(cliService, groupId, node, args); + } + Map tupleMap = raftServer.getMultiRaftGroup(); + for (Map.Entry entry : tupleMap.entrySet()) { + final String group = entry.getKey(); + final Node node = entry.getValue().getNode(); + RestResult result = single(cliService, group, node, args); + if (!result.ok()) { + return result; + } + } + return RestResultUtils.success(); + } + + private RestResult single(CliService cliService, String groupId, Node node, Map args) { + try { + if (node == null) { + return RestResultUtils.failed("not this raft group : " + groupId); + } + final String command = args.get(JRaftConstants.COMMAND_NAME); + JRaftOps ops = JRaftOps.sourceOf(command); + if (Objects.isNull(ops)) { + return RestResultUtils.failed("Not support command : " + command); + } + return ops.execute(cliService, groupId, node, args); + } catch (Throwable ex) { + return RestResultUtils.failed(ex.getMessage()); + } + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftProtocol.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftProtocol.java index 3e3cb8e2d30..bc02daa036e 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftProtocol.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftProtocol.java @@ -23,8 +23,8 @@ import com.alibaba.nacos.consistency.SerializeFactory; import com.alibaba.nacos.consistency.Serializer; import com.alibaba.nacos.consistency.cp.CPProtocol; -import com.alibaba.nacos.consistency.cp.MetadataKey; import com.alibaba.nacos.consistency.cp.LogProcessor4CP; +import com.alibaba.nacos.consistency.cp.MetadataKey; import com.alibaba.nacos.consistency.entity.GetRequest; import com.alibaba.nacos.consistency.entity.Log; import com.alibaba.nacos.consistency.entity.Response; @@ -48,7 +48,7 @@ import java.util.concurrent.atomic.AtomicBoolean; /** - * A concrete implementation of CP protocol: JRaft + * A concrete implementation of CP protocol: JRaft. * *

        *                                           ┌──────────────────────┐
      @@ -90,130 +90,135 @@
        * @author liaochuntao
        */
       @SuppressWarnings("all")
      -public class JRaftProtocol
      -		extends AbstractConsistencyProtocol
      -		implements CPProtocol {
      -
      -	private final AtomicBoolean initialized = new AtomicBoolean(false);
      -	private final AtomicBoolean shutdowned = new AtomicBoolean(false);
      -	private RaftConfig raftConfig;
      -	private JRaftServer raftServer;
      -	private JRaftMaintainService jRaftMaintainService;
      -	private ServerMemberManager memberManager;
      -	private final Serializer serializer = SerializeFactory.getDefault();
      -
      -	public JRaftProtocol(ServerMemberManager memberManager) throws Exception {
      -		this.memberManager = memberManager;
      -		this.raftServer = new JRaftServer();
      -		this.jRaftMaintainService = new JRaftMaintainService(raftServer);
      -	}
      -
      -	@Override
      -	public void init(RaftConfig config) {
      -		if (initialized.compareAndSet(false, true)) {
      -			this.raftConfig = config;
      -			NotifyCenter.registerToSharePublisher(RaftEvent.class);
      -			this.raftServer.init(this.raftConfig);
      -			this.raftServer.start();
      -
      -			// There is only one consumer to ensure that the internal consumption
      -			// is sequential and there is no concurrent competition
      -			NotifyCenter.registerSubscribe(new Subscribe() {
      -				@Override
      -				public void onEvent(RaftEvent event) {
      -					Loggers.RAFT.info("This Raft event changes : {}", event);
      -					final String groupId = event.getGroupId();
      -					Map> value = new HashMap<>();
      -					Map properties = new HashMap<>();
      -					final String leader = event.getLeader();
      -					final Long term = event.getTerm();
      -					final List raftClusterInfo = event.getRaftClusterInfo();
      -
      -					// Leader information needs to be selectively updated. If it is valid data,
      -					// the information in the protocol metadata is updated.
      -					MapUtils.putIfValNoEmpty(properties, MetadataKey.LEADER_META_DATA, leader);
      -					MapUtils.putIfValNoNull(properties, MetadataKey.TERM_META_DATA, term);
      -					MapUtils.putIfValNoEmpty(properties, MetadataKey.RAFT_GROUP_MEMBER, raftClusterInfo);
      -
      -					value.put(groupId, properties);
      -					metaData.load(value);
      -
      -					// The metadata information is injected into the metadata information of the node
      -					injectProtocolMetaData(metaData);
      -				}
      -
      -				@Override
      -				public Class subscribeType() {
      -					return RaftEvent.class;
      -				}
      -
      -			});
      -		}
      -	}
      -
      -	@Override
      -	public void addLogProcessors(Collection processors) {
      -		raftServer.createMultiRaftGroup(processors);
      -	}
      -
      -	@Override
      -	public Response getData(GetRequest request) throws Exception {
      -		CompletableFuture future = aGetData(request);
      -		return future.get(5_000L, TimeUnit.MILLISECONDS);
      -	}
      -
      -	@Override
      -	public CompletableFuture aGetData(GetRequest request) {
      -		return raftServer.get(request);
      -	}
      -
      -	@Override
      -	public Response submit(Log data) throws Exception {
      -		CompletableFuture future = submitAsync(data);
      -		// Here you wait for 10 seconds, as long as possible, for the request to complete
      -		return future.get(10_000L, TimeUnit.MILLISECONDS);
      -	}
      -
      -	@Override
      -	public CompletableFuture submitAsync(Log data) {
      -		return raftServer.commit(data.getGroup(), data, new CompletableFuture<>());
      -	}
      -
      -	@Override
      -	public void memberChange(Set addresses) {
      -		for (int i = 0; i < 5; i++) {
      -			if (this.raftServer.peerChange(jRaftMaintainService, addresses)) {
      -				return;
      -			}
      -			ThreadUtils.sleep(100L);
      -		}
      -		Loggers.RAFT.warn("peer removal failed");
      -	}
      -
      -	@Override
      -	public void shutdown() {
      -		if (initialized.get() && shutdowned.compareAndSet(false, true)) {
      -			raftServer.shutdown();
      -		}
      -	}
      -
      -	@Override
      -	public RestResult execute(Map args) {
      -		return jRaftMaintainService.execute(args);
      -	}
      -
      -	private void injectProtocolMetaData(ProtocolMetaData metaData) {
      -		Member member = memberManager.getSelf();
      -		member.setExtendVal("raftMetaData", metaData);
      -		memberManager.update(member);
      -	}
      -
      -	@Override
      -	public boolean isLeader(String group) {
      -		Node node = raftServer.findNodeByGroup(group);
      -		if (node == null) {
      -			throw new NoSuchRaftGroupException(group);
      -		}
      -		return node.isLeader();
      -	}
      +public class JRaftProtocol extends AbstractConsistencyProtocol
      +        implements CPProtocol {
      +    
      +    private final AtomicBoolean initialized = new AtomicBoolean(false);
      +    
      +    private final AtomicBoolean shutdowned = new AtomicBoolean(false);
      +    
      +    private final Serializer serializer = SerializeFactory.getDefault();
      +    
      +    private RaftConfig raftConfig;
      +    
      +    private JRaftServer raftServer;
      +    
      +    private JRaftMaintainService jRaftMaintainService;
      +    
      +    private ServerMemberManager memberManager;
      +    
      +    public JRaftProtocol(ServerMemberManager memberManager) throws Exception {
      +        this.memberManager = memberManager;
      +        this.raftServer = new JRaftServer();
      +        this.jRaftMaintainService = new JRaftMaintainService(raftServer);
      +    }
      +    
      +    @Override
      +    public void init(RaftConfig config) {
      +        if (initialized.compareAndSet(false, true)) {
      +            this.raftConfig = config;
      +            NotifyCenter.registerToSharePublisher(RaftEvent.class);
      +            this.raftServer.init(this.raftConfig);
      +            this.raftServer.start();
      +            
      +            // There is only one consumer to ensure that the internal consumption
      +            // is sequential and there is no concurrent competition
      +            NotifyCenter.registerSubscribe(new Subscribe() {
      +                @Override
      +                public void onEvent(RaftEvent event) {
      +                    Loggers.RAFT.info("This Raft event changes : {}", event);
      +                    final String groupId = event.getGroupId();
      +                    Map> value = new HashMap<>();
      +                    Map properties = new HashMap<>();
      +                    final String leader = event.getLeader();
      +                    final Long term = event.getTerm();
      +                    final List raftClusterInfo = event.getRaftClusterInfo();
      +                    
      +                    // Leader information needs to be selectively updated. If it is valid data,
      +                    // the information in the protocol metadata is updated.
      +                    MapUtils.putIfValNoEmpty(properties, MetadataKey.LEADER_META_DATA, leader);
      +                    MapUtils.putIfValNoNull(properties, MetadataKey.TERM_META_DATA, term);
      +                    MapUtils.putIfValNoEmpty(properties, MetadataKey.RAFT_GROUP_MEMBER, raftClusterInfo);
      +                    
      +                    value.put(groupId, properties);
      +                    metaData.load(value);
      +                    
      +                    // The metadata information is injected into the metadata information of the node
      +                    injectProtocolMetaData(metaData);
      +                }
      +                
      +                @Override
      +                public Class subscribeType() {
      +                    return RaftEvent.class;
      +                }
      +                
      +            });
      +        }
      +    }
      +    
      +    @Override
      +    public void addLogProcessors(Collection processors) {
      +        raftServer.createMultiRaftGroup(processors);
      +    }
      +    
      +    @Override
      +    public Response getData(GetRequest request) throws Exception {
      +        CompletableFuture future = aGetData(request);
      +        return future.get(5_000L, TimeUnit.MILLISECONDS);
      +    }
      +    
      +    @Override
      +    public CompletableFuture aGetData(GetRequest request) {
      +        return raftServer.get(request);
      +    }
      +    
      +    @Override
      +    public Response submit(Log data) throws Exception {
      +        CompletableFuture future = submitAsync(data);
      +        // Here you wait for 10 seconds, as long as possible, for the request to complete
      +        return future.get(10_000L, TimeUnit.MILLISECONDS);
      +    }
      +    
      +    @Override
      +    public CompletableFuture submitAsync(Log data) {
      +        return raftServer.commit(data.getGroup(), data, new CompletableFuture<>());
      +    }
      +    
      +    @Override
      +    public void memberChange(Set addresses) {
      +        for (int i = 0; i < 5; i++) {
      +            if (this.raftServer.peerChange(jRaftMaintainService, addresses)) {
      +                return;
      +            }
      +            ThreadUtils.sleep(100L);
      +        }
      +        Loggers.RAFT.warn("peer removal failed");
      +    }
      +    
      +    @Override
      +    public void shutdown() {
      +        if (initialized.get() && shutdowned.compareAndSet(false, true)) {
      +            raftServer.shutdown();
      +        }
      +    }
      +    
      +    @Override
      +    public RestResult execute(Map args) {
      +        return jRaftMaintainService.execute(args);
      +    }
      +    
      +    private void injectProtocolMetaData(ProtocolMetaData metaData) {
      +        Member member = memberManager.getSelf();
      +        member.setExtendVal("raftMetaData", metaData);
      +        memberManager.update(member);
      +    }
      +    
      +    @Override
      +    public boolean isLeader(String group) {
      +        Node node = raftServer.findNodeByGroup(group);
      +        if (node == null) {
      +            throw new NoSuchRaftGroupException(group);
      +        }
      +        return node.isLeader();
      +    }
       }
      diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftServer.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftServer.java
      index 3bb81e67625..27bfd1aa0b6 100644
      --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftServer.java
      +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JRaftServer.java
      @@ -85,16 +85,14 @@
       import java.util.function.BiConsumer;
       
       /**
      - * JRaft server instance, away from Spring IOC management
      + * JRaft server instance, away from Spring IOC management.
        *
        * 

      - * Why do we need to create a raft group based on the value of LogProcessor group (), - * that is, each function module has its own state machine. Because each LogProcessor - * corresponds to a different functional module, such as Nacos's naming module and - * config module, these two modules are independent of each other and do not affect - * each other. If we have only one state machine, it is equal to the log of all functional - * modules The processing is loaded together. Any module that has an exception during - * the log processing and a long block operation will affect the normal operation of + * Why do we need to create a raft group based on the value of LogProcessor group (), that is, each function module has + * its own state machine. Because each LogProcessor corresponds to a different functional module, such as Nacos's naming + * module and config module, these two modules are independent of each other and do not affect each other. If we have + * only one state machine, it is equal to the log of all functional modules The processing is loaded together. Any + * module that has an exception during the log processing and a long block operation will affect the normal operation of * other functional modules. *

      * @@ -102,490 +100,467 @@ */ @SuppressWarnings("all") public class JRaftServer { - - // Existential life cycle - - private RpcServer rpcServer; - private CliClientServiceImpl cliClientService; - private CliService cliService; - private Map multiRaftGroup = new ConcurrentHashMap<>(); - - // Ordinary member variable - - private volatile boolean isStarted = false; - private volatile boolean isShutdown = false; - private Configuration conf; - - private RpcProcessor userProcessor; - private NodeOptions nodeOptions; - private Serializer serializer; - private Collection processors = Collections - .synchronizedSet(new HashSet<>()); - - private String selfIp; - private int selfPort; - - private RaftConfig raftConfig; - private PeerId localPeerId; - private int failoverRetries; - private int rpcRequestTimeoutMs; - - static { - // Set bolt buffer - // System.getProperties().setProperty("bolt.channel_write_buf_low_water_mark", String.valueOf(64 * 1024 * 1024)); - // System.getProperties().setProperty("bolt.channel_write_buf_high_water_mark", String.valueOf(256 * 1024 * 1024)); - - System.getProperties().setProperty("bolt.netty.buffer.low.watermark", - String.valueOf(128 * 1024 * 1024)); - System.getProperties().setProperty("bolt.netty.buffer.high.watermark", - String.valueOf(256 * 1024 * 1024)); - } - - public JRaftServer() { - this.conf = new Configuration(); - } - - public void setFailoverRetries(int failoverRetries) { - this.failoverRetries = failoverRetries; - } - - void init(RaftConfig config) { - this.raftConfig = config; - this.serializer = SerializeFactory.getDefault(); - Loggers.RAFT.info("Initializes the Raft protocol, raft-config info : {}", config); - RaftExecutor.init(config); - - final String self = config.getSelfMember(); - String[] info = self.split(":"); - selfIp = info[0]; - selfPort = Integer.parseInt(info[1]); - localPeerId = PeerId.parsePeer(self); - nodeOptions = new NodeOptions(); - - // Set the election timeout time. The default is 5 seconds. - int electionTimeout = Math.max(ConvertUtils - .toInt(config.getVal(RaftSysConstants.RAFT_ELECTION_TIMEOUT_MS), - RaftSysConstants.DEFAULT_ELECTION_TIMEOUT), - RaftSysConstants.DEFAULT_ELECTION_TIMEOUT); - - rpcRequestTimeoutMs = ConvertUtils - .toInt(raftConfig.getVal(RaftSysConstants.RAFT_RPC_REQUEST_TIMEOUT_MS), - RaftSysConstants.DEFAULT_RAFT_RPC_REQUEST_TIMEOUT_MS); - - nodeOptions.setSharedElectionTimer(true); - nodeOptions.setSharedVoteTimer(true); - nodeOptions.setSharedStepDownTimer(true); - nodeOptions.setSharedSnapshotTimer(true); - - nodeOptions.setElectionTimeoutMs(electionTimeout); - RaftOptions raftOptions = RaftOptionsBuilder.initRaftOptions(raftConfig); - nodeOptions.setRaftOptions(raftOptions); - // open jraft node metrics record function - nodeOptions.setEnableMetrics(true); - - CliOptions cliOptions = new CliOptions(); - - this.cliClientService = new CliClientServiceImpl(); - this.cliClientService.init(cliOptions); - this.cliService = RaftServiceFactory.createAndInitCliService(cliOptions); - } - - synchronized void start() { - if (!isStarted) { - Loggers.RAFT.info("========= The raft protocol is starting... ========="); - try { - // init raft group node - com.alipay.sofa.jraft.NodeManager raftNodeManager = com.alipay.sofa.jraft.NodeManager - .getInstance(); - for (String address : raftConfig.getMembers()) { - PeerId peerId = PeerId.parsePeer(address); - conf.addPeer(peerId); - raftNodeManager.addAddress(peerId.getEndpoint()); - } - nodeOptions.setInitialConf(conf); - - rpcServer = JRaftUtils.initRpcServer(this, localPeerId); - - if (!this.rpcServer.init(null)) { - Loggers.RAFT.error("Fail to init [RpcServer]."); - throw new RuntimeException("Fail to init [RpcServer]."); - } - - // Initialize multi raft group service framework - isStarted = true; - createMultiRaftGroup(processors); - Loggers.RAFT - .info("========= The raft protocol start finished... ========="); - } - catch (Exception e) { - Loggers.RAFT.error("raft protocol start failure, error : {}", e); - throw new JRaftException(e); - } - } - } - - synchronized void createMultiRaftGroup(Collection processors) { - // There is no reason why the LogProcessor cannot be processed because of the synchronization - if (!this.isStarted) { - this.processors.addAll(processors); - return; - } - - final String parentPath = Paths - .get(ApplicationUtils.getNacosHome(), "data/protocol/raft").toString(); - - for (LogProcessor4CP processor : processors) { - final String groupName = processor.group(); - if (multiRaftGroup.containsKey(groupName)) { - throw new DuplicateRaftGroupException(groupName); - } - - // Ensure that each Raft Group has its own configuration and NodeOptions - Configuration configuration = conf.copy(); - NodeOptions copy = nodeOptions.copy(); - JRaftUtils.initDirectory(parentPath, groupName, copy); - - // Here, the LogProcessor is passed into StateMachine, and when the StateMachine - // triggers onApply, the onApply of the LogProcessor is actually called - NacosStateMachine machine = new NacosStateMachine(this, processor); - - copy.setFsm(machine); - copy.setInitialConf(configuration); - - // Set snapshot interval, default 1800 seconds - int doSnapshotInterval = ConvertUtils.toInt(raftConfig - .getVal(RaftSysConstants.RAFT_SNAPSHOT_INTERVAL_SECS), - RaftSysConstants.DEFAULT_RAFT_SNAPSHOT_INTERVAL_SECS); - - // If the business module does not implement a snapshot processor, cancel the snapshot - doSnapshotInterval = CollectionUtils - .isEmpty(processor.loadSnapshotOperate()) ? 0 : doSnapshotInterval; - - copy.setSnapshotIntervalSecs(doSnapshotInterval); - Loggers.RAFT.info("create raft group : {}", groupName); - RaftGroupService raftGroupService = new RaftGroupService(groupName, - localPeerId, copy, rpcServer, true); - - // Because RpcServer has been started before, it is not allowed to start again here - Node node = raftGroupService.start(false); - machine.setNode(node); - RouteTable.getInstance().updateConfiguration(groupName, configuration); - - RaftExecutor.executeByCommon( - () -> registerSelfToCluster(groupName, localPeerId, configuration)); - - // Turn on the leader auto refresh for this group - Random random = new Random(); - long period = nodeOptions.getElectionTimeoutMs() + random.nextInt(5 * 1000); - RaftExecutor.scheduleRaftMemberRefreshJob(() -> refreshRouteTable(groupName), - nodeOptions.getElectionTimeoutMs(), period, TimeUnit.MILLISECONDS); - multiRaftGroup.put(groupName, - new RaftGroupTuple(node, processor, raftGroupService, machine)); - } - } - - CompletableFuture get(final GetRequest request) { - final String group = request.getGroup(); - CompletableFuture future = new CompletableFuture<>(); - final RaftGroupTuple tuple = findTupleByGroup(group); - if (Objects.isNull(tuple)) { - future.completeExceptionally(new NoSuchRaftGroupException(group)); - return future; - } - final Node node = tuple.node; - final LogProcessor processor = tuple.processor; - try { - node.readIndex(BytesUtil.EMPTY_BYTES, new ReadIndexClosure() { - @Override - public void run(Status status, long index, byte[] reqCtx) { - if (status.isOk()) { - try { - Response response = processor.onRequest(request); - future.complete(response); - } - catch (Throwable t) { - MetricsMonitor.raftReadIndexFailed(); - future.completeExceptionally(new ConsistencyException( - "The conformance protocol is temporarily unavailable for reading", - t)); - } - return; - } - MetricsMonitor.raftReadIndexFailed(); - Loggers.RAFT.error("ReadIndex has error : {}", status.getErrorMsg()); - future.completeExceptionally(new ConsistencyException( - "The conformance protocol is temporarily unavailable for reading, " - + status.getErrorMsg())); - } - }); - return future; - } - catch (Throwable e) { - MetricsMonitor.raftReadFromLeader(); - Loggers.RAFT.warn("Raft linear read failed, go to Leader read logic : {}", - e.toString()); - // run raft read - readFromLeader(request, future); - return future; - } - } - - public void readFromLeader(final GetRequest request, - final CompletableFuture future) { - commit(request.getGroup(), request, future) - .whenComplete(new BiConsumer() { - @Override - public void accept(Response response, Throwable throwable) { - if (Objects.nonNull(throwable)) { - future.completeExceptionally(new ConsistencyException( - "The conformance protocol is temporarily unavailable for reading", - throwable)); - return; - } - if (response.getSuccess()) { - future.complete(response); - } - else { - future.completeExceptionally(new ConsistencyException( - "The conformance protocol is temporarily unavailable for reading, " - + response.getErrMsg())); - } - } - }); - } - - public CompletableFuture commit(final String group, final Message data, - final CompletableFuture future) { - LoggerUtils - .printIfDebugEnabled(Loggers.RAFT, "data requested this time : {}", data); - final RaftGroupTuple tuple = findTupleByGroup(group); - if (tuple == null) { - future.completeExceptionally(new IllegalArgumentException( - "No corresponding Raft Group found : " + group)); - return future; - } - - FailoverClosureImpl closure = new FailoverClosureImpl(future); - - final Node node = tuple.node; - if (node.isLeader()) { - // The leader node directly applies this request - applyOperation(node, data, closure); - } - else { - // Forward to Leader for request processing - invokeToLeader(group, data, rpcRequestTimeoutMs, closure); - } - return future; - } - - /** - * Add yourself to the Raft cluster - * - * @param groupId raft group - * @param selfIp local raft node address - * @param conf {@link Configuration} without self info - * @return join success - */ - void registerSelfToCluster(String groupId, PeerId selfIp, Configuration conf) { - for (; ; ) { - List peerIds = cliService.getPeers(groupId, conf); - if (peerIds.contains(selfIp)) { - return; - } - Status status = cliService.addPeer(groupId, conf, selfIp); - if (status.isOk()) { - return; - } - Loggers.RAFT.warn("Failed to join the cluster, retry..."); - ThreadUtils.sleep(1_000L); - } - } - - protected PeerId getLeader(final String raftGroupId) { - return RouteTable.getInstance().selectLeader(raftGroupId); - } - - synchronized void shutdown() { - if (isShutdown) { - return; - } - isShutdown = true; - try { - Loggers.RAFT - .info("========= The raft protocol is starting to close ========="); - - for (Map.Entry entry : multiRaftGroup.entrySet()) { - final RaftGroupTuple tuple = entry.getValue(); - final Node node = tuple.getNode(); - tuple.node.shutdown(); - tuple.raftGroupService.shutdown(); - } - - cliService.shutdown(); - cliClientService.shutdown(); - - Loggers.RAFT.info("========= The raft protocol has been closed ========="); - } - catch (Throwable t) { - Loggers.RAFT - .error("There was an error in the raft protocol shutdown, error : {}", - t); - } - } - - public void applyOperation(Node node, Message data, FailoverClosure closure) { - final Task task = new Task(); - task.setDone(new NacosClosure(data, status -> { - NacosClosure.NacosStatus nacosStatus = (NacosClosure.NacosStatus) status; - closure.setThrowable(nacosStatus.getThrowable()); - closure.setResponse(nacosStatus.getResponse()); - closure.run(nacosStatus); - })); - task.setData(ByteBuffer.wrap(data.toByteArray())); - node.apply(task); - } - - private void invokeToLeader(final String group, final Message request, - final int timeoutMillis, FailoverClosure closure) { - try { - final Endpoint leaderIp = Optional.ofNullable(getLeader(group)) - .orElseThrow(() -> new NoLeaderException(group)).getEndpoint(); - cliClientService.getRpcClient() - .invokeAsync(leaderIp, request, new InvokeCallback() { - @Override - public void complete(Object o, Throwable ex) { - if (Objects.nonNull(ex)) { - closure.setThrowable(ex); - closure.run( - new Status(RaftError.UNKNOWN, ex.getMessage())); - return; - } - closure.setResponse((Response) o); - closure.run(Status.OK()); - } - - @Override - public Executor executor() { - return RaftExecutor.getRaftCliServiceExecutor(); - } - }, timeoutMillis); - } - catch (Exception e) { - closure.setThrowable(e); - closure.run(new Status(RaftError.UNKNOWN, e.toString())); - } - } - - boolean peerChange(JRaftMaintainService maintainService, Set newPeers) { - Set oldPeers = new HashSet<>(this.raftConfig.getMembers()); - oldPeers.removeAll(newPeers); - - if (oldPeers.isEmpty()) { - return true; - } - - Set waitRemove = oldPeers; - AtomicInteger successCnt = new AtomicInteger(0); - multiRaftGroup.forEach(new BiConsumer() { - @Override - public void accept(String group, RaftGroupTuple tuple) { - Map params = new HashMap<>(); - params.put(JRaftConstants.GROUP_ID, group); - params.put(JRaftConstants.COMMAND_NAME, JRaftConstants.REMOVE_PEERS); - params.put(JRaftConstants.COMMAND_VALUE, Joiner.on(",").join(waitRemove)); - RestResult result = maintainService.execute(params); - if (result.ok()) { - successCnt.incrementAndGet(); - } - else { - Loggers.RAFT.error("Node removal failed : {}", result); - } - } - }); - this.raftConfig.setMembers(localPeerId.toString(), newPeers); - - return successCnt.get() == multiRaftGroup.size(); - } - - void refreshRouteTable(String group) { - if (isShutdown) { - return; - } - - final String groupName = group; - Status status = null; - try { - RouteTable instance = RouteTable.getInstance(); - Configuration oldConf = instance.getConfiguration(groupName); - String oldLeader = Optional.ofNullable(instance.selectLeader(groupName)) - .orElse(PeerId.emptyPeer()).getEndpoint().toString(); - status = instance.refreshConfiguration(this.cliClientService, groupName, - rpcRequestTimeoutMs); - if (!status.isOk()) { - Loggers.RAFT - .error("Fail to refresh route configuration for group : {}, status is : {}", - groupName, status); - } - } - catch (Exception e) { - Loggers.RAFT - .error("Fail to refresh route configuration for group : {}, error is : {}", - groupName, e); - } - } - - public RaftGroupTuple findTupleByGroup(final String group) { - RaftGroupTuple tuple = multiRaftGroup.get(group); - return tuple; - } - - public Node findNodeByGroup(final String group) { - final RaftGroupTuple tuple = multiRaftGroup.get(group); - if (Objects.nonNull(tuple)) { - return tuple.node; - } - return null; - } - - Map getMultiRaftGroup() { - return multiRaftGroup; - } - - CliService getCliService() { - return cliService; - } - - public static class RaftGroupTuple { - - private LogProcessor processor; - private Node node; - private RaftGroupService raftGroupService; - private NacosStateMachine machine; - - @JustForTest - public RaftGroupTuple() { - } - - public RaftGroupTuple(Node node, LogProcessor processor, - RaftGroupService raftGroupService, NacosStateMachine machine) { - this.node = node; - this.processor = processor; - this.raftGroupService = raftGroupService; - this.machine = machine; - } - - public Node getNode() { - return node; - } - - public LogProcessor getProcessor() { - return processor; - } - - public RaftGroupService getRaftGroupService() { - return raftGroupService; - } - } - + + // Existential life cycle + + static { + // Set bolt buffer + // System.getProperties().setProperty("bolt.channel_write_buf_low_water_mark", String.valueOf(64 * 1024 * 1024)); + // System.getProperties().setProperty("bolt.channel_write_buf_high_water_mark", String.valueOf(256 * 1024 * 1024)); + + System.getProperties().setProperty("bolt.netty.buffer.low.watermark", String.valueOf(128 * 1024 * 1024)); + System.getProperties().setProperty("bolt.netty.buffer.high.watermark", String.valueOf(256 * 1024 * 1024)); + } + + private RpcServer rpcServer; + + private CliClientServiceImpl cliClientService; + + private CliService cliService; + + // Ordinary member variable + + private Map multiRaftGroup = new ConcurrentHashMap<>(); + + private volatile boolean isStarted = false; + + private volatile boolean isShutdown = false; + + private Configuration conf; + + private RpcProcessor userProcessor; + + private NodeOptions nodeOptions; + + private Serializer serializer; + + private Collection processors = Collections.synchronizedSet(new HashSet<>()); + + private String selfIp; + + private int selfPort; + + private RaftConfig raftConfig; + + private PeerId localPeerId; + + private int failoverRetries; + + private int rpcRequestTimeoutMs; + + public JRaftServer() { + this.conf = new Configuration(); + } + + public void setFailoverRetries(int failoverRetries) { + this.failoverRetries = failoverRetries; + } + + void init(RaftConfig config) { + this.raftConfig = config; + this.serializer = SerializeFactory.getDefault(); + Loggers.RAFT.info("Initializes the Raft protocol, raft-config info : {}", config); + RaftExecutor.init(config); + + final String self = config.getSelfMember(); + String[] info = self.split(":"); + selfIp = info[0]; + selfPort = Integer.parseInt(info[1]); + localPeerId = PeerId.parsePeer(self); + nodeOptions = new NodeOptions(); + + // Set the election timeout time. The default is 5 seconds. + int electionTimeout = Math.max(ConvertUtils.toInt(config.getVal(RaftSysConstants.RAFT_ELECTION_TIMEOUT_MS), + RaftSysConstants.DEFAULT_ELECTION_TIMEOUT), RaftSysConstants.DEFAULT_ELECTION_TIMEOUT); + + rpcRequestTimeoutMs = ConvertUtils.toInt(raftConfig.getVal(RaftSysConstants.RAFT_RPC_REQUEST_TIMEOUT_MS), + RaftSysConstants.DEFAULT_RAFT_RPC_REQUEST_TIMEOUT_MS); + + nodeOptions.setSharedElectionTimer(true); + nodeOptions.setSharedVoteTimer(true); + nodeOptions.setSharedStepDownTimer(true); + nodeOptions.setSharedSnapshotTimer(true); + + nodeOptions.setElectionTimeoutMs(electionTimeout); + RaftOptions raftOptions = RaftOptionsBuilder.initRaftOptions(raftConfig); + nodeOptions.setRaftOptions(raftOptions); + // open jraft node metrics record function + nodeOptions.setEnableMetrics(true); + + CliOptions cliOptions = new CliOptions(); + + this.cliClientService = new CliClientServiceImpl(); + this.cliClientService.init(cliOptions); + this.cliService = RaftServiceFactory.createAndInitCliService(cliOptions); + } + + synchronized void start() { + if (!isStarted) { + Loggers.RAFT.info("========= The raft protocol is starting... ========="); + try { + // init raft group node + com.alipay.sofa.jraft.NodeManager raftNodeManager = com.alipay.sofa.jraft.NodeManager.getInstance(); + for (String address : raftConfig.getMembers()) { + PeerId peerId = PeerId.parsePeer(address); + conf.addPeer(peerId); + raftNodeManager.addAddress(peerId.getEndpoint()); + } + nodeOptions.setInitialConf(conf); + + rpcServer = JRaftUtils.initRpcServer(this, localPeerId); + + if (!this.rpcServer.init(null)) { + Loggers.RAFT.error("Fail to init [RpcServer]."); + throw new RuntimeException("Fail to init [RpcServer]."); + } + + // Initialize multi raft group service framework + isStarted = true; + createMultiRaftGroup(processors); + Loggers.RAFT.info("========= The raft protocol start finished... ========="); + } catch (Exception e) { + Loggers.RAFT.error("raft protocol start failure, error : {}", e); + throw new JRaftException(e); + } + } + } + + synchronized void createMultiRaftGroup(Collection processors) { + // There is no reason why the LogProcessor cannot be processed because of the synchronization + if (!this.isStarted) { + this.processors.addAll(processors); + return; + } + + final String parentPath = Paths.get(ApplicationUtils.getNacosHome(), "data/protocol/raft").toString(); + + for (LogProcessor4CP processor : processors) { + final String groupName = processor.group(); + if (multiRaftGroup.containsKey(groupName)) { + throw new DuplicateRaftGroupException(groupName); + } + + // Ensure that each Raft Group has its own configuration and NodeOptions + Configuration configuration = conf.copy(); + NodeOptions copy = nodeOptions.copy(); + JRaftUtils.initDirectory(parentPath, groupName, copy); + + // Here, the LogProcessor is passed into StateMachine, and when the StateMachine + // triggers onApply, the onApply of the LogProcessor is actually called + NacosStateMachine machine = new NacosStateMachine(this, processor); + + copy.setFsm(machine); + copy.setInitialConf(configuration); + + // Set snapshot interval, default 1800 seconds + int doSnapshotInterval = ConvertUtils.toInt(raftConfig.getVal(RaftSysConstants.RAFT_SNAPSHOT_INTERVAL_SECS), + RaftSysConstants.DEFAULT_RAFT_SNAPSHOT_INTERVAL_SECS); + + // If the business module does not implement a snapshot processor, cancel the snapshot + doSnapshotInterval = CollectionUtils.isEmpty(processor.loadSnapshotOperate()) ? 0 : doSnapshotInterval; + + copy.setSnapshotIntervalSecs(doSnapshotInterval); + Loggers.RAFT.info("create raft group : {}", groupName); + RaftGroupService raftGroupService = new RaftGroupService(groupName, localPeerId, copy, rpcServer, true); + + // Because RpcServer has been started before, it is not allowed to start again here + Node node = raftGroupService.start(false); + machine.setNode(node); + RouteTable.getInstance().updateConfiguration(groupName, configuration); + + RaftExecutor.executeByCommon(() -> registerSelfToCluster(groupName, localPeerId, configuration)); + + // Turn on the leader auto refresh for this group + Random random = new Random(); + long period = nodeOptions.getElectionTimeoutMs() + random.nextInt(5 * 1000); + RaftExecutor.scheduleRaftMemberRefreshJob(() -> refreshRouteTable(groupName), + nodeOptions.getElectionTimeoutMs(), period, TimeUnit.MILLISECONDS); + multiRaftGroup.put(groupName, new RaftGroupTuple(node, processor, raftGroupService, machine)); + } + } + + CompletableFuture get(final GetRequest request) { + final String group = request.getGroup(); + CompletableFuture future = new CompletableFuture<>(); + final RaftGroupTuple tuple = findTupleByGroup(group); + if (Objects.isNull(tuple)) { + future.completeExceptionally(new NoSuchRaftGroupException(group)); + return future; + } + final Node node = tuple.node; + final LogProcessor processor = tuple.processor; + try { + node.readIndex(BytesUtil.EMPTY_BYTES, new ReadIndexClosure() { + @Override + public void run(Status status, long index, byte[] reqCtx) { + if (status.isOk()) { + try { + Response response = processor.onRequest(request); + future.complete(response); + } catch (Throwable t) { + MetricsMonitor.raftReadIndexFailed(); + future.completeExceptionally(new ConsistencyException( + "The conformance protocol is temporarily unavailable for reading", t)); + } + return; + } + MetricsMonitor.raftReadIndexFailed(); + Loggers.RAFT.error("ReadIndex has error : {}", status.getErrorMsg()); + future.completeExceptionally(new ConsistencyException( + "The conformance protocol is temporarily unavailable for reading, " + status + .getErrorMsg())); + } + }); + return future; + } catch (Throwable e) { + MetricsMonitor.raftReadFromLeader(); + Loggers.RAFT.warn("Raft linear read failed, go to Leader read logic : {}", e.toString()); + // run raft read + readFromLeader(request, future); + return future; + } + } + + public void readFromLeader(final GetRequest request, final CompletableFuture future) { + commit(request.getGroup(), request, future).whenComplete(new BiConsumer() { + @Override + public void accept(Response response, Throwable throwable) { + if (Objects.nonNull(throwable)) { + future.completeExceptionally( + new ConsistencyException("The conformance protocol is temporarily unavailable for reading", + throwable)); + return; + } + if (response.getSuccess()) { + future.complete(response); + } else { + future.completeExceptionally(new ConsistencyException( + "The conformance protocol is temporarily unavailable for reading, " + response + .getErrMsg())); + } + } + }); + } + + public CompletableFuture commit(final String group, final Message data, + final CompletableFuture future) { + LoggerUtils.printIfDebugEnabled(Loggers.RAFT, "data requested this time : {}", data); + final RaftGroupTuple tuple = findTupleByGroup(group); + if (tuple == null) { + future.completeExceptionally(new IllegalArgumentException("No corresponding Raft Group found : " + group)); + return future; + } + + FailoverClosureImpl closure = new FailoverClosureImpl(future); + + final Node node = tuple.node; + if (node.isLeader()) { + // The leader node directly applies this request + applyOperation(node, data, closure); + } else { + // Forward to Leader for request processing + invokeToLeader(group, data, rpcRequestTimeoutMs, closure); + } + return future; + } + + /** + * Add yourself to the Raft cluster + * + * @param groupId raft group + * @param selfIp local raft node address + * @param conf {@link Configuration} without self info + * @return join success + */ + void registerSelfToCluster(String groupId, PeerId selfIp, Configuration conf) { + for (; ; ) { + List peerIds = cliService.getPeers(groupId, conf); + if (peerIds.contains(selfIp)) { + return; + } + Status status = cliService.addPeer(groupId, conf, selfIp); + if (status.isOk()) { + return; + } + Loggers.RAFT.warn("Failed to join the cluster, retry..."); + ThreadUtils.sleep(1_000L); + } + } + + protected PeerId getLeader(final String raftGroupId) { + return RouteTable.getInstance().selectLeader(raftGroupId); + } + + synchronized void shutdown() { + if (isShutdown) { + return; + } + isShutdown = true; + try { + Loggers.RAFT.info("========= The raft protocol is starting to close ========="); + + for (Map.Entry entry : multiRaftGroup.entrySet()) { + final RaftGroupTuple tuple = entry.getValue(); + final Node node = tuple.getNode(); + tuple.node.shutdown(); + tuple.raftGroupService.shutdown(); + } + + cliService.shutdown(); + cliClientService.shutdown(); + + Loggers.RAFT.info("========= The raft protocol has been closed ========="); + } catch (Throwable t) { + Loggers.RAFT.error("There was an error in the raft protocol shutdown, error : {}", t); + } + } + + public void applyOperation(Node node, Message data, FailoverClosure closure) { + final Task task = new Task(); + task.setDone(new NacosClosure(data, status -> { + NacosClosure.NacosStatus nacosStatus = (NacosClosure.NacosStatus) status; + closure.setThrowable(nacosStatus.getThrowable()); + closure.setResponse(nacosStatus.getResponse()); + closure.run(nacosStatus); + })); + task.setData(ByteBuffer.wrap(data.toByteArray())); + node.apply(task); + } + + private void invokeToLeader(final String group, final Message request, final int timeoutMillis, + FailoverClosure closure) { + try { + final Endpoint leaderIp = Optional.ofNullable(getLeader(group)) + .orElseThrow(() -> new NoLeaderException(group)).getEndpoint(); + cliClientService.getRpcClient().invokeAsync(leaderIp, request, new InvokeCallback() { + @Override + public void complete(Object o, Throwable ex) { + if (Objects.nonNull(ex)) { + closure.setThrowable(ex); + closure.run(new Status(RaftError.UNKNOWN, ex.getMessage())); + return; + } + closure.setResponse((Response) o); + closure.run(Status.OK()); + } + + @Override + public Executor executor() { + return RaftExecutor.getRaftCliServiceExecutor(); + } + }, timeoutMillis); + } catch (Exception e) { + closure.setThrowable(e); + closure.run(new Status(RaftError.UNKNOWN, e.toString())); + } + } + + boolean peerChange(JRaftMaintainService maintainService, Set newPeers) { + Set oldPeers = new HashSet<>(this.raftConfig.getMembers()); + oldPeers.removeAll(newPeers); + + if (oldPeers.isEmpty()) { + return true; + } + + Set waitRemove = oldPeers; + AtomicInteger successCnt = new AtomicInteger(0); + multiRaftGroup.forEach(new BiConsumer() { + @Override + public void accept(String group, RaftGroupTuple tuple) { + Map params = new HashMap<>(); + params.put(JRaftConstants.GROUP_ID, group); + params.put(JRaftConstants.COMMAND_NAME, JRaftConstants.REMOVE_PEERS); + params.put(JRaftConstants.COMMAND_VALUE, Joiner.on(",").join(waitRemove)); + RestResult result = maintainService.execute(params); + if (result.ok()) { + successCnt.incrementAndGet(); + } else { + Loggers.RAFT.error("Node removal failed : {}", result); + } + } + }); + this.raftConfig.setMembers(localPeerId.toString(), newPeers); + + return successCnt.get() == multiRaftGroup.size(); + } + + void refreshRouteTable(String group) { + if (isShutdown) { + return; + } + + final String groupName = group; + Status status = null; + try { + RouteTable instance = RouteTable.getInstance(); + Configuration oldConf = instance.getConfiguration(groupName); + String oldLeader = Optional.ofNullable(instance.selectLeader(groupName)).orElse(PeerId.emptyPeer()) + .getEndpoint().toString(); + status = instance.refreshConfiguration(this.cliClientService, groupName, rpcRequestTimeoutMs); + if (!status.isOk()) { + Loggers.RAFT + .error("Fail to refresh route configuration for group : {}, status is : {}", groupName, status); + } + } catch (Exception e) { + Loggers.RAFT.error("Fail to refresh route configuration for group : {}, error is : {}", groupName, e); + } + } + + public RaftGroupTuple findTupleByGroup(final String group) { + RaftGroupTuple tuple = multiRaftGroup.get(group); + return tuple; + } + + public Node findNodeByGroup(final String group) { + final RaftGroupTuple tuple = multiRaftGroup.get(group); + if (Objects.nonNull(tuple)) { + return tuple.node; + } + return null; + } + + Map getMultiRaftGroup() { + return multiRaftGroup; + } + + CliService getCliService() { + return cliService; + } + + public static class RaftGroupTuple { + + private LogProcessor processor; + + private Node node; + + private RaftGroupService raftGroupService; + + private NacosStateMachine machine; + + @JustForTest + public RaftGroupTuple() { + } + + public RaftGroupTuple(Node node, LogProcessor processor, RaftGroupService raftGroupService, + NacosStateMachine machine) { + this.node = node; + this.processor = processor; + this.raftGroupService = raftGroupService; + this.machine = machine; + } + + public Node getNode() { + return node; + } + + public LogProcessor getProcessor() { + return processor; + } + + public RaftGroupService getRaftGroupService() { + return raftGroupService; + } + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JSnapshotOperation.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JSnapshotOperation.java index 29d34be53d9..3fb58926d4b 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JSnapshotOperation.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/JSnapshotOperation.java @@ -25,46 +25,46 @@ import com.google.protobuf.ZeroByteStringHelper; /** + * JRaft snapshot operation. + * * @author liaochuntao */ -@SuppressWarnings("all") +@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule") interface JSnapshotOperation { - + /** - * do snapshot save operation + * do snapshot save operation. * * @param writer {@link SnapshotWriter} * @param done {@link Closure} */ void onSnapshotSave(SnapshotWriter writer, Closure done); - + /** - * do snapshot load operation + * do snapshot load operation. * * @param reader {@link SnapshotReader} * @return operation label */ boolean onSnapshotLoad(SnapshotReader reader); - + /** - * return actually snapshot executor + * return actually snapshot executor. * * @return name */ String info(); - + /** - * Metadata information for snapshot files + * Metadata information for snapshot files. * * @param metadata meta data - * @param type * @return {@link LocalFileMetaOutter.LocalFileMeta} + * @throws Exception Exception */ default LocalFileMetaOutter.LocalFileMeta buildMetadata(final LocalFileMeta metadata) throws Exception { - return metadata == null ? null - : LocalFileMetaOutter.LocalFileMeta.newBuilder() - .setUserMeta(ZeroByteStringHelper.wrap(JacksonUtils.toJsonBytes(metadata))) - .build(); + return metadata == null ? null : LocalFileMetaOutter.LocalFileMeta.newBuilder() + .setUserMeta(ZeroByteStringHelper.wrap(JacksonUtils.toJsonBytes(metadata))).build(); } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/NacosClosure.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/NacosClosure.java index 515b5303a28..bfd026fd384 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/NacosClosure.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/NacosClosure.java @@ -23,97 +23,96 @@ import com.google.protobuf.Message; /** + * implement jraft closure. + * * @author liaochuntao */ public class NacosClosure implements Closure { - + private final Message message; + private final Closure closure; + private final NacosStatus nacosStatus = new NacosStatus(); - + public NacosClosure(Message message, Closure closure) { this.message = message; this.closure = closure; } - + @Override public void run(Status status) { nacosStatus.setStatus(status); closure.run(nacosStatus); } - + public void setResponse(Response response) { this.nacosStatus.setResponse(response); } - + public void setThrowable(Throwable throwable) { this.nacosStatus.setThrowable(throwable); } - + public Message getMessage() { return message; } - + // Pass the Throwable inside the state machine to the outer layer - + @SuppressWarnings("PMD.ClassNamingShouldBeCamelRule") public static class NacosStatus extends Status { - + private Status status; - + private Response response = null; - + private Throwable throwable = null; - + public void setStatus(Status status) { this.status = status; } - + @Override public void reset() { status.reset(); } - + @Override public boolean isOk() { return status.isOk(); } - - @Override - public void setCode(int code) { - status.setCode(code); - } - + @Override public int getCode() { return status.getCode(); } - + @Override - public RaftError getRaftError() { - return status.getRaftError(); + public void setCode(int code) { + status.setCode(code); } - + @Override - public void setErrorMsg(String errMsg) { - status.setErrorMsg(errMsg); + public RaftError getRaftError() { + return status.getRaftError(); } - + @Override public void setError(int code, String fmt, Object... args) { status.setError(code, fmt, args); } - + @Override public void setError(RaftError error, String fmt, Object... args) { status.setError(error, fmt, args); } - + @Override public String toString() { return status.toString(); } - + @Override public Status copy() { NacosStatus copy = new NacosStatus(); @@ -122,28 +121,32 @@ public Status copy() { copy.throwable = this.throwable; return copy; } - + @Override public String getErrorMsg() { return status.getErrorMsg(); } - + + @Override + public void setErrorMsg(String errMsg) { + status.setErrorMsg(errMsg); + } + public Response getResponse() { return response; } - + public void setResponse(Response response) { this.response = response; } - + public Throwable getThrowable() { return throwable; } - + public void setThrowable(Throwable throwable) { this.throwable = throwable; } - - + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/NacosStateMachine.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/NacosStateMachine.java index d62f2159937..2651b759704 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/NacosStateMachine.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/NacosStateMachine.java @@ -61,274 +61,265 @@ import java.util.function.BiConsumer; /** + * JRaft StateMachine implemented. + * * @author liaochuntao */ class NacosStateMachine extends StateMachineAdapter { - - protected final JRaftServer server; - protected final LogProcessor processor; - private final AtomicBoolean isLeader = new AtomicBoolean(false); - private final String groupId; - private Collection operations; - private Node node; - private volatile long term = -1; - private volatile String leaderIp = "unknown"; - - NacosStateMachine(JRaftServer server, LogProcessor4CP processor) { - this.server = server; - this.processor = processor; - this.groupId = processor.group(); - adapterToJRaftSnapshot(processor.loadSnapshotOperate()); - } - - @Override - public void onApply(Iterator iter) { - int index = 0; - int applied = 0; - Message message = null; - NacosClosure closure = null; - try { - while (iter.hasNext()) { - Status status = Status.OK(); - try { - if (iter.done() != null) { - closure = (NacosClosure) iter.done(); - message = closure.getMessage(); - } - else { - final ByteBuffer data = iter.getData(); - message = parse(data.array()); - } - - LoggerUtils.printIfDebugEnabled(Loggers.RAFT, "receive log : {}", message); - - if (message instanceof Log) { - Response response = processor.onApply((Log) message); - postProcessor(response, closure); - } - - if (message instanceof GetRequest) { - Response response = processor.onRequest((GetRequest) message); - postProcessor(response, closure); - } - } - catch (Throwable e) { - index++; - status.setError(RaftError.UNKNOWN, e.toString()); - Optional.ofNullable(closure) - .ifPresent(closure1 -> closure1.setThrowable(e)); - throw e; - } - finally { - Optional.ofNullable(closure) - .ifPresent(closure1 -> closure1.run(status)); - } - - applied++; - index++; - iter.next(); - } - } - catch (Throwable t) { - Loggers.RAFT.error("processor : {}, stateMachine meet critical error: {}.", - processor, t); - iter.setErrorAndRollback(index - applied, new Status(RaftError.ESTATEMACHINE, - "StateMachine meet critical error: %s.", ExceptionUtil.getStackTrace(t))); - } - } - - private Message parse(byte[] bytes) { - Message result = null; - try { - result = Log.parseFrom(bytes); - return result; - } catch (Throwable ignore) { } - - try { - result = GetRequest.parseFrom(bytes); - return result; - } catch (Throwable ignore) {} - - throw new ConsistencyException("The current array cannot be serialized to the corresponding object"); - } - - public void setNode(Node node) { - this.node = node; - } - - @Override - public void onSnapshotSave(SnapshotWriter writer, Closure done) { - for (JSnapshotOperation operation : operations) { - try { - operation.onSnapshotSave(writer, done); - } - catch (Throwable t) { - Loggers.RAFT - .error("There was an error saving the snapshot , error : {}, operation : {}", - t, operation.info()); - throw t; - } - } - } - - @Override - public boolean onSnapshotLoad(SnapshotReader reader) { - for (JSnapshotOperation operation : operations) { - try { - if (!operation.onSnapshotLoad(reader)) { - Loggers.RAFT.error("Snapshot load failed on : {}", operation.info()); - return false; - } - } - catch (Throwable t) { - Loggers.RAFT.error("Snapshot load failed on : {}, has error : {}", - operation.info(), t); - return false; - } - } - return true; - } - - @Override - public void onLeaderStart(final long term) { - super.onLeaderStart(term); - this.term = term; - this.isLeader.set(true); - this.leaderIp = node.getNodeId().getPeerId().getEndpoint().toString(); - NotifyCenter.publishEvent( - RaftEvent.builder().groupId(groupId).leader(leaderIp).term(term) - .raftClusterInfo(allPeers()).build()); - } - - @Override - public void onLeaderStop(final Status status) { - super.onLeaderStop(status); - this.isLeader.set(false); - } - - @Override - public void onStartFollowing(LeaderChangeContext ctx) { - this.term = ctx.getTerm(); - this.leaderIp = ctx.getLeaderId().getEndpoint().toString(); - NotifyCenter.publishEvent( - RaftEvent.builder().groupId(groupId).leader(leaderIp).term(ctx.getTerm()) - .raftClusterInfo(allPeers()).build()); - } - - @Override - public void onConfigurationCommitted(Configuration conf) { - NotifyCenter.publishEvent( - RaftEvent.builder().groupId(groupId) - .raftClusterInfo(JRaftUtils.toStrings(conf.getPeers())).build()); - } - - @Override - public void onError(RaftException e) { - super.onError(e); - processor.onError(e); - } - - public boolean isLeader() { - return isLeader.get(); - } - - private List allPeers() { - if (node == null) { - return Collections.emptyList(); - } - - if (node.isLeader()) { - return JRaftUtils.toStrings(node.listPeers()); - } - - return JRaftUtils.toStrings( - RouteTable.getInstance().getConfiguration(node.getGroupId()).getPeers()); - } - - private void postProcessor(Response data, NacosClosure closure) { - if (Objects.nonNull(closure)) { - closure.setResponse(data); - } - } - - public long getTerm() { - return term; - } - - private void adapterToJRaftSnapshot(Collection userOperates) { - List tmp = new ArrayList<>(); - - for (SnapshotOperation item : userOperates) { - - if (item == null) { - Loggers.RAFT.error("Existing SnapshotOperation for null"); - continue; - } - - tmp.add(new JSnapshotOperation() { - - @Override - public void onSnapshotSave(SnapshotWriter writer, Closure done) { - final Writer wCtx = new Writer(writer.getPath()); - - // Do a layer of proxy operation to shield different Raft - // components from implementing snapshots - - final BiConsumer callFinally = (result, t) -> { - boolean[] results = new boolean[wCtx.listFiles().size()]; - int[] index = new int[] { 0 }; - wCtx.listFiles().forEach((file, meta) -> { - try { - results[index[0]++] = writer - .addFile(file, buildMetadata(meta)); - } - catch (Exception e) { - throw new ConsistencyException(e); - } - }); - final Status status = result && BooleanUtils.and(results) ? - Status.OK() : - new Status(RaftError.EIO, - "Fail to compress snapshot at %s, error is %s", - writer.getPath(), - t == null ? "" : t.getMessage()); - done.run(status); - }; - item.onSnapshotSave(wCtx, callFinally); - } - - @Override - public boolean onSnapshotLoad(SnapshotReader reader) { - final Map metaMap = new HashMap<>( - reader.listFiles().size()); - for (String fileName : reader.listFiles()) { - final LocalFileMetaOutter.LocalFileMeta meta = (LocalFileMetaOutter.LocalFileMeta) reader - .getFileMeta(fileName); - - byte[] bytes = meta.getUserMeta().toByteArray(); - - final LocalFileMeta fileMeta; - if (bytes == null || bytes.length == 0) { - fileMeta = new LocalFileMeta(); - } - else { - fileMeta = JacksonUtils.toObj(bytes, LocalFileMeta.class); - } - - metaMap.put(fileName, fileMeta); - } - final Reader rCtx = new Reader(reader.getPath(), metaMap); - return item.onSnapshotLoad(rCtx); - } - - @Override - public String info() { - return item.toString(); - } - }); - } - - this.operations = Collections.unmodifiableList(tmp); - } - + + protected final JRaftServer server; + + protected final LogProcessor processor; + + private final AtomicBoolean isLeader = new AtomicBoolean(false); + + private final String groupId; + + private Collection operations; + + private Node node; + + private volatile long term = -1; + + private volatile String leaderIp = "unknown"; + + NacosStateMachine(JRaftServer server, LogProcessor4CP processor) { + this.server = server; + this.processor = processor; + this.groupId = processor.group(); + adapterToJRaftSnapshot(processor.loadSnapshotOperate()); + } + + @Override + public void onApply(Iterator iter) { + int index = 0; + int applied = 0; + Message message; + NacosClosure closure = null; + try { + while (iter.hasNext()) { + Status status = Status.OK(); + try { + if (iter.done() != null) { + closure = (NacosClosure) iter.done(); + message = closure.getMessage(); + } else { + final ByteBuffer data = iter.getData(); + message = parse(data.array()); + } + + LoggerUtils.printIfDebugEnabled(Loggers.RAFT, "receive log : {}", message); + + if (message instanceof Log) { + Response response = processor.onApply((Log) message); + postProcessor(response, closure); + } + + if (message instanceof GetRequest) { + Response response = processor.onRequest((GetRequest) message); + postProcessor(response, closure); + } + } catch (Throwable e) { + index++; + status.setError(RaftError.UNKNOWN, e.toString()); + Optional.ofNullable(closure).ifPresent(closure1 -> closure1.setThrowable(e)); + throw e; + } finally { + Optional.ofNullable(closure).ifPresent(closure1 -> closure1.run(status)); + } + + applied++; + index++; + iter.next(); + } + } catch (Throwable t) { + Loggers.RAFT.error("processor : {}, stateMachine meet critical error: {}.", processor, t); + iter.setErrorAndRollback(index - applied, + new Status(RaftError.ESTATEMACHINE, "StateMachine meet critical error: %s.", + ExceptionUtil.getStackTrace(t))); + } + } + + private Message parse(byte[] bytes) { + Message result; + try { + result = Log.parseFrom(bytes); + return result; + } catch (Throwable ignore) { + } + + try { + result = GetRequest.parseFrom(bytes); + return result; + } catch (Throwable ignore) { + } + + throw new ConsistencyException("The current array cannot be serialized to the corresponding object"); + } + + public void setNode(Node node) { + this.node = node; + } + + @Override + public void onSnapshotSave(SnapshotWriter writer, Closure done) { + for (JSnapshotOperation operation : operations) { + try { + operation.onSnapshotSave(writer, done); + } catch (Throwable t) { + Loggers.RAFT.error("There was an error saving the snapshot , error : {}, operation : {}", t, + operation.info()); + throw t; + } + } + } + + @Override + public boolean onSnapshotLoad(SnapshotReader reader) { + for (JSnapshotOperation operation : operations) { + try { + if (!operation.onSnapshotLoad(reader)) { + Loggers.RAFT.error("Snapshot load failed on : {}", operation.info()); + return false; + } + } catch (Throwable t) { + Loggers.RAFT.error("Snapshot load failed on : {}, has error : {}", operation.info(), t); + return false; + } + } + return true; + } + + @Override + public void onLeaderStart(final long term) { + super.onLeaderStart(term); + this.term = term; + this.isLeader.set(true); + this.leaderIp = node.getNodeId().getPeerId().getEndpoint().toString(); + NotifyCenter.publishEvent( + RaftEvent.builder().groupId(groupId).leader(leaderIp).term(term).raftClusterInfo(allPeers()).build()); + } + + @Override + public void onLeaderStop(final Status status) { + super.onLeaderStop(status); + this.isLeader.set(false); + } + + @Override + public void onStartFollowing(LeaderChangeContext ctx) { + this.term = ctx.getTerm(); + this.leaderIp = ctx.getLeaderId().getEndpoint().toString(); + NotifyCenter.publishEvent( + RaftEvent.builder().groupId(groupId).leader(leaderIp).term(ctx.getTerm()).raftClusterInfo(allPeers()) + .build()); + } + + @Override + public void onConfigurationCommitted(Configuration conf) { + NotifyCenter.publishEvent( + RaftEvent.builder().groupId(groupId).raftClusterInfo(JRaftUtils.toStrings(conf.getPeers())).build()); + } + + @Override + public void onError(RaftException e) { + super.onError(e); + processor.onError(e); + } + + public boolean isLeader() { + return isLeader.get(); + } + + private List allPeers() { + if (node == null) { + return Collections.emptyList(); + } + + if (node.isLeader()) { + return JRaftUtils.toStrings(node.listPeers()); + } + + return JRaftUtils.toStrings(RouteTable.getInstance().getConfiguration(node.getGroupId()).getPeers()); + } + + private void postProcessor(Response data, NacosClosure closure) { + if (Objects.nonNull(closure)) { + closure.setResponse(data); + } + } + + public long getTerm() { + return term; + } + + private void adapterToJRaftSnapshot(Collection userOperates) { + List tmp = new ArrayList<>(); + + for (SnapshotOperation item : userOperates) { + + if (item == null) { + Loggers.RAFT.error("Existing SnapshotOperation for null"); + continue; + } + + tmp.add(new JSnapshotOperation() { + + @Override + public void onSnapshotSave(SnapshotWriter writer, Closure done) { + final Writer wCtx = new Writer(writer.getPath()); + + // Do a layer of proxy operation to shield different Raft + // components from implementing snapshots + + final BiConsumer callFinally = (result, t) -> { + boolean[] results = new boolean[wCtx.listFiles().size()]; + int[] index = new int[] {0}; + wCtx.listFiles().forEach((file, meta) -> { + try { + results[index[0]++] = writer.addFile(file, buildMetadata(meta)); + } catch (Exception e) { + throw new ConsistencyException(e); + } + }); + final Status status = result && BooleanUtils.and(results) ? Status.OK() + : new Status(RaftError.EIO, "Fail to compress snapshot at %s, error is %s", + writer.getPath(), t == null ? "" : t.getMessage()); + done.run(status); + }; + item.onSnapshotSave(wCtx, callFinally); + } + + @Override + public boolean onSnapshotLoad(SnapshotReader reader) { + final Map metaMap = new HashMap<>(reader.listFiles().size()); + for (String fileName : reader.listFiles()) { + final LocalFileMetaOutter.LocalFileMeta meta = (LocalFileMetaOutter.LocalFileMeta) reader + .getFileMeta(fileName); + + byte[] bytes = meta.getUserMeta().toByteArray(); + + final LocalFileMeta fileMeta; + if (bytes == null || bytes.length == 0) { + fileMeta = new LocalFileMeta(); + } else { + fileMeta = JacksonUtils.toObj(bytes, LocalFileMeta.class); + } + + metaMap.put(fileName, fileMeta); + } + final Reader rCtx = new Reader(reader.getPath(), metaMap); + return item.onSnapshotLoad(rCtx); + } + + @Override + public String info() { + return item.toString(); + } + }); + } + + this.operations = Collections.unmodifiableList(tmp); + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftConfig.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftConfig.java index 7768d094592..a605f497833 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftConfig.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftConfig.java @@ -19,6 +19,8 @@ import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.consistency.Config; import com.alibaba.nacos.consistency.cp.LogProcessor4CP; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; import java.util.Collections; import java.util.HashMap; @@ -26,72 +28,73 @@ import java.util.Map; import java.util.Set; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - /** + * raft config. + * * @author liaochuntao */ @Component @ConfigurationProperties(prefix = "nacos.core.protocol.raft") public class RaftConfig implements Config { - + private static final long serialVersionUID = 9174789390266064002L; - + private Map data = Collections.synchronizedMap(new HashMap<>()); + private String selfAddress; + private Set members = Collections.synchronizedSet(new HashSet<>()); - + @Override public void setMembers(String self, Set members) { this.selfAddress = self; this.members.clear(); this.members.addAll(members); } - + @Override public String getSelfMember() { return selfAddress; } - + @Override public Set getMembers() { return members; } - + @Override public void addMembers(Set members) { this.members.addAll(members); } - + @Override public void removeMembers(Set members) { this.members.removeAll(members); } - + public Map getData() { return data; } - + public void setData(Map data) { this.data = Collections.synchronizedMap(data); } - + @Override public void setVal(String key, String value) { data.put(key, value); } - + @Override public String getVal(String key) { return data.get(key); } - + @Override public String getValOfDefault(String key, String defaultVal) { return data.getOrDefault(key, defaultVal); } - + @Override public String toString() { try { diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftErrorEvent.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftErrorEvent.java index fd4ad70801f..40cfbf94ad9 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftErrorEvent.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftErrorEvent.java @@ -19,9 +19,22 @@ import com.alibaba.nacos.core.notify.Event; /** + * The RAFT protocol runs an exception event. If this event is published, it means that the current raft Group cannot + * continue to run normally + * * @author liaochuntao */ public class RaftErrorEvent implements Event { + private static final long serialVersionUID = 3016514657754158167L; - + + private String groupName; + + public String getGroupName() { + return groupName; + } + + public void setGroupName(String groupName) { + this.groupName = groupName; + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftEvent.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftEvent.java index b94d6265b2d..b2fcc3b41b7 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftEvent.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftEvent.java @@ -22,85 +22,98 @@ import java.util.List; /** + * Changes to metadata information during the raft protocol run. + * * @author liaochuntao */ +@SuppressWarnings("all") public class RaftEvent implements SlowEvent { - + private static final long serialVersionUID = -4304258594602886451L; - + private String groupId; - + private String leader = null; - + private Long term = null; - + private List raftClusterInfo = Collections.emptyList(); - + public static RaftEventBuilder builder() { return new RaftEventBuilder(); } - + public String getGroupId() { return groupId; } - + public void setGroupId(String groupId) { this.groupId = groupId; } - + public String getLeader() { return leader; } - + public void setLeader(String leader) { this.leader = leader; } - + public Long getTerm() { return term; } - + public void setTerm(Long term) { this.term = term; } - + public List getRaftClusterInfo() { return raftClusterInfo; } - + public void setRaftClusterInfo(List raftClusterInfo) { this.raftClusterInfo = raftClusterInfo; } - + + @Override + public String toString() { + return "RaftEvent{" + "groupId='" + groupId + '\'' + ", leader='" + leader + '\'' + ", term=" + term + + ", raftClusterInfo=" + raftClusterInfo + '}'; + } + public static final class RaftEventBuilder { + private String groupId; + private String leader; + private Long term = null; + private List raftClusterInfo = Collections.emptyList(); - + private RaftEventBuilder() { } - + public RaftEventBuilder groupId(String groupId) { this.groupId = groupId; return this; } - + public RaftEventBuilder leader(String leader) { this.leader = leader; return this; } - + public RaftEventBuilder term(long term) { this.term = term; return this; } - + public RaftEventBuilder raftClusterInfo(List raftClusterInfo) { this.raftClusterInfo = raftClusterInfo; return this; } - + public RaftEvent build() { RaftEvent raftEvent = new RaftEvent(); raftEvent.setGroupId(groupId); @@ -110,10 +123,4 @@ public RaftEvent build() { return raftEvent; } } - - @Override - public String toString() { - return "RaftEvent{" + "groupId='" + groupId + '\'' + ", leader='" + leader + '\'' - + ", term=" + term + ", raftClusterInfo=" + raftClusterInfo + '}'; - } } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftSysConstants.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftSysConstants.java index 80c796c35c6..5ac21a0491a 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftSysConstants.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/RaftSysConstants.java @@ -17,204 +17,216 @@ package com.alibaba.nacos.core.distributed.raft; /** + * jraft system constants. + * * @author liaochuntao */ +@SuppressWarnings("all") public final class RaftSysConstants { - + // ========= default setting value ========= // - + /** * {@link RaftSysConstants#RAFT_ELECTION_TIMEOUT_MS} */ public static final int DEFAULT_ELECTION_TIMEOUT = 5000; - + /** * {@link RaftSysConstants#RAFT_SNAPSHOT_INTERVAL_SECS} */ public static final int DEFAULT_RAFT_SNAPSHOT_INTERVAL_SECS = 30 * 60; - + /** * {@link RaftSysConstants#RAFT_CLI_SERVICE_THREAD_NUM} */ public static final int DEFAULT_RAFT_CLI_SERVICE_THREAD_NUM = 8; - + /** * {@link RaftSysConstants#RAFT_READ_INDEX_TYPE} */ public static final String DEFAULT_READ_INDEX_TYPE = "ReadOnlySafe"; - + /** * {@link RaftSysConstants#RAFT_RPC_REQUEST_TIMEOUT_MS} */ public static final int DEFAULT_RAFT_RPC_REQUEST_TIMEOUT_MS = 5000; - + /** - * The maximum size of each file RPC (snapshot copy) request between nodes is 128 K by default - * 节点之间每次文件 RPC (snapshot拷贝)请求的最大大小,默认为 128 K + * The maximum size of each file RPC (snapshot copy) request between nodes is 128 K by default 节点之间每次文件 RPC + * (snapshot拷贝)请求的最大大小,默认为 128 K */ public static final int DEFAULT_MAX_BYTE_COUNT_PER_RPC = 128 * 1024; + /** - * The maximum number of logs sent from the leader to the followers is 1024 by default - * 从 leader 往 follower 发送的最大日志个数,默认 1024 + * The maximum number of logs sent from the leader to the followers is 1024 by default 从 leader 往 follower + * 发送的最大日志个数,默认 1024 */ public static final int DEFAULT_MAX_ENTRIES_SIZE = 1024; + /** - * The maximum body size of the log sent from the leader to the followers is 512K by default - * 从 leader 往 follower 发送日志的最大 body 大小,默认 512K + * The maximum body size of the log sent from the leader to the followers is 512K by default 从 leader 往 follower + * 发送日志的最大 body 大小,默认 512K */ public static final int DEFAULT_MAX_BODY_SIZE = 512 * 1024; + /** - * The maximum size of the log storage buffer is 256K by default - * 日志存储缓冲区最大大小,默认256K + * The maximum size of the log storage buffer is 256K by default 日志存储缓冲区最大大小,默认256K */ public static final int DEFAULT_MAX_APPEND_BUFFER_SIZE = 256 * 1024; + /** * The election timer interval will be a random maximum outside the specified time, 1 second by default * 选举定时器间隔会在指定时间之外随机的最大范围,默认1秒 */ public static final int DEFAULT_MAX_ELECTION_DELAY_MS = 1000; + /** - * Specifies the ratio of the election timeout to the heartbeat interval. Heartbeat interval is equal to the electionTimeoutMs/electionHeartbeatFactor, default one of 10 points. - * 指定选举超时时间和心跳间隔时间之间的比值。心跳间隔等于electionTimeoutMs/electionHeartbeatFactor,默认10分之一。 + * Specifies the ratio of the election timeout to the heartbeat interval. Heartbeat interval is equal to the + * electionTimeoutMs/electionHeartbeatFactor, default one of 10 points. 指定选举超时时间和心跳间隔时间之间的比值。心跳间隔等于electionTimeoutMs/electionHeartbeatFactor,默认10分之一。 */ public static final int DEFAULT_ELECTION_HEARTBEAT_FACTOR = 10; + /** - * The tasks submitted to the leader will accumulate one batch into the maximum batch size stored in the log, and 32 tasks will be assigned by default - * 向 leader 提交的任务累积一个批次刷入日志存储的最大批次大小,默认 32 个任务 + * The tasks submitted to the leader will accumulate one batch into the maximum batch size stored in the log, and 32 + * tasks will be assigned by default 向 leader 提交的任务累积一个批次刷入日志存储的最大批次大小,默认 32 个任务 */ public static final int DEFAULT_APPLY_BATCH = 32; + /** - * Call fsync when necessary when writing log, meta information, and it should always be true - * 写入日志、元信息的时候必要的时候调用 fsync,通常都应该为 true + * Call fsync when necessary when writing log, meta information, and it should always be true 写入日志、元信息的时候必要的时候调用 + * fsync,通常都应该为 true */ public static final boolean DEFAULT_SYNC = true; + /** - * If fsync is called by writing snapshot/raft information, the default is false. If sync is true, it is better to respect sync - * 写入 snapshot/raft 元信息是否调用 fsync,默认为 false,在 sync 为 true 的情况下,优选尊重 sync + * If fsync is called by writing snapshot/raft information, the default is false. If sync is true, it is better to + * respect sync 写入 snapshot/raft 元信息是否调用 fsync,默认为 false,在 sync 为 true 的情况下,优选尊重 sync */ public static final boolean DEFAULT_SYNC_META = false; + /** - * Internal disruptor buffer size, need to be appropriately adjusted for high write throughput applications, default 16384 - * 内部 disruptor buffer 大小,如果是写入吞吐量较高的应用,需要适当调高该值,默认 16384 + * Internal disruptor buffer size, need to be appropriately adjusted for high write throughput applications, default + * 16384 内部 disruptor buffer 大小,如果是写入吞吐量较高的应用,需要适当调高该值,默认 16384 */ public static final int DEFAULT_DISRUPTOR_BUFFER_SIZE = 16384; + /** - * Whether to enable replicated pipeline request optimization by default - * 是否启用复制的 pipeline 请求优化,默认打开 + * Whether to enable replicated pipeline request optimization by default 是否启用复制的 pipeline 请求优化,默认打开 */ public static final boolean DEFAULT_REPLICATOR_PIPELINE = true; + /** - * Maximum in-flight requests with pipeline requests enabled, 256 by default - * 在启用 pipeline 请求情况下,最大 in-flight 请求数,默认256 + * Maximum in-flight requests with pipeline requests enabled, 256 by default 在启用 pipeline 请求情况下,最大 in-flight + * 请求数,默认256 */ public static final int DEFAULT_MAX_REPLICATOR_INFLIGHT_MSGS = 256; + /** - * Whether LogEntry checksum is enabled - * 是否启用 LogEntry checksum + * Whether LogEntry checksum is enabled 是否启用 LogEntry checksum */ public static final boolean DEFAULT_ENABLE_LOG_ENTRY_CHECKSUM = false; - + // ========= setting key ========= // - + /** * Election timeout in milliseconds */ public static final String RAFT_ELECTION_TIMEOUT_MS = "election_timeout_ms"; - + /** * Snapshot interval in seconds */ public static final String RAFT_SNAPSHOT_INTERVAL_SECS = "snapshot_interval_secs"; - + /** * Requested retries */ public static final String REQUEST_FAILOVER_RETRIES = "request_failoverRetries"; - + /** * raft internal worker threads */ public static final String RAFT_CORE_THREAD_NUM = "core_thread_num"; - + /** * Number of threads required for raft business request processing */ public static final String RAFT_CLI_SERVICE_THREAD_NUM = "cli_service_thread_num"; - + /** * raft linear read strategy, defaults to index */ public static final String RAFT_READ_INDEX_TYPE = "read_index_type"; - + /** * rpc request timeout, default 5 seconds */ public static final String RAFT_RPC_REQUEST_TIMEOUT_MS = "rpc_request_timeout_ms"; - + /** * Maximum size of each file RPC (snapshot copy) request between nodes, default is 128 K */ public static final String MAX_BYTE_COUNT_PER_RPC = "max_byte_count_per_rpc"; - + /** * Maximum number of logs sent from leader to follower, default is 1024 */ public static final String MAX_ENTRIES_SIZE = "max_entries_size"; - + /** * Maximum body size for sending logs from leader to follower, default is 512K */ public static final String MAX_BODY_SIZE = "max_body_size"; - + /** * Maximum log storage buffer size, default 256K */ public static final String MAX_APPEND_BUFFER_SIZE = "max_append_buffer_size"; - + /** * Election timer interval will be a random maximum outside the specified time, default is 1 second */ public static final String MAX_ELECTION_DELAY_MS = "max_election_delay_ms"; - + /** * Specify the ratio between election timeout and heartbeat interval. Heartbeat interval is equal to * electionTimeoutMs/electionHeartbeatFactor,One tenth by default. */ public static final String ELECTION_HEARTBEAT_FACTOR = "election_heartbeat_factor"; - + /** - * The tasks submitted to the leader accumulate the maximum batch - * size of a batch flush log storage. The default is 32 tasks. + * The tasks submitted to the leader accumulate the maximum batch size of a batch flush log storage. The default is + * 32 tasks. */ public static final String APPLY_BATCH = "apply_batch"; - + /** * Call fsync when necessary when writing logs and meta information, usually should be true */ public static final String SYNC = "sync"; - + /** - * Whether to write snapshot / raft meta-information to call fsync. - * The default is false. When sync is true, it is preferred to respect sync. + * Whether to write snapshot / raft meta-information to call fsync. The default is false. When sync is true, it is + * preferred to respect sync. */ public static final String SYNC_META = "sync_meta"; - + /** - * Internal disruptor buffer size. For applications with high write throughput, - * you need to increase this value. The default value is 16384. + * Internal disruptor buffer size. For applications with high write throughput, you need to increase this value. The + * default value is 16384. */ public static final String DISRUPTOR_BUFFER_SIZE = "disruptor_buffer_size"; - + /** * Whether to enable replication of pipeline request optimization, which is enabled by default */ public static final String REPLICATOR_PIPELINE = "replicator_pipeline"; - + /** * Maximum number of in-flight requests with pipeline requests enabled, default is 256 */ public static final String MAX_REPLICATOR_INFLIGHT_MSGS = "max_replicator_inflight_msgs"; - + /** * Whether to enable LogEntry checksum */ diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/DuplicateRaftGroupException.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/DuplicateRaftGroupException.java index 22e15dc51a5..a6e98b83211 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/DuplicateRaftGroupException.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/DuplicateRaftGroupException.java @@ -17,14 +17,14 @@ package com.alibaba.nacos.core.distributed.raft.exception; /** - * Duplicate groupId when creating Raft Group throws this exception + * Duplicate groupId when creating Raft Group throws this exception. * * @author liaochuntao */ public class DuplicateRaftGroupException extends RuntimeException { - + private static final long serialVersionUID = -6276695537457486790L; - + public DuplicateRaftGroupException(String group) { super("The Raft Group [" + group + "] is already used"); } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/JRaftException.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/JRaftException.java index 36e873d78e2..d201fd9a240 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/JRaftException.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/JRaftException.java @@ -17,30 +17,31 @@ package com.alibaba.nacos.core.distributed.raft.exception; /** + * Abnormal JRaft. + * * @author liaochuntao */ @SuppressWarnings("PMD.ClassNamingShouldBeCamelRule") public class JRaftException extends RuntimeException { - - private static final long serialVersionUID = 8802314713344513544L; - - public JRaftException() { - } - - public JRaftException(String message) { - super(message); - } - - public JRaftException(String message, Throwable cause) { - super(message, cause); - } - - public JRaftException(Throwable cause) { - super(cause); - } - - public JRaftException(String message, Throwable cause, boolean enableSuppression, - boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + + private static final long serialVersionUID = 8802314713344513544L; + + public JRaftException() { + } + + public JRaftException(String message) { + super(message); + } + + public JRaftException(String message, Throwable cause) { + super(message, cause); + } + + public JRaftException(Throwable cause) { + super(cause); + } + + public JRaftException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/NoLeaderException.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/NoLeaderException.java index 8f36bd44dde..86ec8e08119 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/NoLeaderException.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/NoLeaderException.java @@ -17,29 +17,29 @@ package com.alibaba.nacos.core.distributed.raft.exception; /** - * This exception is thrown if the current Raft Group Cluster does not elect a leader + * This exception is thrown if the current Raft Group Cluster does not elect a leader. * * @author liaochuntao */ public class NoLeaderException extends Exception { - + private static final long serialVersionUID = 1755681688785678765L; - + public NoLeaderException() { } - + public NoLeaderException(String group) { super("The Raft Group [" + group + "] did not find the Leader node"); } - + public NoLeaderException(String message, Throwable cause) { super(message, cause); } - + public NoLeaderException(Throwable cause) { super(cause); } - + public NoLeaderException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/NoSuchRaftGroupException.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/NoSuchRaftGroupException.java index 6c1407c3d5d..625ea7336e2 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/NoSuchRaftGroupException.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/exception/NoSuchRaftGroupException.java @@ -17,29 +17,31 @@ package com.alibaba.nacos.core.distributed.raft.exception; /** + * no this raft group exception. + * * @author liaochuntao */ public class NoSuchRaftGroupException extends RuntimeException { - - private static final long serialVersionUID = 1755681688785678765L; - - public NoSuchRaftGroupException() { - } - - public NoSuchRaftGroupException(String message) { - super(message); - } - - public NoSuchRaftGroupException(String message, Throwable cause) { - super(message, cause); - } - - public NoSuchRaftGroupException(Throwable cause) { - super(cause); - } - - public NoSuchRaftGroupException(String message, Throwable cause, - boolean enableSuppression, boolean writableStackTrace) { - super(message, cause, enableSuppression, writableStackTrace); - } + + private static final long serialVersionUID = 1755681688785678765L; + + public NoSuchRaftGroupException() { + } + + public NoSuchRaftGroupException(String message) { + super(message); + } + + public NoSuchRaftGroupException(String message, Throwable cause) { + super(message, cause); + } + + public NoSuchRaftGroupException(Throwable cause) { + super(cause); + } + + public NoSuchRaftGroupException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { + super(message, cause, enableSuppression, writableStackTrace); + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessor.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessor.java index ef8d88fd699..51800655e29 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessor.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessor.java @@ -23,80 +23,73 @@ import com.alibaba.nacos.core.utils.Loggers; import com.alipay.sofa.jraft.Status; import com.alipay.sofa.jraft.rpc.RpcContext; -import com.google.protobuf.ByteString; import com.google.protobuf.Message; -import org.slf4j.Logger; import java.util.Objects; /** + * abstract rpc processor. + * * @author liaochuntao */ public abstract class AbstractProcessor { - - private final Serializer serializer; - - public AbstractProcessor(Serializer serializer) { - this.serializer = serializer; - } - - protected void handleRequest(final JRaftServer server, final String group, final RpcContext rpcCtx, Message log) { - try { - final JRaftServer.RaftGroupTuple tuple = server.findTupleByGroup(group); - if (Objects.isNull(tuple)) { - rpcCtx.sendResponse(Response.newBuilder() - .setSuccess(false) - .setErrMsg("Could not find the corresponding Raft Group : " + group) - .build()); - return; - } - if (tuple.getNode().isLeader()) { - execute(server, rpcCtx, log, tuple); - } - else { - rpcCtx.sendResponse(Response.newBuilder() - .setSuccess(false) - .setErrMsg("Could not find leader : " + group) - .build()); - } - } catch (Throwable e) { - Loggers.RAFT.error("handleRequest has error : {}", e); - rpcCtx.sendResponse(Response.newBuilder() - .setSuccess(false) - .setErrMsg(e.toString()) - .build()); - } - } - - protected void execute(JRaftServer server, final RpcContext asyncCtx, final Message log, final JRaftServer.RaftGroupTuple tuple) { - FailoverClosure closure = new FailoverClosure() { - - Response data; - Throwable ex; - - @Override - public void setResponse(Response data) { - this.data = data; - } - - @Override - public void setThrowable(Throwable throwable) { - this.ex = throwable; - } - - @Override - public void run(Status status) { - if (Objects.nonNull(ex)) { - Loggers.RAFT.error("execute has error : {}", ex); - asyncCtx.sendResponse(Response.newBuilder().setErrMsg(ex.toString()) - .setSuccess(false).build()); - } else { - asyncCtx.sendResponse(data); - } - } - }; - - server.applyOperation(tuple.getNode(), log, closure); - } - + + private final Serializer serializer; + + public AbstractProcessor(Serializer serializer) { + this.serializer = serializer; + } + + protected void handleRequest(final JRaftServer server, final String group, final RpcContext rpcCtx, Message log) { + try { + final JRaftServer.RaftGroupTuple tuple = server.findTupleByGroup(group); + if (Objects.isNull(tuple)) { + rpcCtx.sendResponse(Response.newBuilder().setSuccess(false) + .setErrMsg("Could not find the corresponding Raft Group : " + group).build()); + return; + } + if (tuple.getNode().isLeader()) { + execute(server, rpcCtx, log, tuple); + } else { + rpcCtx.sendResponse( + Response.newBuilder().setSuccess(false).setErrMsg("Could not find leader : " + group).build()); + } + } catch (Throwable e) { + Loggers.RAFT.error("handleRequest has error : {}", e); + rpcCtx.sendResponse(Response.newBuilder().setSuccess(false).setErrMsg(e.toString()).build()); + } + } + + protected void execute(JRaftServer server, final RpcContext asyncCtx, final Message log, + final JRaftServer.RaftGroupTuple tuple) { + FailoverClosure closure = new FailoverClosure() { + + Response data; + + Throwable ex; + + @Override + public void setResponse(Response data) { + this.data = data; + } + + @Override + public void setThrowable(Throwable throwable) { + this.ex = throwable; + } + + @Override + public void run(Status status) { + if (Objects.nonNull(ex)) { + Loggers.RAFT.error("execute has error : {}", ex); + asyncCtx.sendResponse(Response.newBuilder().setErrMsg(ex.toString()).setSuccess(false).build()); + } else { + asyncCtx.sendResponse(data); + } + } + }; + + server.applyOperation(tuple.getNode(), log, closure); + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/NacosGetRequestProcessor.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/NacosGetRequestProcessor.java index 673241fc8a6..8097908fe14 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/NacosGetRequestProcessor.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/NacosGetRequestProcessor.java @@ -23,26 +23,28 @@ import com.alipay.sofa.jraft.rpc.RpcProcessor; /** + * deal with {@link GetRequest}. + * * @author liaochuntao */ public class NacosGetRequestProcessor extends AbstractProcessor implements RpcProcessor { - - private static final String INTEREST_NAME = GetRequest.class.getName(); - - private final JRaftServer server; - - public NacosGetRequestProcessor(JRaftServer server, Serializer serializer) { - super(serializer); - this.server = server; - } - - @Override - public void handleRequest(final RpcContext rpcCtx, GetRequest request) { - handleRequest(server, request.getGroup(), rpcCtx, request); - } - - @Override - public String interest() { - return INTEREST_NAME; - } + + private static final String INTEREST_NAME = GetRequest.class.getName(); + + private final JRaftServer server; + + public NacosGetRequestProcessor(JRaftServer server, Serializer serializer) { + super(serializer); + this.server = server; + } + + @Override + public void handleRequest(final RpcContext rpcCtx, GetRequest request) { + handleRequest(server, request.getGroup(), rpcCtx, request); + } + + @Override + public String interest() { + return INTEREST_NAME; + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/NacosLogProcessor.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/NacosLogProcessor.java index 7944e760ef0..acbc66bd9b4 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/NacosLogProcessor.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/processor/NacosLogProcessor.java @@ -23,29 +23,29 @@ import com.alipay.sofa.jraft.rpc.RpcProcessor; /** + * deal with {@link Log}. + * * @author liaochuntao */ public class NacosLogProcessor extends AbstractProcessor implements RpcProcessor { - + private static final String INTEREST_NAME = Log.class.getName(); - + private final JRaftServer server; - + public NacosLogProcessor(JRaftServer server, Serializer serializer) { super(serializer); this.server = server; } - + @Override public void handleRequest(final RpcContext rpcCtx, Log log) { handleRequest(server, log.getGroup(), rpcCtx, log); } - + @Override public String interest() { return INTEREST_NAME; } - - - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/FailoverClosure.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/FailoverClosure.java index 7f362dd0cc8..f07c4186b95 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/FailoverClosure.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/FailoverClosure.java @@ -20,24 +20,24 @@ import com.alipay.sofa.jraft.Closure; /** - * Failure callback based on Closure + * Failure callback based on Closure. * * @author liaochuntao */ public interface FailoverClosure extends Closure { - + /** - * Set the return interface if needed + * Set the return interface if needed. * * @param response {@link Response} data */ void setResponse(Response response); - + /** - * Catch exception + * Catch exception. * * @param throwable {@link Throwable} */ void setThrowable(Throwable throwable); - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/FailoverClosureImpl.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/FailoverClosureImpl.java index 9ec4b3a13d6..ade0751007e 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/FailoverClosureImpl.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/FailoverClosureImpl.java @@ -24,40 +24,41 @@ import java.util.concurrent.CompletableFuture; /** - * Closure with internal retry mechanism + * Closure with internal retry mechanism. * * @author liaochuntao */ public class FailoverClosureImpl implements FailoverClosure { - - private final CompletableFuture future; - private volatile Response data; - private volatile Throwable throwable; - - public FailoverClosureImpl(final CompletableFuture future) { - this.future = future; - } - - @Override - public void setResponse(Response data) { - this.data = data; - } - - @Override - public void setThrowable(Throwable throwable) { - this.throwable = throwable; - } - - @Override - public void run(Status status) { - if (status.isOk()) { - future.complete(data); - return; - } - final Throwable throwable = this.throwable; - future.completeExceptionally(Objects.nonNull(throwable) ? - new ConsistencyException(throwable.toString()) : - new ConsistencyException("operation failure")); - } - + + private final CompletableFuture future; + + private volatile Response data; + + private volatile Throwable throwable; + + public FailoverClosureImpl(final CompletableFuture future) { + this.future = future; + } + + @Override + public void setResponse(Response data) { + this.data = data; + } + + @Override + public void setThrowable(Throwable throwable) { + this.throwable = throwable; + } + + @Override + public void run(Status status) { + if (status.isOk()) { + future.complete(data); + return; + } + final Throwable throwable = this.throwable; + future.completeExceptionally(Objects.nonNull(throwable) ? new ConsistencyException(throwable.toString()) + : new ConsistencyException("operation failure")); + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftConstants.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftConstants.java index 5c757da0fb0..66af0a2bb4f 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftConstants.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftConstants.java @@ -17,29 +17,31 @@ package com.alibaba.nacos.core.distributed.raft.utils; /** + * constant. + * * @author liaochuntao */ @SuppressWarnings("PMD.ClassNamingShouldBeCamelRule") public class JRaftConstants { - - public static final String JRAFT_EXTEND_INFO_KEY = JRaftLogOperation.class.getCanonicalName(); - - public static final String GROUP_ID = "groupId"; - - public static final String COMMAND_NAME = "command"; - - public static final String COMMAND_VALUE = "value"; - - public static final String TRANSFER_LEADER = "transferLeader"; - - public static final String RESET_RAFT_CLUSTER = "restRaftCluster"; - - public static final String DO_SNAPSHOT = "doSnapshot"; - - public static final String REMOVE_PEER = "removePeer"; - - public static final String REMOVE_PEERS = "removePeers"; - - public static final String CHANGE_PEERS = "changePeers"; - + + public static final String JRAFT_EXTEND_INFO_KEY = JRaftLogOperation.class.getCanonicalName(); + + public static final String GROUP_ID = "groupId"; + + public static final String COMMAND_NAME = "command"; + + public static final String COMMAND_VALUE = "value"; + + public static final String TRANSFER_LEADER = "transferLeader"; + + public static final String RESET_RAFT_CLUSTER = "restRaftCluster"; + + public static final String DO_SNAPSHOT = "doSnapshot"; + + public static final String REMOVE_PEER = "removePeer"; + + public static final String REMOVE_PEERS = "removePeers"; + + public static final String CHANGE_PEERS = "changePeers"; + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftLogOperation.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftLogOperation.java index 14ee401b079..0e7eb499546 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftLogOperation.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftLogOperation.java @@ -17,13 +17,15 @@ package com.alibaba.nacos.core.distributed.raft.utils; /** + * JRaft for additional information on logging operations. + * * @author liaochuntao */ @SuppressWarnings("PMD.ClassNamingShouldBeCamelRule") public class JRaftLogOperation { - - public static final String MODIFY_OPERATION = "modify"; - - public static final String READ_OPERATION = "read"; - + + public static final String MODIFY_OPERATION = "modify"; + + public static final String READ_OPERATION = "read"; + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftOps.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftOps.java index b90ebafc6cd..105b75df9b3 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftOps.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftOps.java @@ -30,146 +30,135 @@ import java.util.Objects; /** + * jraft maintain service. + * * @author liaochuntao */ @SuppressWarnings("all") public enum JRaftOps { - - TRANSFER_LEADER("transferLeader") { - @Override - public RestResult execute(CliService cliService, String groupId, - Node node, Map args) { - final Configuration conf = node.getOptions().getInitialConf(); - final PeerId leader = PeerId - .parsePeer(args.get(JRaftConstants.COMMAND_VALUE)); - Status status = cliService.transferLeader(groupId, conf, leader); - if (status.isOk()) { - return RestResultUtils.success(); - } - return RestResultUtils.failed(status.getErrorMsg()); - } - }, - - RESET_RAFT_CLUSTER("restRaftCluster") { - - @Override - public RestResult execute(CliService cliService, String groupId, - Node node, Map args) { - final Configuration conf = node.getOptions().getInitialConf(); - final String peerIds = args.get(JRaftConstants.COMMAND_VALUE); - Configuration newConf = JRaftUtils.getConfiguration(peerIds); - Status status = cliService.changePeers(groupId, conf, newConf); - if (status.isOk()) { - return RestResultUtils.success(); - } - return RestResultUtils.failed(status.getErrorMsg()); - } - }, - - DO_SNAPSHOT("doSnapshot") { - @Override - public RestResult execute(CliService cliService, String groupId, - Node node, Map args) { - final Configuration conf = node.getOptions().getInitialConf(); - final PeerId peerId = PeerId - .parsePeer(args.get(JRaftConstants.COMMAND_VALUE)); - Status status = cliService.snapshot(groupId, peerId); - if (status.isOk()) { - return RestResultUtils.success(); - } - return RestResultUtils.failed(status.getErrorMsg()); - } - }, - - REMOVE_PEER("removePeer") { - @Override - public RestResult execute(CliService cliService, String groupId, - Node node, Map args) { - final Configuration conf = node.getOptions().getInitialConf(); - - List peerIds = cliService.getPeers(groupId, conf); - - final PeerId waitRemove = PeerId - .parsePeer(args.get(JRaftConstants.COMMAND_VALUE)); - - if (!peerIds.contains(waitRemove)) { - return RestResultUtils.success(); - } - - Status status = cliService.removePeer(groupId, conf, waitRemove); - if (status.isOk()) { - return RestResultUtils.success(); - } - return RestResultUtils.failed(status.getErrorMsg()); - } - }, - - REMOVE_PEERS("removePeers") { - @Override - public RestResult execute(CliService cliService, String groupId, - Node node, Map args) { - final Configuration conf = node.getOptions().getInitialConf(); - final String peers = args.get(JRaftConstants.COMMAND_VALUE); - for (String s : peers.split(",")) { - - List peerIds = cliService.getPeers(groupId, conf); - final PeerId waitRemove = PeerId.parsePeer(s); - - if (!peerIds.contains(waitRemove)) { - continue; - } - - Status status = cliService.removePeer(groupId, conf, waitRemove); - if (!status.isOk()) { - return RestResultUtils.failed(status.getErrorMsg()); - } - } - return RestResultUtils.success(); - } - }, - - CHANGE_PEERS("changePeers") { - @Override - public RestResult execute(CliService cliService, String groupId, - Node node, Map args) { - final Configuration conf = node.getOptions().getInitialConf(); - final Configuration newConf = new Configuration(); - String peers = args.get(JRaftConstants.COMMAND_VALUE); - for (String peer : peers.split(",")) { - newConf.addPeer(PeerId.parsePeer(peer.trim())); - } - - if (Objects.equals(conf, newConf)) { - return RestResultUtils.success(); - } - - Status status = cliService.changePeers(groupId, conf, newConf); - if (status.isOk()) { - return RestResultUtils.success(); - } - return RestResultUtils.failed(status.getErrorMsg()); - } - } - - ; - - private String name; - - JRaftOps(String name) { - this.name = name; - } - - public RestResult execute(CliService cliService, String groupId, Node node, - Map args) { - return RestResultUtils.success(); - } - - public static JRaftOps sourceOf(String command) { - for (JRaftOps enums : JRaftOps.values()) { - if (Objects.equals(command, enums.name)) { - return enums; - } - } - return null; - } + + TRANSFER_LEADER("transferLeader") { + @Override + public RestResult execute(CliService cliService, String groupId, Node node, Map args) { + final Configuration conf = node.getOptions().getInitialConf(); + final PeerId leader = PeerId.parsePeer(args.get(JRaftConstants.COMMAND_VALUE)); + Status status = cliService.transferLeader(groupId, conf, leader); + if (status.isOk()) { + return RestResultUtils.success(); + } + return RestResultUtils.failed(status.getErrorMsg()); + } + }, + + RESET_RAFT_CLUSTER("restRaftCluster") { + @Override + public RestResult execute(CliService cliService, String groupId, Node node, Map args) { + final Configuration conf = node.getOptions().getInitialConf(); + final String peerIds = args.get(JRaftConstants.COMMAND_VALUE); + Configuration newConf = JRaftUtils.getConfiguration(peerIds); + Status status = cliService.changePeers(groupId, conf, newConf); + if (status.isOk()) { + return RestResultUtils.success(); + } + return RestResultUtils.failed(status.getErrorMsg()); + } + }, + + DO_SNAPSHOT("doSnapshot") { + @Override + public RestResult execute(CliService cliService, String groupId, Node node, Map args) { + final Configuration conf = node.getOptions().getInitialConf(); + final PeerId peerId = PeerId.parsePeer(args.get(JRaftConstants.COMMAND_VALUE)); + Status status = cliService.snapshot(groupId, peerId); + if (status.isOk()) { + return RestResultUtils.success(); + } + return RestResultUtils.failed(status.getErrorMsg()); + } + }, + + REMOVE_PEER("removePeer") { + @Override + public RestResult execute(CliService cliService, String groupId, Node node, Map args) { + final Configuration conf = node.getOptions().getInitialConf(); + + List peerIds = cliService.getPeers(groupId, conf); + + final PeerId waitRemove = PeerId.parsePeer(args.get(JRaftConstants.COMMAND_VALUE)); + + if (!peerIds.contains(waitRemove)) { + return RestResultUtils.success(); + } + + Status status = cliService.removePeer(groupId, conf, waitRemove); + if (status.isOk()) { + return RestResultUtils.success(); + } + return RestResultUtils.failed(status.getErrorMsg()); + } + }, + + REMOVE_PEERS("removePeers") { + @Override + public RestResult execute(CliService cliService, String groupId, Node node, Map args) { + final Configuration conf = node.getOptions().getInitialConf(); + final String peers = args.get(JRaftConstants.COMMAND_VALUE); + for (String s : peers.split(",")) { + + List peerIds = cliService.getPeers(groupId, conf); + final PeerId waitRemove = PeerId.parsePeer(s); + + if (!peerIds.contains(waitRemove)) { + continue; + } + + Status status = cliService.removePeer(groupId, conf, waitRemove); + if (!status.isOk()) { + return RestResultUtils.failed(status.getErrorMsg()); + } + } + return RestResultUtils.success(); + } + }, + + CHANGE_PEERS("changePeers") { + @Override + public RestResult execute(CliService cliService, String groupId, Node node, Map args) { + final Configuration conf = node.getOptions().getInitialConf(); + final Configuration newConf = new Configuration(); + String peers = args.get(JRaftConstants.COMMAND_VALUE); + for (String peer : peers.split(",")) { + newConf.addPeer(PeerId.parsePeer(peer.trim())); + } + + if (Objects.equals(conf, newConf)) { + return RestResultUtils.success(); + } + + Status status = cliService.changePeers(groupId, conf, newConf); + if (status.isOk()) { + return RestResultUtils.success(); + } + return RestResultUtils.failed(status.getErrorMsg()); + } + }; + + private String name; + + JRaftOps(String name) { + this.name = name; + } + + public static JRaftOps sourceOf(String command) { + for (JRaftOps enums : JRaftOps.values()) { + if (Objects.equals(command, enums.name)) { + return enums; + } + } + return null; + } + + public RestResult execute(CliService cliService, String groupId, Node node, Map args) { + return RestResultUtils.success(); + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftUtils.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftUtils.java index f52f086d5a3..c672f6b36ae 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftUtils.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/JRaftUtils.java @@ -16,10 +16,9 @@ package com.alibaba.nacos.core.distributed.raft.utils; -import com.alibaba.nacos.core.utils.DiskUtils; +import com.alibaba.nacos.common.utils.ThreadUtils; import com.alibaba.nacos.consistency.SerializeFactory; import com.alibaba.nacos.consistency.entity.GetRequest; -import com.alibaba.nacos.common.utils.ThreadUtils; import com.alibaba.nacos.consistency.entity.Log; import com.alibaba.nacos.consistency.entity.Response; import com.alibaba.nacos.core.cluster.ServerMemberManager; @@ -27,6 +26,7 @@ import com.alibaba.nacos.core.distributed.raft.processor.NacosGetRequestProcessor; import com.alibaba.nacos.core.distributed.raft.processor.NacosLogProcessor; import com.alibaba.nacos.core.utils.ApplicationUtils; +import com.alibaba.nacos.core.utils.DiskUtils; import com.alibaba.nacos.core.utils.Loggers; import com.alipay.sofa.jraft.CliService; import com.alipay.sofa.jraft.RouteTable; @@ -51,68 +51,64 @@ import java.util.stream.Collectors; /** + * JRaft utils. + * * @author liaochuntao */ @SuppressWarnings("all") public class JRaftUtils { - + public static RpcServer initRpcServer(JRaftServer server, PeerId peerId) { GrpcRaftRpcFactory raftRpcFactory = (GrpcRaftRpcFactory) RpcFactoryHelper.rpcFactory(); raftRpcFactory.registerProtobufSerializer(Log.class.getName(), Log.getDefaultInstance()); raftRpcFactory.registerProtobufSerializer(GetRequest.class.getName(), GetRequest.getDefaultInstance()); raftRpcFactory.registerProtobufSerializer(Response.class.getName(), Response.getDefaultInstance()); - + MarshallerRegistry registry = raftRpcFactory.getMarshallerRegistry(); registry.registerResponseInstance(Log.class.getName(), Response.getDefaultInstance()); registry.registerResponseInstance(GetRequest.class.getName(), Response.getDefaultInstance()); - + final RpcServer rpcServer = raftRpcFactory.createRpcServer(new Endpoint(peerId.getIp(), peerId.getPort())); RaftRpcServerFactory.addRaftRequestProcessors(rpcServer, RaftExecutor.getRaftCoreExecutor(), RaftExecutor.getRaftCliServiceExecutor()); - - + rpcServer.registerProcessor(new NacosLogProcessor(server, SerializeFactory.getDefault())); rpcServer.registerProcessor(new NacosGetRequestProcessor(server, SerializeFactory.getDefault())); - + return rpcServer; } - + public static final void initDirectory(String parentPath, String groupName, NodeOptions copy) { final String logUri = Paths.get(parentPath, groupName, "log").toString(); - final String snapshotUri = Paths.get(parentPath, groupName, "snapshot") - .toString(); - final String metaDataUri = Paths.get(parentPath, groupName, "meta-data") - .toString(); - + final String snapshotUri = Paths.get(parentPath, groupName, "snapshot").toString(); + final String metaDataUri = Paths.get(parentPath, groupName, "meta-data").toString(); + // Initialize the raft file storage path for different services try { DiskUtils.forceMkdir(new File(logUri)); DiskUtils.forceMkdir(new File(snapshotUri)); DiskUtils.forceMkdir(new File(metaDataUri)); - } - catch (Exception e) { + } catch (Exception e) { Loggers.RAFT.error("Init Raft-File dir have some error : {}", e); throw new RuntimeException(e); } - + copy.setLogUri(logUri); copy.setRaftMetaUri(metaDataUri); copy.setSnapshotUri(snapshotUri); } - + public static final Log injectExtendInfo(Log log, final String operate) { - Log gLog = Log.newBuilder(log) - .putExtendInfo(JRaftConstants.JRAFT_EXTEND_INFO_KEY, operate) - .build(); + Log gLog = Log.newBuilder(log).putExtendInfo(JRaftConstants.JRAFT_EXTEND_INFO_KEY, operate).build(); return gLog; } - + public static List toStrings(List peerIds) { - return peerIds.stream().map(peerId -> peerId.getEndpoint().toString()) - .collect(Collectors.toList()); + return peerIds.stream().map(peerId -> peerId.getEndpoint().toString()).collect(Collectors.toList()); } - - public static void joinCluster(CliService cliService, Collection members, Configuration conf, String group, PeerId self) { + + public static void joinCluster(CliService cliService, Collection members, Configuration conf, String group, + PeerId self) { ServerMemberManager memberManager = ApplicationUtils.getBean(ServerMemberManager.class); if (!memberManager.isFirstIp()) { return; @@ -122,7 +118,7 @@ public static void joinCluster(CliService cliService, Collection members peerIds.add(PeerId.parsePeer(s)); } peerIds.remove(self); - for ( ; ; ) { + for (; ; ) { if (peerIds.isEmpty()) { return; } @@ -130,12 +126,12 @@ public static void joinCluster(CliService cliService, Collection members Iterator iterator = peerIds.iterator(); while (iterator.hasNext()) { final PeerId peerId = iterator.next(); - + if (conf.contains(peerId)) { iterator.remove(); continue; } - + Status status = cliService.addPeer(group, conf, peerId); if (status.isOk()) { iterator.remove(); @@ -144,5 +140,5 @@ public static void joinCluster(CliService cliService, Collection members ThreadUtils.sleep(1000L); } } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftExecutor.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftExecutor.java index ade9f2c70c3..358bae6df93 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftExecutor.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftExecutor.java @@ -21,90 +21,90 @@ import com.alibaba.nacos.core.distributed.raft.JRaftServer; import com.alibaba.nacos.core.distributed.raft.RaftConfig; import com.alibaba.nacos.core.distributed.raft.RaftSysConstants; - import com.alibaba.nacos.core.utils.ClassUtils; + import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** + * raft executor. + * * @author liaochuntao */ public final class RaftExecutor { - - private static ExecutorService raftCoreExecutor; - private static ExecutorService raftCliServiceExecutor; - private static ScheduledExecutorService raftCommonExecutor; - private static ExecutorService raftSnapshotExecutor; - - private static final String OWNER = ClassUtils.getCanonicalName(JRaftServer.class); - - private RaftExecutor() { - } - - public static void init(RaftConfig config) { - - int raftCoreThreadNum = Integer.parseInt( - config.getValOfDefault(RaftSysConstants.RAFT_CORE_THREAD_NUM, "8")); - int raftCliServiceThreadNum = Integer.parseInt( - config.getValOfDefault(RaftSysConstants.RAFT_CLI_SERVICE_THREAD_NUM, - "4")); - - raftCoreExecutor = ExecutorFactory.Managed - .newFixedExecutorService(OWNER, raftCoreThreadNum, - new NameThreadFactory("com.alibaba.naocs.core.raft-core")); - - raftCliServiceExecutor = ExecutorFactory.Managed - .newFixedExecutorService(OWNER, raftCliServiceThreadNum, - new NameThreadFactory("com.alibaba.naocs.core.raft-cli-service")); - - raftCommonExecutor = ExecutorFactory.Managed - .newScheduledExecutorService(OWNER, 8, - new NameThreadFactory("com.alibaba.nacos.core.protocol.raft-common")); - - int snapshotNum = raftCoreThreadNum / 2; - snapshotNum = snapshotNum == 0 ? raftCoreThreadNum : snapshotNum; - - raftSnapshotExecutor = ExecutorFactory.Managed. - newFixedExecutorService(OWNER, snapshotNum, - new NameThreadFactory("com.alibaba.naocs.core.raft-snapshot")); - - } - - public static void scheduleRaftMemberRefreshJob(Runnable runnable, long initialDelay, - long period, TimeUnit unit) { - raftCommonExecutor - .scheduleAtFixedRate(runnable, initialDelay, period, unit); - } - - public static ExecutorService getRaftCoreExecutor() { - return raftCoreExecutor; - } - - public static ExecutorService getRaftCliServiceExecutor() { - return raftCliServiceExecutor; - } - - public static void executeByCommon(Runnable r) { - raftCommonExecutor.execute(r); - } - - public static void scheduleByCommon(Runnable r, long delayMs) { - raftCommonExecutor.schedule(r, delayMs, TimeUnit.MILLISECONDS); - } - - public static void scheduleAtFixedRateByCommon(Runnable command, - long initialDelayMs, - long periodMs) { - raftCommonExecutor.scheduleAtFixedRate(command, initialDelayMs, periodMs, TimeUnit.MILLISECONDS); - } - - public static ScheduledExecutorService getRaftCommonExecutor() { - return raftCommonExecutor; - } - - public static void doSnapshot(Runnable runnable) { - raftSnapshotExecutor.execute(runnable); - } - + + private static ExecutorService raftCoreExecutor; + + private static ExecutorService raftCliServiceExecutor; + + private static ScheduledExecutorService raftCommonExecutor; + + private static ExecutorService raftSnapshotExecutor; + + private static final String OWNER = ClassUtils.getCanonicalName(JRaftServer.class); + + private RaftExecutor() { + } + + /** + * init raft executor by {@link RaftConfig}. + * + * @param config {@link RaftConfig} + */ + public static void init(RaftConfig config) { + + int raftCoreThreadNum = Integer.parseInt(config.getValOfDefault(RaftSysConstants.RAFT_CORE_THREAD_NUM, "8")); + int raftCliServiceThreadNum = Integer + .parseInt(config.getValOfDefault(RaftSysConstants.RAFT_CLI_SERVICE_THREAD_NUM, "4")); + + raftCoreExecutor = ExecutorFactory.Managed.newFixedExecutorService(OWNER, raftCoreThreadNum, + new NameThreadFactory("com.alibaba.naocs.core.raft-core")); + + raftCliServiceExecutor = ExecutorFactory.Managed.newFixedExecutorService(OWNER, raftCliServiceThreadNum, + new NameThreadFactory("com.alibaba.naocs.core.raft-cli-service")); + + raftCommonExecutor = ExecutorFactory.Managed.newScheduledExecutorService(OWNER, 8, + new NameThreadFactory("com.alibaba.nacos.core.protocol.raft-common")); + + int snapshotNum = raftCoreThreadNum / 2; + snapshotNum = snapshotNum == 0 ? raftCoreThreadNum : snapshotNum; + + raftSnapshotExecutor = ExecutorFactory.Managed.newFixedExecutorService(OWNER, snapshotNum, + new NameThreadFactory("com.alibaba.naocs.core.raft-snapshot")); + + } + + public static void scheduleRaftMemberRefreshJob(Runnable runnable, long initialDelay, long period, TimeUnit unit) { + raftCommonExecutor.scheduleAtFixedRate(runnable, initialDelay, period, unit); + } + + public static ExecutorService getRaftCoreExecutor() { + return raftCoreExecutor; + } + + public static ExecutorService getRaftCliServiceExecutor() { + return raftCliServiceExecutor; + } + + public static void executeByCommon(Runnable r) { + raftCommonExecutor.execute(r); + } + + public static void scheduleByCommon(Runnable r, long delayMs) { + raftCommonExecutor.schedule(r, delayMs, TimeUnit.MILLISECONDS); + } + + public static void scheduleAtFixedRateByCommon(Runnable command, long initialDelayMs, long periodMs) { + raftCommonExecutor.scheduleAtFixedRate(command, initialDelayMs, periodMs, TimeUnit.MILLISECONDS); + } + + public static ScheduledExecutorService getRaftCommonExecutor() { + return raftCommonExecutor; + } + + public static void doSnapshot(Runnable runnable) { + raftSnapshotExecutor.execute(runnable); + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftOptionsBuilder.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftOptionsBuilder.java index e4066e53f30..b46494a4a3e 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftOptionsBuilder.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RaftOptionsBuilder.java @@ -51,79 +51,75 @@ import static com.alibaba.nacos.core.distributed.raft.RaftSysConstants.SYNC_META; /** + * build {@link RaftOptions}. + * * @author liaochuntao */ public class RaftOptionsBuilder { - - public static RaftOptions initRaftOptions(RaftConfig config) { - RaftOptions raftOptions = new RaftOptions(); - raftOptions.setReadOnlyOptions(raftReadIndexType(config)); - - raftOptions.setMaxByteCountPerRpc(ConvertUtils - .toInt(config.getVal(MAX_BYTE_COUNT_PER_RPC), - DEFAULT_MAX_BYTE_COUNT_PER_RPC)); - - raftOptions.setMaxEntriesSize(ConvertUtils - .toInt(config.getVal(MAX_ENTRIES_SIZE), DEFAULT_MAX_ENTRIES_SIZE)); - - raftOptions.setMaxBodySize( - ConvertUtils.toInt(config.getVal(MAX_BODY_SIZE), DEFAULT_MAX_BODY_SIZE)); - - raftOptions.setMaxAppendBufferSize(ConvertUtils - .toInt(config.getVal(MAX_APPEND_BUFFER_SIZE), - DEFAULT_MAX_APPEND_BUFFER_SIZE)); - - raftOptions.setMaxElectionDelayMs(ConvertUtils - .toInt(config.getVal(MAX_ELECTION_DELAY_MS), - DEFAULT_MAX_ELECTION_DELAY_MS)); - - raftOptions.setElectionHeartbeatFactor(ConvertUtils - .toInt(config.getVal(ELECTION_HEARTBEAT_FACTOR), - DEFAULT_ELECTION_HEARTBEAT_FACTOR)); - - raftOptions.setApplyBatch( - ConvertUtils.toInt(config.getVal(APPLY_BATCH), DEFAULT_APPLY_BATCH)); - - raftOptions.setSync(ConvertUtils.toBoolean(config.getVal(SYNC), DEFAULT_SYNC)); - - raftOptions.setSyncMeta( - ConvertUtils.toBoolean(config.getVal(SYNC_META), DEFAULT_SYNC_META)); - - raftOptions.setDisruptorBufferSize(ConvertUtils - .toInt(config.getVal(DISRUPTOR_BUFFER_SIZE), - DEFAULT_DISRUPTOR_BUFFER_SIZE)); - - raftOptions.setReplicatorPipeline(ConvertUtils - .toBoolean(config.getVal(REPLICATOR_PIPELINE), - DEFAULT_REPLICATOR_PIPELINE)); - - raftOptions.setMaxReplicatorInflightMsgs(ConvertUtils - .toInt(config.getVal(MAX_REPLICATOR_INFLIGHT_MSGS), - DEFAULT_MAX_REPLICATOR_INFLIGHT_MSGS)); - - raftOptions.setEnableLogEntryChecksum(ConvertUtils - .toBoolean(config.getVal(ENABLE_LOG_ENTRY_CHECKSUM), - DEFAULT_ENABLE_LOG_ENTRY_CHECKSUM)); - - return raftOptions; - } - - private static ReadOnlyOption raftReadIndexType(RaftConfig config) { - String readOnySafe = "ReadOnlySafe"; - String readOnlyLeaseBased = "ReadOnlyLeaseBased"; - - String val = config.getVal(RaftSysConstants.DEFAULT_READ_INDEX_TYPE); - - if (StringUtils.isBlank(val) || StringUtils.equals(readOnySafe, val)) { - return ReadOnlyOption.ReadOnlySafe; - } - - if (StringUtils.equals(readOnlyLeaseBased, val)) { - return ReadOnlyOption.ReadOnlyLeaseBased; - } - throw new IllegalArgumentException("Illegal Raft system parameters => " - + RaftSysConstants.DEFAULT_READ_INDEX_TYPE + " : [" + val + "]"); - - } - + + /** + * By {@link RaftConfig} creating a {@link RaftOptions}. + * + * @param config {@link RaftConfig} + * @return {@link RaftOptions} + */ + public static RaftOptions initRaftOptions(RaftConfig config) { + RaftOptions raftOptions = new RaftOptions(); + raftOptions.setReadOnlyOptions(raftReadIndexType(config)); + + raftOptions.setMaxByteCountPerRpc( + ConvertUtils.toInt(config.getVal(MAX_BYTE_COUNT_PER_RPC), DEFAULT_MAX_BYTE_COUNT_PER_RPC)); + + raftOptions.setMaxEntriesSize(ConvertUtils.toInt(config.getVal(MAX_ENTRIES_SIZE), DEFAULT_MAX_ENTRIES_SIZE)); + + raftOptions.setMaxBodySize(ConvertUtils.toInt(config.getVal(MAX_BODY_SIZE), DEFAULT_MAX_BODY_SIZE)); + + raftOptions.setMaxAppendBufferSize( + ConvertUtils.toInt(config.getVal(MAX_APPEND_BUFFER_SIZE), DEFAULT_MAX_APPEND_BUFFER_SIZE)); + + raftOptions.setMaxElectionDelayMs( + ConvertUtils.toInt(config.getVal(MAX_ELECTION_DELAY_MS), DEFAULT_MAX_ELECTION_DELAY_MS)); + + raftOptions.setElectionHeartbeatFactor( + ConvertUtils.toInt(config.getVal(ELECTION_HEARTBEAT_FACTOR), DEFAULT_ELECTION_HEARTBEAT_FACTOR)); + + raftOptions.setApplyBatch(ConvertUtils.toInt(config.getVal(APPLY_BATCH), DEFAULT_APPLY_BATCH)); + + raftOptions.setSync(ConvertUtils.toBoolean(config.getVal(SYNC), DEFAULT_SYNC)); + + raftOptions.setSyncMeta(ConvertUtils.toBoolean(config.getVal(SYNC_META), DEFAULT_SYNC_META)); + + raftOptions.setDisruptorBufferSize( + ConvertUtils.toInt(config.getVal(DISRUPTOR_BUFFER_SIZE), DEFAULT_DISRUPTOR_BUFFER_SIZE)); + + raftOptions.setReplicatorPipeline( + ConvertUtils.toBoolean(config.getVal(REPLICATOR_PIPELINE), DEFAULT_REPLICATOR_PIPELINE)); + + raftOptions.setMaxReplicatorInflightMsgs( + ConvertUtils.toInt(config.getVal(MAX_REPLICATOR_INFLIGHT_MSGS), DEFAULT_MAX_REPLICATOR_INFLIGHT_MSGS)); + + raftOptions.setEnableLogEntryChecksum( + ConvertUtils.toBoolean(config.getVal(ENABLE_LOG_ENTRY_CHECKSUM), DEFAULT_ENABLE_LOG_ENTRY_CHECKSUM)); + + return raftOptions; + } + + private static ReadOnlyOption raftReadIndexType(RaftConfig config) { + String readOnySafe = "ReadOnlySafe"; + String readOnlyLeaseBased = "ReadOnlyLeaseBased"; + + String val = config.getVal(RaftSysConstants.DEFAULT_READ_INDEX_TYPE); + + if (StringUtils.isBlank(val) || StringUtils.equals(readOnySafe, val)) { + return ReadOnlyOption.ReadOnlySafe; + } + + if (StringUtils.equals(readOnlyLeaseBased, val)) { + return ReadOnlyOption.ReadOnlyLeaseBased; + } + throw new IllegalArgumentException( + "Illegal Raft system parameters => " + RaftSysConstants.DEFAULT_READ_INDEX_TYPE + " : [" + val + "]"); + + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RetryRunner.java b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RetryRunner.java index 1effbf58cf6..d55c9020b20 100644 --- a/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RetryRunner.java +++ b/core/src/main/java/com/alibaba/nacos/core/distributed/raft/utils/RetryRunner.java @@ -17,16 +17,16 @@ package com.alibaba.nacos.core.distributed.raft.utils; /** - * Retry function + * Retry function. * * @author liaochuntao */ @FunctionalInterface public interface RetryRunner { - + /** - * Tasks that require retry + * Tasks that require retry. */ void run(); - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java b/core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java index e18a072d5fe..026431ed614 100644 --- a/core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java +++ b/core/src/main/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessor.java @@ -13,12 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.env; import org.springframework.boot.SpringApplication; import org.springframework.boot.env.EnvironmentPostProcessor; import org.springframework.core.Ordered; -import org.springframework.core.env.*; +import org.springframework.core.env.CompositePropertySource; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.Environment; +import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.PropertySource; import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; @@ -33,50 +38,50 @@ /** * A lowest precedence {@link EnvironmentPostProcessor} implementation to append Nacos default {@link PropertySource} - * with lowest order in {@link Environment} + * with lowest order in {@link Environment}. * * @author Mercy * @since 0.2.2 */ public class NacosDefaultPropertySourceEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { - + /** - * The name of Nacos default {@link PropertySource} + * The name of Nacos default {@link PropertySource}. */ public static final String PROPERTY_SOURCE_NAME = "nacos-default"; - + /** - * The resource location pattern of Nacos default {@link PropertySource} + * The resource location pattern of Nacos default {@link PropertySource}. * * @see ResourcePatternResolver#CLASSPATH_ALL_URL_PREFIX */ - public static final String RESOURCE_LOCATION_PATTERN = CLASSPATH_ALL_URL_PREFIX - + "META-INF/nacos-default.properties"; - + public static final String RESOURCE_LOCATION_PATTERN = + CLASSPATH_ALL_URL_PREFIX + "META-INF/nacos-default.properties"; + private static final String FILE_ENCODING = "UTF-8"; - + @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - + ResourceLoader resourceLoader = getResourceLoader(application); - + processPropertySource(environment, resourceLoader); - + } - + private ResourceLoader getResourceLoader(SpringApplication application) { - + ResourceLoader resourceLoader = application.getResourceLoader(); - + if (resourceLoader == null) { resourceLoader = new DefaultResourceLoader(application.getClassLoader()); } - + return resourceLoader; } - + private void processPropertySource(ConfigurableEnvironment environment, ResourceLoader resourceLoader) { - + try { PropertySource nacosDefaultPropertySource = buildPropertySource(resourceLoader); MutablePropertySources propertySources = environment.getPropertySources(); @@ -86,27 +91,27 @@ private void processPropertySource(ConfigurableEnvironment environment, Resource throw new IllegalStateException(e.getMessage(), e); } } - + private PropertySource buildPropertySource(ResourceLoader resourceLoader) throws IOException { CompositePropertySource propertySource = new CompositePropertySource(PROPERTY_SOURCE_NAME); appendPropertySource(propertySource, resourceLoader); return propertySource; } - + private void appendPropertySource(CompositePropertySource propertySource, ResourceLoader resourceLoader) - throws IOException { + throws IOException { ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(resourceLoader); Resource[] resources = resourcePatternResolver.getResources(RESOURCE_LOCATION_PATTERN); for (Resource resource : resources) { // Add if exists if (resource.exists()) { String internalName = String.valueOf(resource.getURL()); - propertySource.addPropertySource(new ResourcePropertySource(internalName, - new EncodedResource(resource, FILE_ENCODING))); + propertySource.addPropertySource( + new ResourcePropertySource(internalName, new EncodedResource(resource, FILE_ENCODING))); } } } - + @Override public int getOrder() { return LOWEST_PRECEDENCE; diff --git a/core/src/main/java/com/alibaba/nacos/core/env/ReloadableConfigs.java b/core/src/main/java/com/alibaba/nacos/core/env/ReloadableConfigs.java index debf22c8187..32d704a378b 100644 --- a/core/src/main/java/com/alibaba/nacos/core/env/ReloadableConfigs.java +++ b/core/src/main/java/com/alibaba/nacos/core/env/ReloadableConfigs.java @@ -13,8 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.nacos.core.env; +package com.alibaba.nacos.core.env; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; @@ -28,24 +28,29 @@ import java.util.Properties; /** - * Reload application.properties + * Reload application.properties. * * @author nkorange * @since 1.2.0 */ @Component public class ReloadableConfigs { - + + private static final String FILE_PREFIX = "file:"; + private Properties properties; - + @Value("${spring.config.location:}") private String path; - - private static final String FILE_PREFIX = "file:"; - + + /** + * Periodically load configuration file information. + * + * @throws IOException IOException + */ @Scheduled(fixedRate = 5000) public void reload() throws IOException { - Properties properties = new Properties(); + final Properties properties = new Properties(); InputStream inputStream = null; if (StringUtils.isNotBlank(path) && path.contains(FILE_PREFIX)) { String[] paths = path.split(","); @@ -62,7 +67,7 @@ public void reload() throws IOException { inputStream.close(); this.properties = properties; } - + public final Properties getProperties() { return properties; } diff --git a/core/src/main/java/com/alibaba/nacos/core/exception/SnakflowerException.java b/core/src/main/java/com/alibaba/nacos/core/exception/SnakflowerException.java index d09d7e696ef..fdd5dccec0e 100644 --- a/core/src/main/java/com/alibaba/nacos/core/exception/SnakflowerException.java +++ b/core/src/main/java/com/alibaba/nacos/core/exception/SnakflowerException.java @@ -17,28 +17,30 @@ package com.alibaba.nacos.core.exception; /** + * SnakflowerException. + * * @author liaochuntao */ public class SnakflowerException extends RuntimeException { - + public SnakflowerException() { super(); } - + public SnakflowerException(String message) { super(message); } - + public SnakflowerException(String message, Throwable cause) { super(message, cause); } - + public SnakflowerException(Throwable cause) { super(cause); } - - protected SnakflowerException(String message, Throwable cause, - boolean enableSuppression, boolean writableStackTrace) { + + protected SnakflowerException(String message, Throwable cause, boolean enableSuppression, + boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } } \ No newline at end of file diff --git a/core/src/main/java/com/alibaba/nacos/core/file/FileChangeEvent.java b/core/src/main/java/com/alibaba/nacos/core/file/FileChangeEvent.java index d6654828f3d..3cdabf500bd 100644 --- a/core/src/main/java/com/alibaba/nacos/core/file/FileChangeEvent.java +++ b/core/src/main/java/com/alibaba/nacos/core/file/FileChangeEvent.java @@ -17,62 +17,69 @@ package com.alibaba.nacos.core.file; import java.io.Serializable; -import java.nio.file.WatchEvent; /** + * file change event. + * * @author liaochuntao */ public class FileChangeEvent implements Serializable { - + private static final long serialVersionUID = -4255584033113954765L; - + private String paths; - + private Object context; - + public static FileChangeEventBuilder builder() { return new FileChangeEventBuilder(); } - + public String getPaths() { return paths; } - + public void setPaths(String paths) { this.paths = paths; } - + public Object getContext() { return context; } - + public void setContext(Object context) { this.context = context; } - + @Override public String toString() { - return "FileChangeEvent{" + "paths='" + paths + '\'' + ", context=" + context - + '}'; + return "FileChangeEvent{" + "paths='" + paths + '\'' + ", context=" + context + '}'; } - + public static final class FileChangeEventBuilder { + private String paths; + private Object context; - + private FileChangeEventBuilder() { } - + public FileChangeEventBuilder paths(String paths) { this.paths = paths; return this; } - + public FileChangeEventBuilder context(Object context) { this.context = context; return this; } - + + /** + * build FileChangeEvent. + * + * @return {@link FileChangeEvent} + */ public FileChangeEvent build() { FileChangeEvent fileChangeEvent = new FileChangeEvent(); fileChangeEvent.setPaths(paths); diff --git a/core/src/main/java/com/alibaba/nacos/core/file/FileWatcher.java b/core/src/main/java/com/alibaba/nacos/core/file/FileWatcher.java index 519b724fd47..b51b4526c8c 100644 --- a/core/src/main/java/com/alibaba/nacos/core/file/FileWatcher.java +++ b/core/src/main/java/com/alibaba/nacos/core/file/FileWatcher.java @@ -20,34 +20,36 @@ import java.util.concurrent.Executor; /** + * file watcher. + * * @author liaochuntao */ @SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule") public abstract class FileWatcher { - + /** - * Triggered when a file change occurs + * Triggered when a file change occurs. * * @param event {@link FileChangeEvent} */ public abstract void onChange(FileChangeEvent event); - + /** - * WatchEvent context information + * WatchEvent context information. * * @param context {@link WatchEvent#context()} * @return is this watcher interest context */ public abstract boolean interest(String context); - + /** - * If the FileWatcher has its own thread pool, use this thread - * pool to execute, otherwise use the WatchFileManager thread + * If the FileWatcher has its own thread pool, use this thread pool to execute, otherwise use the WatchFileManager + * thread. * * @return {@link Executor} */ public Executor executor() { return null; } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/file/WatchFileCenter.java b/core/src/main/java/com/alibaba/nacos/core/file/WatchFileCenter.java index 564405ab8ba..273ba6f2e9f 100644 --- a/core/src/main/java/com/alibaba/nacos/core/file/WatchFileCenter.java +++ b/core/src/main/java/com/alibaba/nacos/core/file/WatchFileCenter.java @@ -43,223 +43,237 @@ import java.util.concurrent.atomic.AtomicBoolean; /** - * Unified file change monitoring management center, which uses {@link WatchService} internally. - * One file directory corresponds to one {@link WatchService}. It can only monitor up to 32 file - * directories. When a file change occurs, a {@link FileChangeEvent} will be issued + * Unified file change monitoring management center, which uses {@link WatchService} internally. One file directory + * corresponds to one {@link WatchService}. It can only monitor up to 32 file directories. When a file change occurs, a + * {@link FileChangeEvent} will be issued * * @author liaochuntao */ public class WatchFileCenter { - - private static final Logger LOGGER = LoggerFactory.getLogger(WatchFileCenter.class); - - /** - * Maximum number of monitored file directories - */ - private static final int MAX_WATCH_FILE_JOB = Integer - .getInteger("nacos.watch-file.max-dirs", 16); - - private static final Map MANAGER = new HashMap( - MAX_WATCH_FILE_JOB); - - private static final FileSystem FILE_SYSTEM = FileSystems.getDefault(); - - private static final AtomicBoolean CLOSED = new AtomicBoolean(false); - - static { + + private static final Logger LOGGER = LoggerFactory.getLogger(WatchFileCenter.class); + + /** + * Maximum number of monitored file directories. + */ + private static final int MAX_WATCH_FILE_JOB = Integer.getInteger("nacos.watch-file.max-dirs", 16); + + private static final Map MANAGER = new HashMap(MAX_WATCH_FILE_JOB); + + private static final FileSystem FILE_SYSTEM = FileSystems.getDefault(); + + private static final AtomicBoolean CLOSED = new AtomicBoolean(false); + + static { ThreadUtils.addShutdownHook(new Runnable() { - @Override - public void run() { - shutdown(); - } - }); - } - - /** - * The number of directories that are currently monitored - */ - private static int NOW_WATCH_JOB_CNT = 0; - - public synchronized static boolean registerWatcher(final String paths, - FileWatcher watcher) throws NacosException { - checkState(); - NOW_WATCH_JOB_CNT++; - if (NOW_WATCH_JOB_CNT > MAX_WATCH_FILE_JOB) { - return false; - } - WatchDirJob job = MANAGER.get(paths); - if (job == null) { - job = new WatchDirJob(paths); - job.start(); - MANAGER.put(paths, job); - } - job.addSubscribe(watcher); - return true; - } - - public synchronized static boolean deregisterAllWatcher(final String path) { - WatchDirJob job = MANAGER.get(path); - if (job != null) { - job.shutdown(); - MANAGER.remove(path); - return true; - } - return false; - } - - public static void shutdown() { - if (!CLOSED.compareAndSet(false, true)) { - return; - } - LOGGER.warn("[WatchFileCenter] start close"); - for (Map.Entry entry : MANAGER.entrySet()) { - LOGGER.warn("[WatchFileCenter] start to shutdown this watcher which is watch : " + entry.getKey()); - try { - entry.getValue().shutdown(); - } catch (Throwable e) { - LOGGER.error("[WatchFileCenter] shutdown has error : {}", e); - } - } - MANAGER.clear(); - LOGGER.warn("[WatchFileCenter] already closed"); - } - - public synchronized static boolean deregisterWatcher(final String path, final FileWatcher watcher) { - WatchDirJob job = MANAGER.get(path); - if (job != null) { - job.watchers.remove(watcher); - return true; - } - return false; - } - - private static class WatchDirJob extends Thread { - - private ExecutorService callBackExecutor; - - private final String paths; - - private WatchService watchService; - - private volatile boolean watch = true; - - private Set watchers = new ConcurrentHashSet<>(); - - public WatchDirJob(String paths) throws NacosException { - setName(paths); - this.paths = paths; - final Path p = Paths.get(paths); - if (!p.toFile().isDirectory()) { - throw new IllegalArgumentException("Must be a file directory : " + paths); - } - - this.callBackExecutor = ExecutorFactory - .newSingleExecutorService( - new NameThreadFactory("com.alibaba.nacos.core.file.watch-" + paths)); - - try { - WatchService service = FILE_SYSTEM.newWatchService(); - p.register(service, StandardWatchEventKinds.OVERFLOW, - StandardWatchEventKinds.ENTRY_MODIFY, - StandardWatchEventKinds.ENTRY_CREATE, - StandardWatchEventKinds.ENTRY_DELETE); - this.watchService = service; - } - catch (Throwable ex) { - throw new NacosException(NacosException.SERVER_ERROR, ex); - } - } - - void addSubscribe(final FileWatcher watcher) { - watchers.add(watcher); - } - - void shutdown() { - watch = false; + @Override + public void run() { + shutdown(); + } + }); + } + + /** + * The number of directories that are currently monitored. + */ + @SuppressWarnings("checkstyle:StaticVariableName") + private static int NOW_WATCH_JOB_CNT = 0; + + /** + * Register {@link FileWatcher} in this directory. + * + * @param paths directory + * @param watcher {@link FileWatcher} + * @return register is success + * @throws NacosException NacosException + */ + public static synchronized boolean registerWatcher(final String paths, FileWatcher watcher) throws NacosException { + checkState(); + NOW_WATCH_JOB_CNT++; + if (NOW_WATCH_JOB_CNT > MAX_WATCH_FILE_JOB) { + return false; + } + WatchDirJob job = MANAGER.get(paths); + if (job == null) { + job = new WatchDirJob(paths); + job.start(); + MANAGER.put(paths, job); + } + job.addSubscribe(watcher); + return true; + } + + /** + * Deregister all {@link FileWatcher} in this directory. + * + * @param path directory + * @return deregister is success + */ + public static synchronized boolean deregisterAllWatcher(final String path) { + WatchDirJob job = MANAGER.get(path); + if (job != null) { + job.shutdown(); + MANAGER.remove(path); + return true; + } + return false; + } + + /** + * close {@link WatchFileCenter}. + */ + public static void shutdown() { + if (!CLOSED.compareAndSet(false, true)) { + return; + } + LOGGER.warn("[WatchFileCenter] start close"); + for (Map.Entry entry : MANAGER.entrySet()) { + LOGGER.warn("[WatchFileCenter] start to shutdown this watcher which is watch : " + entry.getKey()); + try { + entry.getValue().shutdown(); + } catch (Throwable e) { + LOGGER.error("[WatchFileCenter] shutdown has error : {}", e); + } + } + MANAGER.clear(); + LOGGER.warn("[WatchFileCenter] already closed"); + } + + /** + * Deregister {@link FileWatcher} in this directory. + * + * @param path directory + * @param watcher {@link FileWatcher} + * @return deregister is success + */ + public static synchronized boolean deregisterWatcher(final String path, final FileWatcher watcher) { + WatchDirJob job = MANAGER.get(path); + if (job != null) { + job.watchers.remove(watcher); + return true; + } + return false; + } + + private static class WatchDirJob extends Thread { + + private ExecutorService callBackExecutor; + + private final String paths; + + private WatchService watchService; + + private volatile boolean watch = true; + + private Set watchers = new ConcurrentHashSet<>(); + + public WatchDirJob(String paths) throws NacosException { + setName(paths); + this.paths = paths; + final Path p = Paths.get(paths); + if (!p.toFile().isDirectory()) { + throw new IllegalArgumentException("Must be a file directory : " + paths); + } + + this.callBackExecutor = ExecutorFactory + .newSingleExecutorService(new NameThreadFactory("com.alibaba.nacos.core.file.watch-" + paths)); + + try { + WatchService service = FILE_SYSTEM.newWatchService(); + p.register(service, StandardWatchEventKinds.OVERFLOW, StandardWatchEventKinds.ENTRY_MODIFY, + StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); + this.watchService = service; + } catch (Throwable ex) { + throw new NacosException(NacosException.SERVER_ERROR, ex); + } + } + + void addSubscribe(final FileWatcher watcher) { + watchers.add(watcher); + } + + void shutdown() { + watch = false; ThreadUtils.shutdownThreadPool(this.callBackExecutor); - } - - @Override - public void run() { - while (watch) { - try { - final WatchKey watchKey = watchService.take(); - final List> events = watchKey.pollEvents(); - watchKey.reset(); - if (callBackExecutor.isShutdown()) { - return; - } - if(events.isEmpty()) { + } + + @Override + public void run() { + while (watch) { + try { + final WatchKey watchKey = watchService.take(); + final List> events = watchKey.pollEvents(); + watchKey.reset(); + if (callBackExecutor.isShutdown()) { + return; + } + if (events.isEmpty()) { continue; } - callBackExecutor.execute(new Runnable() { - @Override - public void run() { - for (WatchEvent event : events) { - WatchEvent.Kind kind = event.kind(); - - // Since the OS's event cache may be overflow, a backstop is needed - if (StandardWatchEventKinds.OVERFLOW.equals(kind)) { - eventOverflow(); - } - else { - eventProcess(event.context()); - } - } - } - }); - } - catch (InterruptedException ignore) { - Thread.interrupted(); - } catch (Throwable ex) { - LOGGER.error("An exception occurred during file listening : {}", ex); - } - } - } - - private void eventProcess(Object context) { - final FileChangeEvent fileChangeEvent = FileChangeEvent.builder().paths(paths) - .context(context).build(); - final String str = String.valueOf(context); - for (final FileWatcher watcher : watchers) { - if (watcher.interest(str)) { - Runnable job = new Runnable() { - @Override - public void run() { - watcher.onChange(fileChangeEvent); - } - }; - Executor executor = watcher.executor(); - if (executor == null) { - try { - job.run(); - } catch (Throwable ex) { - LOGGER.error("File change event callback error : {}", ex); - } - } - else { - executor.execute(job); - } - } - } - } - - private void eventOverflow() { - File dir = Paths.get(paths).toFile(); - for (File file : Objects.requireNonNull(dir.listFiles())) { - // Subdirectories do not participate in listening - if (file.isDirectory()) { - continue; - } - eventProcess(file.getName()); - } - } - - } - - private static void checkState() { - if (CLOSED.get()) { - throw new IllegalStateException("WatchFileCenter already shutdown"); - } - } -} + callBackExecutor.execute(new Runnable() { + @Override + public void run() { + for (WatchEvent event : events) { + WatchEvent.Kind kind = event.kind(); + + // Since the OS's event cache may be overflow, a backstop is needed + if (StandardWatchEventKinds.OVERFLOW.equals(kind)) { + eventOverflow(); + } else { + eventProcess(event.context()); + } + } + } + }); + } catch (InterruptedException ignore) { + Thread.interrupted(); + } catch (Throwable ex) { + LOGGER.error("An exception occurred during file listening : {}", ex); + } + } + } + + private void eventProcess(Object context) { + final FileChangeEvent fileChangeEvent = FileChangeEvent.builder().paths(paths).context(context).build(); + final String str = String.valueOf(context); + for (final FileWatcher watcher : watchers) { + if (watcher.interest(str)) { + Runnable job = new Runnable() { + @Override + public void run() { + watcher.onChange(fileChangeEvent); + } + }; + Executor executor = watcher.executor(); + if (executor == null) { + try { + job.run(); + } catch (Throwable ex) { + LOGGER.error("File change event callback error : {}", ex); + } + } else { + executor.execute(job); + } + } + } + } + + private void eventOverflow() { + File dir = Paths.get(paths).toFile(); + for (File file : Objects.requireNonNull(dir.listFiles())) { + // Subdirectories do not participate in listening + if (file.isDirectory()) { + continue; + } + eventProcess(file.getName()); + } + } + + } + + private static void checkState() { + if (CLOSED.get()) { + throw new IllegalStateException("WatchFileCenter already shutdown"); + } + } +} \ No newline at end of file diff --git a/core/src/main/java/com/alibaba/nacos/core/monitor/MetricsMonitor.java b/core/src/main/java/com/alibaba/nacos/core/monitor/MetricsMonitor.java index 91cccd7fdb3..79ccf7e5744 100644 --- a/core/src/main/java/com/alibaba/nacos/core/monitor/MetricsMonitor.java +++ b/core/src/main/java/com/alibaba/nacos/core/monitor/MetricsMonitor.java @@ -16,39 +16,45 @@ package com.alibaba.nacos.core.monitor; -import io.micrometer.core.instrument.*; +import io.micrometer.core.instrument.DistributionSummary; +import io.micrometer.core.instrument.Timer; /** + * The Metrics center. + * * @author liaochuntao */ public final class MetricsMonitor { - - private static final DistributionSummary RAFT_READ_INDEX_FAILED; - private static final DistributionSummary RAFT_FROM_LEADER; - private static final Timer RAFT_APPLY_LOG_TIMER; - private static final Timer RAFT_APPLY_READ_TIMER; - - static { - RAFT_READ_INDEX_FAILED = NacosMeterRegistry.summary("protocol", "raft_read_index_failed"); - RAFT_FROM_LEADER = NacosMeterRegistry.summary("protocol", "raft_read_from_leader"); - - RAFT_APPLY_LOG_TIMER = NacosMeterRegistry.timer("protocol", "raft_apply_log_timer"); - RAFT_APPLY_READ_TIMER = NacosMeterRegistry.timer("protocol", "raft_apply_read_timer"); - } - - public static void raftReadIndexFailed() { - RAFT_READ_INDEX_FAILED.record(1); - } - - public static void raftReadFromLeader() { - RAFT_FROM_LEADER.record(1); - } - - public static Timer getRaftApplyLogTimer() { - return RAFT_APPLY_LOG_TIMER; - } - - public static Timer getRaftApplyReadTimer() { - return RAFT_APPLY_READ_TIMER; - } + + private static final DistributionSummary RAFT_READ_INDEX_FAILED; + + private static final DistributionSummary RAFT_FROM_LEADER; + + private static final Timer RAFT_APPLY_LOG_TIMER; + + private static final Timer RAFT_APPLY_READ_TIMER; + + static { + RAFT_READ_INDEX_FAILED = NacosMeterRegistry.summary("protocol", "raft_read_index_failed"); + RAFT_FROM_LEADER = NacosMeterRegistry.summary("protocol", "raft_read_from_leader"); + + RAFT_APPLY_LOG_TIMER = NacosMeterRegistry.timer("protocol", "raft_apply_log_timer"); + RAFT_APPLY_READ_TIMER = NacosMeterRegistry.timer("protocol", "raft_apply_read_timer"); + } + + public static void raftReadIndexFailed() { + RAFT_READ_INDEX_FAILED.record(1); + } + + public static void raftReadFromLeader() { + RAFT_FROM_LEADER.record(1); + } + + public static Timer getRaftApplyLogTimer() { + return RAFT_APPLY_LOG_TIMER; + } + + public static Timer getRaftApplyReadTimer() { + return RAFT_APPLY_READ_TIMER; + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/monitor/NacosMeterRegistry.java b/core/src/main/java/com/alibaba/nacos/core/monitor/NacosMeterRegistry.java index 3d41e9678d9..9dc27fdd63a 100644 --- a/core/src/main/java/com/alibaba/nacos/core/monitor/NacosMeterRegistry.java +++ b/core/src/main/java/com/alibaba/nacos/core/monitor/NacosMeterRegistry.java @@ -26,28 +26,29 @@ import java.util.List; /** - * Metrics unified usage center + * Metrics unified usage center. * * @author liaochuntao */ +@SuppressWarnings("all") public final class NacosMeterRegistry { - - private static final CompositeMeterRegistry METER_REGISTRY = new CompositeMeterRegistry(); - - public static DistributionSummary summary(String module, String name) { - ImmutableTag moduleTag = new ImmutableTag("module", module); - List tags = new ArrayList<>(); - tags.add(moduleTag); - tags.add(new ImmutableTag("name", name)); - return METER_REGISTRY.summary("nacos_monitor", tags); - } - - public static Timer timer(String module, String name) { - ImmutableTag moduleTag = new ImmutableTag("module", module); - List tags = new ArrayList<>(); - tags.add(moduleTag); - tags.add(new ImmutableTag("name", name)); - return METER_REGISTRY.timer("nacos_monitor", tags); - } - + + private static final CompositeMeterRegistry METER_REGISTRY = new CompositeMeterRegistry(); + + public static DistributionSummary summary(String module, String name) { + ImmutableTag moduleTag = new ImmutableTag("module", module); + List tags = new ArrayList<>(); + tags.add(moduleTag); + tags.add(new ImmutableTag("name", name)); + return METER_REGISTRY.summary("nacos_monitor", tags); + } + + public static Timer timer(String module, String name) { + ImmutableTag moduleTag = new ImmutableTag("module", module); + List tags = new ArrayList<>(); + tags.add(moduleTag); + tags.add(new ImmutableTag("name", name)); + return METER_REGISTRY.timer("nacos_monitor", tags); + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/notify/DefaultPublisher.java b/core/src/main/java/com/alibaba/nacos/core/notify/DefaultPublisher.java index 5237e698a9c..bcd4ff2b73f 100644 --- a/core/src/main/java/com/alibaba/nacos/core/notify/DefaultPublisher.java +++ b/core/src/main/java/com/alibaba/nacos/core/notify/DefaultPublisher.java @@ -17,7 +17,6 @@ package com.alibaba.nacos.core.notify; import com.alibaba.nacos.common.utils.ConcurrentHashSet; -import com.alibaba.nacos.common.utils.LoggerUtils; import com.alibaba.nacos.common.utils.ThreadUtils; import com.alibaba.nacos.core.notify.listener.SmartSubscribe; import com.alibaba.nacos.core.notify.listener.Subscribe; @@ -33,181 +32,177 @@ import static com.alibaba.nacos.core.notify.NotifyCenter.RING_BUFFER_SIZE; /** - * The default event publisher implementation - * - * Internally, use {@link ArrayBlockingQueue} as a message staging queue + * The default event publisher implementation. Internally, use {@link ArrayBlockingQueue} as a message staging queue * * @author liaochuntao */ public class DefaultPublisher extends Thread implements EventPublisher { - - private static final Logger LOGGER = LoggerFactory.getLogger(NotifyCenter.class); - - private volatile boolean initialized = false; - private volatile boolean canOpen = false; - private volatile boolean shutdown = false; - - private Class eventType; - private final ConcurrentHashSet subscribes = new ConcurrentHashSet<>(); - private int queueMaxSize = -1; - private BlockingQueue queue; - private volatile Long lastEventSequence = -1L; - private final AtomicReferenceFieldUpdater updater = AtomicReferenceFieldUpdater.newUpdater(DefaultPublisher.class, Long.class, "lastEventSequence"); - - @Override - public void init(Class type, int bufferSize) { - setDaemon(true); - setName("nacos.publisher-" + type.getName()); - this.eventType = type; - this.queueMaxSize = bufferSize; - this.queue = new ArrayBlockingQueue<>(bufferSize); - start(); - } - - public ConcurrentHashSet getSubscribes() { - return subscribes; - } - - @Override - public synchronized void start() { - super.start(); - if (!initialized) { - if (queueMaxSize == -1) { - queueMaxSize = RING_BUFFER_SIZE; - } - initialized = true; - } - } - - public long currentEventSize() { - return queue.size(); - } - - @Override - public void run() { - openEventHandler(); - } - - void openEventHandler() { - try { - // To ensure that messages are not lost, enable EventHandler when - // waiting for the first Subscriber to register - for (; ; ) { - if (shutdown || canOpen) { - break; - } - ThreadUtils.sleep(1_000L); - } - - for (; ; ) { - if (shutdown) { - break; - } - final Event event = queue.take(); - receiveEvent(event); - updater.compareAndSet(this, lastEventSequence, Math.max(lastEventSequence, event.sequence())); - } - } - catch (Throwable ex) { - LOGGER.error("Event listener exception : {}", ex); - } - } - - @Override - public void addSubscribe(Subscribe subscribe) { - subscribes.add(subscribe); - canOpen = true; - } - - @Override - public void unSubscribe(Subscribe subscribe) { - subscribes.remove(subscribe); - } - - @Override - public boolean publish(Event event) { - checkIsStart(); - boolean success = this.queue.offer(event); - if (!success) { - LOGGER.warn( - "Unable to plug in due to interruption, synchronize sending time, event : {}", - event); - receiveEvent(event); - return true; - } - return true; - } - - void checkIsStart() { - if (!initialized) { - throw new IllegalStateException("Publisher does not start"); - } - } - - @Override - public void shutdown() { - this.shutdown = true; - this.queue.clear(); - } - - public boolean isInitialized() { - return initialized; - } - - void receiveEvent(Event event) { - final long currentEventSequence = event.sequence(); - final String sourceName = event.getClass().getName(); - - // Notification single event listener - for (Subscribe subscribe : subscribes) { - // Whether to ignore expiration events - if (subscribe.ignoreExpireEvent() - && lastEventSequence > currentEventSequence) { - LOGGER.debug( - "[NotifyCenter] the {} is unacceptable to this subscriber, because had expire", - event.getClass()); - continue; - } - - final String targetName = subscribe.subscribeType().getName(); - if (!Objects.equals(sourceName, targetName)) { - continue; - } - - notifySubscriber(subscribe, event); - } - - // Notification multi-event event listener - for (SmartSubscribe subscribe : SMART_SUBSCRIBES) { - // If you are a multi-event listener, you need to make additional logical judgments - if (!subscribe.canNotify(event)) { - LOGGER.debug( - "[NotifyCenter] the {} is unacceptable to this multi-event subscriber", - event.getClass()); - continue; - } - notifySubscriber(subscribe, event); - } - } - - @Override - public void notifySubscriber(final Subscribe subscribe, final Event event) { - - LOGGER.debug("[NotifyCenter] the {} will received by {}", event, - subscribe); - - final Runnable job = () -> subscribe.onEvent(event); - final Executor executor = subscribe.executor(); - if (Objects.nonNull(executor)) { - executor.execute(job); - } - else { - try { - job.run(); - } - catch (Throwable e) { - LOGGER.error("Event callback exception : {}", e); - } - } - } + + private static final Logger LOGGER = LoggerFactory.getLogger(NotifyCenter.class); + + private final ConcurrentHashSet subscribes = new ConcurrentHashSet<>(); + + private final AtomicReferenceFieldUpdater updater = AtomicReferenceFieldUpdater + .newUpdater(DefaultPublisher.class, Long.class, "lastEventSequence"); + + private volatile boolean initialized = false; + + private volatile boolean canOpen = false; + + private volatile boolean shutdown = false; + + private Class eventType; + + private int queueMaxSize = -1; + + private BlockingQueue queue; + + private volatile Long lastEventSequence = -1L; + + @Override + public void init(Class type, int bufferSize) { + setDaemon(true); + setName("nacos.publisher-" + type.getName()); + this.eventType = type; + this.queueMaxSize = bufferSize; + this.queue = new ArrayBlockingQueue<>(bufferSize); + start(); + } + + public ConcurrentHashSet getSubscribes() { + return subscribes; + } + + @Override + public synchronized void start() { + super.start(); + if (!initialized) { + if (queueMaxSize == -1) { + queueMaxSize = RING_BUFFER_SIZE; + } + initialized = true; + } + } + + public long currentEventSize() { + return queue.size(); + } + + @Override + public void run() { + openEventHandler(); + } + + void openEventHandler() { + try { + // To ensure that messages are not lost, enable EventHandler when + // waiting for the first Subscriber to register + for (; ; ) { + if (shutdown || canOpen) { + break; + } + ThreadUtils.sleep(1_000L); + } + + for (; ; ) { + if (shutdown) { + break; + } + final Event event = queue.take(); + receiveEvent(event); + updater.compareAndSet(this, lastEventSequence, Math.max(lastEventSequence, event.sequence())); + } + } catch (Throwable ex) { + LOGGER.error("Event listener exception : {}", ex); + } + } + + @Override + public void addSubscribe(Subscribe subscribe) { + subscribes.add(subscribe); + canOpen = true; + } + + @Override + public void unSubscribe(Subscribe subscribe) { + subscribes.remove(subscribe); + } + + @Override + public boolean publish(Event event) { + checkIsStart(); + boolean success = this.queue.offer(event); + if (!success) { + LOGGER.warn("Unable to plug in due to interruption, synchronize sending time, event : {}", event); + receiveEvent(event); + return true; + } + return true; + } + + void checkIsStart() { + if (!initialized) { + throw new IllegalStateException("Publisher does not start"); + } + } + + @Override + public void shutdown() { + this.shutdown = true; + this.queue.clear(); + } + + public boolean isInitialized() { + return initialized; + } + + void receiveEvent(Event event) { + final long currentEventSequence = event.sequence(); + final String sourceName = event.getClass().getName(); + + // Notification single event listener + for (Subscribe subscribe : subscribes) { + // Whether to ignore expiration events + if (subscribe.ignoreExpireEvent() && lastEventSequence > currentEventSequence) { + LOGGER.debug("[NotifyCenter] the {} is unacceptable to this subscriber, because had expire", + event.getClass()); + continue; + } + + final String targetName = subscribe.subscribeType().getName(); + if (!Objects.equals(sourceName, targetName)) { + continue; + } + + notifySubscriber(subscribe, event); + } + + // Notification multi-event event listener + for (SmartSubscribe subscribe : SMART_SUBSCRIBES) { + // If you are a multi-event listener, you need to make additional logical judgments + if (!subscribe.canNotify(event)) { + LOGGER.debug("[NotifyCenter] the {} is unacceptable to this multi-event subscriber", event.getClass()); + continue; + } + notifySubscriber(subscribe, event); + } + } + + @Override + public void notifySubscriber(final Subscribe subscribe, final Event event) { + + LOGGER.debug("[NotifyCenter] the {} will received by {}", event, subscribe); + + final Runnable job = () -> subscribe.onEvent(event); + final Executor executor = subscribe.executor(); + if (Objects.nonNull(executor)) { + executor.execute(job); + } else { + try { + job.run(); + } catch (Throwable e) { + LOGGER.error("Event callback exception : {}", e); + } + } + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/notify/Event.java b/core/src/main/java/com/alibaba/nacos/core/notify/Event.java index 98f78bb4562..53ada36346c 100644 --- a/core/src/main/java/com/alibaba/nacos/core/notify/Event.java +++ b/core/src/main/java/com/alibaba/nacos/core/notify/Event.java @@ -19,17 +19,19 @@ import java.io.Serializable; /** + * event. + * * @author liaochuntao */ public interface Event extends Serializable { - + /** - * Event sequence number, which can be used to handle the sequence of events + * Event sequence number, which can be used to handle the sequence of events. * * @return sequence num, It's best to make sure it's monotone */ default long sequence() { return System.currentTimeMillis(); } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/notify/EventPublisher.java b/core/src/main/java/com/alibaba/nacos/core/notify/EventPublisher.java index fc0b99203dc..7b181c1c085 100644 --- a/core/src/main/java/com/alibaba/nacos/core/notify/EventPublisher.java +++ b/core/src/main/java/com/alibaba/nacos/core/notify/EventPublisher.java @@ -23,64 +23,64 @@ import java.util.Set; /** - * Event publisher + * Event publisher. * * @author liaochuntao */ public interface EventPublisher { - - /** - * Multi-event listener collection list - */ - Set SMART_SUBSCRIBES = new ConcurrentHashSet<>(); - - /** - * Initializes the event publisher - * - * @param type {@link Class} - * @param bufferSize Message staging queue size - */ - void init(Class type, int bufferSize); - - /** - * The number of currently staged events - * - * @return event size - */ - long currentEventSize(); - - /** - * Add listener - * - * @param subscribe {@link Subscribe} - */ - void addSubscribe(Subscribe subscribe); - - /** - * Remove listener - * - * @param subscribe {@link Subscribe} - */ - void unSubscribe(Subscribe subscribe); - - /** - * publish event - * - * @param event {@link Event} - * @return publish event is success - */ - boolean publish(Event event); - - /** - * Notify listener - * - * @param subscribe {@link Subscribe} - * @param event {@link Event} - */ - void notifySubscriber(Subscribe subscribe, Event event); - - /** - * shutdown this publisher - */ - void shutdown(); + + /** + * Multi-event listener collection list. + */ + Set SMART_SUBSCRIBES = new ConcurrentHashSet<>(); + + /** + * Initializes the event publisher. + * + * @param type {@link Class} + * @param bufferSize Message staging queue size + */ + void init(Class type, int bufferSize); + + /** + * The number of currently staged events. + * + * @return event size + */ + long currentEventSize(); + + /** + * Add listener. + * + * @param subscribe {@link Subscribe} + */ + void addSubscribe(Subscribe subscribe); + + /** + * Remove listener. + * + * @param subscribe {@link Subscribe} + */ + void unSubscribe(Subscribe subscribe); + + /** + * publish event. + * + * @param event {@link Event} + * @return publish event is success + */ + boolean publish(Event event); + + /** + * Notify listener. + * + * @param subscribe {@link Subscribe} + * @param event {@link Event} + */ + void notifySubscriber(Subscribe subscribe, Event event); + + /** + * shutdown this publisher. + */ + void shutdown(); } diff --git a/core/src/main/java/com/alibaba/nacos/core/notify/NotifyCenter.java b/core/src/main/java/com/alibaba/nacos/core/notify/NotifyCenter.java index e1165c3e70e..2ca5a2c246d 100644 --- a/core/src/main/java/com/alibaba/nacos/core/notify/NotifyCenter.java +++ b/core/src/main/java/com/alibaba/nacos/core/notify/NotifyCenter.java @@ -35,250 +35,246 @@ import java.util.function.BiFunction; /** + * notify center. + * * @author liaochuntao */ @SuppressWarnings("all") public class NotifyCenter { - - private static final Logger LOGGER = LoggerFactory.getLogger(NotifyCenter.class); - - public static int RING_BUFFER_SIZE = 16384; - - public static int SHATE_BUFFER_SIZE = 1024; - - private static final AtomicBoolean CLOSED = new AtomicBoolean(false); - - private static BiFunction, Integer, EventPublisher> BUILD_FACTORY = null; - - private static final NotifyCenter INSTANCE = new NotifyCenter(); - - private EventPublisher sharePublisher; - - /** - * Publisher management container - */ - private final Map publisherMap = new ConcurrentHashMap<>(16); - - /** - * Multi-event listening list - */ - private final Set smartSubscribes = new ConcurrentHashSet<>(); - - static { - // Internal ArrayBlockingQueue buffer size. For applications with high write throughput, - // this value needs to be increased appropriately. default value is 16384 - String ringBufferSizeProperty = "nacos.core.notify.ring-buffer-size"; - RING_BUFFER_SIZE = Integer.getInteger(ringBufferSizeProperty, 16384); - - // The size of the public publisher's message staging queue buffer - String shareBufferSizeProperty = "nacos.core.notify.share-buffer-size"; - SHATE_BUFFER_SIZE = Integer.getInteger(shareBufferSizeProperty, 1024); - - ServiceLoader loader = ServiceLoader.load(EventPublisher.class); - Iterator iterator = loader.iterator(); - - if (iterator.hasNext()) { - BUILD_FACTORY = (cls, buffer) -> { - loader.reload(); - EventPublisher publisher = ServiceLoader.load(EventPublisher.class).iterator().next(); - publisher.init(cls, buffer); - return publisher; - }; - } else { - BUILD_FACTORY = (cls, buffer) -> { - EventPublisher publisher = new DefaultPublisher(); - publisher.init(cls, buffer); - return publisher; - }; - } - - INSTANCE.sharePublisher = BUILD_FACTORY.apply(SlowEvent.class, SHATE_BUFFER_SIZE); + + private static final Logger LOGGER = LoggerFactory.getLogger(NotifyCenter.class); + + private static final AtomicBoolean CLOSED = new AtomicBoolean(false); + + private static final NotifyCenter INSTANCE = new NotifyCenter(); + + private static final AtomicBoolean closed = new AtomicBoolean(false); + + public static int RING_BUFFER_SIZE = 16384; + + public static int SHATE_BUFFER_SIZE = 1024; + + private static BiFunction, Integer, EventPublisher> BUILD_FACTORY = null; + + static { + // Internal ArrayBlockingQueue buffer size. For applications with high write throughput, + // this value needs to be increased appropriately. default value is 16384 + String ringBufferSizeProperty = "nacos.core.notify.ring-buffer-size"; + RING_BUFFER_SIZE = Integer.getInteger(ringBufferSizeProperty, 16384); + + // The size of the public publisher's message staging queue buffer + String shareBufferSizeProperty = "nacos.core.notify.share-buffer-size"; + SHATE_BUFFER_SIZE = Integer.getInteger(shareBufferSizeProperty, 1024); + + ServiceLoader loader = ServiceLoader.load(EventPublisher.class); + Iterator iterator = loader.iterator(); + + if (iterator.hasNext()) { + BUILD_FACTORY = (cls, buffer) -> { + loader.reload(); + EventPublisher publisher = ServiceLoader.load(EventPublisher.class).iterator().next(); + publisher.init(cls, buffer); + return publisher; + }; + } else { + BUILD_FACTORY = (cls, buffer) -> { + EventPublisher publisher = new DefaultPublisher(); + publisher.init(cls, buffer); + return publisher; + }; + } + + INSTANCE.sharePublisher = BUILD_FACTORY.apply(SlowEvent.class, SHATE_BUFFER_SIZE); ThreadUtils.addShutdownHook(new Thread(() -> { - shutdown(); - })); - - } - - @JustForTest - public static Map getPublisherMap() { - return INSTANCE.publisherMap; - } - - @JustForTest - public static EventPublisher getPublisher(Class topic) { - if (SlowEvent.class.isAssignableFrom(topic)) { - return INSTANCE.sharePublisher; - } - return INSTANCE.publisherMap.get(topic.getCanonicalName()); - } - - @JustForTest - public static Set getSmartSubscribes() { - return EventPublisher.SMART_SUBSCRIBES; - } - - @JustForTest - public static EventPublisher getSharePublisher() { - return INSTANCE.sharePublisher; - } - - private static final AtomicBoolean closed = new AtomicBoolean(false); - - public static void shutdown() { - if (!closed.compareAndSet(false, true)) { - return; - } - LOGGER.warn("[NotifyCenter] Start destroying Publisher"); - try { - INSTANCE.publisherMap.forEach(new BiConsumer() { - @Override - public void accept(String s, EventPublisher publisher) { - publisher.shutdown(); - } - }); - - INSTANCE.sharePublisher.shutdown(); - } - catch (Throwable e) { - LOGGER.error("NotifyCenter shutdown has error : {}", e); - } - LOGGER.warn("[NotifyCenter] Destruction of the end"); - } - - /** - * Register a Subscriber. If the Publisher concerned by the - * Subscriber does not exist, then PublihserMap will preempt - * a placeholder Publisher first. not call {@link Publisher#start()} - * - * @param eventType Types of events that Subscriber cares about - * @param consumer subscriber - * @param event type - */ - public static void registerSubscribe(final Subscribe consumer) { - final Class cls = consumer.subscribeType(); - // If you want to listen to multiple events, you do it separately, - // without automatically registering the appropriate publisher - if (consumer instanceof SmartSubscribe) { - EventPublisher.SMART_SUBSCRIBES.add((SmartSubscribe) consumer); - return; - } - // If the event does not require additional queue resources, - // go to share-publisher to reduce resource waste - if (SlowEvent.class.isAssignableFrom(cls)) { - INSTANCE.sharePublisher.addSubscribe(consumer); - return; - } - final String topic = consumer.subscribeType().getCanonicalName(); - INSTANCE.publisherMap.computeIfAbsent(topic, s -> BUILD_FACTORY.apply(cls, RING_BUFFER_SIZE)); - EventPublisher publisher = INSTANCE.publisherMap.get(topic); - publisher.addSubscribe(consumer); - } - - /** - * deregister subscriber - * - * @param consumer subscriber - * @param - */ - public static void deregisterSubscribe(final Subscribe consumer) { - final Class cls = consumer.subscribeType(); - if (consumer instanceof SmartSubscribe) { - EventPublisher.SMART_SUBSCRIBES.remove((SmartSubscribe) consumer); - return; - } - if (SlowEvent.class.isAssignableFrom(cls)) { - INSTANCE.sharePublisher.unSubscribe(consumer); - return; - } - final String topic = consumer.subscribeType().getCanonicalName(); - if (INSTANCE.publisherMap.containsKey(topic)) { - EventPublisher publisher = INSTANCE.publisherMap.get(topic); - publisher.unSubscribe(consumer); - return; - } - throw new NoSuchElementException("The subcriber has no event publisher"); - } - - /** - * request publisher publish event - * Publishers load lazily, calling publisher. Start () only when the event is actually published - * - * @param event - */ - public static boolean publishEvent(final Event event) { - try { - return publishEvent(event.getClass(), event); - } catch (Throwable ex) { - LOGGER.error("There was an exception to the message publishing : {}", ex); - return false; - } - } - - /** - * request publisher publish event - * Publishers load lazily, calling publisher. Start () only when the event is actually published - * - * @param eventType - * @param event - */ - private static boolean publishEvent(final Class eventType, - final Event event) { - final String topic = eventType.getCanonicalName(); - if (SlowEvent.class.isAssignableFrom(eventType)) { - return INSTANCE.sharePublisher.publish(event); - } - - if (INSTANCE.publisherMap.containsKey(topic)) { - EventPublisher publisher = INSTANCE.publisherMap.get(topic); - return publisher.publish(event); - } - throw new NoSuchElementException( - "There are no [" + topic + "] publishers for this event, please register"); - } - - /** - * register to share-publisher - * - * @param supplier - * @param eventType - * @return - */ - public static EventPublisher registerToSharePublisher( - final Class eventType) { - return INSTANCE.sharePublisher; - } - - /** - * register publisher - * - * @param supplier - * @param eventType - * @param queueMaxSize - * @return - */ - public static EventPublisher registerToPublisher(final Class eventType, - final int queueMaxSize) { - - if (SlowEvent.class.isAssignableFrom(eventType)) { - return INSTANCE.sharePublisher; - } - - final String topic = eventType.getCanonicalName(); - INSTANCE.publisherMap.computeIfAbsent(topic, s -> BUILD_FACTORY.apply(eventType, queueMaxSize)); - EventPublisher publisher = INSTANCE.publisherMap.get(topic); - return publisher; - } - - /** - * deregister publisher - * - * @param eventType - * @return - */ - public static void deregisterPublisher(final Class eventType) { - final String topic = eventType.getCanonicalName(); - EventPublisher publisher = INSTANCE.publisherMap.remove(topic); - publisher.shutdown(); - } - + shutdown(); + })); + + } + + /** + * Publisher management container + */ + private final Map publisherMap = new ConcurrentHashMap<>(16); + + /** + * Multi-event listening list + */ + private final Set smartSubscribes = new ConcurrentHashSet<>(); + + private EventPublisher sharePublisher; + + @JustForTest + public static Map getPublisherMap() { + return INSTANCE.publisherMap; + } + + @JustForTest + public static EventPublisher getPublisher(Class topic) { + if (SlowEvent.class.isAssignableFrom(topic)) { + return INSTANCE.sharePublisher; + } + return INSTANCE.publisherMap.get(topic.getCanonicalName()); + } + + @JustForTest + public static Set getSmartSubscribes() { + return EventPublisher.SMART_SUBSCRIBES; + } + + @JustForTest + public static EventPublisher getSharePublisher() { + return INSTANCE.sharePublisher; + } + + public static void shutdown() { + if (!closed.compareAndSet(false, true)) { + return; + } + LOGGER.warn("[NotifyCenter] Start destroying Publisher"); + try { + INSTANCE.publisherMap.forEach(new BiConsumer() { + @Override + public void accept(String s, EventPublisher publisher) { + publisher.shutdown(); + } + }); + + INSTANCE.sharePublisher.shutdown(); + } catch (Throwable e) { + LOGGER.error("NotifyCenter shutdown has error : {}", e); + } + LOGGER.warn("[NotifyCenter] Destruction of the end"); + } + + /** + * Register a Subscriber. If the Publisher concerned by the Subscriber does not exist, then PublihserMap will + * preempt a placeholder Publisher first. not call {@link Publisher#start()} + * + * @param eventType Types of events that Subscriber cares about + * @param consumer subscriber + * @param event type + */ + public static void registerSubscribe(final Subscribe consumer) { + final Class cls = consumer.subscribeType(); + // If you want to listen to multiple events, you do it separately, + // without automatically registering the appropriate publisher + if (consumer instanceof SmartSubscribe) { + EventPublisher.SMART_SUBSCRIBES.add((SmartSubscribe) consumer); + return; + } + // If the event does not require additional queue resources, + // go to share-publisher to reduce resource waste + if (SlowEvent.class.isAssignableFrom(cls)) { + INSTANCE.sharePublisher.addSubscribe(consumer); + return; + } + final String topic = consumer.subscribeType().getCanonicalName(); + INSTANCE.publisherMap.computeIfAbsent(topic, s -> BUILD_FACTORY.apply(cls, RING_BUFFER_SIZE)); + EventPublisher publisher = INSTANCE.publisherMap.get(topic); + publisher.addSubscribe(consumer); + } + + /** + * deregister subscriber + * + * @param consumer subscriber + * @param + */ + public static void deregisterSubscribe(final Subscribe consumer) { + final Class cls = consumer.subscribeType(); + if (consumer instanceof SmartSubscribe) { + EventPublisher.SMART_SUBSCRIBES.remove((SmartSubscribe) consumer); + return; + } + if (SlowEvent.class.isAssignableFrom(cls)) { + INSTANCE.sharePublisher.unSubscribe(consumer); + return; + } + final String topic = consumer.subscribeType().getCanonicalName(); + if (INSTANCE.publisherMap.containsKey(topic)) { + EventPublisher publisher = INSTANCE.publisherMap.get(topic); + publisher.unSubscribe(consumer); + return; + } + throw new NoSuchElementException("The subcriber has no event publisher"); + } + + /** + * request publisher publish event Publishers load lazily, calling publisher. Start () only when the event is + * actually published + * + * @param event + */ + public static boolean publishEvent(final Event event) { + try { + return publishEvent(event.getClass(), event); + } catch (Throwable ex) { + LOGGER.error("There was an exception to the message publishing : {}", ex); + return false; + } + } + + /** + * request publisher publish event Publishers load lazily, calling publisher. Start () only when the event is + * actually published + * + * @param eventType + * @param event + */ + private static boolean publishEvent(final Class eventType, final Event event) { + final String topic = eventType.getCanonicalName(); + if (SlowEvent.class.isAssignableFrom(eventType)) { + return INSTANCE.sharePublisher.publish(event); + } + + if (INSTANCE.publisherMap.containsKey(topic)) { + EventPublisher publisher = INSTANCE.publisherMap.get(topic); + return publisher.publish(event); + } + throw new NoSuchElementException("There are no [" + topic + "] publishers for this event, please register"); + } + + /** + * register to share-publisher + * + * @param supplier + * @param eventType + * @return + */ + public static EventPublisher registerToSharePublisher(final Class eventType) { + return INSTANCE.sharePublisher; + } + + /** + * register publisher + * + * @param supplier + * @param eventType + * @param queueMaxSize + * @return + */ + public static EventPublisher registerToPublisher(final Class eventType, final int queueMaxSize) { + + if (SlowEvent.class.isAssignableFrom(eventType)) { + return INSTANCE.sharePublisher; + } + + final String topic = eventType.getCanonicalName(); + INSTANCE.publisherMap.computeIfAbsent(topic, s -> BUILD_FACTORY.apply(eventType, queueMaxSize)); + EventPublisher publisher = INSTANCE.publisherMap.get(topic); + return publisher; + } + + /** + * deregister publisher + * + * @param eventType + * @return + */ + public static void deregisterPublisher(final Class eventType) { + final String topic = eventType.getCanonicalName(); + EventPublisher publisher = INSTANCE.publisherMap.remove(topic); + publisher.shutdown(); + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/notify/SlowEvent.java b/core/src/main/java/com/alibaba/nacos/core/notify/SlowEvent.java index bdc7d500193..f105b68b842 100644 --- a/core/src/main/java/com/alibaba/nacos/core/notify/SlowEvent.java +++ b/core/src/main/java/com/alibaba/nacos/core/notify/SlowEvent.java @@ -17,9 +17,10 @@ package com.alibaba.nacos.core.notify; /** - * this event share one event-queue + * this event share one event-queue. * * @author liaochuntao */ public interface SlowEvent extends Event { + } diff --git a/core/src/main/java/com/alibaba/nacos/core/notify/listener/SmartSubscribe.java b/core/src/main/java/com/alibaba/nacos/core/notify/listener/SmartSubscribe.java index c272c480bc5..074cfa557cc 100644 --- a/core/src/main/java/com/alibaba/nacos/core/notify/listener/SmartSubscribe.java +++ b/core/src/main/java/com/alibaba/nacos/core/notify/listener/SmartSubscribe.java @@ -19,28 +19,28 @@ import com.alibaba.nacos.core.notify.Event; /** - * Subscribers to multiple events can be listened to + * Subscribers to multiple events can be listened to. * * @author liaochuntao */ @SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule") public abstract class SmartSubscribe implements Subscribe { - - /** - * Determines if the processing message is acceptable - * - * @param event {@link Event} - * @return Determines if the processing message is acceptable - */ - public abstract boolean canNotify(Event event); - - @Override - public final Class subscribeType() { - return null; - } - - @Override - public final boolean ignoreExpireEvent() { - return false; - } + + /** + * Determines if the processing message is acceptable. + * + * @param event {@link Event} + * @return Determines if the processing message is acceptable + */ + public abstract boolean canNotify(Event event); + + @Override + public final Class subscribeType() { + return null; + } + + @Override + public final boolean ignoreExpireEvent() { + return false; + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/notify/listener/Subscribe.java b/core/src/main/java/com/alibaba/nacos/core/notify/listener/Subscribe.java index e052e6dddc0..0f28f5f397b 100644 --- a/core/src/main/java/com/alibaba/nacos/core/notify/listener/Subscribe.java +++ b/core/src/main/java/com/alibaba/nacos/core/notify/listener/Subscribe.java @@ -17,43 +17,46 @@ package com.alibaba.nacos.core.notify.listener; import com.alibaba.nacos.core.notify.Event; + import java.util.concurrent.Executor; /** + * subscriber. + * * @author liaochuntao */ public interface Subscribe { - + /** - * Event callback + * Event callback. * * @param event {@link Event} */ void onEvent(T event); - + /** - * Type of this subscriber's subscription + * Type of this subscriber's subscription. * * @return Class which extends {@link Event} */ Class subscribeType(); - + /** - * It is up to the listener to determine whether the callback is asynchronous or synchronous + * It is up to the listener to determine whether the callback is asynchronous or synchronous. * * @return {@link Executor} */ default Executor executor() { return null; } - + /** - * Whether to ignore expired events + * Whether to ignore expired events. * * @return default value is {@link Boolean#FALSE} */ default boolean ignoreExpireEvent() { return false; } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/package-info.java b/core/src/main/java/com/alibaba/nacos/core/package-info.java deleted file mode 100644 index c5d00286ec6..00000000000 --- a/core/src/main/java/com/alibaba/nacos/core/package-info.java +++ /dev/null @@ -1,20 +0,0 @@ -/* - * Copyright 1999-2018 Alibaba Group Holding Ltd. - * - * Licensed 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.alibaba.nacos.core; diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/ApplicationUtils.java b/core/src/main/java/com/alibaba/nacos/core/utils/ApplicationUtils.java index 06456acf68c..0c809a2efd0 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/ApplicationUtils.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/ApplicationUtils.java @@ -57,482 +57,467 @@ import static com.alibaba.nacos.core.utils.Constants.STANDALONE_MODE_PROPERTY_NAME; /** + * Nacos global tool class. + * * @author liaochuntao */ -public class ApplicationUtils - implements ApplicationContextInitializer { - - private static ApplicationContext applicationContext; - private static ConfigurableEnvironment environment; - - public static String getId() { - return applicationContext.getId(); - } - - public static String getApplicationName() { - return applicationContext.getApplicationName(); - } - - public static String getDisplayName() { - return applicationContext.getDisplayName(); - } - - public static long getStartupDate() { - return applicationContext.getStartupDate(); - } - - public static ApplicationContext getParent() { - return applicationContext.getParent(); - } - - public static AutowireCapableBeanFactory getAutowireCapableBeanFactory() - throws IllegalStateException { - return applicationContext.getAutowireCapableBeanFactory(); - } - - public static BeanFactory getParentBeanFactory() { - return applicationContext.getParentBeanFactory(); - } - - public static boolean containsLocalBean(String name) { - return applicationContext.containsLocalBean(name); - } - - public static boolean containsBeanDefinition(String beanName) { - return applicationContext.containsLocalBean(beanName); - } - - public static int getBeanDefinitionCount() { - return applicationContext.getBeanDefinitionCount(); - } - - public static String[] getBeanDefinitionNames() { - return applicationContext.getBeanDefinitionNames(); - } - - public static String[] getBeanNamesForType(ResolvableType type) { - return applicationContext.getBeanNamesForType(type); - } - - public static String[] getBeanNamesForType(Class type) { - return applicationContext.getBeanNamesForType(type); - } - - public static String[] getBeanNamesForType(Class type, - boolean includeNonSingletons, boolean allowEagerInit) { - return applicationContext - .getBeanNamesForType(type, includeNonSingletons, allowEagerInit); - } - - public static Map getBeansOfType(Class type) throws BeansException { - return applicationContext.getBeansOfType(type); - } - - public static Map getBeansOfType(Class type, - boolean includeNonSingletons, boolean allowEagerInit) throws BeansException { - return applicationContext - .getBeansOfType(type, includeNonSingletons, allowEagerInit); - } - - public static String[] getBeanNamesForAnnotation( - Class annotationType) { - return applicationContext.getBeanNamesForAnnotation(annotationType); - } - - public static Map getBeansWithAnnotation( - Class annotationType) throws BeansException { - return applicationContext.getBeansWithAnnotation(annotationType); - } - - public static A findAnnotationOnBean(String beanName, - Class annotationType) throws NoSuchBeanDefinitionException { - return applicationContext.findAnnotationOnBean(beanName, annotationType); - } - - public static Object getBean(String name) throws BeansException { - return applicationContext.getBean(name); - } - - public static T getBean(String name, Class requiredType) - throws BeansException { - return applicationContext.getBean(name, requiredType); - } - - public static Object getBean(String name, Object... args) throws BeansException { - return applicationContext.getBean(name, args); - } - - public static T getBean(Class requiredType) throws BeansException { - return applicationContext.getBean(requiredType); - } - - public static void getBeanIfExist(Class requiredType, Consumer consumer) - throws BeansException { - try { - T bean = applicationContext.getBean(requiredType); - consumer.accept(bean); - } - catch (NoSuchBeanDefinitionException ignore) { - } - } - - public static T getBean(Class requiredType, Object... args) - throws BeansException { - return applicationContext.getBean(requiredType, args); - } - - public static ObjectProvider getBeanProvider(Class requiredType) { - return applicationContext.getBeanProvider(requiredType); - } - - public static ObjectProvider getBeanProvider(ResolvableType requiredType) { - return applicationContext.getBeanProvider(requiredType); - } - - public static boolean containsBean(String name) { - return applicationContext.containsBean(name); - } - - public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { - return applicationContext.isSingleton(name); - } - - public static boolean isPrototype(String name) throws NoSuchBeanDefinitionException { - return applicationContext.isPrototype(name); - } - - public static boolean isTypeMatch(String name, ResolvableType typeToMatch) - throws NoSuchBeanDefinitionException { - return applicationContext.isTypeMatch(name, typeToMatch); - } - - public static boolean isTypeMatch(String name, Class typeToMatch) - throws NoSuchBeanDefinitionException { - return applicationContext.isTypeMatch(name, typeToMatch); - } - - public static Class getType(String name) throws NoSuchBeanDefinitionException { - return applicationContext.getType(name); - } - - public static String[] getAliases(String name) { - return applicationContext.getAliases(name); - } - - public static void publishEvent(Object event) { - applicationContext.publishEvent(event); - } - - public static String getMessage(String code, Object[] args, String defaultMessage, - Locale locale) { - return applicationContext.getMessage(code, args, defaultMessage, locale); - } - - public static String getMessage(String code, Object[] args, Locale locale) - throws NoSuchMessageException { - return applicationContext.getMessage(code, args, locale); - } - - public static String getMessage(MessageSourceResolvable resolvable, Locale locale) - throws NoSuchMessageException { - return applicationContext.getMessage(resolvable, locale); - } - - public static Resource[] getResources(String locationPattern) throws IOException { - return applicationContext.getResources(locationPattern); - } - - public static Resource getResource(String location) { - return applicationContext.getResource(location); - } - - public static ClassLoader getClassLoader() { - return applicationContext.getClassLoader(); - } - - public static ApplicationContext getApplicationContext() { - return applicationContext; - } - - public static ConfigurableEnvironment getEnvironment() { - return environment; - } - - public static String[] getActiveProfiles() { - return environment.getActiveProfiles(); - } - - public static String[] getDefaultProfiles() { - return environment.getDefaultProfiles(); - } - - public static boolean acceptsProfiles(String... strings) { - return environment.acceptsProfiles(strings); - } - - public static boolean acceptsProfiles(Profiles profiles) { - return environment.acceptsProfiles(profiles); - } - - public static boolean containsProperty(String key) { - return environment.containsProperty(key); - } - - public static String getProperty(String key) { - return environment.getProperty(key); - } - - public static String getProperty(String key, String defaultValue) { - return environment.getProperty(key, defaultValue); - } - - public static T getProperty(String key, Class targetType) { - return environment.getProperty(key, targetType); - } - - public static T getProperty(String key, Class targetType, T defaultValue) { - return environment.getProperty(key, targetType, defaultValue); - } - - public static String getRequiredProperty(String key) throws IllegalStateException { - return environment.getRequiredProperty(key); - } - - public static T getRequiredProperty(String key, Class targetType) - throws IllegalStateException { - return environment.getRequiredProperty(key, targetType); - } - - public static String resolvePlaceholders(String text) { - return environment.resolvePlaceholders(text); - } - - public static String resolveRequiredPlaceholders(String text) - throws IllegalArgumentException { - return environment.resolveRequiredPlaceholders(text); - } - - private static String localAddress = ""; - - public static String getLocalAddress() { - if (StringUtils.isBlank(localAddress)) { - localAddress = InetUtils.getSelfIp() + ":" + getPort(); - } - return localAddress; - } - - public static void setLocalAddress(String localAddress) { - ApplicationUtils.localAddress = localAddress; - } - - private static int port = -1; - - public static int getPort() { - if (port == -1) { - port = getProperty("server.port", Integer.class, 8848); - } - return port; - } - - public static void setPort(int port) { - ApplicationUtils.port = port; - } - - public static final String STANDALONE_MODE_ALONE = "standalone"; - public static final String STANDALONE_MODE_CLUSTER = "cluster"; - - public static final String FUNCTION_MODE_CONFIG = "config"; - public static final String FUNCTION_MODE_NAMING = "naming"; - - /** - * The key of nacos home. - */ - public static final String NACOS_HOME_KEY = "nacos.home"; - - private static Boolean isStandalone = null; - - private static String functionModeType = null; - - private static String contextPath = ""; - - public static String getContextPath() { - if (StringUtils.isBlank(contextPath)) { - if (StringUtils.isBlank(contextPath)) { - contextPath = getProperty(Constants.WEB_CONTEXT_PATH, "/nacos"); - } - if (Constants.ROOT_WEB_CONTEXT_PATH.equals(contextPath)) { - return StringUtils.EMPTY; - } - else { - return contextPath; - } - } - return contextPath; - } - - public static void setContextPath(String contextPath) { - ApplicationUtils.contextPath = contextPath; - } - - @JustForTest - public static void setIsStandalone(Boolean isStandalone) { - ApplicationUtils.isStandalone = isStandalone; - } - - /** - * Standalone mode or not - */ - public static boolean getStandaloneMode() { - if (Objects.isNull(isStandalone)) { - isStandalone = Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME); - } - return isStandalone; - } - - /** - * server - */ - public static String getFunctionMode() { - if (StringUtils.isEmpty(functionModeType)) { - functionModeType = System.getProperty(FUNCTION_MODE_PROPERTY_NAME); - } - return functionModeType; - } - - @JustForTest - private static String NACOS_HOME_PATH = null; - - public static String getNacosHome() { - if (StringUtils.isBlank(NACOS_HOME_PATH)) { - String nacosHome = System.getProperty(NACOS_HOME_KEY); - if (StringUtils.isBlank(nacosHome)) { - nacosHome = Paths.get(System.getProperty("user.home"), "nacos").toString(); - } - return nacosHome; - } - // test-first - return NACOS_HOME_PATH; - } - - @JustForTest - public static void setNacosHomePath(String nacosHomePath) { - NACOS_HOME_PATH = nacosHomePath; - } - - private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory - .getOperatingSystemMXBean(); - - public static List getIPsBySystemEnv(String key) { - String env = getSystemEnv(key); - List ips = new ArrayList<>(); - if (StringUtils.isNotEmpty(env)) { - ips = Arrays.asList(env.split(",")); - } - return ips; - } - - public static String getSystemEnv(String key) { - return System.getenv(key); - } - - public static float getLoad() { - return (float) operatingSystemMXBean.getSystemLoadAverage(); - } - - public static float getCPU() { - return (float) operatingSystemMXBean.getSystemCpuLoad(); - } - - public static float getMem() { - return (float) (1 - (double) operatingSystemMXBean.getFreePhysicalMemorySize() - / (double) operatingSystemMXBean.getTotalPhysicalMemorySize()); - } - - public static String getConfFilePath() { - return Paths.get(getNacosHome(), "conf").toString(); - } - - public static String getClusterConfFilePath() { - return Paths.get(getNacosHome(), "conf", "cluster.conf").toString(); - } - - public static List readClusterConf() throws IOException { - try (Reader reader = new InputStreamReader( - new FileInputStream(new File(getClusterConfFilePath())), - StandardCharsets.UTF_8)) { - return analyzeClusterConf(reader); - } catch (FileNotFoundException ignore) { - List tmp = new ArrayList<>(); - String clusters = ApplicationUtils.getMemberList(); - if (StringUtils.isNotBlank(clusters)) { - String[] details = clusters.split(","); - for (String item : details) { - tmp.add(item.trim()); - } - } - return tmp; - } - } - - public static List analyzeClusterConf(Reader reader) throws IOException { - List instanceList = new ArrayList(); - List lines = IoUtils.readLines(reader); - String comment = "#"; - for (String line : lines) { - String instance = line.trim(); - if (instance.startsWith(comment)) { - // # it is ip - continue; - } - if (instance.contains(comment)) { - // 192.168.71.52:8848 # Instance A - instance = instance.substring(0, instance.indexOf(comment)); - instance = instance.trim(); - } - int multiIndex = instance.indexOf(Constants.COMMA_DIVISION); - if (multiIndex > 0) { - // support the format: ip1:port,ip2:port # multi inline - instanceList - .addAll(Arrays.asList(instance.split(Constants.COMMA_DIVISION))); - } - else { - //support the format: 192.168.71.52:8848 - instanceList.add(instance); - } - } - return instanceList; - } - - public static void writeClusterConf(String content) throws IOException { - DiskUtils.writeFile(new File(getClusterConfFilePath()), content.getBytes(StandardCharsets.UTF_8), false); - } - - public static String getMemberList() { - String val = null; - if (environment == null) { - val = System.getenv("nacos.member.list"); - if (StringUtils.isBlank(val)) { - val = System.getProperty("nacos.member.list"); - } - } else { - val = getProperty("nacos.member.list"); - } - return val; - } - - @Override - public void initialize(ConfigurableApplicationContext context) { - applicationContext = context; - environment = context.getEnvironment(); - } - - public static void injectEnvironment(ConfigurableEnvironment environment) { - ApplicationUtils.environment = environment; - } - - public static void injectContext(ConfigurableApplicationContext context) { - ApplicationUtils.applicationContext = context; - } - +@SuppressWarnings("all") +public class ApplicationUtils implements ApplicationContextInitializer { + + public static final String STANDALONE_MODE_ALONE = "standalone"; + + public static final String STANDALONE_MODE_CLUSTER = "cluster"; + + public static final String FUNCTION_MODE_CONFIG = "config"; + + public static final String FUNCTION_MODE_NAMING = "naming"; + + /** + * The key of nacos home. + */ + public static final String NACOS_HOME_KEY = "nacos.home"; + + private static ApplicationContext applicationContext; + + private static ConfigurableEnvironment environment; + + private static String localAddress = ""; + + private static int port = -1; + + private static Boolean isStandalone = null; + + private static String functionModeType = null; + + private static String contextPath = ""; + + @JustForTest + private static String NACOS_HOME_PATH = null; + + private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory + .getOperatingSystemMXBean(); + + public static String getId() { + return applicationContext.getId(); + } + + public static String getApplicationName() { + return applicationContext.getApplicationName(); + } + + public static String getDisplayName() { + return applicationContext.getDisplayName(); + } + + public static long getStartupDate() { + return applicationContext.getStartupDate(); + } + + public static ApplicationContext getParent() { + return applicationContext.getParent(); + } + + public static AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException { + return applicationContext.getAutowireCapableBeanFactory(); + } + + public static BeanFactory getParentBeanFactory() { + return applicationContext.getParentBeanFactory(); + } + + public static boolean containsLocalBean(String name) { + return applicationContext.containsLocalBean(name); + } + + public static boolean containsBeanDefinition(String beanName) { + return applicationContext.containsLocalBean(beanName); + } + + public static int getBeanDefinitionCount() { + return applicationContext.getBeanDefinitionCount(); + } + + public static String[] getBeanDefinitionNames() { + return applicationContext.getBeanDefinitionNames(); + } + + public static String[] getBeanNamesForType(ResolvableType type) { + return applicationContext.getBeanNamesForType(type); + } + + public static String[] getBeanNamesForType(Class type) { + return applicationContext.getBeanNamesForType(type); + } + + public static String[] getBeanNamesForType(Class type, boolean includeNonSingletons, boolean allowEagerInit) { + return applicationContext.getBeanNamesForType(type, includeNonSingletons, allowEagerInit); + } + + public static Map getBeansOfType(Class type) throws BeansException { + return applicationContext.getBeansOfType(type); + } + + public static Map getBeansOfType(Class type, boolean includeNonSingletons, boolean allowEagerInit) + throws BeansException { + return applicationContext.getBeansOfType(type, includeNonSingletons, allowEagerInit); + } + + public static String[] getBeanNamesForAnnotation(Class annotationType) { + return applicationContext.getBeanNamesForAnnotation(annotationType); + } + + public static Map getBeansWithAnnotation(Class annotationType) + throws BeansException { + return applicationContext.getBeansWithAnnotation(annotationType); + } + + public static A findAnnotationOnBean(String beanName, Class annotationType) + throws NoSuchBeanDefinitionException { + return applicationContext.findAnnotationOnBean(beanName, annotationType); + } + + public static Object getBean(String name) throws BeansException { + return applicationContext.getBean(name); + } + + public static T getBean(String name, Class requiredType) throws BeansException { + return applicationContext.getBean(name, requiredType); + } + + public static Object getBean(String name, Object... args) throws BeansException { + return applicationContext.getBean(name, args); + } + + public static T getBean(Class requiredType) throws BeansException { + return applicationContext.getBean(requiredType); + } + + public static void getBeanIfExist(Class requiredType, Consumer consumer) throws BeansException { + try { + T bean = applicationContext.getBean(requiredType); + consumer.accept(bean); + } catch (NoSuchBeanDefinitionException ignore) { + } + } + + public static T getBean(Class requiredType, Object... args) throws BeansException { + return applicationContext.getBean(requiredType, args); + } + + public static ObjectProvider getBeanProvider(Class requiredType) { + return applicationContext.getBeanProvider(requiredType); + } + + public static ObjectProvider getBeanProvider(ResolvableType requiredType) { + return applicationContext.getBeanProvider(requiredType); + } + + public static boolean containsBean(String name) { + return applicationContext.containsBean(name); + } + + public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + return applicationContext.isSingleton(name); + } + + public static boolean isPrototype(String name) throws NoSuchBeanDefinitionException { + return applicationContext.isPrototype(name); + } + + public static boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException { + return applicationContext.isTypeMatch(name, typeToMatch); + } + + public static boolean isTypeMatch(String name, Class typeToMatch) throws NoSuchBeanDefinitionException { + return applicationContext.isTypeMatch(name, typeToMatch); + } + + public static Class getType(String name) throws NoSuchBeanDefinitionException { + return applicationContext.getType(name); + } + + public static String[] getAliases(String name) { + return applicationContext.getAliases(name); + } + + public static void publishEvent(Object event) { + applicationContext.publishEvent(event); + } + + public static String getMessage(String code, Object[] args, String defaultMessage, Locale locale) { + return applicationContext.getMessage(code, args, defaultMessage, locale); + } + + public static String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException { + return applicationContext.getMessage(code, args, locale); + } + + public static String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException { + return applicationContext.getMessage(resolvable, locale); + } + + public static Resource[] getResources(String locationPattern) throws IOException { + return applicationContext.getResources(locationPattern); + } + + public static Resource getResource(String location) { + return applicationContext.getResource(location); + } + + public static ClassLoader getClassLoader() { + return applicationContext.getClassLoader(); + } + + public static ApplicationContext getApplicationContext() { + return applicationContext; + } + + public static ConfigurableEnvironment getEnvironment() { + return environment; + } + + public static String[] getActiveProfiles() { + return environment.getActiveProfiles(); + } + + public static String[] getDefaultProfiles() { + return environment.getDefaultProfiles(); + } + + public static boolean acceptsProfiles(String... strings) { + return environment.acceptsProfiles(strings); + } + + public static boolean acceptsProfiles(Profiles profiles) { + return environment.acceptsProfiles(profiles); + } + + public static boolean containsProperty(String key) { + return environment.containsProperty(key); + } + + public static String getProperty(String key) { + return environment.getProperty(key); + } + + public static String getProperty(String key, String defaultValue) { + return environment.getProperty(key, defaultValue); + } + + public static T getProperty(String key, Class targetType) { + return environment.getProperty(key, targetType); + } + + public static T getProperty(String key, Class targetType, T defaultValue) { + return environment.getProperty(key, targetType, defaultValue); + } + + public static String getRequiredProperty(String key) throws IllegalStateException { + return environment.getRequiredProperty(key); + } + + public static T getRequiredProperty(String key, Class targetType) throws IllegalStateException { + return environment.getRequiredProperty(key, targetType); + } + + public static String resolvePlaceholders(String text) { + return environment.resolvePlaceholders(text); + } + + public static String resolveRequiredPlaceholders(String text) throws IllegalArgumentException { + return environment.resolveRequiredPlaceholders(text); + } + + public static String getLocalAddress() { + if (StringUtils.isBlank(localAddress)) { + localAddress = InetUtils.getSelfIp() + ":" + getPort(); + } + return localAddress; + } + + public static void setLocalAddress(String localAddress) { + ApplicationUtils.localAddress = localAddress; + } + + public static int getPort() { + if (port == -1) { + port = getProperty("server.port", Integer.class, 8848); + } + return port; + } + + public static void setPort(int port) { + ApplicationUtils.port = port; + } + + public static String getContextPath() { + if (StringUtils.isBlank(contextPath)) { + if (StringUtils.isBlank(contextPath)) { + contextPath = getProperty(Constants.WEB_CONTEXT_PATH, "/nacos"); + } + if (Constants.ROOT_WEB_CONTEXT_PATH.equals(contextPath)) { + return StringUtils.EMPTY; + } else { + return contextPath; + } + } + return contextPath; + } + + public static void setContextPath(String contextPath) { + ApplicationUtils.contextPath = contextPath; + } + + @JustForTest + public static void setIsStandalone(Boolean isStandalone) { + ApplicationUtils.isStandalone = isStandalone; + } + + /** + * Standalone mode or not + */ + public static boolean getStandaloneMode() { + if (Objects.isNull(isStandalone)) { + isStandalone = Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME); + } + return isStandalone; + } + + /** + * server + */ + public static String getFunctionMode() { + if (StringUtils.isEmpty(functionModeType)) { + functionModeType = System.getProperty(FUNCTION_MODE_PROPERTY_NAME); + } + return functionModeType; + } + + public static String getNacosHome() { + if (StringUtils.isBlank(NACOS_HOME_PATH)) { + String nacosHome = System.getProperty(NACOS_HOME_KEY); + if (StringUtils.isBlank(nacosHome)) { + nacosHome = Paths.get(System.getProperty("user.home"), "nacos").toString(); + } + return nacosHome; + } + // test-first + return NACOS_HOME_PATH; + } + + @JustForTest + public static void setNacosHomePath(String nacosHomePath) { + NACOS_HOME_PATH = nacosHomePath; + } + + public static List getIPsBySystemEnv(String key) { + String env = getSystemEnv(key); + List ips = new ArrayList<>(); + if (StringUtils.isNotEmpty(env)) { + ips = Arrays.asList(env.split(",")); + } + return ips; + } + + public static String getSystemEnv(String key) { + return System.getenv(key); + } + + public static float getLoad() { + return (float) operatingSystemMXBean.getSystemLoadAverage(); + } + + public static float getCPU() { + return (float) operatingSystemMXBean.getSystemCpuLoad(); + } + + public static float getMem() { + return (float) (1 - (double) operatingSystemMXBean.getFreePhysicalMemorySize() / (double) operatingSystemMXBean + .getTotalPhysicalMemorySize()); + } + + public static String getConfFilePath() { + return Paths.get(getNacosHome(), "conf").toString(); + } + + public static String getClusterConfFilePath() { + return Paths.get(getNacosHome(), "conf", "cluster.conf").toString(); + } + + public static List readClusterConf() throws IOException { + try (Reader reader = new InputStreamReader(new FileInputStream(new File(getClusterConfFilePath())), + StandardCharsets.UTF_8)) { + return analyzeClusterConf(reader); + } catch (FileNotFoundException ignore) { + List tmp = new ArrayList<>(); + String clusters = ApplicationUtils.getMemberList(); + if (StringUtils.isNotBlank(clusters)) { + String[] details = clusters.split(","); + for (String item : details) { + tmp.add(item.trim()); + } + } + return tmp; + } + } + + public static List analyzeClusterConf(Reader reader) throws IOException { + List instanceList = new ArrayList(); + List lines = IoUtils.readLines(reader); + String comment = "#"; + for (String line : lines) { + String instance = line.trim(); + if (instance.startsWith(comment)) { + // # it is ip + continue; + } + if (instance.contains(comment)) { + // 192.168.71.52:8848 # Instance A + instance = instance.substring(0, instance.indexOf(comment)); + instance = instance.trim(); + } + int multiIndex = instance.indexOf(Constants.COMMA_DIVISION); + if (multiIndex > 0) { + // support the format: ip1:port,ip2:port # multi inline + instanceList.addAll(Arrays.asList(instance.split(Constants.COMMA_DIVISION))); + } else { + //support the format: 192.168.71.52:8848 + instanceList.add(instance); + } + } + return instanceList; + } + + public static void writeClusterConf(String content) throws IOException { + DiskUtils.writeFile(new File(getClusterConfFilePath()), content.getBytes(StandardCharsets.UTF_8), false); + } + + public static String getMemberList() { + String val = null; + if (environment == null) { + val = System.getenv("nacos.member.list"); + if (StringUtils.isBlank(val)) { + val = System.getProperty("nacos.member.list"); + } + } else { + val = getProperty("nacos.member.list"); + } + return val; + } + + public static void injectEnvironment(ConfigurableEnvironment environment) { + ApplicationUtils.environment = environment; + } + + public static void injectContext(ConfigurableApplicationContext context) { + ApplicationUtils.applicationContext = context; + } + + @Override + public void initialize(ConfigurableApplicationContext context) { + applicationContext = context; + environment = context.getEnvironment(); + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/ClassUtils.java b/core/src/main/java/com/alibaba/nacos/core/utils/ClassUtils.java index 42a3a02bf09..7831425d5ce 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/ClassUtils.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/ClassUtils.java @@ -21,55 +21,57 @@ import java.util.Objects; /** + * class operation utils. + * * @author liaochuntao */ @SuppressWarnings("all") public final class ClassUtils { - - public static Class resolveGenericType(Class declaredClass) { - return (Class) ResolvableType.forClass(declaredClass).getSuperType().resolveGeneric(0); - } - - public static Class resolveGenericTypeByInterface(Class declaredClass) { - return (Class) ResolvableType.forClass(declaredClass).getInterfaces()[0].resolveGeneric(0); - } - - public static Class findClassByName(String className) { - try { - return Class.forName(className); - } catch (Exception e) { - throw new RuntimeException("this class name not found"); - } - } - - public static String getName(Object obj) { - Objects.requireNonNull(obj, "obj"); - return obj.getClass().getName(); - } - - public static String getCanonicalName(Object obj) { - Objects.requireNonNull(obj, "obj"); - return obj.getClass().getCanonicalName(); - } - - public static String getSimplaName(Object obj) { - Objects.requireNonNull(obj, "obj"); - return obj.getClass().getSimpleName(); - } - - public static String getName(Class cls) { - Objects.requireNonNull(cls, "cls"); - return cls.getName(); - } - - public static String getCanonicalName(Class cls) { - Objects.requireNonNull(cls, "cls"); - return cls.getCanonicalName(); - } - - public static String getSimplaName(Class cls) { - Objects.requireNonNull(cls, "cls"); - return cls.getSimpleName(); - } - + + public static Class resolveGenericType(Class declaredClass) { + return (Class) ResolvableType.forClass(declaredClass).getSuperType().resolveGeneric(0); + } + + public static Class resolveGenericTypeByInterface(Class declaredClass) { + return (Class) ResolvableType.forClass(declaredClass).getInterfaces()[0].resolveGeneric(0); + } + + public static Class findClassByName(String className) { + try { + return Class.forName(className); + } catch (Exception e) { + throw new RuntimeException("this class name not found"); + } + } + + public static String getName(Object obj) { + Objects.requireNonNull(obj, "obj"); + return obj.getClass().getName(); + } + + public static String getCanonicalName(Object obj) { + Objects.requireNonNull(obj, "obj"); + return obj.getClass().getCanonicalName(); + } + + public static String getSimplaName(Object obj) { + Objects.requireNonNull(obj, "obj"); + return obj.getClass().getSimpleName(); + } + + public static String getName(Class cls) { + Objects.requireNonNull(cls, "cls"); + return cls.getName(); + } + + public static String getCanonicalName(Class cls) { + Objects.requireNonNull(cls, "cls"); + return cls.getCanonicalName(); + } + + public static String getSimplaName(Class cls) { + Objects.requireNonNull(cls, "cls"); + return cls.getSimpleName(); + } + } \ No newline at end of file diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/Commons.java b/core/src/main/java/com/alibaba/nacos/core/utils/Commons.java index 7d9ee6209b0..527f1714d83 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/Commons.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/Commons.java @@ -17,16 +17,18 @@ package com.alibaba.nacos.core.utils; /** + * Constants. + * * @author liaochuntao */ public final class Commons { - + public static final String NACOS_SERVER_CONTEXT = "/nacos"; - + public static final String NACOS_SERVER_VERSION = "/v1"; - + public static final String DEFAULT_NACOS_CORE_CONTEXT = NACOS_SERVER_VERSION + "/core"; - + public static final String NACOS_CORE_CONTEXT = DEFAULT_NACOS_CORE_CONTEXT; - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/Constants.java b/core/src/main/java/com/alibaba/nacos/core/utils/Constants.java index da4d7284452..5135c22664f 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/Constants.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/Constants.java @@ -13,43 +13,44 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.utils; /** - * Nacos common constants + * Nacos common constants. * * @author Mercy * @since 0.2.2 */ public interface Constants { - + /** - * Spring Profile : "standalone" + * Spring Profile : "standalone". */ String STANDALONE_SPRING_PROFILE = "standalone"; - + /** - * The System property name of Standalone mode + * The System property name of Standalone mode. */ String STANDALONE_MODE_PROPERTY_NAME = "nacos.standalone"; - + /** - * The System property name of Function mode + * The System property name of Function mode. */ String FUNCTION_MODE_PROPERTY_NAME = "nacos.functionMode"; - + /** - * The System property name of prefer hostname over ip + * The System property name of prefer hostname over ip. */ String PREFER_HOSTNAME_OVER_IP_PROPERTY_NAME = "nacos.preferHostnameOverIp"; - + /** - * the root context path + * the root context path. */ String ROOT_WEB_CONTEXT_PATH = "/"; - + String NACOS_SERVER_IP = "nacos.server.ip"; - + String USE_ONLY_SITE_INTERFACES = "nacos.inetutils.use-only-site-local-interfaces"; String PREFERRED_NETWORKS = "nacos.inetutils.preferred-networks"; String IGNORED_INTERFACES = "nacos.inetutils.ignored-interfaces"; @@ -58,6 +59,6 @@ public interface Constants { String SYSTEM_PREFER_HOSTNAME_OVER_IP = "nacos.preferHostnameOverIp"; String WEB_CONTEXT_PATH = "server.servlet.context-path"; String COMMA_DIVISION = ","; - + String NACOS_SERVER_HEADER = "Nacos-Server"; } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/DiskUtils.java b/core/src/main/java/com/alibaba/nacos/core/utils/DiskUtils.java index 023d9644c22..a43faf5e3af 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/DiskUtils.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/DiskUtils.java @@ -16,6 +16,13 @@ package com.alibaba.nacos.core.utils; +import com.alibaba.nacos.common.utils.ByteUtils; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.io.output.NullOutputStream; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.BufferedReader; @@ -40,36 +47,53 @@ import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; -import com.alibaba.nacos.common.utils.ByteUtils; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.io.output.NullOutputStream; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - /** + * IO operates on the utility class. + * * @author liaochuntao */ public final class DiskUtils { - - private static final Logger logger = LoggerFactory.getLogger(DiskUtils.class); - - private final static String NO_SPACE_CN = "设备上没有空间"; - private final static String NO_SPACE_EN = "No space left on device"; - private final static String DISK_QUATA_CN = "超出磁盘限额"; - private final static String DISK_QUATA_EN = "Disk quota exceeded"; - + + private static final Logger LOGGER = LoggerFactory.getLogger(DiskUtils.class); + + private static final String NO_SPACE_CN = "设备上没有空间"; + + private static final String NO_SPACE_EN = "No space left on device"; + + private static final String DISK_QUATA_CN = "超出磁盘限额"; + + private static final String DISK_QUATA_EN = "Disk quota exceeded"; + private static final Charset CHARSET = StandardCharsets.UTF_8; + private static final CharsetDecoder DECODER = CHARSET.newDecoder(); - + public static void touch(String path, String fileName) throws IOException { FileUtils.touch(Paths.get(path, fileName).toFile()); } - + + /** + * Implements the same behaviour as the "touch" utility on Unix. It creates a new file with size 0 or, if the file + * exists already, it is opened and closed without modifying it, but updating the file date and time. + * + *

      NOTE: As from v1.3, this method throws an IOException if the last + * modified date of the file cannot be set. Also, as from v1.3 this method creates parent directories if they do not + * exist. + * + * @param file the File to touch + * @throws IOException If an I/O problem occurs + */ public static void touch(File file) throws IOException { FileUtils.touch(file); } - + + /** + * read file which under the path. + * + * @param path directory + * @param fileName filename + * @return content + */ public static String readFile(String path, String fileName) { File file = openFile(path, fileName); if (file.exists()) { @@ -77,7 +101,13 @@ public static String readFile(String path, String fileName) { } return null; } - + + /** + * read file content by {@link InputStream}. + * + * @param is {@link InputStream} + * @return content + */ public static String readFile(InputStream is) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) { StringBuilder textBuilder = new StringBuilder(); @@ -90,7 +120,13 @@ public static String readFile(InputStream is) { return null; } } - + + /** + * read this file content. + * + * @param file {@link File} + * @return content + */ public static String readFile(File file) { try (FileChannel fileChannel = new FileInputStream(file).getChannel()) { StringBuilder text = new StringBuilder(); @@ -111,7 +147,13 @@ public static String readFile(File file) { return null; } } - + + /** + * read this file content then return bytes. + * + * @param file {@link File} + * @return content bytes + */ public static byte[] readFileBytes(File file) { if (file.exists()) { String result = readFile(file); @@ -121,12 +163,20 @@ public static byte[] readFileBytes(File file) { } return null; } - + public static byte[] readFileBytes(String path, String fileName) { File file = openFile(path, fileName); return readFileBytes(file); } - + + /** + * Writes the contents to the target file. + * + * @param file target file + * @param content content + * @param append write append mode + * @return write success + */ public static boolean writeFile(File file, byte[] content, boolean append) { try (FileChannel fileChannel = new FileOutputStream(file, append).getChannel()) { ByteBuffer buffer = ByteBuffer.wrap(content); @@ -135,17 +185,23 @@ public static boolean writeFile(File file, byte[] content, boolean append) { } catch (IOException ioe) { if (ioe.getMessage() != null) { String errMsg = ioe.getMessage(); - if (NO_SPACE_CN.equals(errMsg) || NO_SPACE_EN.equals(errMsg) - || errMsg.contains(DISK_QUATA_CN) - || errMsg.contains(DISK_QUATA_EN)) { - logger.warn("磁盘满,自杀退出"); + if (NO_SPACE_CN.equals(errMsg) || NO_SPACE_EN.equals(errMsg) || errMsg.contains(DISK_QUATA_CN) || errMsg + .contains(DISK_QUATA_EN)) { + LOGGER.warn("磁盘满,自杀退出"); System.exit(0); } } } return false; } - + + /** + * delete target file. + * + * @param path directory + * @param fileName filename + * @return delete success + */ public static boolean deleteFile(String path, String fileName) { File file = openFile(path, fileName); if (file.exists()) { @@ -153,36 +209,44 @@ public static boolean deleteFile(String path, String fileName) { } return false; } - + public static void deleteDirectory(String path) throws IOException { FileUtils.deleteDirectory(new File(path)); } - + public static void forceMkdir(String path) throws IOException { FileUtils.forceMkdir(new File(path)); } - + public static void forceMkdir(File file) throws IOException { FileUtils.forceMkdir(file); } - + public static void deleteDirThenMkdir(String path) throws IOException { deleteDirectory(path); forceMkdir(path); } - + public static void copyDirectory(File srcDir, File destDir) throws IOException { FileUtils.copyDirectory(srcDir, destDir); } - + public static void copyFile(File src, File target) throws IOException { FileUtils.copyFile(src, target); } - + public static File openFile(String path, String fileName) { return openFile(path, fileName, false); } - + + /** + * open file. + * + * @param path directory + * @param fileName filename + * @param rewrite if rewrite is true, will delete old file and create new one + * @return {@link File} + */ public static File openFile(String path, String fileName, boolean rewrite) { File directory = new File(path); boolean mkdirs = true; @@ -190,7 +254,7 @@ public static File openFile(String path, String fileName, boolean rewrite) { mkdirs = directory.mkdirs(); } if (!mkdirs) { - logger.error("[DiskUtils] can't create directory"); + LOGGER.error("[DiskUtils] can't create directory"); return null; } File file = new File(path, fileName); @@ -214,24 +278,33 @@ public static File openFile(String path, String fileName, boolean rewrite) { } return file; } - + // copy from sofa-jraft - + + /** + * Compress a folder in a directory. + * + * @param rootDir directory + * @param sourceDir folder + * @param outputFile output file + * @param checksum checksum + * @throws IOException IOException + */ public static void compress(final String rootDir, final String sourceDir, final String outputFile, - final Checksum checksum) throws IOException { - try (final FileOutputStream fos = new FileOutputStream(outputFile); - final CheckedOutputStream cos = new CheckedOutputStream(fos, checksum); - final ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(cos))) { + final Checksum checksum) throws IOException { + try (final FileOutputStream fos = new FileOutputStream( + outputFile); final CheckedOutputStream cos = new CheckedOutputStream(fos, checksum); + final ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(cos))) { compressDirectoryToZipFile(rootDir, sourceDir, zos); zos.flush(); fos.getFD().sync(); } } - + // copy from sofa-jraft - + private static void compressDirectoryToZipFile(final String rootDir, final String sourceDir, - final ZipOutputStream zos) throws IOException { + final ZipOutputStream zos) throws IOException { final String dir = Paths.get(rootDir, sourceDir).toString(); final File[] files = Objects.requireNonNull(new File(dir).listFiles(), "files"); for (final File file : files) { @@ -240,28 +313,36 @@ private static void compressDirectoryToZipFile(final String rootDir, final Strin compressDirectoryToZipFile(rootDir, child, zos); } else { zos.putNextEntry(new ZipEntry(child)); - try (final FileInputStream fis = new FileInputStream(file); - final BufferedInputStream bis = new BufferedInputStream(fis)) { + try (final FileInputStream fis = new FileInputStream( + file); final BufferedInputStream bis = new BufferedInputStream(fis)) { IOUtils.copy(bis, zos); } } } } - + // copy from sofa-jraft - + + /** + * Unzip the target file to the specified folder. + * + * @param sourceFile target file + * @param outputDir specified folder + * @param checksum checksum + * @throws IOException IOException + */ public static void decompress(final String sourceFile, final String outputDir, final Checksum checksum) throws IOException { - try (final FileInputStream fis = new FileInputStream(sourceFile); - final CheckedInputStream cis = new CheckedInputStream(fis, checksum); - final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(cis))) { + try (final FileInputStream fis = new FileInputStream( + sourceFile); final CheckedInputStream cis = new CheckedInputStream(fis, checksum); + final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(cis))) { ZipEntry entry; while ((entry = zis.getNextEntry()) != null) { final String fileName = entry.getName(); final File entryFile = new File(Paths.get(outputDir, fileName).toString()); FileUtils.forceMkdir(entryFile.getParentFile()); - try (final FileOutputStream fos = new FileOutputStream(entryFile); - final BufferedOutputStream bos = new BufferedOutputStream(fos)) { + try (final FileOutputStream fos = new FileOutputStream( + entryFile); final BufferedOutputStream bos = new BufferedOutputStream(fos)) { IOUtils.copy(zis, bos); bos.flush(); fos.getFD().sync(); @@ -274,5 +355,5 @@ public static void decompress(final String sourceFile, final String outputDir, f IOUtils.copy(cis, NullOutputStream.NULL_OUTPUT_STREAM); } } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/GenericType.java b/core/src/main/java/com/alibaba/nacos/core/utils/GenericType.java index f744d92f459..5dd578e3cbc 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/GenericType.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/GenericType.java @@ -19,12 +19,12 @@ import com.google.common.reflect.TypeToken; /** - * Encapsulates third party tools for generics acquisition + * Encapsulates third party tools for generics acquisition. * * @author liaochuntao */ public class GenericType extends TypeToken { - - private static final long serialVersionUID = -2103808581228167629L; - + + private static final long serialVersionUID = -2103808581228167629L; + } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/GlobalExecutor.java b/core/src/main/java/com/alibaba/nacos/core/utils/GlobalExecutor.java index 0fde48550d1..b981daea6f4 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/GlobalExecutor.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/GlobalExecutor.java @@ -22,32 +22,35 @@ import java.util.concurrent.TimeUnit; /** + * core module global executor. + * * @author liaochuntao */ +@SuppressWarnings("all") public class GlobalExecutor { - + private static final ScheduledExecutorService COMMON_EXECUTOR = ExecutorFactory.Managed.newScheduledExecutorService( ClassUtils.getCanonicalName(GlobalExecutor.class), 4, new NameThreadFactory("com.alibaba.nacos.core.common") ); - + public static void runWithoutThread(Runnable runnable) { runnable.run(); } - + public static void executeByCommon(Runnable runnable) { if (COMMON_EXECUTOR.isShutdown()) { return; } COMMON_EXECUTOR.execute(runnable); } - + public static void scheduleByCommon(Runnable runnable, long delayMs) { if (COMMON_EXECUTOR.isShutdown()) { return; } COMMON_EXECUTOR.schedule(runnable, delayMs, TimeUnit.MILLISECONDS); } - -} + +} \ No newline at end of file diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/InetUtils.java b/core/src/main/java/com/alibaba/nacos/core/utils/InetUtils.java index fe813359792..fa4bccd1cde 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/InetUtils.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/InetUtils.java @@ -34,75 +34,52 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; -import static com.alibaba.nacos.core.utils.Constants.*; +import static com.alibaba.nacos.core.utils.Constants.IGNORED_INTERFACES; +import static com.alibaba.nacos.core.utils.Constants.IP_ADDRESS; +import static com.alibaba.nacos.core.utils.Constants.NACOS_SERVER_IP; +import static com.alibaba.nacos.core.utils.Constants.PREFERRED_NETWORKS; +import static com.alibaba.nacos.core.utils.Constants.PREFER_HOSTNAME_OVER_IP; +import static com.alibaba.nacos.core.utils.Constants.SYSTEM_PREFER_HOSTNAME_OVER_IP; +import static com.alibaba.nacos.core.utils.Constants.USE_ONLY_SITE_INTERFACES; /** + * Network card operation tool class. + * * @author Nacos */ public class InetUtils { - - /** - * {@link com.alibaba.nacos.core.cluster.ServerMemberManager} is listener - */ - @SuppressWarnings("PMD.ClassNamingShouldBeCamelRule") - public static class IPChangeEvent implements SlowEvent { - - private String oldIp; - private String newIp; - - public String getOldIp() { - return oldIp; - } - - public void setOldIp(String oldIp) { - this.oldIp = oldIp; - } - - public String getNewIp() { - return newIp; - } - - public void setNewIp(String newIp) { - this.newIp = newIp; - } - - @Override - public String toString() { - return "IPChangeEvent{" + "oldIp='" + oldIp + '\'' + ", newIp='" - + newIp + '\'' + '}'; - } - } - - private static final Logger log = LoggerFactory.getLogger(InetUtils.class); - + + private static final Logger LOG = LoggerFactory.getLogger(InetUtils.class); + private static final String NUM = "(25[0-5]|2[0-4]\\d|[0-1]\\d{2}|[1-9]?\\d)"; - private static final String IP_REGEX = "^" + NUM + "\\." + NUM + "\\." + NUM - + "\\." + NUM + "$"; + + private static final String IP_REGEX = "^" + NUM + "\\." + NUM + "\\." + NUM + "\\." + NUM + "$"; + private static final Pattern IP_PATTERN = Pattern.compile(IP_REGEX); - + private static String selfIp; - + private static boolean useOnlySiteLocalInterface = false; - + private static boolean preferHostnameOverIp = false; - + private static List preferredNetworks = new ArrayList(); - + private static List ignoredInterfaces = new ArrayList(); - + static { NotifyCenter.registerToSharePublisher(IPChangeEvent.class); - + useOnlySiteLocalInterface = Boolean.parseBoolean(PropertyUtil.getProperty(USE_ONLY_SITE_INTERFACES)); - + List networks = PropertyUtil.getPropertyList(PREFERRED_NETWORKS); preferredNetworks.addAll(networks); - + List interfaces = PropertyUtil.getPropertyList(IGNORED_INTERFACES); ignoredInterfaces.addAll(interfaces); - + final long delayMs = Long.getLong("nacos.core.inet.auto-refresh", 30_000L); - + Runnable ipAutoRefresh = new Runnable() { @Override public void run() { @@ -111,38 +88,36 @@ public void run() { if (StringUtils.isBlank(nacosIp)) { nacosIp = PropertyUtil.getProperty(IP_ADDRESS); } - + if (!StringUtils.isBlank(nacosIp) && !isIP(nacosIp)) { throw new RuntimeException("nacos address " + nacosIp + " is not ip"); } String tmpSelfIp = nacosIp; if (StringUtils.isBlank(tmpSelfIp)) { preferHostnameOverIp = Boolean.getBoolean(SYSTEM_PREFER_HOSTNAME_OVER_IP); - + if (!preferHostnameOverIp) { - preferHostnameOverIp = Boolean.parseBoolean(PropertyUtil.getProperty(PREFER_HOSTNAME_OVER_IP)); + preferHostnameOverIp = Boolean + .parseBoolean(PropertyUtil.getProperty(PREFER_HOSTNAME_OVER_IP)); } - + if (preferHostnameOverIp) { - InetAddress inetAddress = null; + InetAddress inetAddress; try { inetAddress = InetAddress.getLocalHost(); if (inetAddress.getHostName().equals(inetAddress.getCanonicalHostName())) { tmpSelfIp = inetAddress.getHostName(); - } - else { + } else { tmpSelfIp = inetAddress.getCanonicalHostName(); } + } catch (UnknownHostException ignore) { + LOG.warn("Unable to retrieve localhost"); } - catch (UnknownHostException ignore) { - log.warn("Unable to retrieve localhost"); - } - } - else { - tmpSelfIp = findFirstNonLoopbackAddress().getHostAddress(); + } else { + tmpSelfIp = Objects.requireNonNull(findFirstNonLoopbackAddress()).getHostAddress(); } } - + if (!Objects.equals(selfIp, tmpSelfIp) && Objects.nonNull(selfIp)) { IPChangeEvent event = new IPChangeEvent(); event.setOldIp(selfIp); @@ -155,40 +130,42 @@ public void run() { } } }; - + GlobalExecutor.runWithoutThread(ipAutoRefresh); GlobalExecutor.scheduleByCommon(ipAutoRefresh, delayMs); } - + public static String getSelfIp() { return selfIp; } - + + /** + * findFirstNonLoopbackAddress. + * + * @return {@link InetAddress} + */ public static InetAddress findFirstNonLoopbackAddress() { InetAddress result = null; - + try { int lowest = Integer.MAX_VALUE; - for (Enumeration nics = NetworkInterface - .getNetworkInterfaces(); nics.hasMoreElements(); ) { + for (Enumeration nics = NetworkInterface.getNetworkInterfaces(); + nics.hasMoreElements(); ) { NetworkInterface ifc = nics.nextElement(); if (ifc.isUp()) { - log.debug("Testing interface: " + ifc.getDisplayName()); + LOG.debug("Testing interface: " + ifc.getDisplayName()); if (ifc.getIndex() < lowest || result == null) { lowest = ifc.getIndex(); } else { continue; } - + if (!ignoreInterface(ifc.getDisplayName())) { - for (Enumeration addrs = ifc - .getInetAddresses(); addrs.hasMoreElements(); ) { + for (Enumeration addrs = ifc.getInetAddresses(); addrs.hasMoreElements(); ) { InetAddress address = addrs.nextElement(); - if (address instanceof Inet4Address - && !address.isLoopbackAddress() - && isPreferredAddress(address)) { - log.debug("Found non-loopback interface: " - + ifc.getDisplayName()); + if (address instanceof Inet4Address && !address.isLoopbackAddress() && isPreferredAddress( + address)) { + LOG.debug("Found non-loopback interface: " + ifc.getDisplayName()); result = address; } } @@ -196,27 +173,27 @@ && isPreferredAddress(address)) { } } } catch (IOException ex) { - log.error("Cannot get first non-loopback address", ex); + LOG.error("Cannot get first non-loopback address", ex); } - + if (result != null) { return result; } - + try { return InetAddress.getLocalHost(); } catch (UnknownHostException e) { - log.warn("Unable to retrieve localhost"); + LOG.warn("Unable to retrieve localhost"); } - + return null; } - - public static boolean isPreferredAddress(InetAddress address) { + + private static boolean isPreferredAddress(InetAddress address) { if (useOnlySiteLocalInterface) { final boolean siteLocalAddress = address.isSiteLocalAddress(); if (!siteLocalAddress) { - log.debug("Ignoring address: " + address.getHostAddress()); + LOG.debug("Ignoring address: " + address.getHostAddress()); } return siteLocalAddress; } @@ -229,23 +206,55 @@ public static boolean isPreferredAddress(InetAddress address) { return true; } } - + return false; } - - public static boolean ignoreInterface(String interfaceName) { + + private static boolean ignoreInterface(String interfaceName) { for (String regex : ignoredInterfaces) { if (interfaceName.matches(regex)) { - log.debug("Ignoring interface: " + interfaceName); + LOG.debug("Ignoring interface: " + interfaceName); return true; } } return false; } - + public static boolean isIP(String str) { Matcher matcher = IP_PATTERN.matcher(str); return matcher.matches(); } - + + /** + * {@link com.alibaba.nacos.core.cluster.ServerMemberManager} is listener. + */ + @SuppressWarnings({"PMD.ClassNamingShouldBeCamelRule", "checkstyle:AbbreviationAsWordInName"}) + public static class IPChangeEvent implements SlowEvent { + + private String oldIp; + + private String newIp; + + public String getOldIp() { + return oldIp; + } + + public void setOldIp(String oldIp) { + this.oldIp = oldIp; + } + + public String getNewIp() { + return newIp; + } + + public void setNewIp(String newIp) { + this.newIp = newIp; + } + + @Override + public String toString() { + return "IPChangeEvent{" + "oldIp='" + oldIp + '\'' + ", newIp='" + newIp + '\'' + '}'; + } + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/Loggers.java b/core/src/main/java/com/alibaba/nacos/core/utils/Loggers.java index 8dd19276792..4bcda7b9e03 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/Loggers.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/Loggers.java @@ -13,25 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Loggers for core + * Loggers for core. * * @author nkorange * @since 1.2.0 */ public class Loggers { - + public static final Logger AUTH = LoggerFactory.getLogger("com.alibaba.nacos.core.auth"); - + public static final Logger CORE = LoggerFactory.getLogger("com.alibaba.nacos.core"); - + public static final Logger RAFT = LoggerFactory.getLogger("com.alibaba.nacos.core.protocol.raft"); - + public static final Logger CLUSTER = LoggerFactory.getLogger("com.alibaba.nacos.core.cluster"); - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/OverrideParameterRequestWrapper.java b/core/src/main/java/com/alibaba/nacos/core/utils/OverrideParameterRequestWrapper.java index e01809870d4..4d238908ba6 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/OverrideParameterRequestWrapper.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/OverrideParameterRequestWrapper.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.utils; import javax.servlet.http.HttpServletRequest; @@ -22,16 +23,16 @@ /** * A request wrapper to override the parameters. - *

      - * Referenced article is https://blog.csdn.net/xieyuooo/article/details/8447301 + * + *

      Referenced article is https://blog.csdn.net/xieyuooo/article/details/8447301 * * @author nkorange * @since 0.8.0 */ public class OverrideParameterRequestWrapper extends HttpServletRequestWrapper { - + private Map params = new HashMap<>(); - + /** * Constructs a request object wrapping the given request. * @@ -42,23 +43,39 @@ public OverrideParameterRequestWrapper(HttpServletRequest request) { super(request); this.params.putAll(request.getParameterMap()); } - + public static OverrideParameterRequestWrapper buildRequest(HttpServletRequest request) { return new OverrideParameterRequestWrapper(request); } - + + /** + * build OverrideParameterRequestWrapper and addParameter. + * + * @param request origin HttpServletRequest + * @param name name + * @param value value + * @return {@link OverrideParameterRequestWrapper} + */ public static OverrideParameterRequestWrapper buildRequest(HttpServletRequest request, String name, String value) { OverrideParameterRequestWrapper requestWrapper = new OverrideParameterRequestWrapper(request); requestWrapper.addParameter(name, value); return requestWrapper; } - - public static OverrideParameterRequestWrapper buildRequest(HttpServletRequest request, Map appendParameters) { + + /** + * build OverrideParameterRequestWrapper and addParameter. + * + * @param request origin HttpServletRequest + * @param appendParameters need to append to request + * @return {@link OverrideParameterRequestWrapper} + */ + public static OverrideParameterRequestWrapper buildRequest(HttpServletRequest request, + Map appendParameters) { OverrideParameterRequestWrapper requestWrapper = new OverrideParameterRequestWrapper(request); requestWrapper.params.putAll(appendParameters); return requestWrapper; } - + @Override public String getParameter(String name) { String[] values = params.get(name); @@ -67,21 +84,27 @@ public String getParameter(String name) { } return values[0]; } - + @Override public Map getParameterMap() { return params; } - + @Override public String[] getParameterValues(String name) { return params.get(name); } - + + /** + * addParameter. + * + * @param name name + * @param value value + */ public void addParameter(String name, String value) { if (value != null) { - params.put(name, new String[]{value}); + params.put(name, new String[] {value}); } } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/PropertyUtil.java b/core/src/main/java/com/alibaba/nacos/core/utils/PropertyUtil.java index 10dbd958beb..cb95202e01f 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/PropertyUtil.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/PropertyUtil.java @@ -28,12 +28,16 @@ import java.util.Properties; /** + * operation property. + * * @author Nacos */ public class PropertyUtil { + + private static final Logger LOGGER = LoggerFactory.getLogger(PropertyUtil.class); + private static Properties properties = new Properties(); - private static final Logger log = LoggerFactory.getLogger(PropertyUtil.class); - + static { InputStream inputStream = null; try { @@ -41,38 +45,37 @@ public class PropertyUtil { if (StringUtils.isNotBlank(baseDir)) { inputStream = new FileInputStream(baseDir + "/conf/application.properties"); } else { - inputStream = PropertyUtil.class - .getResourceAsStream("/application.properties"); + inputStream = PropertyUtil.class.getResourceAsStream("/application.properties"); } properties.load(inputStream); } catch (Exception e) { - log.error("read property file error:" + e); + LOGGER.error("read property file error:" + e); } finally { IOUtils.closeQuietly(inputStream); } } - + public static String getProperty(String key) { return properties.getProperty(key); } - + public static String getProperty(String key, String defaultValue) { return properties.getProperty(key, defaultValue); } - + public static List getPropertyList(String key) { List valueList = new ArrayList<>(); - + for (int i = 0; i < Integer.MAX_VALUE; i++) { String value = properties.getProperty(key + "[" + i + "]"); if (StringUtils.isBlank(value)) { break; } - + valueList.add(value); } - + return valueList; } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/ReuseHttpRequest.java b/core/src/main/java/com/alibaba/nacos/core/utils/ReuseHttpRequest.java index 8334fce113c..0d2be058f02 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/ReuseHttpRequest.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/ReuseHttpRequest.java @@ -24,33 +24,35 @@ import java.util.Set; /** + * ReuseHttpRequest. + * * @author liaochuntao */ public interface ReuseHttpRequest extends HttpServletRequest { - - /** - * get request body - * - * @return object - * @throws Exception - */ - Object getBody() throws Exception; - - /** - * Remove duplicate values from the array - * - * @param request {@link HttpServletRequest} - * @return {@link Map} - */ - default Map toDuplication(HttpServletRequest request) { - Map tmp = request.getParameterMap(); - Map result = new HashMap<>(tmp.size()); - Set set = new HashSet<>(); - for (Map.Entry entry : tmp.entrySet()) { - set.addAll(Arrays.asList(entry.getValue())); - result.put(entry.getKey(), set.toArray(new String[0])); - set.clear(); - } - return result; - } + + /** + * get request body. + * + * @return object + * @throws Exception exception + */ + Object getBody() throws Exception; + + /** + * Remove duplicate values from the array. + * + * @param request {@link HttpServletRequest} + * @return {@link Map} + */ + default Map toDuplication(HttpServletRequest request) { + Map tmp = request.getParameterMap(); + Map result = new HashMap<>(tmp.size()); + Set set = new HashSet<>(); + for (Map.Entry entry : tmp.entrySet()) { + set.addAll(Arrays.asList(entry.getValue())); + result.put(entry.getKey(), set.toArray(new String[0])); + set.clear(); + } + return result; + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/ReuseHttpServletRequest.java b/core/src/main/java/com/alibaba/nacos/core/utils/ReuseHttpServletRequest.java index be1e1fcf507..94471dc0370 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/ReuseHttpServletRequest.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/ReuseHttpServletRequest.java @@ -35,100 +35,104 @@ import java.util.Map; /** + * httprequest wrapper. + * * @author liaochuntao */ public class ReuseHttpServletRequest extends HttpServletRequestWrapper implements ReuseHttpRequest { - - private byte[] body; - private Map stringMap; - private final HttpServletRequest target; - - /** - * Constructs a request object wrapping the given request. - * - * @param request The request to wrap - * @throws IllegalArgumentException if the request is null - */ - public ReuseHttpServletRequest(HttpServletRequest request) throws IOException { - super(request); - this.target = request; - this.body = toBytes(request.getInputStream()); - this.stringMap = toDuplication(request); - } - - @Override - public Object getBody() throws Exception { - if (StringUtils.containsIgnoreCase(target.getContentType(), MediaType.MULTIPART_FORM_DATA)) { - return target.getParts(); - } else { - String s = ByteUtils.toString(body); - if (StringUtils.isBlank(s)) { - return HttpUtils.encodingParams(HttpUtils.translateParameterMap(stringMap), - StandardCharsets.UTF_8.name()); - } - return s; - } - } - - private byte[] toBytes(InputStream inputStream) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - byte[] buffer = new byte[1024]; - int n = 0; - while ((n = inputStream.read(buffer)) != -1) { - bos.write(buffer, 0, n); - } - return bos.toByteArray(); - } - - @Override - public BufferedReader getReader() throws IOException { - return new BufferedReader(new InputStreamReader(getInputStream())); - } - - @Override - public Map getParameterMap() { - return stringMap; - } - - @Override - public String getParameter(String name) { - String[] values = stringMap.get(name); - if (values == null || values.length == 0) { - return null; - } - return values[0]; - } - - @Override - public String[] getParameterValues(String name) { - return stringMap.get(name); - } - - @Override - public ServletInputStream getInputStream() throws IOException { - - final ByteArrayInputStream inputStream = new ByteArrayInputStream(body); - - return new ServletInputStream() { - @Override - public int read() throws IOException { - return inputStream.read(); - } - - @Override - public boolean isFinished() { - return false; - } - - @Override - public boolean isReady() { - return false; - } - - @Override - public void setReadListener(ReadListener readListener) { - } - }; - } - + + private final HttpServletRequest target; + + private byte[] body; + + private Map stringMap; + + /** + * Constructs a request object wrapping the given request. + * + * @param request The request to wrap + * @throws IllegalArgumentException if the request is null + */ + public ReuseHttpServletRequest(HttpServletRequest request) throws IOException { + super(request); + this.target = request; + this.body = toBytes(request.getInputStream()); + this.stringMap = toDuplication(request); + } + + @Override + public Object getBody() throws Exception { + if (StringUtils.containsIgnoreCase(target.getContentType(), MediaType.MULTIPART_FORM_DATA)) { + return target.getParts(); + } else { + String s = ByteUtils.toString(body); + if (StringUtils.isBlank(s)) { + return HttpUtils + .encodingParams(HttpUtils.translateParameterMap(stringMap), StandardCharsets.UTF_8.name()); + } + return s; + } + } + + private byte[] toBytes(InputStream inputStream) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] buffer = new byte[1024]; + int n = 0; + while ((n = inputStream.read(buffer)) != -1) { + bos.write(buffer, 0, n); + } + return bos.toByteArray(); + } + + @Override + public BufferedReader getReader() throws IOException { + return new BufferedReader(new InputStreamReader(getInputStream())); + } + + @Override + public Map getParameterMap() { + return stringMap; + } + + @Override + public String getParameter(String name) { + String[] values = stringMap.get(name); + if (values == null || values.length == 0) { + return null; + } + return values[0]; + } + + @Override + public String[] getParameterValues(String name) { + return stringMap.get(name); + } + + @Override + public ServletInputStream getInputStream() throws IOException { + + final ByteArrayInputStream inputStream = new ByteArrayInputStream(body); + + return new ServletInputStream() { + @Override + public int read() throws IOException { + return inputStream.read(); + } + + @Override + public boolean isFinished() { + return false; + } + + @Override + public boolean isReady() { + return false; + } + + @Override + public void setReadListener(ReadListener readListener) { + } + }; + } + } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/ReuseUploadFileHttpServletRequest.java b/core/src/main/java/com/alibaba/nacos/core/utils/ReuseUploadFileHttpServletRequest.java index 7da3e8b01f6..4296c04e2d4 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/ReuseUploadFileHttpServletRequest.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/ReuseUploadFileHttpServletRequest.java @@ -17,8 +17,6 @@ package com.alibaba.nacos.core.utils; import com.alibaba.nacos.common.http.HttpUtils; -import com.alibaba.nacos.common.utils.ByteUtils; -import com.alibaba.nacos.common.utils.StringUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.multipart.MultipartException; @@ -27,57 +25,55 @@ import javax.servlet.http.HttpServletRequest; import java.nio.charset.StandardCharsets; -import java.util.Enumeration; -import java.util.HashMap; import java.util.Map; import java.util.Objects; /** + * httprequest wrapper. + * * @author liaochuntao */ -public class ReuseUploadFileHttpServletRequest extends - StandardMultipartHttpServletRequest implements ReuseHttpRequest { - - private final HttpServletRequest request; - private Map stringMap; - - public ReuseUploadFileHttpServletRequest(HttpServletRequest request) - throws MultipartException { - super(request); - this.request = request; - this.stringMap = toDuplication(request); - } - - @Override - public Map getParameterMap() { - return stringMap; - } - - @Override - public String getParameter(String name) { - String[] values = stringMap.get(name); - if (values == null || values.length == 0) { - return null; - } - return values[0]; - } - - @Override - public String[] getParameterValues(String name) { - return stringMap.get(name); - } - - @Override - public Object getBody() throws Exception { - MultipartFile target = super.getFile("file"); - if (Objects.nonNull(target)) { - MultiValueMap parts = new LinkedMultiValueMap<>(); - parts.add("file", target.getResource()); - return parts; - } else { - // The content-type for the configuration publication might be "multipart/form-data" - return HttpUtils.encodingParams(HttpUtils.translateParameterMap(stringMap), - StandardCharsets.UTF_8.name()); - } - } +public class ReuseUploadFileHttpServletRequest extends StandardMultipartHttpServletRequest implements ReuseHttpRequest { + + private final HttpServletRequest request; + + private Map stringMap; + + public ReuseUploadFileHttpServletRequest(HttpServletRequest request) throws MultipartException { + super(request); + this.request = request; + this.stringMap = toDuplication(request); + } + + @Override + public Map getParameterMap() { + return stringMap; + } + + @Override + public String getParameter(String name) { + String[] values = stringMap.get(name); + if (values == null || values.length == 0) { + return null; + } + return values[0]; + } + + @Override + public String[] getParameterValues(String name) { + return stringMap.get(name); + } + + @Override + public Object getBody() throws Exception { + MultipartFile target = super.getFile("file"); + if (Objects.nonNull(target)) { + MultiValueMap parts = new LinkedMultiValueMap<>(); + parts.add("file", target.getResource()); + return parts; + } else { + // The content-type for the configuration publication might be "multipart/form-data" + return HttpUtils.encodingParams(HttpUtils.translateParameterMap(stringMap), StandardCharsets.UTF_8.name()); + } + } } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/TimerContext.java b/core/src/main/java/com/alibaba/nacos/core/utils/TimerContext.java index b8495fd34e2..157e81c260c 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/TimerContext.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/TimerContext.java @@ -21,51 +21,68 @@ import com.alibaba.nacos.common.utils.StringUtils; import org.slf4j.Logger; -import java.util.concurrent.Callable; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; /** - * Simple task time calculation,Currently only the task time statistics task that - * supports synchronizing code blocks is supported + * Simple task time calculation,Currently only the task time statistics task that supports synchronizing code blocks is + * supported. * * @author liaochuntao */ public class TimerContext { - + private static final ThreadLocal> TIME_RECORD = new ThreadLocal<>(); - + public static void start(final String name) { long startTime = System.currentTimeMillis(); TIME_RECORD.set(Pair.with(name, startTime)); } - + public static void end(final Logger logger) { end(logger, LoggerUtils.DEBUG); } - + + /** + * End the task and print based on the log level. + * + * @param logger logger + * @param level logger level + */ public static void end(final Logger logger, final String level) { long endTime = System.currentTimeMillis(); Pair record = TIME_RECORD.get(); if (StringUtils.equals(level, LoggerUtils.DEBUG)) { - LoggerUtils.printIfDebugEnabled(logger, "{} cost time : {} ms", record.getFirst(), (endTime - record.getSecond())); + LoggerUtils.printIfDebugEnabled(logger, "{} cost time : {} ms", record.getFirst(), + (endTime - record.getSecond())); } if (StringUtils.equals(level, LoggerUtils.INFO)) { - LoggerUtils.printIfInfoEnabled(logger, "{} cost time : {} ms", record.getFirst(), (endTime - record.getSecond())); + LoggerUtils.printIfInfoEnabled(logger, "{} cost time : {} ms", record.getFirst(), + (endTime - record.getSecond())); } if (StringUtils.equals(level, LoggerUtils.TRACE)) { - LoggerUtils.printIfTraceEnabled(logger, "{} cost time : {} ms", record.getFirst(), (endTime - record.getSecond())); + LoggerUtils.printIfTraceEnabled(logger, "{} cost time : {} ms", record.getFirst(), + (endTime - record.getSecond())); } if (StringUtils.equals(level, LoggerUtils.ERROR)) { - LoggerUtils.printIfErrorEnabled(logger, "{} cost time : {} ms", record.getFirst(), (endTime - record.getSecond())); + LoggerUtils.printIfErrorEnabled(logger, "{} cost time : {} ms", record.getFirst(), + (endTime - record.getSecond())); } if (StringUtils.equals(level, LoggerUtils.WARN)) { - LoggerUtils.printIfWarnEnabled(logger, "{} cost time : {} ms", record.getFirst(), (endTime - record.getSecond())); + LoggerUtils.printIfWarnEnabled(logger, "{} cost time : {} ms", record.getFirst(), + (endTime - record.getSecond())); } TIME_RECORD.remove(); } - + + /** + * Execution with time-consuming calculations for {@link Runnable}. + * + * @param job runnable + * @param name job name + * @param logger logger + */ public static void run(final Runnable job, final String name, final Logger logger) { start(name); try { @@ -74,7 +91,14 @@ public static void run(final Runnable job, final String name, final Logger logge end(logger); } } - + + /** + * Execution with time-consuming calculations for {@link Supplier}. + * + * @param job Supplier + * @param name job name + * @param logger logger + */ public static V run(final Supplier job, final String name, final Logger logger) { start(name); try { @@ -83,7 +107,15 @@ public static V run(final Supplier job, final String name, final Logger l end(logger); } } - + + /** + * Execution with time-consuming calculations for {@link Function}. + * + * @param job Function + * @param args args + * @param name job name + * @param logger logger + */ public static R run(final Function job, T args, final String name, final Logger logger) { start(name); try { @@ -92,7 +124,15 @@ public static R run(final Function job, T args, final String name, end(logger); } } - + + /** + * Execution with time-consuming calculations for {@link Consumer}. + * + * @param job Consumer + * @param args args + * @param name job name + * @param logger logger + */ public static void run(final Consumer job, T args, final String name, final Logger logger) { start(name); try { @@ -101,5 +141,5 @@ public static void run(final Consumer job, T args, final String name, fin end(logger); } } - + } diff --git a/core/src/main/java/com/alibaba/nacos/core/utils/WebUtils.java b/core/src/main/java/com/alibaba/nacos/core/utils/WebUtils.java index 61a77f52f89..20c6b29aab5 100644 --- a/core/src/main/java/com/alibaba/nacos/core/utils/WebUtils.java +++ b/core/src/main/java/com/alibaba/nacos/core/utils/WebUtils.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.utils; import com.alibaba.nacos.common.constant.HttpHeaderConsts; @@ -30,10 +31,19 @@ import java.util.function.Function; /** + * web utils. + * * @author nkorange */ public class WebUtils { - + + /** + * get target value from parameterMap, if not found will throw {@link IllegalArgumentException}. + * + * @param req {@link HttpServletRequest} + * @param key key + * @return value + */ public static String required(final HttpServletRequest req, final String key) { String value = req.getParameter(key); if (StringUtils.isEmpty(value)) { @@ -42,7 +52,15 @@ public static String required(final HttpServletRequest req, final String key) { String encoding = req.getParameter("encoding"); return resolveValue(value, encoding); } - + + /** + * get target value from parameterMap, if not found will return default value. + * + * @param req {@link HttpServletRequest} + * @param key key + * @param defaultValue default value + * @return value + */ public static String optional(final HttpServletRequest req, final String key, final String defaultValue) { if (!req.getParameterMap().containsKey(key) || req.getParameterMap().get(key)[0] == null) { return defaultValue; @@ -54,51 +72,81 @@ public static String optional(final HttpServletRequest req, final String key, fi String encoding = req.getParameter("encoding"); return resolveValue(value, encoding); } - + + /** + * decode target value. + * + * @param value value + * @param encoding encode + * @return Decoded data + */ private static String resolveValue(String value, String encoding) { if (StringUtils.isEmpty(encoding)) { encoding = StandardCharsets.UTF_8.name(); } try { value = HttpUtils.decode(new String(value.getBytes(StandardCharsets.UTF_8), encoding), encoding); - } catch (UnsupportedEncodingException ignore) { } + } catch (UnsupportedEncodingException ignore) { + } return value.trim(); } - + + /** + * get accept encode from request. + * + * @param req {@link HttpServletRequest} + * @return accept encode + */ public static String getAcceptEncoding(HttpServletRequest req) { String encode = StringUtils.defaultIfEmpty(req.getHeader("Accept-Charset"), StandardCharsets.UTF_8.name()); encode = encode.contains(",") ? encode.substring(0, encode.indexOf(",")) : encode; return encode.contains(";") ? encode.substring(0, encode.indexOf(";")) : encode; } - + /** * Returns the value of the request header "user-agent" as a String. * * @param request HttpServletRequest - * @return the value of the request header "user-agent", or the value of the - * request header "client-version" if the request does not have a - * header of "user-agent" + * @return the value of the request header "user-agent", or the value of the request header "client-version" if the + * request does not have a header of "user-agent". */ public static String getUserAgent(HttpServletRequest request) { String userAgent = request.getHeader(HttpHeaderConsts.USER_AGENT_HEADER); if (StringUtils.isEmpty(userAgent)) { - userAgent = StringUtils.defaultIfEmpty(request.getHeader(HttpHeaderConsts.CLIENT_VERSION_HEADER), StringUtils.EMPTY); + userAgent = StringUtils + .defaultIfEmpty(request.getHeader(HttpHeaderConsts.CLIENT_VERSION_HEADER), StringUtils.EMPTY); } return userAgent; } - - public static void response(HttpServletResponse response, String body, int code) throws - IOException { + + /** + * response data to client. + * + * @param response {@link HttpServletResponse} + * @param body body + * @param code http code + * @throws IOException IOException + */ + public static void response(HttpServletResponse response, String body, int code) throws IOException { response.setCharacterEncoding(StandardCharsets.UTF_8.name()); response.setContentType("application/json;charset=UTF-8"); response.getWriter().write(body); response.setStatus(code); } - - public static void process(DeferredResult deferredResult, CompletableFuture future, Function errorHandler) { - + + /** + * Register DeferredResult in the callback of CompletableFuture. + * + * @param deferredResult {@link DeferredResult} + * @param future {@link CompletableFuture} + * @param errorHandler {@link Function} + * @param target type + */ + public static void process(DeferredResult deferredResult, CompletableFuture future, + Function errorHandler) { + deferredResult.onTimeout(future::join); - + future.whenComplete((t, throwable) -> { if (Objects.nonNull(throwable)) { deferredResult.setResult(errorHandler.apply(throwable)); @@ -107,11 +155,21 @@ public static void process(DeferredResult deferredResult, CompletableFut deferredResult.setResult(t); }); } - - public static void process(DeferredResult deferredResult, CompletableFuture future, Runnable success, Function errorHandler) { - + + /** + * Register DeferredResult in the callback of CompletableFuture. + * + * @param deferredResult {@link DeferredResult} + * @param future {@link CompletableFuture} + * @param success if future success, callback runnable + * @param errorHandler {@link Function} + * @param target type + */ + public static void process(DeferredResult deferredResult, CompletableFuture future, Runnable success, + Function errorHandler) { + deferredResult.onTimeout(future::join); - + future.whenComplete((t, throwable) -> { if (Objects.nonNull(throwable)) { deferredResult.setResult(errorHandler.apply(throwable)); diff --git a/core/src/test/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessorTest.java b/core/src/test/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessorTest.java index a24cdc9d43a..bc370daad7d 100644 --- a/core/src/test/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessorTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/distributed/raft/processor/AbstractProcessorTest.java @@ -33,43 +33,44 @@ import java.util.concurrent.atomic.AtomicReference; public class AbstractProcessorTest { - - private JRaftServer server = new JRaftServer() { - @Override - public void applyOperation(Node node, Message data, FailoverClosure closure) { - closure.setResponse(Response.newBuilder().setSuccess(false).setErrMsg("Error message transmission").build()); - closure.run(new Status(RaftError.UNKNOWN, "Error message transmission")); - } - }; - - @Test - public void testErrorThroughRPC() { - final AtomicReference reference = new AtomicReference<>(); - - RpcContext context = new RpcContext() { - @Override - public void sendResponse(Object responseObj) { - reference.set((Response) responseObj); - } - - @Override - public Connection getConnection() { - return null; - } - - @Override - public String getRemoteAddress() { - return null; - } - }; - AbstractProcessor processor = new NacosLogProcessor(server, SerializeFactory.getDefault()); - processor.execute(server, context, Log.newBuilder().build(), new JRaftServer.RaftGroupTuple()); - - Response response = reference.get(); - Assert.assertNotNull(response); - - Assert.assertEquals("Error message transmission", response.getErrMsg()); - Assert.assertFalse(response.getSuccess()); - } - + + private JRaftServer server = new JRaftServer() { + @Override + public void applyOperation(Node node, Message data, FailoverClosure closure) { + closure.setResponse( + Response.newBuilder().setSuccess(false).setErrMsg("Error message transmission").build()); + closure.run(new Status(RaftError.UNKNOWN, "Error message transmission")); + } + }; + + @Test + public void testErrorThroughRpc() { + final AtomicReference reference = new AtomicReference<>(); + + RpcContext context = new RpcContext() { + @Override + public void sendResponse(Object responseObj) { + reference.set((Response) responseObj); + } + + @Override + public Connection getConnection() { + return null; + } + + @Override + public String getRemoteAddress() { + return null; + } + }; + AbstractProcessor processor = new NacosLogProcessor(server, SerializeFactory.getDefault()); + processor.execute(server, context, Log.newBuilder().build(), new JRaftServer.RaftGroupTuple()); + + Response response = reference.get(); + Assert.assertNotNull(response); + + Assert.assertEquals("Error message transmission", response.getErrMsg()); + Assert.assertFalse(response.getSuccess()); + } + } diff --git a/core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java b/core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java index 019437f720c..ef984624044 100644 --- a/core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/env/NacosDefaultPropertySourceEnvironmentPostProcessorTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.env; import org.junit.Assert; @@ -33,19 +34,18 @@ import static java.util.Arrays.asList; /** - * {@link NacosDefaultPropertySourceEnvironmentPostProcessor} Test + * {@link NacosDefaultPropertySourceEnvironmentPostProcessor} Test. * * @author Mercy * @since 0.2.2 */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = NacosDefaultPropertySourceEnvironmentPostProcessorTest.class, - webEnvironment = SpringBootTest.WebEnvironment.NONE) +@SpringBootTest(classes = NacosDefaultPropertySourceEnvironmentPostProcessorTest.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) public class NacosDefaultPropertySourceEnvironmentPostProcessorTest { - + @Autowired private ConfigurableEnvironment environment; - + @Test public void testNacosDefaultPropertySourcePresent() { MutablePropertySources propertySources = environment.getPropertySources(); @@ -58,51 +58,44 @@ public void testNacosDefaultPropertySourcePresent() { // make sure propertySource is last one Assert.assertEquals(propertySources.size() - 1, propertySources.precedenceOf(propertySource)); } - + @Test public void testDefaultProperties() { - + // Web Server assertPropertyEquals("server.port", "8848"); assertPropertyEquals("server.tomcat.uri-encoding", "UTF-8"); - + // HTTP Encoding assertPropertyEquals("spring.http.encoding.force", "true"); assertPropertyEquals("spring.http.encoding.enabled", "true"); - + // i18n assertPropertyEquals("spring.messages.encoding", "UTF-8"); } - + @Test public void testDefaultPropertyNames() { - - assertPropertyNames( - "nacos.version", - "server.servlet.contextPath", - "server.port", - "server.tomcat.uri-encoding", - "spring.http.encoding.force", - "spring.http.encoding.enabled", - "spring.messages.encoding", - "spring.autoconfigure.exclude" - ); + + assertPropertyNames("nacos.version", "server.servlet.contextPath", "server.port", "server.tomcat.uri-encoding", + "spring.http.encoding.force", "spring.http.encoding.enabled", "spring.messages.encoding", + "spring.autoconfigure.exclude"); } - + private void assertPropertyNames(String... propertyNames) { - + CompositePropertySource propertySource = getNacosDefaultPropertySource(); - + Assert.assertEquals("Please Properties from resources[" + RESOURCE_LOCATION_PATTERN + "]", new HashSet(asList(propertyNames)), new HashSet(asList(propertySource.getPropertyNames()))); } - + private void assertPropertyEquals(String propertyName, String expectedValue) { PropertySource propertySource = getNacosDefaultPropertySource(); Assert.assertEquals(expectedValue, propertySource.getProperty(propertyName)); } - + private CompositePropertySource getNacosDefaultPropertySource() { MutablePropertySources propertySources = environment.getPropertySources(); // Get PropertySource via PROPERTY_SOURCE_NAME diff --git a/core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java b/core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java index 7ebb73a57c0..d82703dcc21 100644 --- a/core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/listener/StandaloneProfileApplicationListenerTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.nacos.core.listener; import com.alibaba.nacos.core.code.StandaloneProfileApplicationListener; @@ -29,28 +30,26 @@ import static com.alibaba.nacos.core.utils.Constants.STANDALONE_SPRING_PROFILE; /** - * {@link StandaloneProfileApplicationListener} Test + * {@link StandaloneProfileApplicationListener} Test. * * @author Mercy * @since 0.2.2 */ @RunWith(SpringRunner.class) -@SpringBootTest( - classes = StandaloneProfileApplicationListenerTest.class, - webEnvironment = SpringBootTest.WebEnvironment.NONE) +@SpringBootTest(classes = StandaloneProfileApplicationListenerTest.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) public class StandaloneProfileApplicationListenerTest { - + + @Autowired + private Environment environment; + @BeforeClass public static void init() { System.setProperty("nacos.standalone", "true"); } - - @Autowired - private Environment environment; - + @Test public void testProfile() { Assert.assertTrue(ArrayUtils.contains(environment.getActiveProfiles(), STANDALONE_SPRING_PROFILE)); } - + } diff --git a/core/src/test/java/com/alibaba/nacos/core/utils/ClassUtilsTest.java b/core/src/test/java/com/alibaba/nacos/core/utils/ClassUtilsTest.java index d5da5c35611..c1b5e6a3765 100644 --- a/core/src/test/java/com/alibaba/nacos/core/utils/ClassUtilsTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/utils/ClassUtilsTest.java @@ -23,11 +23,13 @@ import java.util.List; public class ClassUtilsTest { - - @Test - public void test_generic() { - GenericType> genericType = new GenericType>(){}; - Assert.assertEquals(genericType.getType(), new TypeToken>(){}.getType()); - } - + + @Test + public void testGeneric() { + GenericType> genericType = new GenericType>() { + }; + Assert.assertEquals(genericType.getType(), new TypeToken>() { + }.getType()); + } + } diff --git a/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java b/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java index 22b4014478b..a60c826c2f0 100644 --- a/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java +++ b/core/src/test/java/com/alibaba/nacos/core/utils/SystemUtilsTest.java @@ -13,10 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.nacos.core.utils; +package com.alibaba.nacos.core.utils; -import com.alibaba.nacos.core.utils.ApplicationUtils; import org.apache.commons.io.FileUtils; import org.junit.Assert; import org.junit.BeforeClass; @@ -31,68 +30,70 @@ import static com.alibaba.nacos.core.utils.Constants.STANDALONE_MODE_PROPERTY_NAME; /** - * {@link ApplicationUtils} Test + * {@link ApplicationUtils} Test. * * @author Mercy * @since 0.2.2 */ public class SystemUtilsTest { - - private static final Random random = new Random(); - - private static boolean standaloneMode = random.nextBoolean(); - private static boolean preferHostMode = random.nextBoolean(); - + + private static final Random RANDOM = new Random(); + + private static boolean standaloneMode = RANDOM.nextBoolean(); + + private static boolean preferHostMode = RANDOM.nextBoolean(); + @BeforeClass public static void init() { System.setProperty("nacos.standalone", String.valueOf(standaloneMode)); System.setProperty("nacos.preferHostnameOverIp", String.valueOf(preferHostMode)); } - + @Test public void testStandaloneModeConstants() { - + System.out.printf("System property \"%s\" = %s \n", "nacos.standalone", standaloneMode); - + if ("true".equalsIgnoreCase(System.getProperty("nacos.standalone"))) { Assert.assertTrue(Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME)); } else { Assert.assertFalse(Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME)); } - + Assert.assertEquals(standaloneMode, Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME)); - + } - + @Test public void testPreferHostModeConstants() { - + System.out.printf("System property \"%s\" = %s \n", "nacos.preferrHostnameOverIp", preferHostMode); - + if ("true".equalsIgnoreCase(System.getProperty("nacos.preferHostnameOverIp"))) { Assert.assertTrue(Boolean.getBoolean(PREFER_HOSTNAME_OVER_IP_PROPERTY_NAME)); } else { Assert.assertFalse(Boolean.getBoolean(PREFER_HOSTNAME_OVER_IP_PROPERTY_NAME)); } - + Assert.assertEquals(preferHostMode, Boolean.getBoolean(PREFER_HOSTNAME_OVER_IP_PROPERTY_NAME)); - + } - + @Test public void testReadClusterConf() throws IOException { FileUtils.forceMkdir(new File(ApplicationUtils.getConfFilePath())); - + String lineSeparator = System.getProperty("line.separator"); - + /* * #it is ip * #example * 192.168.1.1:8848 */ - ApplicationUtils.writeClusterConf("#it is ip" + lineSeparator + "#example" + lineSeparator + "192.168.1.1:8848"); + ApplicationUtils + .writeClusterConf("#it is ip" + lineSeparator + "#example" + lineSeparator + "192.168.1.1:8848"); Assert.assertEquals(ApplicationUtils.readClusterConf().get(0), "192.168.1.1:8848"); - + /* * #it is ip * #example @@ -100,11 +101,11 @@ public void testReadClusterConf() throws IOException { * 192.168.1.2:8848 # Instance A */ ApplicationUtils.writeClusterConf( - "#it is ip" + lineSeparator + " #example" + lineSeparator + " # 192.168.1.1:8848" + lineSeparator - + " 192.168.1.2:8848 # Instance A " + lineSeparator + "192.168.1.3#:8848"); + "#it is ip" + lineSeparator + " #example" + lineSeparator + " # 192.168.1.1:8848" + lineSeparator + + " 192.168.1.2:8848 # Instance A " + lineSeparator + "192.168.1.3#:8848"); List instanceList = ApplicationUtils.readClusterConf(); Assert.assertEquals(instanceList.get(0), "192.168.1.2:8848"); Assert.assertEquals(instanceList.get(1), "192.168.1.3"); } - + } diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ConsistencyService.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/ConsistencyService.java index ae27e97bc5c..5b3b2ed6e4f 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ConsistencyService.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/ConsistencyService.java @@ -83,4 +83,4 @@ public interface ConsistencyService { * @return true if available */ boolean isAvailable(); -} +} \ No newline at end of file diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/DistroConsistencyServiceImpl.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/DistroConsistencyServiceImpl.java index 572f7c9566f..982cd784f05 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/DistroConsistencyServiceImpl.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/ephemeral/distro/DistroConsistencyServiceImpl.java @@ -463,4 +463,4 @@ private void handle(Pair pair) { } } } -} +} \ No newline at end of file diff --git a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java index 6a5d56e0d35..b3e453cbb05 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/consistency/persistent/raft/RaftCore.java @@ -1125,4 +1125,4 @@ public void run() { } } } -} +} \ No newline at end of file diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java b/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java index ed876582195..607a4a8f6e5 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/Cluster.java @@ -457,4 +457,4 @@ public void validate() { "cluster name can only have these characters: 0-9a-zA-Z-, current: " + getName()); } } -} +} \ No newline at end of file diff --git a/naming/src/main/java/com/alibaba/nacos/naming/core/ServiceManager.java b/naming/src/main/java/com/alibaba/nacos/naming/core/ServiceManager.java index 2b98048af48..c4cefe66e9b 100644 --- a/naming/src/main/java/com/alibaba/nacos/naming/core/ServiceManager.java +++ b/naming/src/main/java/com/alibaba/nacos/naming/core/ServiceManager.java @@ -1020,4 +1020,4 @@ public String toString() { return JacksonUtils.toJson(this); } } -} +} \ No newline at end of file