Remove UpgradeJudgement.java

This commit is contained in:
KomachiSion 2022-08-26 15:44:45 +08:00
parent 7af6e869d7
commit 28ddce8d56
27 changed files with 36 additions and 1252 deletions

View File

@ -1,51 +0,0 @@
/*
* Copyright 1999-2020 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.naming.core.v2.upgrade;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteDelayTaskEngine;
import com.alibaba.nacos.naming.monitor.MetricsMonitor;
/**
* Default upgrade checker for self node.
*
* @author xiweng.yy
*/
public class DefaultSelfUpgradeChecker implements SelfUpgradeChecker {
private static final String DEFAULT = "default";
@Override
public String checkType() {
return DEFAULT;
}
@Override
public boolean isReadyToUpgrade(ServiceManager serviceManager, DoubleWriteDelayTaskEngine taskEngine) {
return checkServiceAndInstanceNumber(serviceManager) && checkDoubleWriteStatus(taskEngine);
}
private boolean checkServiceAndInstanceNumber(ServiceManager serviceManager) {
boolean result = serviceManager.getServiceCount() == MetricsMonitor.getDomCountMonitor().get();
result &= serviceManager.getInstanceCount() == MetricsMonitor.getIpCountMonitor().get();
return result;
}
private boolean checkDoubleWriteStatus(DoubleWriteDelayTaskEngine taskEngine) {
return taskEngine.isEmpty();
}
}

View File

@ -1,44 +0,0 @@
/*
* Copyright 1999-2020 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.naming.core.v2.upgrade;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteDelayTaskEngine;
/**
* Upgrade checker for self-node to judge whether current node is ready to upgrade.
*
* @author xiweng.yy
*/
public interface SelfUpgradeChecker {
/**
* Get the check type of this self upgrade checker.
*
* @return type
*/
String checkType();
/**
* Judge whether current node is ready to upgrade.
*
* @param serviceManager service manager for v1 mode.
* @param taskEngine double write task engine
* @return {@code true} if current node is ready to upgrade, otherwise {@code false}
*/
boolean isReadyToUpgrade(ServiceManager serviceManager, DoubleWriteDelayTaskEngine taskEngine);
}

View File

@ -1,55 +0,0 @@
/*
* Copyright 1999-2020 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.naming.core.v2.upgrade;
import com.alibaba.nacos.common.spi.NacosServiceLoader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* SPI holder for self upgrade checker.
*
* @author xiweng.yy
*/
public class SelfUpgradeCheckerSpiHolder {
private static final SelfUpgradeCheckerSpiHolder INSTANCE = new SelfUpgradeCheckerSpiHolder();
private static final DefaultSelfUpgradeChecker DEFAULT_SELF_UPGRADE_CHECKER = new DefaultSelfUpgradeChecker();
private final Map<String, SelfUpgradeChecker> selfUpgradeCheckerMap;
private SelfUpgradeCheckerSpiHolder() {
Collection<SelfUpgradeChecker> checkers = NacosServiceLoader.load(SelfUpgradeChecker.class);
selfUpgradeCheckerMap = new HashMap<>(checkers.size());
for (SelfUpgradeChecker each : checkers) {
selfUpgradeCheckerMap.put(each.checkType(), each);
}
}
/**
* Find target type self checker.
*
* @param type target type
* @return target {@link SelfUpgradeChecker} if exist, otherwise {@link DefaultSelfUpgradeChecker}
*/
public static SelfUpgradeChecker findSelfChecker(String type) {
return INSTANCE.selfUpgradeCheckerMap.getOrDefault(type, DEFAULT_SELF_UPGRADE_CHECKER);
}
}

View File

@ -1,225 +0,0 @@
/*
* Copyright 1999-2020 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.naming.core.v2.upgrade;
import com.alibaba.nacos.common.JustForTest;
import com.alibaba.nacos.common.executor.ExecutorFactory;
import com.alibaba.nacos.common.executor.NameThreadFactory;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.alibaba.nacos.core.cluster.Member;
import com.alibaba.nacos.core.cluster.MemberMetaDataConstants;
import com.alibaba.nacos.core.cluster.MembersChangeEvent;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.RefreshStorageDataTask;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteDelayTaskEngine;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.execute.AsyncServicesCheckTask;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.NamingExecuteTaskDispatcher;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.codehaus.jackson.Version;
import org.codehaus.jackson.util.VersionUtil;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Ability judgement during upgrading.
*
* @author xiweng.yy
*/
@Component
public class UpgradeJudgement extends Subscriber<MembersChangeEvent> {
/**
* Only when all cluster upgrade upper 2.0.0, this features is true.
*/
private final AtomicBoolean useGrpcFeatures = new AtomicBoolean(false);
/**
* Only when all cluster upgrade upper 1.4.0, this features is true.
*/
private final AtomicBoolean useJraftFeatures = new AtomicBoolean(false);
private final AtomicBoolean all20XVersion = new AtomicBoolean(false);
private final ServerMemberManager memberManager;
private final ServiceManager serviceManager;
private final DoubleWriteDelayTaskEngine doubleWriteDelayTaskEngine;
private ScheduledExecutorService upgradeChecker;
private SelfUpgradeChecker selfUpgradeChecker;
private static final int MAJOR_VERSION = 2;
private static final int MINOR_VERSION = 4;
public UpgradeJudgement(ServerMemberManager memberManager, ServiceManager serviceManager,
UpgradeStates upgradeStates, DoubleWriteDelayTaskEngine doubleWriteDelayTaskEngine) {
this.memberManager = memberManager;
this.serviceManager = serviceManager;
this.doubleWriteDelayTaskEngine = doubleWriteDelayTaskEngine;
Boolean upgraded = upgradeStates.isUpgraded();
upgraded = upgraded != null && upgraded;
boolean isStandaloneMode = EnvUtil.getStandaloneMode();
boolean isSupportUpgradeFrom1X = EnvUtil.isSupportUpgradeFrom1X();
if (isStandaloneMode || upgraded || !isSupportUpgradeFrom1X) {
useGrpcFeatures.set(true);
useJraftFeatures.set(true);
all20XVersion.set(true);
}
if (!isStandaloneMode && isSupportUpgradeFrom1X) {
initUpgradeChecker();
NotifyCenter.registerSubscriber(this);
}
}
private void initUpgradeChecker() {
selfUpgradeChecker = SelfUpgradeCheckerSpiHolder
.findSelfChecker(EnvUtil.getProperty("upgrading.checker.type", "default"));
upgradeChecker = ExecutorFactory.newSingleScheduledExecutorService(new NameThreadFactory("upgrading.checker"));
upgradeChecker.scheduleAtFixedRate(() -> {
if (isUseGrpcFeatures()) {
return;
}
boolean canUpgrade = checkForUpgrade();
Loggers.SRV_LOG.info("upgrade check result {}", canUpgrade);
if (canUpgrade) {
doUpgrade();
}
}, 100L, 5000L, TimeUnit.MILLISECONDS);
}
@JustForTest
void setUseGrpcFeatures(boolean value) {
useGrpcFeatures.set(value);
}
@JustForTest
void setUseJraftFeatures(boolean value) {
useJraftFeatures.set(value);
}
public boolean isUseGrpcFeatures() {
return useGrpcFeatures.get();
}
public boolean isUseJraftFeatures() {
return useJraftFeatures.get();
}
public boolean isAll20XVersion() {
return all20XVersion.get();
}
@Override
public void onEvent(MembersChangeEvent event) {
if (!event.hasTriggers()) {
Loggers.SRV_LOG
.info("Member change without no trigger. " + "It may be triggered by member lookup on startup. "
+ "Skip.");
return;
}
Loggers.SRV_LOG.info("member change, event: {}", event);
for (Member each : event.getTriggers()) {
Object versionStr = each.getExtendVal(MemberMetaDataConstants.VERSION);
// come from below 1.3.0
if (null == versionStr) {
checkAndDowngrade(false);
all20XVersion.set(false);
return;
}
Version version = VersionUtil.parseVersion(versionStr.toString());
if (version.getMajorVersion() < MAJOR_VERSION) {
checkAndDowngrade(version.getMinorVersion() >= MINOR_VERSION);
all20XVersion.set(false);
return;
}
}
all20XVersion.set(true);
}
private void checkAndDowngrade(boolean jraftFeature) {
boolean isDowngradeGrpc = useGrpcFeatures.compareAndSet(true, false);
boolean isDowngradeJraft = useJraftFeatures.getAndSet(jraftFeature);
if (isDowngradeGrpc && isDowngradeJraft && !jraftFeature) {
Loggers.SRV_LOG.info("Downgrade to 1.X");
NotifyCenter.publishEvent(new UpgradeStates.UpgradeStateChangedEvent(false));
}
}
private boolean checkForUpgrade() {
if (!useGrpcFeatures.get()) {
boolean selfCheckResult = selfUpgradeChecker.isReadyToUpgrade(serviceManager, doubleWriteDelayTaskEngine);
Member self = memberManager.getSelf();
self.setExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE, selfCheckResult);
memberManager.updateMember(self);
if (!selfCheckResult) {
NamingExecuteTaskDispatcher.getInstance().dispatchAndExecuteTask(AsyncServicesCheckTask.class,
new AsyncServicesCheckTask(doubleWriteDelayTaskEngine, this));
}
}
boolean result = true;
for (Member each : memberManager.allMembers()) {
Object isReadyToUpgrade = each.getExtendVal(MemberMetaDataConstants.READY_TO_UPGRADE);
result &= null != isReadyToUpgrade && (boolean) isReadyToUpgrade;
}
return result;
}
private void doUpgrade() {
Loggers.SRV_LOG.info("Upgrade to 2.0.X");
useGrpcFeatures.compareAndSet(false, true);
NotifyCenter.publishEvent(new UpgradeStates.UpgradeStateChangedEvent(true));
useJraftFeatures.set(true);
refreshPersistentServices();
}
private void refreshPersistentServices() {
for (String each : com.alibaba.nacos.naming.core.v2.ServiceManager.getInstance().getAllNamespaces()) {
for (Service service : com.alibaba.nacos.naming.core.v2.ServiceManager.getInstance().getSingletons(each)) {
NamingExecuteTaskDispatcher.getInstance()
.dispatchAndExecuteTask(service, new RefreshStorageDataTask(service));
}
}
}
@Override
public Class<? extends Event> subscribeType() {
return MembersChangeEvent.class;
}
/**
* Shut down.
*/
@PreDestroy
public void shutdown() {
if (null != upgradeChecker) {
upgradeChecker.shutdownNow();
}
NotifyCenter.deregisterSubscriber(this);
}
}

View File

@ -1,141 +0,0 @@
/*
* Copyright (c) 1999-2021 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.naming.core.v2.upgrade;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Properties;
/**
* Persist upgrade states to disk.
*
* @author gengtuo.ygt
* on 2021/5/18
*/
@Component
public class UpgradeStates extends Subscriber<UpgradeStates.UpgradeStateChangedEvent> {
private static final String FILE_NAME = "upgrade.state";
private static final String UPGRADED_KEY = "upgraded";
public static final Path UPGRADE_STATE_FILE =
Paths.get(EnvUtil.getNacosHome() + File.separator + "data" + File.separator + FILE_NAME);
private final Properties properties = new Properties();
@PostConstruct
private void init() throws IOException {
if (Files.isDirectory(UPGRADE_STATE_FILE)) {
throw new IOException(UPGRADE_STATE_FILE + " is a directory");
}
try {
Files.createDirectories(UPGRADE_STATE_FILE.getParent().toAbsolutePath());
} catch (FileAlreadyExistsException ignored) {
}
readFromDisk();
NotifyCenter.registerSubscriber(this);
}
@PreDestroy
private void destroy() throws IOException {
writeToDisk();
}
private void readFromDisk() {
try {
if (Files.notExists(UPGRADE_STATE_FILE)) {
Loggers.SRV_LOG.info("{} file is not exist", FILE_NAME);
return;
}
if (Files.isRegularFile(UPGRADE_STATE_FILE)) {
try (InputStream is = Files.newInputStream(UPGRADE_STATE_FILE)) {
properties.load(is);
}
}
} catch (Exception e) {
Loggers.SRV_LOG.error("Failed to load file " + UPGRADE_STATE_FILE, e);
throw new IllegalStateException(e);
}
}
private void writeToDisk() throws IOException {
try (OutputStream os = Files.newOutputStream(UPGRADE_STATE_FILE,
StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
properties.store(os, null);
}
}
/**
* Cluster has been upgraded at recent process.
*
* @return Has been upgraded
*/
public Boolean isUpgraded() {
String value = properties.getProperty(UPGRADED_KEY);
if (value == null) {
return null;
}
return Boolean.parseBoolean(value);
}
@Override
public void onEvent(UpgradeStateChangedEvent event) {
properties.setProperty(UPGRADED_KEY, String.valueOf(event.isUpgraded));
try {
writeToDisk();
} catch (IOException e) {
Loggers.EVT_LOG.error("Failed to write " + FILE_NAME + " to disk", e);
}
}
@Override
public Class<? extends Event> subscribeType() {
return UpgradeStateChangedEvent.class;
}
public static class UpgradeStateChangedEvent extends Event {
private final boolean isUpgraded;
public UpgradeStateChangedEvent(boolean isUpgraded) {
this.isUpgraded = isUpgraded;
}
public boolean isUpgraded() {
return isUpgraded;
}
}
}

View File

@ -1,41 +0,0 @@
/*
* Copyright 1999-2020 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.naming.core.v2.upgrade.doublewrite;
import com.alibaba.nacos.common.task.AbstractExecuteTask;
import com.alibaba.nacos.naming.core.v2.index.ServiceStorage;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
/**
* Refresh service storage cache data when upgrading.
*
* @author xiweng.yy
*/
public class RefreshStorageDataTask extends AbstractExecuteTask {
private final Service service;
public RefreshStorageDataTask(Service service) {
this.service = service;
}
@Override
public void run() {
ApplicationUtils.getBean(ServiceStorage.class).getPushData(service);
}
}

View File

@ -1,128 +0,0 @@
/*
* Copyright 1999-2020 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.naming.core.v2.upgrade.doublewrite.execute;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.naming.utils.NamingUtils;
import com.alibaba.nacos.common.task.AbstractExecuteTask;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.core.v2.index.ServiceStorage;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteAction;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteContent;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.DoubleWriteDelayTaskEngine;
import com.alibaba.nacos.naming.core.v2.upgrade.doublewrite.delay.ServiceChangeV1Task;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import java.util.HashMap;
import java.util.Map;
/**
* Async services check task for upgrading.
*
* @author xiweng.yy
*/
public class AsyncServicesCheckTask extends AbstractExecuteTask {
private final DoubleWriteDelayTaskEngine doubleWriteDelayTaskEngine;
private final UpgradeJudgement upgradeJudgement;
private static final int INITIALCAPACITY = 64;
public AsyncServicesCheckTask(DoubleWriteDelayTaskEngine doubleWriteDelayTaskEngine,
UpgradeJudgement upgradeJudgement) {
this.doubleWriteDelayTaskEngine = doubleWriteDelayTaskEngine;
this.upgradeJudgement = upgradeJudgement;
}
@Override
public void run() {
if (upgradeJudgement.isUseGrpcFeatures()) {
return;
}
try {
ServiceManager serviceManager = ApplicationUtils.getBean(ServiceManager.class);
ServiceStorage serviceStorage = ApplicationUtils.getBean(ServiceStorage.class);
Map<String, Service> v1Services = new HashMap<>(INITIALCAPACITY);
for (String each : serviceManager.getAllNamespaces()) {
for (Map.Entry<String, Service> entry : serviceManager.chooseServiceMap(each).entrySet()) {
v1Services.put(buildServiceKey(each, entry.getKey()), entry.getValue());
checkService(each, entry.getKey(), entry.getValue(), serviceStorage);
}
}
Map<String, com.alibaba.nacos.naming.core.v2.pojo.Service> v2Services = new HashMap<>(INITIALCAPACITY);
for (String each : com.alibaba.nacos.naming.core.v2.ServiceManager.getInstance().getAllNamespaces()) {
for (com.alibaba.nacos.naming.core.v2.pojo.Service serviceV2
: com.alibaba.nacos.naming.core.v2.ServiceManager.getInstance().getSingletons(each)) {
v2Services.put(buildServiceKey(each, serviceV2.getGroupedServiceName()), serviceV2);
}
}
// only check v2 services when upgrading.
v2Services.keySet().removeIf(v1Services::containsKey);
if (v2Services.isEmpty()) {
return;
}
if (Loggers.SRV_LOG.isDebugEnabled()) {
Loggers.SRV_LOG.debug("{} service in v2 to removed.", v2Services.size());
}
for (com.alibaba.nacos.naming.core.v2.pojo.Service service : v2Services.values()) {
deleteV2Service(service);
}
} catch (Exception e) {
Loggers.SRV_LOG.warn("async check for service error", e);
}
}
private String buildServiceKey(String namespace, String fullServiceName) {
return namespace + "##" + fullServiceName;
}
private void checkService(String namespace, String fullServiceName, Service serviceV1,
ServiceStorage serviceStorage) {
if (upgradeJudgement.isUseGrpcFeatures()) {
return;
}
String groupName = NamingUtils.getGroupName(serviceV1.getName());
String serviceName = NamingUtils.getServiceName(fullServiceName);
com.alibaba.nacos.naming.core.v2.pojo.Service serviceV2 = com.alibaba.nacos.naming.core.v2.pojo.Service
.newService(namespace, groupName, serviceName);
ServiceInfo serviceInfo = serviceStorage.getData(serviceV2);
if (serviceV1.allIPs().size() != serviceInfo.getHosts().size()) {
boolean isEphemeral = serviceV1.allIPs(false).isEmpty();
String key = ServiceChangeV1Task.getKey(namespace, fullServiceName, isEphemeral);
ServiceChangeV1Task task = new ServiceChangeV1Task(namespace, fullServiceName, isEphemeral,
DoubleWriteContent.INSTANCE);
doubleWriteDelayTaskEngine.addTask(key, task);
}
}
private void deleteV2Service(com.alibaba.nacos.naming.core.v2.pojo.Service serviceV2) {
if (upgradeJudgement.isUseGrpcFeatures()) {
return;
}
String namespace = serviceV2.getNamespace();
String serviceName = serviceV2.getGroupedServiceName();
boolean ephemeral = serviceV2.isEphemeral();
String key = ServiceChangeV1Task.getKey(namespace, serviceName, ephemeral);
ServiceChangeV1Task task = new ServiceChangeV1Task(namespace, serviceName,
ephemeral, DoubleWriteContent.BOTH, DoubleWriteAction.REMOVE);
doubleWriteDelayTaskEngine.addTask(key, task);
}
}

View File

@ -1,69 +0,0 @@
/*
* Copyright 1999-2020 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.naming.core.v2.upgrade.doublewrite.execute;
import com.alibaba.nacos.naming.core.Instance;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* A default implementation for instance upgrade/downgrade.
*
* @author gengtuo.ygt
* on 2021/2/25
*/
public class DefaultInstanceUpgradeHelper implements InstanceUpgradeHelper {
private static final String IGNORE_PROPERTIES = "metadata";
/**
* Fallback to default implementation when no other impls met.
*/
@Configuration
public static class Config {
/**
* A default impl of instance upgrade helper.
*
* @return default impl of instance upgrade helper
*/
@Bean
@ConditionalOnMissingBean(InstanceUpgradeHelper.class)
public InstanceUpgradeHelper defaultInstanceUpgradeHelper() {
return new DefaultInstanceUpgradeHelper();
}
}
@Override
public Instance toV1(com.alibaba.nacos.api.naming.pojo.Instance v2) {
Instance v1 = new Instance(v2.getIp(), v2.getPort(), v2.getClusterName());
BeanUtils.copyProperties(v2, v1);
return v1;
}
@Override
public com.alibaba.nacos.api.naming.pojo.Instance toV2(Instance v1) {
com.alibaba.nacos.api.naming.pojo.Instance v2 = new com.alibaba.nacos.api.naming.pojo.Instance();
BeanUtils.copyProperties(v1, v2, IGNORE_PROPERTIES);
v2.getMetadata().putAll(v1.getMetadata());
return v2;
}
}

View File

@ -1,108 +0,0 @@
/*
* Copyright 1999-2020 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.naming.core.v2.upgrade.doublewrite.execute;
import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
/**
* A default implementation for service/cluster upgrade/downgrade.
*
* @author gengtuo.ygt
* on 2021/2/25
*/
public class DefaultServiceMetadataUpgradeHelper implements ServiceMetadataUpgradeHelper {
/**
* Fallback to default implementation when no other impls met.
*/
@Configuration
public static class Config {
/**
* A default impl of service/cluster upgrade helper.
*
* @return default impl of service/cluster upgrade helper
*/
@Bean
@ConditionalOnMissingBean(ServiceMetadataUpgradeHelper.class)
public ServiceMetadataUpgradeHelper defaultServiceMetadataUpgradeHelper() {
return new DefaultServiceMetadataUpgradeHelper();
}
}
@Override
public Service toV1Service(Service v1, com.alibaba.nacos.naming.core.v2.pojo.Service v2, ServiceMetadata v2meta) {
if (null == v1) {
v1 = new Service(v2.getGroupedServiceName());
v1.setGroupName(v2.getGroup());
v1.setNamespaceId(v2.getNamespace());
}
v1.setSelector(v2meta.getSelector());
v1.setProtectThreshold(v2meta.getProtectThreshold());
v1.setMetadata(v2meta.getExtendData());
for (Map.Entry<String, ClusterMetadata> entry : v2meta.getClusters().entrySet()) {
if (!v1.getClusterMap().containsKey(entry.getKey())) {
v1.addCluster(toV1Cluster(new Cluster(entry.getKey(), v1), entry.getValue()));
} else {
toV1Cluster(v1.getClusterMap().get(entry.getKey()), entry.getValue());
}
}
return v1;
}
@Override
public Cluster toV1Cluster(Cluster v1, ClusterMetadata v2meta) {
v1.setDefCkport(v2meta.getHealthyCheckPort());
v1.setUseIPPort4Check(v2meta.isUseInstancePortForCheck());
v1.setHealthChecker(v2meta.getHealthChecker());
v1.setMetadata(v2meta.getExtendData());
return v1;
}
@Override
public ServiceMetadata toV2ServiceMetadata(Service service, boolean ephemeral) {
ServiceMetadata result = new ServiceMetadata();
result.setEphemeral(ephemeral);
result.setProtectThreshold(service.getProtectThreshold());
result.setSelector(service.getSelector());
result.setExtendData(service.getMetadata());
for (Map.Entry<String, Cluster> entry : service.getClusterMap().entrySet()) {
result.getClusters().put(entry.getKey(), toV2ClusterMetadata(entry.getValue()));
}
return result;
}
@Override
public ClusterMetadata toV2ClusterMetadata(Cluster v1) {
ClusterMetadata result = new ClusterMetadata();
result.setHealthyCheckPort(v1.getDefCkport());
result.setUseInstancePortForCheck(v1.isUseIPPort4Check());
result.setExtendData(v1.getMetadata());
result.setHealthChecker(v1.getHealthChecker());
result.setHealthyCheckType(v1.getHealthChecker().getType());
return result;
}
}

View File

@ -16,7 +16,6 @@
package com.alibaba.nacos.naming.healthcheck.interceptor;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.healthcheck.NacosHealthCheckTask;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
@ -31,8 +30,7 @@ public class HealthCheckEnableInterceptor extends AbstractHealthCheckInterceptor
@Override
public boolean intercept(NacosHealthCheckTask object) {
try {
return !ApplicationUtils.getBean(SwitchDomain.class).isHealthCheckEnabled() || !ApplicationUtils
.getBean(UpgradeJudgement.class).isUseGrpcFeatures();
return !ApplicationUtils.getBean(SwitchDomain.class).isHealthCheckEnabled();
} catch (Exception e) {
return true;
}

View File

@ -19,8 +19,8 @@ package com.alibaba.nacos.naming.push;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.api.remote.PushCallBack;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.naming.constants.Constants;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.misc.GlobalExecutor;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.SwitchDomain;
@ -30,19 +30,15 @@ import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.push.v1.ClientInfo;
import com.alibaba.nacos.naming.push.v1.NamingSubscriberServiceV1Impl;
import com.alibaba.nacos.naming.push.v1.PushClient;
import com.alibaba.nacos.naming.push.v1.ServiceChangeEvent;
import com.alibaba.nacos.naming.remote.udp.AckEntry;
import com.alibaba.nacos.naming.remote.udp.AckPacket;
import com.alibaba.nacos.naming.remote.udp.UdpConnector;
import com.alibaba.nacos.naming.constants.Constants;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import org.apache.commons.collections.MapUtils;
import org.codehaus.jackson.util.VersionUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.io.ByteArrayOutputStream;
@ -69,7 +65,7 @@ import java.util.zip.GZIPOutputStream;
*/
@Component
@SuppressWarnings("PMD.ThreadPoolCreationRule")
public class UdpPushService implements ApplicationContextAware, ApplicationListener<ServiceChangeEvent> {
public class UdpPushService implements ApplicationContextAware {
@Autowired
private SwitchDomain switchDomain;
@ -114,80 +110,6 @@ public class UdpPushService implements ApplicationContextAware, ApplicationListe
this.applicationContext = applicationContext;
}
@Override
public void onApplicationEvent(ServiceChangeEvent event) {
// If upgrade to 2.0.X, do not push for v1.
if (ApplicationUtils.getBean(UpgradeJudgement.class).isUseGrpcFeatures()) {
return;
}
Service service = event.getService();
String serviceName = service.getName();
String namespaceId = service.getNamespaceId();
//merge some change events to reduce the push frequency:
if (futureMap.containsKey(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName))) {
return;
}
Future future = GlobalExecutor.scheduleUdpSender(() -> {
try {
Loggers.PUSH.info(serviceName + " is changed, add it to push queue.");
ConcurrentMap<String, PushClient> clients = subscriberServiceV1.getClientMap()
.get(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName));
if (MapUtils.isEmpty(clients)) {
return;
}
Map<String, Object> cache = new HashMap<>(16);
long lastRefTime = System.nanoTime();
for (PushClient client : clients.values()) {
if (client.zombie()) {
Loggers.PUSH.debug("client is zombie: " + client);
clients.remove(client.toString());
Loggers.PUSH.debug("client is zombie: " + client);
continue;
}
AckEntry ackEntry;
Loggers.PUSH.debug("push serviceName: {} to client: {}", serviceName, client);
String key = getPushCacheKey(serviceName, client.getIp(), client.getAgent());
byte[] compressData = null;
Map<String, Object> data = null;
if (switchDomain.getDefaultPushCacheMillis() >= 20000 && cache.containsKey(key)) {
org.javatuples.Pair pair = (org.javatuples.Pair) cache.get(key);
compressData = (byte[]) (pair.getValue0());
data = (Map<String, Object>) pair.getValue1();
Loggers.PUSH.debug("[PUSH-CACHE] cache hit: {}:{}", serviceName, client.getAddrStr());
}
if (compressData != null) {
ackEntry = prepareAckEntry(client, compressData, data, lastRefTime);
} else {
ackEntry = prepareAckEntry(client, prepareHostsData(client), lastRefTime);
if (ackEntry != null) {
cache.put(key,
new org.javatuples.Pair<>(ackEntry.getOrigin().getData(), ackEntry.getData()));
}
}
Loggers.PUSH.info("serviceName: {} changed, schedule push for: {}, agent: {}, key: {}",
client.getServiceName(), client.getAddrStr(), client.getAgent(),
(ackEntry == null ? null : ackEntry.getKey()));
udpPush(ackEntry);
}
} catch (Exception e) {
Loggers.PUSH.error("[NACOS-PUSH] failed to push serviceName: {} to client, error: {}", serviceName, e);
} finally {
futureMap.remove(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName));
}
}, 1000, TimeUnit.MILLISECONDS);
futureMap.put(UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName), future);
}
/**
* Push Data without callback.
*
@ -289,7 +211,6 @@ public class UdpPushService implements ApplicationContextAware, ApplicationListe
* @param service service
*/
public void serviceChanged(Service service) {
this.applicationContext.publishEvent(new ServiceChangeEvent(this, service));
}
/**

View File

@ -1,40 +0,0 @@
/*
* Copyright 1999-2020 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.naming.push.v1;
import com.alibaba.nacos.naming.core.Service;
import org.springframework.context.ApplicationEvent;
/**
* Service change event.
*
* @author pbting
* @date 2019-07-10 5:41 PM
*/
public class ServiceChangeEvent extends ApplicationEvent {
private Service service;
public ServiceChangeEvent(Object source, Service service) {
super(source);
this.service = service;
}
public Service getService() {
return service;
}
}

View File

@ -28,7 +28,6 @@ import com.alibaba.nacos.naming.core.v2.index.ClientServiceIndexesManager;
import com.alibaba.nacos.naming.core.v2.index.ServiceStorage;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.push.NamingSubscriberService;
@ -58,15 +57,11 @@ public class NamingSubscriberServiceV2Impl extends SmartSubscriber implements Na
private final PushDelayTaskExecuteEngine delayTaskEngine;
private final UpgradeJudgement upgradeJudgement;
public NamingSubscriberServiceV2Impl(ClientManagerDelegate clientManager,
ClientServiceIndexesManager indexesManager, ServiceStorage serviceStorage,
NamingMetadataManager metadataManager, PushExecutorDelegate pushExecutor, UpgradeJudgement upgradeJudgement,
SwitchDomain switchDomain) {
NamingMetadataManager metadataManager, PushExecutorDelegate pushExecutor, SwitchDomain switchDomain) {
this.clientManager = clientManager;
this.indexesManager = indexesManager;
this.upgradeJudgement = upgradeJudgement;
this.delayTaskEngine = new PushDelayTaskExecuteEngine(clientManager, indexesManager, serviceStorage,
metadataManager, pushExecutor, switchDomain);
NotifyCenter.registerSubscriber(this, NamingEventPublisherFactory.getInstance());
@ -117,9 +112,6 @@ public class NamingSubscriberServiceV2Impl extends SmartSubscriber implements Na
@Override
public void onEvent(Event event) {
if (!upgradeJudgement.isUseGrpcFeatures()) {
return;
}
if (event instanceof ServiceEvent.ServiceChangedEvent) {
// If service changed, push to all subscribers.
ServiceEvent.ServiceChangedEvent serviceChangedEvent = (ServiceEvent.ServiceChangedEvent) event;

View File

@ -1,50 +0,0 @@
/*
* Copyright 1999-2020 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.naming.remote.rpc.filter;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.remote.request.AbstractNamingRequest;
import com.alibaba.nacos.api.remote.request.Request;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.core.remote.AbstractRequestFilter;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* Grpc request filter.
*
* @author majorhe
*/
@Component
public class GrpcRequestFilter extends AbstractRequestFilter {
@Autowired
private UpgradeJudgement upgradeJudgement;
@Override
protected Response filter(Request request, RequestMeta meta, Class handlerClazz) throws NacosException {
if (request instanceof AbstractNamingRequest && !upgradeJudgement.isUseGrpcFeatures()) {
Response response = getDefaultResponseInstance(handlerClazz);
response.setErrorInfo(NacosException.SERVER_ERROR,
"Nacos cluster is running with 1.X mode, can't accept gRPC request temporarily. Please check the server status or close Double write to force open 2.0 mode. Detail https://nacos.io/en-us/docs/2.0.0-upgrading.html.");
return response;
}
return null;
}
}

View File

@ -17,7 +17,6 @@
package com.alibaba.nacos.naming.web;
import com.alibaba.nacos.core.utils.ReuseHttpServletRequest;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import org.springframework.stereotype.Component;
/**
@ -28,14 +27,9 @@ import org.springframework.stereotype.Component;
@Component
public class DistroTagGeneratorImpl implements DistroTagGenerator {
private final DistroTagGenerator serviceNameTag = new DistroServiceNameTagGenerator();
private final DistroTagGenerator ipPortTag = new DistroIpPortTagGenerator();
private final UpgradeJudgement upgradeJudgement;
public DistroTagGeneratorImpl(UpgradeJudgement upgradeJudgement) {
this.upgradeJudgement = upgradeJudgement;
public DistroTagGeneratorImpl() {
}
@Override
@ -47,13 +41,12 @@ public class DistroTagGeneratorImpl implements DistroTagGenerator {
* Get tag generator according to cluster member ability.
*
* <p>
* If all member is upper than 2.x. Using {@link DistroIpPortTagGenerator}. Otherwise use 1.x {@link
* DistroServiceNameTagGenerator}.
* If all member is upper than 2.x. Using {@link DistroIpPortTagGenerator}.
* </p>
*
* @return actual tag generator
*/
private DistroTagGenerator getTagGenerator() {
return upgradeJudgement.isUseGrpcFeatures() ? ipPortTag : serviceNameTag;
return ipPortTag;
}
}

View File

@ -18,7 +18,6 @@ package com.alibaba.nacos.naming;
import com.alibaba.nacos.naming.core.DistroMapper;
import com.alibaba.nacos.naming.core.ServiceManager;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.push.UdpPushService;
import com.alibaba.nacos.sys.env.EnvUtil;
@ -72,9 +71,6 @@ public abstract class BaseTest {
@Mock
protected UdpPushService pushService;
@Mock
protected UpgradeJudgement upgradeJudgement;
@Spy
protected MockEnvironment environment;
@ -95,8 +91,4 @@ public abstract class BaseTest {
protected void mockInjectDistroMapper() {
doReturn(distroMapper).when(context).getBean(DistroMapper.class);
}
protected void mockInjectUpgradeJudgement() {
doReturn(upgradeJudgement).when(context).getBean(UpgradeJudgement.class);
}
}

View File

@ -26,7 +26,6 @@ import com.alibaba.nacos.core.distributed.distro.component.DistroFailedTaskHandl
import com.alibaba.nacos.core.distributed.distro.component.DistroTransportAgent;
import com.alibaba.nacos.core.distributed.distro.task.DistroTaskEngineHolder;
import com.alibaba.nacos.naming.core.v2.client.manager.ClientManagerDelegate;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import junit.framework.TestCase;
import org.junit.Assert;
import org.junit.Before;
@ -37,55 +36,51 @@ import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class DistroClientComponentRegistryTest extends TestCase {
private DistroClientComponentRegistry distroClientComponentRegistry;
@Mock
private ServerMemberManager serverMemberManager;
@Mock
private DistroProtocol distroProtocol;
@Mock
private DistroTaskEngineHolder taskEngineHolder;
@Mock
private ClientManagerDelegate clientManager;
@Mock
private ClusterRpcClientProxy clusterRpcClientProxy;
@Mock
private UpgradeJudgement upgradeJudgement;
private DistroComponentHolder componentHolder;
@Before
public void setUp() throws Exception {
componentHolder = new DistroComponentHolder();
distroClientComponentRegistry = new DistroClientComponentRegistry(serverMemberManager, distroProtocol,
componentHolder, taskEngineHolder,
clientManager, clusterRpcClientProxy,
upgradeJudgement);
componentHolder, taskEngineHolder, clientManager, clusterRpcClientProxy);
}
@Test
public void testDoRegister() {
distroClientComponentRegistry.doRegister();
DistroDataStorage dataStorage = componentHolder.findDataStorage(DistroClientDataProcessor.TYPE);
Assert.assertNotNull(dataStorage);
DistroDataProcessor dataProcessor = componentHolder.findDataProcessor(DistroClientDataProcessor.TYPE);
Assert.assertNotNull(dataProcessor);
DistroFailedTaskHandler failedTaskHandler = componentHolder.findFailedTaskHandler(DistroClientDataProcessor.TYPE);
DistroFailedTaskHandler failedTaskHandler = componentHolder
.findFailedTaskHandler(DistroClientDataProcessor.TYPE);
Assert.assertNotNull(failedTaskHandler);
DistroTransportAgent transportAgent = componentHolder.findTransportAgent(DistroClientDataProcessor.TYPE);
Assert.assertNotNull(transportAgent);
}
}
}

View File

@ -21,15 +21,12 @@ import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Collections;
import java.util.List;
@ -39,9 +36,6 @@ import static org.junit.Assert.assertTrue;
@RunWith(MockitoJUnitRunner.class)
public class CatalogControllerTest {
@Mock
protected UpgradeJudgement upgradeJudgement;
private CatalogController catalogController;
private Service service;
@ -51,7 +45,6 @@ public class CatalogControllerTest {
@Before
public void setUp() throws NoSuchFieldException, IllegalAccessException, NacosException {
catalogController = new CatalogController();
ReflectionTestUtils.setField(catalogController, "upgradeJudgement", upgradeJudgement);
service = new Service(TEST_SERVICE_NAME);
service.setNamespaceId(Constants.DEFAULT_NAMESPACE_ID);
service.setProtectThreshold(12.34f);

View File

@ -31,7 +31,6 @@ import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@ -59,7 +58,6 @@ public class ClusterControllerTest extends BaseTest {
mockInjectSwitchDomain();
mockInjectDistroMapper();
mockmvc = MockMvcBuilders.standaloneSetup(clusterController).build();
ReflectionTestUtils.setField(clusterController, "upgradeJudgement", upgradeJudgement);
try {
doCallRealMethod().when(serviceManager).checkServiceIsNull(eq(null), anyString(), anyString());
} catch (NacosException e) {

View File

@ -21,7 +21,6 @@ import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.naming.constants.RequestConstant;
import com.alibaba.nacos.naming.core.HealthOperatorV2Impl;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.sys.env.EnvUtil;
import org.junit.Assert;
import org.junit.Before;
@ -29,7 +28,6 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.env.MockEnvironment;
@ -50,9 +48,6 @@ public class HealthControllerTest {
@Mock
private HealthOperatorV2Impl healthOperatorV2;
@Mock
private UpgradeJudgement upgradeJudgement;
@Before
public void setUp() {
EnvUtil.setEnvironment(new MockEnvironment());
@ -72,8 +67,6 @@ public class HealthControllerTest {
servletRequest.addParameter(RequestConstant.PORT_KEY, "8848");
servletRequest.addParameter(RequestConstant.HEALTHY_KEY, "true");
Mockito.when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true);
try {
ResponseEntity responseEntity = healthController.update(servletRequest);
Assert.assertEquals(200, responseEntity.getStatusCodeValue());

View File

@ -39,7 +39,6 @@ import org.springframework.mock.web.MockServletContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
@ -72,7 +71,6 @@ public class InstanceControllerTest extends BaseTest {
public void before() {
super.before();
mockInjectPushServer();
ReflectionTestUtils.setField(instanceController, "upgradeJudgement", upgradeJudgement);
when(instanceUpgradeHelper.toV1(any())).thenReturn(new Instance("1.1.1.1", 9999));
mockmvc = MockMvcBuilders.standaloneSetup(instanceController).build();
}

View File

@ -21,7 +21,6 @@ import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.naming.BaseTest;
import com.alibaba.nacos.naming.core.ServiceOperatorV2Impl;
import com.alibaba.nacos.naming.core.SubscribeManager;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.Assert;
@ -33,7 +32,6 @@ import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.util.ReflectionTestUtils;
import java.util.Arrays;
import java.util.Collections;
@ -47,17 +45,12 @@ public class ServiceControllerTest extends BaseTest {
@Mock
private ServiceOperatorV2Impl serviceOperatorV2;
@Mock
private UpgradeJudgement upgradeJudgement;
@Mock
private SubscribeManager subscribeManager;
@Before
public void before() {
super.before();
ReflectionTestUtils.setField(serviceController, "upgradeJudgement", upgradeJudgement);
Mockito.when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true);
}
@Test
@ -65,7 +58,7 @@ public class ServiceControllerTest extends BaseTest {
Mockito.when(serviceOperatorV2.listService(Mockito.anyString(), Mockito.anyString(), Mockito.anyString()))
.thenReturn(Collections.singletonList("DEFAULT_GROUP@@providers:com.alibaba.nacos.controller.test:1"));
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
servletRequest.addParameter("pageNo", "1");
servletRequest.addParameter("pageSize", "10");
@ -77,7 +70,6 @@ public class ServiceControllerTest extends BaseTest {
@Test
public void testCreate() {
try {
Mockito.when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true);
String res = serviceController.create(TEST_NAMESPACE, TEST_SERVICE_NAME, 0, "", "");
Assert.assertEquals("ok", res);
} catch (Exception e) {
@ -128,7 +120,8 @@ public class ServiceControllerTest extends BaseTest {
@Test
public void testSearchService() {
try {
Mockito.when(serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean()))
Mockito.when(
serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean()))
.thenReturn(Collections.singletonList("result"));
ObjectNode objectNode = serviceController.searchService(TEST_NAMESPACE, "", true);
@ -139,7 +132,8 @@ public class ServiceControllerTest extends BaseTest {
}
try {
Mockito.when(serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean()))
Mockito.when(
serviceOperatorV2.searchServiceName(Mockito.anyString(), Mockito.anyString(), Mockito.anyBoolean()))
.thenReturn(Arrays.asList("re1", "re2"));
Mockito.when(serviceOperatorV2.listAllNamespace()).thenReturn(Arrays.asList("re1", "re2"));

View File

@ -24,7 +24,6 @@ import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.pojo.HealthCheckInstancePublishInfo;
import com.alibaba.nacos.naming.core.v2.pojo.InstancePublishInfo;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.healthcheck.heartbeat.ClientBeatCheckTaskV2;
import com.alibaba.nacos.naming.misc.GlobalConfig;
import com.alibaba.nacos.naming.misc.SwitchDomain;
@ -77,9 +76,6 @@ public class HealthCheckTaskInterceptWrapperTest {
@Mock
private ConfigurableApplicationContext applicationContext;
@Mock
private UpgradeJudgement upgradeJudgement;
private IpPortBasedClient client;
@Before
@ -88,12 +84,10 @@ public class HealthCheckTaskInterceptWrapperTest {
when(applicationContext.getBean(GlobalConfig.class)).thenReturn(globalConfig);
when(applicationContext.getBean(SwitchDomain.class)).thenReturn(switchDomain);
when(applicationContext.getBean(DistroMapper.class)).thenReturn(distroMapper);
when(applicationContext.getBean(UpgradeJudgement.class)).thenReturn(upgradeJudgement);
ApplicationUtils.injectContext(applicationContext);
client = new IpPortBasedClient(CLIENT_ID, true);
when(switchDomain.isHealthCheckEnabled()).thenReturn(true);
when(distroMapper.responsible(client.getResponsibleId())).thenReturn(true);
when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true);
ClientBeatCheckTaskV2 beatCheckTask = new ClientBeatCheckTaskV2(client);
taskWrapper = new HealthCheckTaskInterceptWrapper(beatCheckTask);
}
@ -169,7 +163,8 @@ public class HealthCheckTaskInterceptWrapperTest {
Service service = Service.newService(NAMESPACE, GROUP_NAME, SERVICE_NAME);
InstanceMetadata metadata = new InstanceMetadata();
metadata.getExtendData().put(PreservedMetadataKeys.HEART_BEAT_TIMEOUT, 1000L);
when(namingMetadataManager.getInstanceMetadata(service, instance.getMetadataId())).thenReturn(Optional.of(metadata));
when(namingMetadataManager.getInstanceMetadata(service, instance.getMetadataId()))
.thenReturn(Optional.of(metadata));
when(globalConfig.isExpireInstance()).thenReturn(true);
TimeUnit.SECONDS.sleep(1);
taskWrapper.run();

View File

@ -1,43 +0,0 @@
/*
* Copyright 1999-2020 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.naming.push.v1;
import com.alibaba.nacos.naming.core.Service;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class ServiceChangeEventTest {
@Mock
private Service service;
@Mock
private Object object;
@Test
public void testGetService() {
ServiceChangeEvent serviceChangeEvent = new ServiceChangeEvent(object, service);
Service service = serviceChangeEvent.getService();
Assert.assertNotNull(service);
Assert.assertEquals(service, service);
}
}

View File

@ -21,7 +21,6 @@ import com.alibaba.nacos.naming.core.v2.client.manager.ClientManagerDelegate;
import com.alibaba.nacos.naming.core.v2.event.service.ServiceEvent;
import com.alibaba.nacos.naming.core.v2.index.ClientServiceIndexesManager;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.push.v2.task.PushDelayTask;
@ -64,9 +63,6 @@ public class NamingSubscriberServiceV2ImplTest {
@Mock
private Client client;
@Mock
private UpgradeJudgement upgradeJudgement;
@Mock
private SwitchDomain switchDomain;
@ -74,8 +70,8 @@ public class NamingSubscriberServiceV2ImplTest {
@Before
public void setUp() throws Exception {
subscriberService = new NamingSubscriberServiceV2Impl(clientManager, indexesManager, null, null, null,
upgradeJudgement, switchDomain);
subscriberService = new NamingSubscriberServiceV2Impl(clientManager, indexesManager, null, null, null,
switchDomain);
ReflectionTestUtils.setField(subscriberService, "delayTaskEngine", delayTaskEngine);
when(indexesManager.getAllClientsSubscribeService(service)).thenReturn(Collections.singletonList(testClientId));
when(indexesManager.getAllClientsSubscribeService(service1))
@ -89,7 +85,6 @@ public class NamingSubscriberServiceV2ImplTest {
new Subscriber("1.1.1.1:1111", "Test", "unknown", "1.1.1.1", "N", service.getGroupedServiceName(), 0));
when(client.getSubscriber(service1)).thenReturn(
new Subscriber("1.1.1.1:1111", "Test", "unknown", "1.1.1.1", "N", service1.getGroupedServiceName(), 0));
when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true);
}
@Test

View File

@ -1,61 +0,0 @@
/*
* Copyright 1999-2021 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.naming.remote.rpc.filter;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.remote.request.InstanceRequest;
import com.alibaba.nacos.api.remote.request.RequestMeta;
import com.alibaba.nacos.api.remote.response.Response;
import com.alibaba.nacos.naming.core.v2.upgrade.UpgradeJudgement;
import com.alibaba.nacos.naming.remote.rpc.handler.InstanceRequestHandler;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
/**
* {@link GrpcRequestFilter} unit test.
*
* @author chenglu
* @date 2021-09-17 16:25
*/
@RunWith(MockitoJUnitRunner.class)
public class GrpcRequestFilterTest {
@InjectMocks
private GrpcRequestFilter grpcRequestFilter;
@Mock
private UpgradeJudgement upgradeJudgement;
@Test
public void testFilter() throws NacosException {
Mockito.when(upgradeJudgement.isUseGrpcFeatures()).thenReturn(true).thenReturn(false);
Response response = grpcRequestFilter.filter(new InstanceRequest(), new RequestMeta(), InstanceRequestHandler.class);
Assert.assertNull(response);
try {
grpcRequestFilter.filter(new InstanceRequest(), new RequestMeta(), InstanceRequestHandler.class);
} catch (Exception e) {
Assert.assertTrue(e instanceof NacosException);
}
}
}

View File

@ -1,17 +0,0 @@
#
# Copyright 1999-2020 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.
#
com.alibaba.nacos.naming.core.v2.upgrade.MockSelfUpgradeChecker