index int64 0 0 | repo_id stringlengths 9 205 | file_path stringlengths 31 246 | content stringlengths 1 12.2M | __index_level_0__ int64 0 10k |
|---|---|---|---|---|
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscovery.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.metadata.event.MetadataEvent;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.registry.client.metadata.MetadataUtils;
import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils;
import org.apache.dubbo.registry.client.metadata.store.MetaCacheManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_INFO_CACHE_EXPIRE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_INFO_CACHE_SIZE;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_INFO_CACHE_EXPIRE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METADATA_INFO_CACHE_SIZE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_LOCAL_FILE_CACHE_ENABLED;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_LOAD_METADATA;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY;
import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.EXPORTED_SERVICES_REVISION_PROPERTY_NAME;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getExportedServicesRevision;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.isValidInstance;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.setMetadataStorageType;
/**
* Each service discovery is bond to one application.
*/
public abstract class AbstractServiceDiscovery implements ServiceDiscovery {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(AbstractServiceDiscovery.class);
private volatile boolean isDestroy;
protected final String serviceName;
protected volatile ServiceInstance serviceInstance;
protected volatile MetadataInfo metadataInfo;
protected final ConcurrentHashMap<String, MetadataInfoStat> metadataInfos = new ConcurrentHashMap<>();
protected final ScheduledFuture<?> refreshCacheFuture;
protected MetadataReport metadataReport;
protected String metadataType;
protected final MetaCacheManager metaCacheManager;
protected URL registryURL;
protected Set<ServiceInstancesChangedListener> instanceListeners = new ConcurrentHashSet<>();
protected ApplicationModel applicationModel;
public AbstractServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
this(applicationModel, applicationModel.getApplicationName(), registryURL);
MetadataReportInstance metadataReportInstance =
applicationModel.getBeanFactory().getBean(MetadataReportInstance.class);
metadataType = metadataReportInstance.getMetadataType();
this.metadataReport = metadataReportInstance.getMetadataReport(registryURL.getParameter(REGISTRY_CLUSTER_KEY));
}
public AbstractServiceDiscovery(String serviceName, URL registryURL) {
this(ApplicationModel.defaultModel(), serviceName, registryURL);
}
private AbstractServiceDiscovery(ApplicationModel applicationModel, String serviceName, URL registryURL) {
this.applicationModel = applicationModel;
this.serviceName = serviceName;
this.registryURL = registryURL;
this.metadataInfo = new MetadataInfo(serviceName);
boolean localCacheEnabled = registryURL.getParameter(REGISTRY_LOCAL_FILE_CACHE_ENABLED, true);
this.metaCacheManager = new MetaCacheManager(
localCacheEnabled,
getCacheNameSuffix(),
applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getCacheRefreshingScheduledExecutor());
int metadataInfoCacheExpireTime =
registryURL.getParameter(METADATA_INFO_CACHE_EXPIRE_KEY, DEFAULT_METADATA_INFO_CACHE_EXPIRE);
int metadataInfoCacheSize =
registryURL.getParameter(METADATA_INFO_CACHE_SIZE_KEY, DEFAULT_METADATA_INFO_CACHE_SIZE);
this.refreshCacheFuture = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getSharedScheduledExecutor()
.scheduleAtFixedRate(
() -> {
try {
while (metadataInfos.size() > metadataInfoCacheSize) {
AtomicReference<String> oldestRevision = new AtomicReference<>();
AtomicReference<MetadataInfoStat> oldestStat = new AtomicReference<>();
metadataInfos.forEach((k, v) -> {
if (System.currentTimeMillis() - v.getUpdateTime() > metadataInfoCacheExpireTime
&& (oldestStat.get() == null
|| oldestStat.get().getUpdateTime() > v.getUpdateTime())) {
oldestRevision.set(k);
oldestStat.set(v);
}
});
if (oldestStat.get() != null) {
metadataInfos.remove(oldestRevision.get(), oldestStat.get());
}
}
} catch (Throwable t) {
logger.error(
INTERNAL_ERROR, "", "", "Error occurred when clean up metadata info cache.", t);
}
},
metadataInfoCacheExpireTime / 2,
metadataInfoCacheExpireTime / 2,
TimeUnit.MILLISECONDS);
}
@Override
public synchronized void register() throws RuntimeException {
if (isDestroy) {
return;
}
if (this.serviceInstance == null) {
ServiceInstance serviceInstance = createServiceInstance(this.metadataInfo);
if (!isValidInstance(serviceInstance)) {
return;
}
this.serviceInstance = serviceInstance;
}
boolean revisionUpdated = calOrUpdateInstanceRevision(this.serviceInstance);
if (revisionUpdated) {
reportMetadata(this.metadataInfo);
doRegister(this.serviceInstance);
}
}
/**
* Update assumes that DefaultServiceInstance and its attributes will never get updated once created.
* Checking hasExportedServices() before registration guarantees that at least one service is ready for creating the
* instance.
*/
@Override
public synchronized void update() throws RuntimeException {
if (isDestroy) {
return;
}
if (this.serviceInstance == null) {
register();
}
if (!isValidInstance(this.serviceInstance)) {
return;
}
ServiceInstance oldServiceInstance = this.serviceInstance;
DefaultServiceInstance newServiceInstance =
new DefaultServiceInstance((DefaultServiceInstance) oldServiceInstance);
boolean revisionUpdated = calOrUpdateInstanceRevision(newServiceInstance);
if (revisionUpdated) {
logger.info(String.format(
"Metadata of instance changed, updating instance with revision %s.",
newServiceInstance.getServiceMetadata().getRevision()));
doUpdate(oldServiceInstance, newServiceInstance);
this.serviceInstance = newServiceInstance;
}
}
@Override
public synchronized void unregister() throws RuntimeException {
if (isDestroy) {
return;
}
// fixme, this metadata info might still being shared by other instances
// unReportMetadata(this.metadataInfo);
if (!isValidInstance(this.serviceInstance)) {
return;
}
doUnregister(this.serviceInstance);
}
@Override
public final ServiceInstance getLocalInstance() {
return this.serviceInstance;
}
@Override
public MetadataInfo getLocalMetadata() {
return this.metadataInfo;
}
@Override
public MetadataInfo getLocalMetadata(String revision) {
MetadataInfoStat metadataInfoStat = metadataInfos.get(revision);
if (metadataInfoStat != null) {
return metadataInfoStat.getMetadataInfo();
} else {
return null;
}
}
@Override
public MetadataInfo getRemoteMetadata(String revision, List<ServiceInstance> instances) {
MetadataInfo metadata = metaCacheManager.get(revision);
if (metadata != null && metadata != MetadataInfo.EMPTY) {
metadata.init();
// metadata loaded from cache
if (logger.isDebugEnabled()) {
logger.debug("MetadataInfo for revision=" + revision + ", " + metadata);
}
return metadata;
}
synchronized (metaCacheManager) {
// try to load metadata from remote.
int triedTimes = 0;
while (triedTimes < 3) {
metadata = MetricsEventBus.post(
MetadataEvent.toSubscribeEvent(applicationModel),
() -> MetadataUtils.getRemoteMetadata(revision, instances, metadataReport),
result -> result != MetadataInfo.EMPTY);
if (metadata != MetadataInfo.EMPTY) { // succeeded
metadata.init();
break;
} else { // failed
if (triedTimes > 0) {
if (logger.isDebugEnabled()) {
logger.debug("Retry the " + triedTimes + " times to get metadata for revision=" + revision);
}
}
triedTimes++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
if (metadata == MetadataInfo.EMPTY) {
logger.error(
REGISTRY_FAILED_LOAD_METADATA,
"",
"",
"Failed to get metadata for revision after 3 retries, revision=" + revision);
} else {
metaCacheManager.put(revision, metadata);
}
}
return metadata;
}
@Override
public MetadataInfo getRemoteMetadata(String revision) {
return metaCacheManager.get(revision);
}
@Override
public final void destroy() throws Exception {
isDestroy = true;
metaCacheManager.destroy();
refreshCacheFuture.cancel(true);
doDestroy();
}
@Override
public final boolean isDestroy() {
return isDestroy;
}
@Override
public void register(URL url) {
metadataInfo.addService(url);
}
@Override
public void unregister(URL url) {
metadataInfo.removeService(url);
}
@Override
public void subscribe(URL url, NotifyListener listener) {
metadataInfo.addSubscribedURL(url);
}
@Override
public void unsubscribe(URL url, NotifyListener listener) {
metadataInfo.removeSubscribedURL(url);
}
@Override
public List<URL> lookup(URL url) {
throw new UnsupportedOperationException(
"Service discovery implementation does not support lookup of url list.");
}
/**
* Update Service Instance. Unregister and then register by default.
* Can be override if registry support update instance directly.
* <br/>
* NOTICE: Remind to update {@link AbstractServiceDiscovery#serviceInstance}'s reference if updated
* and report metadata by {@link AbstractServiceDiscovery#reportMetadata(MetadataInfo)}
*
* @param oldServiceInstance origin service instance
* @param newServiceInstance new service instance
*/
protected void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance) {
this.doUnregister(oldServiceInstance);
this.serviceInstance = newServiceInstance;
if (!EMPTY_REVISION.equals(getExportedServicesRevision(newServiceInstance))) {
reportMetadata(newServiceInstance.getServiceMetadata());
this.doRegister(newServiceInstance);
}
}
@Override
public URL getUrl() {
return registryURL;
}
protected abstract void doRegister(ServiceInstance serviceInstance) throws RuntimeException;
protected abstract void doUnregister(ServiceInstance serviceInstance);
protected abstract void doDestroy() throws Exception;
protected ServiceInstance createServiceInstance(MetadataInfo metadataInfo) {
DefaultServiceInstance instance = new DefaultServiceInstance(serviceName, applicationModel);
instance.setServiceMetadata(metadataInfo);
setMetadataStorageType(instance, metadataType);
ServiceInstanceMetadataUtils.customizeInstance(instance, applicationModel);
return instance;
}
protected boolean calOrUpdateInstanceRevision(ServiceInstance instance) {
String existingInstanceRevision = getExportedServicesRevision(instance);
MetadataInfo metadataInfo = instance.getServiceMetadata();
String newRevision = metadataInfo.calAndGetRevision();
if (!newRevision.equals(existingInstanceRevision)) {
instance.getMetadata().put(EXPORTED_SERVICES_REVISION_PROPERTY_NAME, metadataInfo.getRevision());
return true;
}
return false;
}
protected void reportMetadata(MetadataInfo metadataInfo) {
if (metadataInfo == null) {
return;
}
if (metadataReport != null) {
SubscriberMetadataIdentifier identifier =
new SubscriberMetadataIdentifier(serviceName, metadataInfo.getRevision());
if ((DEFAULT_METADATA_STORAGE_TYPE.equals(metadataType) && metadataReport.shouldReportMetadata())
|| REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) {
MetricsEventBus.post(MetadataEvent.toPushEvent(applicationModel), () -> {
metadataReport.publishAppMetadata(identifier, metadataInfo);
return null;
});
}
}
MetadataInfo clonedMetadataInfo = metadataInfo.clone();
metadataInfos.put(metadataInfo.getRevision(), new MetadataInfoStat(clonedMetadataInfo));
}
protected void unReportMetadata(MetadataInfo metadataInfo) {
if (metadataReport != null) {
SubscriberMetadataIdentifier identifier =
new SubscriberMetadataIdentifier(serviceName, metadataInfo.getRevision());
if ((DEFAULT_METADATA_STORAGE_TYPE.equals(metadataType) && metadataReport.shouldReportMetadata())
|| REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) {
metadataReport.unPublishAppMetadata(identifier, metadataInfo);
}
}
}
private String getCacheNameSuffix() {
String name = this.getClass().getSimpleName();
int i = name.indexOf(ServiceDiscovery.class.getSimpleName());
if (i != -1) {
name = name.substring(0, i);
}
StringBuilder stringBuilder = new StringBuilder(128);
Optional<ApplicationConfig> application =
applicationModel.getApplicationConfigManager().getApplication();
if (application.isPresent()) {
stringBuilder.append(application.get().getName());
stringBuilder.append(".");
}
stringBuilder.append(name.toLowerCase());
URL url = this.getUrl();
if (url != null) {
stringBuilder.append(".");
stringBuilder.append(url.getBackupAddress());
}
return stringBuilder.toString();
}
private static class MetadataInfoStat {
private final MetadataInfo metadataInfo;
private final long updateTime = System.currentTimeMillis();
public MetadataInfoStat(MetadataInfo metadataInfo) {
this.metadataInfo = metadataInfo;
}
public MetadataInfo getMetadataInfo() {
return metadataInfo;
}
public long getUpdateTime() {
return updateTime;
}
}
}
| 5,500 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/DefaultServiceDiscoveryFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client;
import org.apache.dubbo.common.URL;
/**
* This class is designed for compatibility purpose. When a specific registry type does not have counterpart service discovery provided,
* the nop instance will be returned.
*/
public class DefaultServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory {
@Override
protected ServiceDiscovery createDiscovery(URL registryURL) {
return new NopServiceDiscovery(registryURL.getApplicationModel(), registryURL);
}
}
| 5,501 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscovery.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.RegistryService;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import java.util.List;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.REGISTRY_DELAY_NOTIFICATION_KEY;
/**
* Defines the common operations of Service Discovery, extended and loaded by ServiceDiscoveryFactory
*/
public interface ServiceDiscovery extends RegistryService, Prioritized {
void register() throws RuntimeException;
void update() throws RuntimeException;
void unregister() throws RuntimeException;
/**
* Gets all service names
*
* @return non-null read-only {@link Set}
*/
Set<String> getServices();
List<ServiceInstance> getInstances(String serviceName) throws NullPointerException;
default void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener)
throws NullPointerException, IllegalArgumentException {}
/**
* unsubscribe to instance change event.
*
* @param listener
* @throws IllegalArgumentException
*/
default void removeServiceInstancesChangedListener(ServiceInstancesChangedListener listener)
throws IllegalArgumentException {}
default ServiceInstancesChangedListener createListener(Set<String> serviceNames) {
return new ServiceInstancesChangedListener(serviceNames, this);
}
ServiceInstance getLocalInstance();
MetadataInfo getLocalMetadata();
default MetadataInfo getLocalMetadata(String revision) {
return getLocalMetadata();
}
MetadataInfo getRemoteMetadata(String revision);
MetadataInfo getRemoteMetadata(String revision, List<ServiceInstance> instances);
/**
* Destroy the {@link ServiceDiscovery}
*
* @throws Exception If met with error
*/
void destroy() throws Exception;
boolean isDestroy();
default URL getUrl() {
return null;
}
default long getDelay() {
return getUrl().getParameter(REGISTRY_DELAY_NOTIFICATION_KEY, 5000);
}
/**
* Get services is the default way for service discovery to be available
*/
default boolean isAvailable() {
return !isDestroy() && CollectionUtils.isNotEmpty(getServices());
}
/**
* A human-readable description of the implementation
*
* @return The description.
*/
@Override
String toString();
}
| 5,502 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/NopServiceDiscovery.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.List;
import java.util.Set;
public class NopServiceDiscovery extends AbstractServiceDiscovery {
public NopServiceDiscovery(String serviceName, URL registryURL) {
super(serviceName, registryURL);
}
public NopServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
super(applicationModel, registryURL);
}
@Override
public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {}
@Override
public void doUnregister(ServiceInstance serviceInstance) {}
@Override
public void doDestroy() throws Exception {}
@Override
public Set<String> getServices() {
return null;
}
@Override
public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException {
return null;
}
@Override
public boolean isAvailable() {
// NopServiceDiscovery is designed for compatibility, check availability is meaningless, just return true
return true;
}
}
| 5,503 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/InstanceAddressURL.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.url.component.URLAddress;
import org.apache.dubbo.common.url.component.URLParam;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.utils.StringUtils.isEmpty;
import static org.apache.dubbo.common.utils.StringUtils.isEquals;
public class InstanceAddressURL extends URL {
private final ServiceInstance instance;
private final MetadataInfo metadataInfo;
// cached numbers
private transient volatile Set<String> providerFirstParams;
// one instance address url serves only one protocol.
private final transient String protocol;
protected InstanceAddressURL() {
this(null, null, null);
}
public InstanceAddressURL(ServiceInstance instance, MetadataInfo metadataInfo) {
this.instance = instance;
this.metadataInfo = metadataInfo;
this.protocol = DUBBO;
}
public InstanceAddressURL(ServiceInstance instance, MetadataInfo metadataInfo, String protocol) {
this.instance = instance;
this.metadataInfo = metadataInfo;
this.protocol = protocol;
}
public ServiceInstance getInstance() {
return instance;
}
public MetadataInfo getMetadataInfo() {
return metadataInfo;
}
@Override
public String getServiceInterface() {
return RpcContext.getServiceContext().getInterfaceName();
}
@Override
public String getGroup() {
return RpcContext.getServiceContext().getGroup();
}
@Override
public String getVersion() {
return RpcContext.getServiceContext().getVersion();
}
@Override
public String getProtocol() {
return protocol;
}
@Override
public String getProtocolServiceKey() {
// if protocol is not specified on consumer side, return serviceKey.
URL consumerURL = RpcContext.getServiceContext().getConsumerUrl();
String consumerProtocol = consumerURL == null ? null : consumerURL.getProtocol();
if (isEquals(consumerProtocol, CONSUMER)) {
return RpcContext.getServiceContext().getServiceKey();
}
// if protocol is specified on consumer side, return accurate protocolServiceKey
else {
return RpcContext.getServiceContext().getProtocolServiceKey();
}
}
@Override
public String getServiceKey() {
return RpcContext.getServiceContext().getServiceKey();
}
@Override
public URL setProtocol(String protocol) {
return new ServiceConfigURL(
protocol, getUsername(), getPassword(), getHost(), getPort(), getPath(), getParameters(), attributes);
}
@Override
public URL setHost(String host) {
return new ServiceConfigURL(
getProtocol(), getUsername(), getPassword(), host, getPort(), getPath(), getParameters(), attributes);
}
@Override
public URL setPort(int port) {
return new ServiceConfigURL(
getProtocol(), getUsername(), getPassword(), getHost(), port, getPath(), getParameters(), attributes);
}
@Override
public URL setPath(String path) {
return new ServiceConfigURL(
getProtocol(), getUsername(), getPassword(), getHost(), getPort(), path, getParameters(), attributes);
}
@Override
public String getAddress() {
return instance.getAddress();
}
@Override
public String getHost() {
return instance.getHost();
}
@Override
public int getPort() {
return instance.getPort();
}
@Override
public String getIp() {
return instance.getHost();
}
@Override
public String getRemoteApplication() {
return instance.getServiceName();
}
@Override
public String getSide() {
return CONSUMER_SIDE;
}
@Override
public String getPath() {
MetadataInfo.ServiceInfo serviceInfo = null;
String protocolServiceKey = getProtocolServiceKey();
if (StringUtils.isNotEmpty(protocolServiceKey)) {
serviceInfo = getServiceInfo(protocolServiceKey);
}
if (serviceInfo == null) {
return getServiceInterface();
}
return serviceInfo.getPath();
}
@Override
public String getOriginalParameter(String key) {
if (VERSION_KEY.equals(key)) {
return getVersion();
} else if (GROUP_KEY.equals(key)) {
return getGroup();
} else if (INTERFACE_KEY.equals(key)) {
return getServiceInterface();
} else if (REMOTE_APPLICATION_KEY.equals(key)) {
return instance.getServiceName();
} else if (SIDE_KEY.equals(key)) {
return getSide();
}
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return getInstanceParameter(key);
}
return getServiceParameter(protocolServiceKey, key);
}
@Override
public String getParameter(String key) {
if (VERSION_KEY.equals(key)) {
return getVersion();
} else if (GROUP_KEY.equals(key)) {
return getGroup();
} else if (INTERFACE_KEY.equals(key)) {
return getServiceInterface();
} else if (REMOTE_APPLICATION_KEY.equals(key)) {
return instance.getServiceName();
} else if (SIDE_KEY.equals(key)) {
return getSide();
}
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getParameter(key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
}
}
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return getInstanceParameter(key);
}
return getServiceParameter(protocolServiceKey, key);
}
@Override
public String getOriginalServiceParameter(String service, String key) {
if (metadataInfo != null) {
String value = metadataInfo.getParameter(key, service);
if (StringUtils.isNotEmpty(value)) {
return value;
}
}
return getInstanceParameter(key);
}
@Override
public String getServiceParameter(String service, String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getServiceParameter(service, key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
}
}
if (metadataInfo != null) {
String value = metadataInfo.getParameter(key, service);
if (StringUtils.isNotEmpty(value)) {
return value;
}
}
return getInstanceParameter(key);
}
/**
* method parameter only exists in ServiceInfo
*
* @param method
* @param key
* @return
*/
@Override
public String getServiceMethodParameter(String protocolServiceKey, String method, String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getServiceMethodParameter(protocolServiceKey, method, key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
}
}
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null == serviceInfo) {
return getParameter(key);
}
String value = serviceInfo.getMethodParameter(method, key, null);
if (StringUtils.isNotEmpty(value)) {
return value;
}
return getParameter(key);
}
@Override
public String getMethodParameter(String method, String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getMethodParameter(method, key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
}
}
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return null;
}
return getServiceMethodParameter(protocolServiceKey, method, key);
}
/**
* method parameter only exists in ServiceInfo
*
* @param method
* @param key
* @return
*/
@Override
public boolean hasServiceMethodParameter(String protocolServiceKey, String method, String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
if (consumerUrl.hasServiceMethodParameter(protocolServiceKey, method, key)) {
return true;
}
}
}
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (isEmpty(method)) {
String suffix = "." + key;
for (String fullKey : getParameters().keySet()) {
if (fullKey.endsWith(suffix)) {
return true;
}
}
return false;
}
if (isEmpty(key)) {
String prefix = method + ".";
for (String fullKey : getParameters().keySet()) {
if (fullKey.startsWith(prefix)) {
return true;
}
}
return false;
}
if (null == serviceInfo) {
return false;
}
return serviceInfo.hasMethodParameter(method, key);
}
@Override
public boolean hasMethodParameter(String method, String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
if (consumerUrl.hasMethodParameter(method, key)) {
return true;
}
}
}
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return false;
}
return hasServiceMethodParameter(protocolServiceKey, method, key);
}
/**
* method parameter only exists in ServiceInfo
*
* @param method
* @return
*/
@Override
public boolean hasServiceMethodParameter(String protocolServiceKey, String method) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
if (consumerUrl.hasServiceMethodParameter(protocolServiceKey, method)) {
return true;
}
}
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null == serviceInfo) {
return false;
}
return serviceInfo.hasMethodParameter(method);
}
@Override
public boolean hasMethodParameter(String method) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
if (consumerUrl.hasMethodParameter(method)) {
return true;
}
}
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return false;
}
return hasServiceMethodParameter(protocolServiceKey, method);
}
@Override
public Map<String, String> getOriginalServiceParameters(String protocolServiceKey) {
Map<String, String> instanceParams = getInstance().getAllParams();
Map<String, String> metadataParams =
(metadataInfo == null ? new HashMap<>() : metadataInfo.getParameters(protocolServiceKey));
int i = instanceParams == null ? 0 : instanceParams.size();
int j = metadataParams == null ? 0 : metadataParams.size();
Map<String, String> params = new HashMap<>((int) ((i + j) / 0.75) + 1);
if (instanceParams != null) {
params.putAll(instanceParams);
}
if (metadataParams != null) {
params.putAll(metadataParams);
}
return params;
}
/**
* Avoid calling this method in RPC call.
*
* @return
*/
@Override
public Map<String, String> getServiceParameters(String protocolServiceKey) {
Map<String, String> instanceParams = getInstance().getAllParams();
Map<String, String> metadataParams =
(metadataInfo == null ? new HashMap<>() : metadataInfo.getParameters(protocolServiceKey));
int i = instanceParams == null ? 0 : instanceParams.size();
int j = metadataParams == null ? 0 : metadataParams.size();
Map<String, String> params = new HashMap<>((int) ((i + j) / 0.75) + 1);
if (instanceParams != null) {
params.putAll(instanceParams);
}
if (metadataParams != null) {
params.putAll(metadataParams);
}
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
Map<String, String> consumerParams = new HashMap<>(consumerUrl.getParameters());
if (CollectionUtils.isNotEmpty(providerFirstParams)) {
providerFirstParams.forEach(consumerParams::remove);
}
params.putAll(consumerParams);
}
return params;
}
@Override
public Map<String, String> getOriginalParameters() {
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return getInstance().getAllParams();
}
return getOriginalServiceParameters(protocolServiceKey);
}
@Override
public Map<String, String> getParameters() {
String protocolServiceKey = getProtocolServiceKey();
if (isEmpty(protocolServiceKey)) {
return getInstance().getAllParams();
}
return getServiceParameters(protocolServiceKey);
}
@Override
public URL addParameter(String key, String value) {
if (isEmpty(key) || isEmpty(value)) {
return this;
}
getInstance().putExtendParam(key, value);
return this;
}
@Override
public URL addParameterIfAbsent(String key, String value) {
if (isEmpty(key) || isEmpty(value)) {
return this;
}
getInstance().putExtendParamIfAbsent(key, value);
return this;
}
public URL addServiceParameter(String protocolServiceKey, String key, String value) {
if (isEmpty(key) || isEmpty(value)) {
return this;
}
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null != serviceInfo) {
serviceInfo.addParameter(key, value);
}
return this;
}
public URL addServiceParameterIfAbsent(String protocolServiceKey, String key, String value) {
if (isEmpty(key) || isEmpty(value)) {
return this;
}
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null != serviceInfo) {
serviceInfo.addParameterIfAbsent(key, value);
}
return this;
}
public URL addConsumerParams(String protocolServiceKey, Map<String, String> params) {
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null != serviceInfo) {
serviceInfo.addConsumerParams(params);
}
return this;
}
/**
* Gets method level value of the specified key.
*
* @param key
* @return
*/
@Override
public String getAnyMethodParameter(String key) {
if (consumerParamFirst(key)) {
URL consumerUrl = RpcContext.getServiceContext().getConsumerUrl();
if (consumerUrl != null) {
String v = consumerUrl.getAnyMethodParameter(key);
if (StringUtils.isNotEmpty(v)) {
return v;
}
}
}
String suffix = "." + key;
String protocolServiceKey = getProtocolServiceKey();
if (StringUtils.isNotEmpty(protocolServiceKey)) {
MetadataInfo.ServiceInfo serviceInfo = getServiceInfo(protocolServiceKey);
if (null == serviceInfo) {
return null;
}
for (String fullKey : serviceInfo.getAllParams().keySet()) {
if (fullKey.endsWith(suffix)) {
return getParameter(fullKey);
}
}
}
return null;
}
@Override
public URLParam getUrlParam() {
throw new UnsupportedOperationException("URLParam is replaced with MetadataInfo in instance url");
}
@Override
public URLAddress getUrlAddress() {
throw new UnsupportedOperationException("URLAddress is replaced with ServiceInstance in instance url");
}
private MetadataInfo.ServiceInfo getServiceInfo(String protocolServiceKey) {
return metadataInfo.getValidServiceInfo(protocolServiceKey);
}
private String getInstanceParameter(String key) {
String value = this.instance.getMetadata().get(key);
if (StringUtils.isNotEmpty(value)) {
return value;
}
return this.instance.getExtendParam(key);
}
private Map<String, String> getInstanceMetadata() {
return this.instance.getMetadata();
}
@Override
public FrameworkModel getOrDefaultFrameworkModel() {
return instance.getOrDefaultApplicationModel().getFrameworkModel();
}
@Override
public ApplicationModel getOrDefaultApplicationModel() {
return instance.getOrDefaultApplicationModel();
}
@Override
public ApplicationModel getApplicationModel() {
return instance.getApplicationModel();
}
@Override
public ScopeModel getScopeModel() {
return Optional.ofNullable(RpcContext.getServiceContext().getConsumerUrl())
.map(URL::getScopeModel)
.orElse(super.getScopeModel());
}
@Override
public ServiceModel getServiceModel() {
return RpcContext.getServiceContext().getConsumerUrl().getServiceModel();
}
public Set<String> getProviderFirstParams() {
return providerFirstParams;
}
public void setProviderFirstParams(Set<String> providerFirstParams) {
this.providerFirstParams = providerFirstParams;
}
private boolean consumerParamFirst(String key) {
if (CollectionUtils.isNotEmpty(providerFirstParams)) {
return !providerFirstParams.contains(key);
} else {
return true;
}
}
@Override
public boolean equals(Object obj) {
// instance metadata equals
if (obj == null) {
return false;
}
if (!(obj instanceof InstanceAddressURL)) {
return false;
}
InstanceAddressURL that = (InstanceAddressURL) obj;
return this.getInstance().equals(that.getInstance());
}
@Override
public int hashCode() {
return getInstance().hashCode();
}
@Override
public String toString() {
if (instance == null) {
return "{}";
}
if (metadataInfo == null) {
return instance.toString();
}
String protocolServiceKey = getProtocolServiceKey();
if (StringUtils.isNotEmpty(protocolServiceKey)) {
return instance.toString() + ", " + metadataInfo.getServiceString(protocolServiceKey);
}
return instance.toString();
}
}
| 5,504 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/OverrideInstanceAddressURL.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.url.component.URLAddress;
import org.apache.dubbo.common.url.component.URLParam;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ScopeModel;
import org.apache.dubbo.rpc.model.ServiceModel;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
public class OverrideInstanceAddressURL extends InstanceAddressURL {
private static final long serialVersionUID = 1373220432794558426L;
private final URLParam overrideParams;
private final InstanceAddressURL originUrl;
public OverrideInstanceAddressURL(InstanceAddressURL originUrl) {
this.originUrl = originUrl;
this.overrideParams = URLParam.parse("");
}
public OverrideInstanceAddressURL(InstanceAddressURL originUrl, URLParam overrideParams) {
this.originUrl = originUrl;
this.overrideParams = overrideParams;
}
@Override
public ServiceInstance getInstance() {
return originUrl.getInstance();
}
@Override
public MetadataInfo getMetadataInfo() {
return originUrl.getMetadataInfo();
}
@Override
public String getServiceInterface() {
return originUrl.getServiceInterface();
}
@Override
public String getGroup() {
return originUrl.getGroup();
}
@Override
public String getVersion() {
return originUrl.getVersion();
}
@Override
public String getProtocol() {
return originUrl.getProtocol();
}
@Override
public String getProtocolServiceKey() {
return originUrl.getProtocolServiceKey();
}
@Override
public String getServiceKey() {
return originUrl.getServiceKey();
}
@Override
public String getAddress() {
return originUrl.getAddress();
}
@Override
public String getHost() {
return originUrl.getHost();
}
@Override
public int getPort() {
return originUrl.getPort();
}
@Override
public String getIp() {
return originUrl.getIp();
}
@Override
public String getPath() {
return originUrl.getPath();
}
@Override
public String getParameter(String key) {
String overrideParam = overrideParams.getParameter(key);
return StringUtils.isNotEmpty(overrideParam) ? overrideParam : originUrl.getParameter(key);
}
@Override
public String getServiceParameter(String service, String key) {
String overrideParam = overrideParams.getParameter(key);
return StringUtils.isNotEmpty(overrideParam) ? overrideParam : originUrl.getServiceParameter(service, key);
}
@Override
public String getServiceMethodParameter(String protocolServiceKey, String method, String key) {
String overrideParam = overrideParams.getMethodParameter(method, key);
return StringUtils.isNotEmpty(overrideParam)
? overrideParam
: originUrl.getServiceMethodParameter(protocolServiceKey, method, key);
}
@Override
public String getMethodParameter(String method, String key) {
String overrideParam = overrideParams.getMethodParameter(method, key);
return StringUtils.isNotEmpty(overrideParam) ? overrideParam : originUrl.getMethodParameter(method, key);
}
@Override
public boolean hasServiceMethodParameter(String protocolServiceKey, String method, String key) {
return StringUtils.isNotEmpty(overrideParams.getMethodParameter(method, key))
|| originUrl.hasServiceMethodParameter(protocolServiceKey, method, key);
}
@Override
public boolean hasMethodParameter(String method, String key) {
return StringUtils.isNotEmpty(overrideParams.getMethodParameter(method, key))
|| originUrl.hasMethodParameter(method, key);
}
@Override
public boolean hasServiceMethodParameter(String protocolServiceKey, String method) {
return overrideParams.hasMethodParameter(method)
|| originUrl.hasServiceMethodParameter(protocolServiceKey, method);
}
@Override
public boolean hasMethodParameter(String method) {
return overrideParams.hasMethodParameter(method) || originUrl.hasMethodParameter(method);
}
@Override
public Map<String, String> getServiceParameters(String protocolServiceKey) {
Map<String, String> parameters = originUrl.getServiceParameters(protocolServiceKey);
Map<String, String> overrideParameters = overrideParams.getParameters();
Map<String, String> result = new HashMap<>((int) (parameters.size() + overrideParameters.size() / 0.75f) + 1);
result.putAll(parameters);
result.putAll(overrideParameters);
return result;
}
@Override
public Map<String, String> getParameters() {
Map<String, String> parameters = originUrl.getParameters();
Map<String, String> overrideParameters = overrideParams.getParameters();
Map<String, String> result = new HashMap<>((int) (parameters.size() + overrideParameters.size() / 0.75f) + 1);
result.putAll(parameters);
result.putAll(overrideParameters);
return result;
}
@Override
public URL addParameter(String key, String value) {
return new OverrideInstanceAddressURL(originUrl, overrideParams.addParameter(key, value));
}
@Override
public URL addParameterIfAbsent(String key, String value) {
return new OverrideInstanceAddressURL(originUrl, overrideParams.addParameterIfAbsent(key, value));
}
@Override
public URL addServiceParameter(String protocolServiceKey, String key, String value) {
return originUrl.addServiceParameter(protocolServiceKey, key, value);
}
@Override
public URL addServiceParameterIfAbsent(String protocolServiceKey, String key, String value) {
return originUrl.addServiceParameterIfAbsent(protocolServiceKey, key, value);
}
@Override
public URL addConsumerParams(String protocolServiceKey, Map<String, String> params) {
return originUrl.addConsumerParams(protocolServiceKey, params);
}
@Override
public String getAnyMethodParameter(String key) {
String overrideParam = overrideParams.getAnyMethodParameter(key);
return StringUtils.isNotEmpty(overrideParam) ? overrideParam : originUrl.getAnyMethodParameter(key);
}
@Override
public URL addParameters(Map<String, String> parameters) {
return new OverrideInstanceAddressURL(originUrl, overrideParams.addParameters(parameters));
}
@Override
public URL addParametersIfAbsent(Map<String, String> parameters) {
return new OverrideInstanceAddressURL(originUrl, overrideParams.addParametersIfAbsent(parameters));
}
@Override
public URLParam getUrlParam() {
return originUrl.getUrlParam();
}
@Override
public URLAddress getUrlAddress() {
return originUrl.getUrlAddress();
}
public URLParam getOverrideParams() {
return overrideParams;
}
@Override
public String getRemoteApplication() {
return originUrl.getRemoteApplication();
}
@Override
public String getSide() {
return originUrl.getSide();
}
@Override
public ScopeModel getScopeModel() {
return originUrl.getScopeModel();
}
@Override
public FrameworkModel getOrDefaultFrameworkModel() {
return originUrl.getOrDefaultFrameworkModel();
}
@Override
public ApplicationModel getOrDefaultApplicationModel() {
return originUrl.getOrDefaultApplicationModel();
}
@Override
public ApplicationModel getApplicationModel() {
return originUrl.getApplicationModel();
}
@Override
public ModuleModel getOrDefaultModuleModel() {
return originUrl.getOrDefaultModuleModel();
}
@Override
public ServiceModel getServiceModel() {
return originUrl.getServiceModel();
}
@Override
public Set<String> getProviderFirstParams() {
return originUrl.getProviderFirstParams();
}
@Override
public void setProviderFirstParams(Set<String> providerFirstParams) {
originUrl.setProviderFirstParams(providerFirstParams);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
OverrideInstanceAddressURL that = (OverrideInstanceAddressURL) o;
return Objects.equals(overrideParams, that.overrideParams) && Objects.equals(originUrl, that.originUrl);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), overrideParams, originUrl);
}
@Override
public String toString() {
return originUrl.toString() + ", overrideParams: " + overrideParams.toString();
}
private Object readResolve() {
// create a new object from the deserialized one
return new OverrideInstanceAddressURL(this.originUrl, this.overrideParams);
}
@Override
protected OverrideInstanceAddressURL newURL(URLAddress urlAddress, URLParam urlParam) {
return new OverrideInstanceAddressURL(originUrl, overrideParams);
}
}
| 5,505 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.support.AbstractRegistryFactory;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.registry.Constants.DEFAULT_REGISTRY;
public class ServiceDiscoveryRegistryFactory extends AbstractRegistryFactory {
@Override
protected String createRegistryCacheKey(URL url) {
return url.toFullString();
}
@Override
protected Registry createRegistry(URL url) {
if (UrlUtils.hasServiceDiscoveryRegistryProtocol(url)) {
String protocol = url.getParameter(REGISTRY_KEY, DEFAULT_REGISTRY);
url = url.setProtocol(protocol).removeParameter(REGISTRY_KEY);
}
return new ServiceDiscoveryRegistry(url, applicationModel);
}
}
| 5,506 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryRegistryDirectory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.url.component.DubboServiceAddressURL;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.Assert;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.AddressListener;
import org.apache.dubbo.registry.Constants;
import org.apache.dubbo.registry.ProviderFirstParams;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.integration.AbstractConfiguratorListener;
import org.apache.dubbo.registry.integration.DynamicDirectory;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.RpcServiceContext;
import org.apache.dubbo.rpc.cluster.Configurator;
import org.apache.dubbo.rpc.cluster.RouterChain;
import org.apache.dubbo.rpc.cluster.directory.StaticDirectory;
import org.apache.dubbo.rpc.cluster.router.state.BitList;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.stream.Collectors;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DISABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.ENABLED_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INSTANCE_REGISTER_MODE;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_DESTROY_INVOKER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_REFER_INVOKER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_UNSUPPORTED;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_HASHMAP_LOAD_FACTOR;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTER_MODE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_TYPE_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.SERVICE_REGISTRY_TYPE;
import static org.apache.dubbo.registry.Constants.CONFIGURATORS_SUFFIX;
import static org.apache.dubbo.rpc.model.ScopeModelUtil.getModuleModel;
public class ServiceDiscoveryRegistryDirectory<T> extends DynamicDirectory<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ServiceDiscoveryRegistryDirectory.class);
/**
* instance address to invoker mapping.
* The initial value is null and the midway may be assigned to null, please use the local variable reference
*/
private volatile Map<ProtocolServiceKeyWithAddress, Invoker<T>> urlInvokerMap;
private volatile ReferenceConfigurationListener referenceConfigurationListener;
private volatile boolean enableConfigurationListen = true;
private volatile List<URL> originalUrls = null;
private volatile Map<String, String> overrideQueryMap;
private final Set<String> providerFirstParams;
private final ModuleModel moduleModel;
private final ProtocolServiceKey consumerProtocolServiceKey;
private final ConcurrentMap<ProtocolServiceKey, URL> customizedConsumerUrlMap = new ConcurrentHashMap<>();
public ServiceDiscoveryRegistryDirectory(Class<T> serviceType, URL url) {
super(serviceType, url);
moduleModel = getModuleModel(url.getScopeModel());
Set<ProviderFirstParams> providerFirstParams = url.getOrDefaultApplicationModel()
.getExtensionLoader(ProviderFirstParams.class)
.getSupportedExtensionInstances();
if (CollectionUtils.isEmpty(providerFirstParams)) {
this.providerFirstParams = null;
} else {
if (providerFirstParams.size() == 1) {
this.providerFirstParams = Collections.unmodifiableSet(
providerFirstParams.iterator().next().params());
} else {
Set<String> params = new HashSet<>();
for (ProviderFirstParams paramsFilter : providerFirstParams) {
if (paramsFilter.params() == null) {
break;
}
params.addAll(paramsFilter.params());
}
this.providerFirstParams = Collections.unmodifiableSet(params);
}
}
String protocol = consumerUrl.getParameter(PROTOCOL_KEY, consumerUrl.getProtocol());
consumerProtocolServiceKey = new ProtocolServiceKey(
consumerUrl.getServiceInterface(),
consumerUrl.getVersion(),
consumerUrl.getGroup(),
!CommonConstants.CONSUMER.equals(protocol) ? protocol : null);
}
@Override
public void subscribe(URL url) {
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
enableConfigurationListen = true;
getConsumerConfigurationListener(moduleModel).addNotifyListener(this);
referenceConfigurationListener = new ReferenceConfigurationListener(this.moduleModel, this, url);
} else {
enableConfigurationListen = false;
}
super.subscribe(url);
}
private ConsumerConfigurationListener getConsumerConfigurationListener(ModuleModel moduleModel) {
return moduleModel
.getBeanFactory()
.getOrRegisterBean(
ConsumerConfigurationListener.class, type -> new ConsumerConfigurationListener(moduleModel));
}
@Override
public void unSubscribe(URL url) {
super.unSubscribe(url);
this.originalUrls = null;
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
getConsumerConfigurationListener(moduleModel).removeNotifyListener(this);
referenceConfigurationListener.stop();
}
}
@Override
public void destroy() {
super.destroy();
if (moduleModel
.modelEnvironment()
.getConfiguration()
.convert(Boolean.class, Constants.ENABLE_CONFIGURATION_LISTEN, true)) {
getConsumerConfigurationListener(moduleModel).removeNotifyListener(this);
referenceConfigurationListener.stop();
}
}
@Override
public void buildRouterChain(URL url) {
this.setRouterChain(
RouterChain.buildChain(getInterface(), url.addParameter(REGISTRY_TYPE_KEY, SERVICE_REGISTRY_TYPE)));
}
@Override
public synchronized void notify(List<URL> instanceUrls) {
if (isDestroyed()) {
return;
}
// Set the context of the address notification thread.
RpcServiceContext.getServiceContext().setConsumerUrl(getConsumerUrl());
// 3.x added for extend URL address
ExtensionLoader<AddressListener> addressListenerExtensionLoader =
getUrl().getOrDefaultModuleModel().getExtensionLoader(AddressListener.class);
List<AddressListener> supportedListeners =
addressListenerExtensionLoader.getActivateExtension(getUrl(), (String[]) null);
if (supportedListeners != null && !supportedListeners.isEmpty()) {
for (AddressListener addressListener : supportedListeners) {
instanceUrls = addressListener.notify(instanceUrls, getConsumerUrl(), this);
}
}
refreshOverrideAndInvoker(instanceUrls);
}
// RefreshOverrideAndInvoker will be executed by registryCenter and configCenter, so it should be synchronized.
@Override
protected synchronized void refreshOverrideAndInvoker(List<URL> instanceUrls) {
// mock zookeeper://xxx?mock=return null
this.directoryUrl = overrideDirectoryWithConfigurator(getOriginalConsumerUrl());
refreshInvoker(instanceUrls);
}
protected URL overrideDirectoryWithConfigurator(URL url) {
// override url with configurator from "app-name.configurators"
url = overrideWithConfigurators(
getConsumerConfigurationListener(moduleModel).getConfigurators(), url);
// override url with configurator from configurators from "service-name.configurators"
if (referenceConfigurationListener != null) {
url = overrideWithConfigurators(referenceConfigurationListener.getConfigurators(), url);
}
return url;
}
private URL overrideWithConfigurators(List<Configurator> configurators, URL url) {
if (CollectionUtils.isNotEmpty(configurators)) {
if (url instanceof DubboServiceAddressURL) {
DubboServiceAddressURL interfaceAddressURL = (DubboServiceAddressURL) url;
URL overriddenURL = interfaceAddressURL.getOverrideURL();
if (overriddenURL == null) {
String appName = interfaceAddressURL.getApplication();
String side = interfaceAddressURL.getSide();
overriddenURL = URLBuilder.from(interfaceAddressURL)
.clearParameters()
.addParameter(APPLICATION_KEY, appName)
.addParameter(SIDE_KEY, side)
.build();
}
for (Configurator configurator : configurators) {
overriddenURL = configurator.configure(overriddenURL);
}
url = new DubboServiceAddressURL(
interfaceAddressURL.getUrlAddress(),
interfaceAddressURL.getUrlParam(),
interfaceAddressURL.getConsumerURL(),
(ServiceConfigURL) overriddenURL);
} else {
for (Configurator configurator : configurators) {
url = configurator.configure(url);
}
}
}
return url;
}
protected InstanceAddressURL overrideWithConfigurator(InstanceAddressURL providerUrl) {
// override url with configurator from "app-name.configurators"
providerUrl = overrideWithConfigurators(
getConsumerConfigurationListener(moduleModel).getConfigurators(), providerUrl);
// override url with configurator from configurators from "service-name.configurators"
if (referenceConfigurationListener != null) {
providerUrl = overrideWithConfigurators(referenceConfigurationListener.getConfigurators(), providerUrl);
}
return providerUrl;
}
private InstanceAddressURL overrideWithConfigurators(List<Configurator> configurators, InstanceAddressURL url) {
if (CollectionUtils.isNotEmpty(configurators)) {
// wrap url
OverrideInstanceAddressURL overrideInstanceAddressURL = new OverrideInstanceAddressURL(url);
if (overrideQueryMap != null) {
// override app-level configs
overrideInstanceAddressURL =
(OverrideInstanceAddressURL) overrideInstanceAddressURL.addParameters(overrideQueryMap);
}
for (Configurator configurator : configurators) {
overrideInstanceAddressURL =
(OverrideInstanceAddressURL) configurator.configure(overrideInstanceAddressURL);
}
return overrideInstanceAddressURL;
}
return url;
}
@Override
public boolean isServiceDiscovery() {
return true;
}
/**
* This implementation makes sure all application names related to serviceListener received address notification.
* <p>
* FIXME, make sure deprecated "interface-application" mapping item be cleared in time.
*/
@Override
public boolean isNotificationReceived() {
return serviceListener == null
|| serviceListener.isDestroyed()
|| serviceListener.getAllInstances().size()
== serviceListener.getServiceNames().size();
}
private void refreshInvoker(List<URL> invokerUrls) {
Assert.notNull(invokerUrls, "invokerUrls should not be null, use EMPTY url to clear current addresses.");
this.originalUrls = invokerUrls;
if (invokerUrls.size() == 1 && EMPTY_PROTOCOL.equals(invokerUrls.get(0).getProtocol())) {
logger.warn(
PROTOCOL_UNSUPPORTED,
"",
"",
String.format(
"Received url with EMPTY protocol from registry %s, will clear all available addresses.",
this));
refreshRouter(
BitList.emptyList(), () -> this.forbidden = true // Forbid to access
);
destroyAllInvokers(); // Close all invokers
} else {
this.forbidden = false; // Allow accessing
if (CollectionUtils.isEmpty(invokerUrls)) {
logger.warn(
PROTOCOL_UNSUPPORTED,
"",
"",
String.format(
"Received empty url list from registry %s, will ignore for protection purpose.", this));
return;
}
// use local reference to avoid NPE as this.urlInvokerMap will be set null concurrently at
// destroyAllInvokers().
Map<ProtocolServiceKeyWithAddress, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap;
// can't use local reference as oldUrlInvokerMap's mappings might be removed directly at toInvokers().
Map<ProtocolServiceKeyWithAddress, Invoker<T>> oldUrlInvokerMap = null;
if (localUrlInvokerMap != null) {
// the initial capacity should be set greater than the maximum number of entries divided by the load
// factor to avoid resizing.
oldUrlInvokerMap =
new LinkedHashMap<>(Math.round(1 + localUrlInvokerMap.size() / DEFAULT_HASHMAP_LOAD_FACTOR));
localUrlInvokerMap.forEach(oldUrlInvokerMap::put);
}
Map<ProtocolServiceKeyWithAddress, Invoker<T>> newUrlInvokerMap =
toInvokers(oldUrlInvokerMap, invokerUrls); // Translate url list to Invoker map
logger.info(String.format("Refreshed invoker size %s from registry %s", newUrlInvokerMap.size(), this));
if (CollectionUtils.isEmptyMap(newUrlInvokerMap)) {
logger.error(
PROTOCOL_UNSUPPORTED,
"",
"",
"Unsupported protocol.",
new IllegalStateException(String.format(
"Cannot create invokers from url address list (total %s)", invokerUrls.size())));
return;
}
List<Invoker<T>> newInvokers = Collections.unmodifiableList(new ArrayList<>(newUrlInvokerMap.values()));
BitList<Invoker<T>> finalInvokers =
multiGroup ? new BitList<>(toMergeInvokerList(newInvokers)) : new BitList<>(newInvokers);
// pre-route and build cache
refreshRouter(finalInvokers.clone(), () -> this.setInvokers(finalInvokers));
this.urlInvokerMap = newUrlInvokerMap;
if (oldUrlInvokerMap != null) {
try {
destroyUnusedInvokers(oldUrlInvokerMap, newUrlInvokerMap); // Close the unused Invoker
} catch (Exception e) {
logger.warn(PROTOCOL_FAILED_DESTROY_INVOKER, "", "", "destroyUnusedInvokers error. ", e);
}
}
}
// notify invokers refreshed
this.invokersChanged();
logger.info("Received invokers changed event from registry. " + "Registry type: instance. "
+ "Service Key: "
+ getConsumerUrl().getServiceKey() + ". " + "Urls Size : "
+ invokerUrls.size() + ". " + "Invokers Size : "
+ getInvokers().size() + ". " + "Available Size: "
+ getValidInvokers().size() + ". " + "Available Invokers : "
+ joinValidInvokerAddresses());
}
/**
* Turn urls into invokers, and if url has been refer, will not re-reference.
* the items that will be put into newUrlInvokeMap will be removed from oldUrlInvokerMap.
*
* @param oldUrlInvokerMap it might be modified during the process.
* @param urls
* @return invokers
*/
private Map<ProtocolServiceKeyWithAddress, Invoker<T>> toInvokers(
Map<ProtocolServiceKeyWithAddress, Invoker<T>> oldUrlInvokerMap, List<URL> urls) {
Map<ProtocolServiceKeyWithAddress, Invoker<T>> newUrlInvokerMap =
new ConcurrentHashMap<>(urls == null ? 1 : (int) (urls.size() / 0.75f + 1));
if (urls == null || urls.isEmpty()) {
return newUrlInvokerMap;
}
for (URL url : urls) {
InstanceAddressURL instanceAddressURL = (InstanceAddressURL) url;
if (EMPTY_PROTOCOL.equals(instanceAddressURL.getProtocol())) {
continue;
}
if (!getUrl().getOrDefaultFrameworkModel()
.getExtensionLoader(Protocol.class)
.hasExtension(instanceAddressURL.getProtocol())) {
// 4-1 - Unsupported protocol
logger.error(
PROTOCOL_UNSUPPORTED,
"protocol extension does not installed",
"",
"Unsupported protocol.",
new IllegalStateException("Unsupported protocol " + instanceAddressURL.getProtocol()
+ " in notified url: "
+ instanceAddressURL + " from registry " + getUrl().getAddress() + " to consumer "
+ NetUtils.getLocalHost() + ", supported protocol: "
+ getUrl().getOrDefaultFrameworkModel()
.getExtensionLoader(Protocol.class)
.getSupportedExtensions()));
continue;
}
instanceAddressURL.setProviderFirstParams(providerFirstParams);
// Override provider urls if needed
if (enableConfigurationListen) {
instanceAddressURL = overrideWithConfigurator(instanceAddressURL);
}
// filter all the service available (version wildcard, group wildcard, protocol wildcard)
int port = instanceAddressURL.getPort();
List<ProtocolServiceKey> matchedProtocolServiceKeys =
instanceAddressURL.getMetadataInfo().getMatchedServiceInfos(consumerProtocolServiceKey).stream()
.filter(serviceInfo -> serviceInfo.getPort() <= 0 || serviceInfo.getPort() == port)
.map(MetadataInfo.ServiceInfo::getProtocolServiceKey)
.collect(Collectors.toList());
// see org.apache.dubbo.common.ProtocolServiceKey.isSameWith
// check if needed to override the consumer url
boolean shouldWrap = matchedProtocolServiceKeys.size() != 1
|| !consumerProtocolServiceKey.isSameWith(matchedProtocolServiceKeys.get(0));
for (ProtocolServiceKey matchedProtocolServiceKey : matchedProtocolServiceKeys) {
ProtocolServiceKeyWithAddress protocolServiceKeyWithAddress =
new ProtocolServiceKeyWithAddress(matchedProtocolServiceKey, instanceAddressURL.getAddress());
Invoker<T> invoker =
oldUrlInvokerMap == null ? null : oldUrlInvokerMap.get(protocolServiceKeyWithAddress);
if (invoker == null
|| urlChanged(
invoker,
instanceAddressURL,
matchedProtocolServiceKey)) { // Not in the cache, refer again
try {
boolean enabled;
if (instanceAddressURL.hasParameter(DISABLED_KEY)) {
enabled = !instanceAddressURL.getParameter(DISABLED_KEY, false);
} else {
enabled = instanceAddressURL.getParameter(ENABLED_KEY, true);
}
if (enabled) {
if (shouldWrap) {
URL newConsumerUrl = ConcurrentHashMapUtils.computeIfAbsent(
customizedConsumerUrlMap, matchedProtocolServiceKey, k -> consumerUrl
.setProtocol(k.getProtocol())
.addParameter(CommonConstants.GROUP_KEY, k.getGroup())
.addParameter(CommonConstants.VERSION_KEY, k.getVersion()));
RpcContext.getServiceContext().setConsumerUrl(newConsumerUrl);
invoker = new InstanceWrappedInvoker<>(
protocol.refer(serviceType, instanceAddressURL),
newConsumerUrl,
matchedProtocolServiceKey);
} else {
invoker = protocol.refer(serviceType, instanceAddressURL);
}
}
} catch (Throwable t) {
logger.error(
PROTOCOL_FAILED_REFER_INVOKER,
"",
"",
"Failed to refer invoker for interface:" + serviceType + ",url:(" + instanceAddressURL
+ ")" + t.getMessage(),
t);
}
if (invoker != null) { // Put new invoker in cache
newUrlInvokerMap.put(protocolServiceKeyWithAddress, invoker);
}
} else {
newUrlInvokerMap.put(protocolServiceKeyWithAddress, invoker);
oldUrlInvokerMap.remove(protocolServiceKeyWithAddress, invoker);
}
}
}
return newUrlInvokerMap;
}
private boolean urlChanged(Invoker<T> invoker, InstanceAddressURL newURL, ProtocolServiceKey protocolServiceKey) {
InstanceAddressURL oldURL = (InstanceAddressURL) invoker.getUrl();
if (!newURL.getInstance().equals(oldURL.getInstance())) {
return true;
}
if (oldURL instanceof OverrideInstanceAddressURL || newURL instanceof OverrideInstanceAddressURL) {
if (!(oldURL instanceof OverrideInstanceAddressURL && newURL instanceof OverrideInstanceAddressURL)) {
// sub-class changed
return true;
} else {
if (!((OverrideInstanceAddressURL) oldURL)
.getOverrideParams()
.equals(((OverrideInstanceAddressURL) newURL).getOverrideParams())) {
return true;
}
}
}
MetadataInfo.ServiceInfo oldServiceInfo =
oldURL.getMetadataInfo().getValidServiceInfo(protocolServiceKey.toString());
if (null == oldServiceInfo) {
return false;
}
return !oldServiceInfo.equals(newURL.getMetadataInfo().getValidServiceInfo(protocolServiceKey.toString()));
}
private List<Invoker<T>> toMergeInvokerList(List<Invoker<T>> invokers) {
List<Invoker<T>> mergedInvokers = new ArrayList<>();
Map<String, List<Invoker<T>>> groupMap = new HashMap<>();
for (Invoker<T> invoker : invokers) {
String group = invoker.getUrl().getGroup("");
groupMap.computeIfAbsent(group, k -> new ArrayList<>());
groupMap.get(group).add(invoker);
}
if (groupMap.size() == 1) {
mergedInvokers.addAll(groupMap.values().iterator().next());
} else if (groupMap.size() > 1) {
for (List<Invoker<T>> groupList : groupMap.values()) {
StaticDirectory<T> staticDirectory = new StaticDirectory<>(groupList);
staticDirectory.buildRouterChain();
mergedInvokers.add(cluster.join(staticDirectory, false));
}
} else {
mergedInvokers = invokers;
}
return mergedInvokers;
}
/**
* Close all invokers
*/
@Override
protected void destroyAllInvokers() {
Map<ProtocolServiceKeyWithAddress, Invoker<T>> localUrlInvokerMap = this.urlInvokerMap; // local reference
if (localUrlInvokerMap != null) {
for (Invoker<T> invoker : new ArrayList<>(localUrlInvokerMap.values())) {
try {
invoker.destroy();
} catch (Throwable t) {
logger.warn(
PROTOCOL_FAILED_DESTROY_INVOKER,
"",
"",
"Failed to destroy service " + serviceKey + " to provider " + invoker.getUrl(),
t);
}
}
localUrlInvokerMap.clear();
}
this.urlInvokerMap = null;
this.destroyInvokers();
}
@Override
protected Map<String, String> getDirectoryMeta() {
String registryKey = Optional.ofNullable(getRegistry())
.map(Registry::getUrl)
.map(url -> url.getParameter(
RegistryConstants.REGISTRY_CLUSTER_KEY,
url.getParameter(RegistryConstants.REGISTRY_KEY, url.getProtocol())))
.orElse("unknown");
Map<String, String> metas = new HashMap<>();
metas.put(REGISTRY_KEY, registryKey);
metas.put(REGISTER_MODE_KEY, INSTANCE_REGISTER_MODE);
return metas;
}
/**
* Check whether the invoker in the cache needs to be destroyed
* If set attribute of url: refer.autodestroy=false, the invokers will only increase without decreasing,there may be a refer leak
*
* @param oldUrlInvokerMap
* @param newUrlInvokerMap
*/
private void destroyUnusedInvokers(
Map<ProtocolServiceKeyWithAddress, Invoker<T>> oldUrlInvokerMap,
Map<ProtocolServiceKeyWithAddress, Invoker<T>> newUrlInvokerMap) {
if (newUrlInvokerMap == null || newUrlInvokerMap.size() == 0) {
destroyAllInvokers();
return;
}
if (oldUrlInvokerMap == null || oldUrlInvokerMap.size() == 0) {
return;
}
for (Map.Entry<ProtocolServiceKeyWithAddress, Invoker<T>> entry : oldUrlInvokerMap.entrySet()) {
Invoker<T> invoker = entry.getValue();
if (invoker != null) {
try {
invoker.destroy();
if (logger.isDebugEnabled()) {
logger.debug("destroy invoker[" + invoker.getUrl() + "] success. ");
}
} catch (Exception e) {
logger.warn(
PROTOCOL_FAILED_DESTROY_INVOKER,
"",
"",
"destroy invoker[" + invoker.getUrl() + "]failed." + e.getMessage(),
e);
}
}
}
logger.info(oldUrlInvokerMap.size() + " deprecated invokers deleted.");
}
private class ReferenceConfigurationListener extends AbstractConfiguratorListener {
private final ServiceDiscoveryRegistryDirectory<?> directory;
private final URL url;
ReferenceConfigurationListener(
ModuleModel moduleModel, ServiceDiscoveryRegistryDirectory<?> directory, URL url) {
super(moduleModel);
this.directory = directory;
this.url = url;
this.initWith(DynamicConfiguration.getRuleKey(url) + CONFIGURATORS_SUFFIX);
}
void stop() {
this.stopListen(DynamicConfiguration.getRuleKey(url) + CONFIGURATORS_SUFFIX);
}
@Override
protected void notifyOverrides() {
// to notify configurator/router changes
if (directory.originalUrls != null) {
URL backup = RpcContext.getServiceContext().getConsumerUrl();
RpcContext.getServiceContext().setConsumerUrl(directory.getConsumerUrl());
directory.refreshOverrideAndInvoker(directory.originalUrls);
RpcContext.getServiceContext().setConsumerUrl(backup);
}
}
}
private static class ConsumerConfigurationListener extends AbstractConfiguratorListener {
private final List<ServiceDiscoveryRegistryDirectory<?>> listeners = new ArrayList<>();
ConsumerConfigurationListener(ModuleModel moduleModel) {
super(moduleModel);
}
void addNotifyListener(ServiceDiscoveryRegistryDirectory<?> listener) {
if (listeners.isEmpty()) {
this.initWith(moduleModel.getApplicationModel().getApplicationName() + CONFIGURATORS_SUFFIX);
}
this.listeners.add(listener);
}
void removeNotifyListener(ServiceDiscoveryRegistryDirectory<?> listener) {
this.listeners.remove(listener);
if (listeners.isEmpty()) {
this.stopListen(moduleModel.getApplicationModel().getApplicationName() + CONFIGURATORS_SUFFIX);
}
}
@Override
protected void notifyOverrides() {
listeners.forEach(listener -> {
if (listener.originalUrls != null) {
URL backup = RpcContext.getServiceContext().getConsumerUrl();
RpcContext.getServiceContext().setConsumerUrl(listener.getConsumerUrl());
listener.refreshOverrideAndInvoker(listener.originalUrls);
RpcContext.getServiceContext().setConsumerUrl(backup);
}
});
}
}
public static final class ProtocolServiceKeyWithAddress extends ProtocolServiceKey {
private final String address;
public ProtocolServiceKeyWithAddress(ProtocolServiceKey protocolServiceKey, String address) {
super(
protocolServiceKey.getInterfaceName(),
protocolServiceKey.getVersion(),
protocolServiceKey.getGroup(),
protocolServiceKey.getProtocol());
this.address = address;
}
public String getAddress() {
return address;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
ProtocolServiceKeyWithAddress that = (ProtocolServiceKeyWithAddress) o;
return Objects.equals(address, that.address);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), address);
}
}
public static final class InstanceWrappedInvoker<T> implements Invoker<T> {
private final Invoker<T> originInvoker;
private final URL newConsumerUrl;
private final ProtocolServiceKey protocolServiceKey;
public InstanceWrappedInvoker(
Invoker<T> originInvoker, URL newConsumerUrl, ProtocolServiceKey protocolServiceKey) {
this.originInvoker = originInvoker;
this.newConsumerUrl = newConsumerUrl;
this.protocolServiceKey = protocolServiceKey;
}
@Override
public Class<T> getInterface() {
return originInvoker.getInterface();
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
// override consumer url with real protocol service key
RpcContext.getServiceContext().setConsumerUrl(newConsumerUrl);
// recreate invocation due to the protocol service key changed
RpcInvocation copiedInvocation = new RpcInvocation(
invocation.getTargetServiceUniqueName(),
invocation.getServiceModel(),
invocation.getMethodName(),
invocation.getServiceName(),
protocolServiceKey.toString(),
invocation.getParameterTypes(),
invocation.getArguments(),
invocation.getObjectAttachments(),
invocation.getInvoker(),
invocation.getAttributes(),
invocation instanceof RpcInvocation ? ((RpcInvocation) invocation).getInvokeMode() : null);
copiedInvocation.setObjectAttachment(CommonConstants.GROUP_KEY, protocolServiceKey.getGroup());
copiedInvocation.setObjectAttachment(CommonConstants.VERSION_KEY, protocolServiceKey.getVersion());
return originInvoker.invoke(copiedInvocation);
}
@Override
public URL getUrl() {
RpcContext.getServiceContext().setConsumerUrl(newConsumerUrl);
return originInvoker.getUrl();
}
@Override
public boolean isAvailable() {
RpcContext.getServiceContext().setConsumerUrl(newConsumerUrl);
return originInvoker.isAvailable();
}
@Override
public void destroy() {
RpcContext.getServiceContext().setConsumerUrl(newConsumerUrl);
originInvoker.destroy();
}
}
@Override
public String toString() {
return "ServiceDiscoveryRegistryDirectory(" + "registry: "
+ getUrl().getAddress() + ", subscribed key: "
+ (serviceListener == null || CollectionUtils.isEmpty(serviceListener.getServiceNames())
? getConsumerUrl().getServiceKey()
: serviceListener.getServiceNames().toString())
+ ")-"
+ super.toString();
}
}
| 5,507 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceInstanceCustomizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.lang.Prioritized;
import org.apache.dubbo.rpc.model.ApplicationModel;
import static org.apache.dubbo.common.extension.ExtensionScope.APPLICATION;
/**
* The interface to customize {@link ServiceInstance the service instance}
*
* @see ServiceInstance#getMetadata()
* @since 2.7.5
*/
@SPI(scope = APPLICATION)
public interface ServiceInstanceCustomizer extends Prioritized {
/**
* Customizes {@link ServiceInstance the service instance}
*
* @param serviceInstance {@link ServiceInstance the service instance}
*/
void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel);
}
| 5,508 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/ServiceDiscoveryService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client;
public interface ServiceDiscoveryService {
void register() throws RuntimeException;
void update() throws RuntimeException;
void unregister() throws RuntimeException;
}
| 5,509 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/AbstractServiceDiscoveryFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Abstract {@link ServiceDiscoveryFactory} implementation with cache, the subclass
* should implement {@link #createDiscovery(URL)} method to create an instance of {@link ServiceDiscovery}
*
* @see ServiceDiscoveryFactory
* @since 2.7.5
*/
public abstract class AbstractServiceDiscoveryFactory implements ServiceDiscoveryFactory, ScopeModelAware {
protected ApplicationModel applicationModel;
private final ConcurrentMap<String, ServiceDiscovery> discoveries = new ConcurrentHashMap<>();
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
public List<ServiceDiscovery> getAllServiceDiscoveries() {
return Collections.unmodifiableList(new LinkedList<>(discoveries.values()));
}
@Override
public ServiceDiscovery getServiceDiscovery(URL registryURL) {
String key = createRegistryCacheKey(registryURL);
return ConcurrentHashMapUtils.computeIfAbsent(discoveries, key, k -> createDiscovery(registryURL));
}
protected String createRegistryCacheKey(URL url) {
return url.toServiceStringWithoutResolving();
}
protected abstract ServiceDiscovery createDiscovery(URL registryURL);
}
| 5,510 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/package-info.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* * The inspiration of service registration and discovery comes from
* <a href="https://spring.io/projects/spring-cloud-commons">Spring Cloud Commons</a>.
*
* @since 2.7.5
*/
package org.apache.dubbo.registry.client;
| 5,511 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/InvokersChangedListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration;
public interface InvokersChangedListener {
void onChange();
}
| 5,512 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationClusterInvoker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
/**
* FIXME, some methods need to be further optimized.
*
* @param <T>
*/
public interface MigrationClusterInvoker<T> extends ClusterInvoker<T> {
@Override
boolean isServiceDiscovery();
MigrationStep getMigrationStep();
void setMigrationStep(MigrationStep step);
MigrationRule getMigrationRule();
void setMigrationRule(MigrationRule rule);
boolean migrateToForceInterfaceInvoker(MigrationRule newRule);
boolean migrateToForceApplicationInvoker(MigrationRule newRule);
void migrateToApplicationFirstInvoker(MigrationRule newRule);
void reRefer(URL newSubscribeUrl);
}
| 5,513 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleHandler.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_NO_PARAMETERS_URL;
public class MigrationRuleHandler<T> {
public static final String DUBBO_SERVICEDISCOVERY_MIGRATION = "dubbo.application.migration.step";
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(MigrationRuleHandler.class);
private final MigrationClusterInvoker<T> migrationInvoker;
private volatile MigrationStep currentStep;
private volatile Float currentThreshold = 0f;
private final URL consumerURL;
public MigrationRuleHandler(MigrationClusterInvoker<T> invoker, URL url) {
this.migrationInvoker = invoker;
this.consumerURL = url;
}
public synchronized void doMigrate(MigrationRule rule) {
if (migrationInvoker instanceof ServiceDiscoveryMigrationInvoker) {
refreshInvoker(MigrationStep.FORCE_APPLICATION, 1.0f, rule);
return;
}
// initial step : APPLICATION_FIRST
MigrationStep step = MigrationStep.APPLICATION_FIRST;
float threshold = -1f;
try {
step = rule.getStep(consumerURL);
threshold = rule.getThreshold(consumerURL);
} catch (Exception e) {
logger.error(
REGISTRY_NO_PARAMETERS_URL, "", "", "Failed to get step and threshold info from rule: " + rule, e);
}
if (refreshInvoker(step, threshold, rule)) {
// refresh success, update rule
setMigrationRule(rule);
}
}
private boolean refreshInvoker(MigrationStep step, Float threshold, MigrationRule newRule) {
if (step == null || threshold == null) {
throw new IllegalStateException("Step or threshold of migration rule cannot be null");
}
MigrationStep originStep = currentStep;
if ((currentStep == null || currentStep != step) || !currentThreshold.equals(threshold)) {
boolean success = true;
switch (step) {
case APPLICATION_FIRST:
migrationInvoker.migrateToApplicationFirstInvoker(newRule);
break;
case FORCE_APPLICATION:
success = migrationInvoker.migrateToForceApplicationInvoker(newRule);
break;
case FORCE_INTERFACE:
default:
success = migrationInvoker.migrateToForceInterfaceInvoker(newRule);
}
if (success) {
setCurrentStepAndThreshold(step, threshold);
logger.info(
"Succeed Migrated to " + step + " mode. Service Name: " + consumerURL.getDisplayServiceKey());
report(step, originStep, "true");
} else {
// migrate failed, do not save new step and rule
logger.warn(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Migrate to " + step + " mode failed. Probably not satisfy the threshold you set " + threshold
+ ". Please try re-publish configuration if you still after check.");
report(step, originStep, "false");
}
return success;
}
// ignore if step is same with previous, will continue override rule for MigrationInvoker
return true;
}
private void report(MigrationStep step, MigrationStep originStep, String success) {
FrameworkStatusReportService reportService =
consumerURL.getOrDefaultApplicationModel().getBeanFactory().getBean(FrameworkStatusReportService.class);
if (reportService.hasReporter()) {
reportService.reportMigrationStepStatus(reportService.createMigrationStepReport(
consumerURL.getServiceInterface(),
consumerURL.getVersion(),
consumerURL.getGroup(),
String.valueOf(originStep),
String.valueOf(step),
success));
}
}
private void setMigrationRule(MigrationRule rule) {
this.migrationInvoker.setMigrationRule(rule);
}
private void setCurrentStepAndThreshold(MigrationStep currentStep, Float currentThreshold) {
if (currentThreshold != null) {
this.currentThreshold = currentThreshold;
}
if (currentStep != null) {
this.currentStep = currentStep;
this.migrationInvoker.setMigrationStep(currentStep);
}
}
// for test purpose
public MigrationStep getMigrationStep() {
return currentStep;
}
}
| 5,514 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/ServiceDiscoveryMigrationInvoker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.registry.integration.RegistryProtocol;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import java.util.concurrent.CountDownLatch;
public class ServiceDiscoveryMigrationInvoker<T> extends MigrationInvoker<T> {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ServiceDiscoveryMigrationInvoker.class);
public ServiceDiscoveryMigrationInvoker(
RegistryProtocol registryProtocol,
Cluster cluster,
Registry registry,
Class<T> type,
URL url,
URL consumerUrl) {
super(registryProtocol, cluster, registry, type, url, consumerUrl);
}
@Override
public boolean isServiceDiscovery() {
return true;
}
@Override
public boolean migrateToForceInterfaceInvoker(MigrationRule newRule) {
CountDownLatch latch = new CountDownLatch(0);
refreshServiceDiscoveryInvoker(latch);
setCurrentAvailableInvoker(getServiceDiscoveryInvoker());
return true;
}
@Override
public void migrateToApplicationFirstInvoker(MigrationRule newRule) {
CountDownLatch latch = new CountDownLatch(0);
refreshServiceDiscoveryInvoker(latch);
setCurrentAvailableInvoker(getServiceDiscoveryInvoker());
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
ClusterInvoker<T> invoker = getServiceDiscoveryInvoker();
if (invoker == null) {
throw new IllegalStateException(
"There's no service discovery invoker available for service " + invocation.getServiceName());
}
return invoker.invoke(invocation);
}
}
| 5,515 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationInvoker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.status.reporter.FrameworkStatusReportService;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
import org.apache.dubbo.registry.integration.DynamicDirectory;
import org.apache.dubbo.registry.integration.RegistryProtocol;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.cluster.Cluster;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_NOTIFY_EVENT;
import static org.apache.dubbo.registry.client.migration.model.MigrationStep.APPLICATION_FIRST;
import static org.apache.dubbo.rpc.cluster.Constants.REFER_KEY;
public class MigrationInvoker<T> implements MigrationClusterInvoker<T> {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MigrationInvoker.class);
private URL url;
private final URL consumerUrl;
private final Cluster cluster;
private final Registry registry;
private final Class<T> type;
private final RegistryProtocol registryProtocol;
private MigrationRuleListener migrationRuleListener;
private final ConsumerModel consumerModel;
private final FrameworkStatusReportService reportService;
private volatile ClusterInvoker<T> invoker;
private volatile ClusterInvoker<T> serviceDiscoveryInvoker;
private volatile ClusterInvoker<T> currentAvailableInvoker;
private volatile MigrationStep step;
private volatile MigrationRule rule;
private volatile int promotion = 100;
public MigrationInvoker(
RegistryProtocol registryProtocol,
Cluster cluster,
Registry registry,
Class<T> type,
URL url,
URL consumerUrl) {
this(null, null, registryProtocol, cluster, registry, type, url, consumerUrl);
}
@SuppressWarnings("unchecked")
public MigrationInvoker(
ClusterInvoker<T> invoker,
ClusterInvoker<T> serviceDiscoveryInvoker,
RegistryProtocol registryProtocol,
Cluster cluster,
Registry registry,
Class<T> type,
URL url,
URL consumerUrl) {
this.invoker = invoker;
this.serviceDiscoveryInvoker = serviceDiscoveryInvoker;
this.registryProtocol = registryProtocol;
this.cluster = cluster;
this.registry = registry;
this.type = type;
this.url = url;
this.consumerUrl = consumerUrl;
this.consumerModel = (ConsumerModel) consumerUrl.getServiceModel();
this.reportService =
consumerUrl.getOrDefaultApplicationModel().getBeanFactory().getBean(FrameworkStatusReportService.class);
if (consumerModel != null) {
Object object =
consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY);
Map<Registry, MigrationInvoker<?>> invokerMap;
if (object instanceof Map) {
invokerMap = (Map<Registry, MigrationInvoker<?>>) object;
} else {
invokerMap = new ConcurrentHashMap<>();
}
invokerMap.put(registry, this);
consumerModel.getServiceMetadata().addAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY, invokerMap);
}
}
public ClusterInvoker<T> getInvoker() {
return invoker;
}
public void setInvoker(ClusterInvoker<T> invoker) {
this.invoker = invoker;
}
public ClusterInvoker<T> getServiceDiscoveryInvoker() {
return serviceDiscoveryInvoker;
}
public void setServiceDiscoveryInvoker(ClusterInvoker<T> serviceDiscoveryInvoker) {
this.serviceDiscoveryInvoker = serviceDiscoveryInvoker;
}
public ClusterInvoker<T> getCurrentAvailableInvoker() {
return currentAvailableInvoker;
}
@Override
public Class<T> getInterface() {
return type;
}
@Override
public void reRefer(URL newSubscribeUrl) {
// update url to prepare for migration refresh
this.url = url.addParameter(REFER_KEY, StringUtils.toQueryString(newSubscribeUrl.getParameters()));
// re-subscribe immediately
if (invoker != null && !invoker.isDestroyed()) {
doReSubscribe(invoker, newSubscribeUrl);
}
if (serviceDiscoveryInvoker != null && !serviceDiscoveryInvoker.isDestroyed()) {
doReSubscribe(serviceDiscoveryInvoker, newSubscribeUrl);
}
}
private void doReSubscribe(ClusterInvoker<T> invoker, URL newSubscribeUrl) {
DynamicDirectory<T> directory = (DynamicDirectory<T>) invoker.getDirectory();
URL oldSubscribeUrl = directory.getRegisteredConsumerUrl();
Registry registry = directory.getRegistry();
registry.unregister(directory.getRegisteredConsumerUrl());
directory.unSubscribe(RegistryProtocol.toSubscribeUrl(oldSubscribeUrl));
if (directory.isShouldRegister()) {
registry.register(directory.getRegisteredConsumerUrl());
directory.setRegisteredConsumerUrl(newSubscribeUrl);
}
directory.buildRouterChain(newSubscribeUrl);
directory.subscribe(RegistryProtocol.toSubscribeUrl(newSubscribeUrl));
}
@Override
public boolean migrateToForceInterfaceInvoker(MigrationRule newRule) {
CountDownLatch latch = new CountDownLatch(1);
refreshInterfaceInvoker(latch);
if (serviceDiscoveryInvoker == null) {
// serviceDiscoveryInvoker is absent, ignore threshold check
this.currentAvailableInvoker = invoker;
return true;
}
// wait and compare threshold
waitAddressNotify(newRule, latch);
if (newRule.getForce(consumerUrl)) {
// force migrate, ignore threshold check
this.currentAvailableInvoker = invoker;
this.destroyServiceDiscoveryInvoker();
return true;
}
Set<MigrationAddressComparator> detectors = ScopeModelUtil.getApplicationModel(
consumerUrl == null ? null : consumerUrl.getScopeModel())
.getExtensionLoader(MigrationAddressComparator.class)
.getSupportedExtensionInstances();
if (CollectionUtils.isNotEmpty(detectors)) {
if (detectors.stream()
.allMatch(comparator -> comparator.shouldMigrate(invoker, serviceDiscoveryInvoker, newRule))) {
this.currentAvailableInvoker = invoker;
this.destroyServiceDiscoveryInvoker();
return true;
}
}
// compare failed, will not change state
if (step == MigrationStep.FORCE_APPLICATION) {
destroyInterfaceInvoker();
}
return false;
}
@Override
public boolean migrateToForceApplicationInvoker(MigrationRule newRule) {
CountDownLatch latch = new CountDownLatch(1);
refreshServiceDiscoveryInvoker(latch);
if (invoker == null) {
// invoker is absent, ignore threshold check
this.currentAvailableInvoker = serviceDiscoveryInvoker;
return true;
}
// wait and compare threshold
waitAddressNotify(newRule, latch);
if (newRule.getForce(consumerUrl)) {
// force migrate, ignore threshold check
this.currentAvailableInvoker = serviceDiscoveryInvoker;
this.destroyInterfaceInvoker();
return true;
}
Set<MigrationAddressComparator> detectors = ScopeModelUtil.getApplicationModel(
consumerUrl == null ? null : consumerUrl.getScopeModel())
.getExtensionLoader(MigrationAddressComparator.class)
.getSupportedExtensionInstances();
if (CollectionUtils.isNotEmpty(detectors)) {
if (detectors.stream()
.allMatch(comparator -> comparator.shouldMigrate(serviceDiscoveryInvoker, invoker, newRule))) {
this.currentAvailableInvoker = serviceDiscoveryInvoker;
this.destroyInterfaceInvoker();
return true;
}
}
// compare failed, will not change state
if (step == MigrationStep.FORCE_INTERFACE) {
destroyServiceDiscoveryInvoker();
}
return false;
}
@Override
public void migrateToApplicationFirstInvoker(MigrationRule newRule) {
CountDownLatch latch = new CountDownLatch(0);
refreshInterfaceInvoker(latch);
refreshServiceDiscoveryInvoker(latch);
// directly calculate preferred invoker, will not wait until address notify
// calculation will re-occurred when address notify later
calcPreferredInvoker(newRule);
}
@SuppressWarnings("all")
private void waitAddressNotify(MigrationRule newRule, CountDownLatch latch) {
// wait and compare threshold
int delay = newRule.getDelay(consumerUrl);
if (delay > 0) {
try {
Thread.sleep(delay * 1000L);
} catch (InterruptedException e) {
logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Interrupted when waiting for address notify!" + e);
}
} else {
// do not wait address notify by default
delay = 0;
}
try {
latch.await(delay, TimeUnit.SECONDS);
} catch (InterruptedException e) {
logger.error(REGISTRY_FAILED_NOTIFY_EVENT, "", "", "Interrupted when waiting for address notify!" + e);
}
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
if (currentAvailableInvoker != null) {
if (step == APPLICATION_FIRST) {
// call ratio calculation based on random value
if (promotion < 100 && ThreadLocalRandom.current().nextDouble(100) > promotion) {
// fall back to interface mode
return invoker.invoke(invocation);
}
// check if invoker available for each time
return decideInvoker().invoke(invocation);
}
return currentAvailableInvoker.invoke(invocation);
}
switch (step) {
case APPLICATION_FIRST:
currentAvailableInvoker = decideInvoker();
break;
case FORCE_APPLICATION:
currentAvailableInvoker = serviceDiscoveryInvoker;
break;
case FORCE_INTERFACE:
default:
currentAvailableInvoker = invoker;
}
return currentAvailableInvoker.invoke(invocation);
}
private ClusterInvoker<T> decideInvoker() {
if (currentAvailableInvoker == serviceDiscoveryInvoker) {
if (checkInvokerAvailable(serviceDiscoveryInvoker)) {
return serviceDiscoveryInvoker;
}
return invoker;
} else {
return currentAvailableInvoker;
}
}
@Override
public boolean isAvailable() {
return currentAvailableInvoker != null
? currentAvailableInvoker.isAvailable()
: (invoker != null && invoker.isAvailable())
|| (serviceDiscoveryInvoker != null && serviceDiscoveryInvoker.isAvailable());
}
@SuppressWarnings("unchecked")
@Override
public void destroy() {
if (migrationRuleListener != null) {
migrationRuleListener.removeMigrationInvoker(this);
}
if (invoker != null) {
invoker.destroy();
}
if (serviceDiscoveryInvoker != null) {
serviceDiscoveryInvoker.destroy();
}
if (consumerModel != null) {
Object object =
consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY);
Map<Registry, MigrationInvoker<?>> invokerMap;
if (object instanceof Map) {
invokerMap = (Map<Registry, MigrationInvoker<?>>) object;
invokerMap.remove(registry);
if (invokerMap.isEmpty()) {
consumerModel
.getServiceMetadata()
.getAttributeMap()
.remove(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY);
}
}
}
}
@Override
public URL getUrl() {
if (currentAvailableInvoker != null) {
return currentAvailableInvoker.getUrl();
} else if (invoker != null) {
return invoker.getUrl();
} else if (serviceDiscoveryInvoker != null) {
return serviceDiscoveryInvoker.getUrl();
}
return consumerUrl;
}
@Override
public URL getRegistryUrl() {
if (currentAvailableInvoker != null) {
return currentAvailableInvoker.getRegistryUrl();
} else if (invoker != null) {
return invoker.getRegistryUrl();
} else if (serviceDiscoveryInvoker != null) {
return serviceDiscoveryInvoker.getRegistryUrl();
}
return url;
}
@Override
public Directory<T> getDirectory() {
if (currentAvailableInvoker != null) {
return currentAvailableInvoker.getDirectory();
} else if (invoker != null) {
return invoker.getDirectory();
} else if (serviceDiscoveryInvoker != null) {
return serviceDiscoveryInvoker.getDirectory();
}
return null;
}
@Override
public boolean isDestroyed() {
return currentAvailableInvoker != null
? currentAvailableInvoker.isDestroyed()
: (invoker == null || invoker.isDestroyed())
&& (serviceDiscoveryInvoker == null || serviceDiscoveryInvoker.isDestroyed());
}
@Override
public boolean isServiceDiscovery() {
return false;
}
@Override
public MigrationStep getMigrationStep() {
return step;
}
@Override
public void setMigrationStep(MigrationStep step) {
this.step = step;
}
@Override
public MigrationRule getMigrationRule() {
return rule;
}
@Override
public void setMigrationRule(MigrationRule rule) {
this.rule = rule;
promotion = rule.getProportion(consumerUrl);
}
protected void destroyServiceDiscoveryInvoker() {
if (this.invoker != null) {
this.currentAvailableInvoker = this.invoker;
}
if (serviceDiscoveryInvoker != null && !serviceDiscoveryInvoker.isDestroyed()) {
if (logger.isInfoEnabled()) {
logger.info(
"Destroying instance address invokers, will not listen for address changes until re-subscribed, "
+ type.getName());
}
serviceDiscoveryInvoker.destroy();
serviceDiscoveryInvoker = null;
}
}
protected void refreshServiceDiscoveryInvoker(CountDownLatch latch) {
clearListener(serviceDiscoveryInvoker);
if (needRefresh(serviceDiscoveryInvoker)) {
if (logger.isDebugEnabled()) {
logger.debug("Re-subscribing instance addresses, current interface " + type.getName());
}
if (serviceDiscoveryInvoker != null) {
serviceDiscoveryInvoker.destroy();
}
serviceDiscoveryInvoker = registryProtocol.getServiceDiscoveryInvoker(cluster, registry, type, url);
}
setListener(serviceDiscoveryInvoker, () -> {
latch.countDown();
if (reportService.hasReporter()) {
reportService.reportConsumptionStatus(reportService.createConsumptionReport(
consumerUrl.getServiceInterface(), consumerUrl.getVersion(), consumerUrl.getGroup(), "app"));
}
if (step == APPLICATION_FIRST) {
calcPreferredInvoker(rule);
}
});
}
protected void refreshInterfaceInvoker(CountDownLatch latch) {
clearListener(invoker);
if (needRefresh(invoker)) {
if (logger.isDebugEnabled()) {
logger.debug("Re-subscribing interface addresses for interface " + type.getName());
}
if (invoker != null) {
invoker.destroy();
}
invoker = registryProtocol.getInvoker(cluster, registry, type, url);
}
setListener(invoker, () -> {
latch.countDown();
if (reportService.hasReporter()) {
reportService.reportConsumptionStatus(reportService.createConsumptionReport(
consumerUrl.getServiceInterface(),
consumerUrl.getVersion(),
consumerUrl.getGroup(),
"interface"));
}
if (step == APPLICATION_FIRST) {
calcPreferredInvoker(rule);
}
});
}
private synchronized void calcPreferredInvoker(MigrationRule migrationRule) {
if (serviceDiscoveryInvoker == null || invoker == null) {
return;
}
Set<MigrationAddressComparator> detectors = ScopeModelUtil.getApplicationModel(
consumerUrl == null ? null : consumerUrl.getScopeModel())
.getExtensionLoader(MigrationAddressComparator.class)
.getSupportedExtensionInstances();
if (CollectionUtils.isNotEmpty(detectors)) {
// pick preferred invoker
// the real invoker choice in invocation will be affected by promotion
if (detectors.stream()
.allMatch(
comparator -> comparator.shouldMigrate(serviceDiscoveryInvoker, invoker, migrationRule))) {
this.currentAvailableInvoker = serviceDiscoveryInvoker;
} else {
this.currentAvailableInvoker = invoker;
}
}
}
protected void destroyInterfaceInvoker() {
if (this.serviceDiscoveryInvoker != null) {
this.currentAvailableInvoker = this.serviceDiscoveryInvoker;
}
if (invoker != null && !invoker.isDestroyed()) {
if (logger.isInfoEnabled()) {
logger.info(
"Destroying interface address invokers, will not listen for address changes until re-subscribed, "
+ type.getName());
}
invoker.destroy();
invoker = null;
}
}
private void clearListener(ClusterInvoker<T> invoker) {
if (invoker == null) {
return;
}
DynamicDirectory<T> directory = (DynamicDirectory<T>) invoker.getDirectory();
directory.setInvokersChangedListener(null);
}
private void setListener(ClusterInvoker<T> invoker, InvokersChangedListener listener) {
if (invoker == null) {
return;
}
DynamicDirectory<T> directory = (DynamicDirectory<T>) invoker.getDirectory();
directory.setInvokersChangedListener(listener);
}
private boolean needRefresh(ClusterInvoker<T> invoker) {
return invoker == null || invoker.isDestroyed() || !invoker.hasProxyInvokers();
}
public boolean checkInvokerAvailable(ClusterInvoker<T> invoker) {
return invoker != null && !invoker.isDestroyed() && invoker.isAvailable();
}
protected void setCurrentAvailableInvoker(ClusterInvoker<T> currentAvailableInvoker) {
this.currentAvailableInvoker = currentAvailableInvoker;
}
protected void setMigrationRuleListener(MigrationRuleListener migrationRuleListener) {
this.migrationRuleListener = migrationRuleListener;
}
public Cluster getCluster() {
return cluster;
}
public URL getConsumerUrl() {
return consumerUrl;
}
@Override
public String toString() {
return "MigrationInvoker{" + "serviceKey="
+ consumerUrl.getServiceKey() + ", invoker="
+ decideInvoker() + ", step="
+ step + '}';
}
}
| 5,516 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/PreMigratingConditionChecker.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
@SPI
public interface PreMigratingConditionChecker {
boolean checkCondition(URL consumerUrl);
}
| 5,517 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/DefaultMigrationAddressComparator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH;
public class DefaultMigrationAddressComparator implements MigrationAddressComparator {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DefaultMigrationAddressComparator.class);
private static final String MIGRATION_THRESHOLD = "dubbo.application.migration.threshold";
private static final String DEFAULT_THRESHOLD_STRING = "0.0";
private static final float DEFAULT_THREAD = 0f;
public static final String OLD_ADDRESS_SIZE = "OLD_ADDRESS_SIZE";
public static final String NEW_ADDRESS_SIZE = "NEW_ADDRESS_SIZE";
private final ConcurrentMap<String, Map<String, Integer>> serviceMigrationData = new ConcurrentHashMap<>();
@Override
public <T> boolean shouldMigrate(ClusterInvoker<T> newInvoker, ClusterInvoker<T> oldInvoker, MigrationRule rule) {
Map<String, Integer> migrationData = ConcurrentHashMapUtils.computeIfAbsent(
serviceMigrationData, oldInvoker.getUrl().getDisplayServiceKey(), _k -> new ConcurrentHashMap<>());
if (!newInvoker.hasProxyInvokers()) {
migrationData.put(OLD_ADDRESS_SIZE, getAddressSize(oldInvoker));
migrationData.put(NEW_ADDRESS_SIZE, -1);
logger.info("No " + getInvokerType(newInvoker) + " address available, stop compare.");
return false;
}
if (!oldInvoker.hasProxyInvokers()) {
migrationData.put(OLD_ADDRESS_SIZE, -1);
migrationData.put(NEW_ADDRESS_SIZE, getAddressSize(newInvoker));
logger.info("No " + getInvokerType(oldInvoker) + " address available, stop compare.");
return true;
}
int newAddressSize = getAddressSize(newInvoker);
int oldAddressSize = getAddressSize(oldInvoker);
migrationData.put(OLD_ADDRESS_SIZE, oldAddressSize);
migrationData.put(NEW_ADDRESS_SIZE, newAddressSize);
String rawThreshold = null;
Float configuredThreshold = rule == null ? null : rule.getThreshold(oldInvoker.getUrl());
if (configuredThreshold != null && configuredThreshold >= 0) {
rawThreshold = String.valueOf(configuredThreshold);
}
rawThreshold = StringUtils.isNotEmpty(rawThreshold)
? rawThreshold
: ConfigurationUtils.getCachedDynamicProperty(
newInvoker.getUrl().getScopeModel(), MIGRATION_THRESHOLD, DEFAULT_THRESHOLD_STRING);
float threshold;
try {
threshold = Float.parseFloat(rawThreshold);
} catch (Exception e) {
logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Invalid migration threshold " + rawThreshold);
threshold = DEFAULT_THREAD;
}
logger.info("serviceKey:" + oldInvoker.getUrl().getServiceKey() + " Instance address size " + newAddressSize
+ ", interface address size " + oldAddressSize + ", threshold " + threshold);
if (newAddressSize != 0 && oldAddressSize == 0) {
return true;
}
if (newAddressSize == 0 && oldAddressSize == 0) {
return false;
}
return ((float) newAddressSize / (float) oldAddressSize) >= threshold;
}
private <T> int getAddressSize(ClusterInvoker<T> invoker) {
if (invoker == null) {
return -1;
}
List<Invoker<T>> invokers = invoker.getDirectory().getAllInvokers();
return CollectionUtils.isNotEmpty(invokers) ? invokers.size() : 0;
}
@Override
public Map<String, Integer> getAddressSize(String displayServiceKey) {
return serviceMigrationData.get(displayServiceKey);
}
private String getInvokerType(ClusterInvoker<?> invoker) {
if (invoker.isServiceDiscovery()) {
return "instance";
}
return "interface";
}
}
| 5,518 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationAddressComparator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import java.util.Map;
@SPI
public interface MigrationAddressComparator {
<T> boolean shouldMigrate(ClusterInvoker<T> newInvoker, ClusterInvoker<T> oldInvoker, MigrationRule rule);
Map<String, Integer> getAddressSize(String displayServiceKey);
}
| 5,519 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/MigrationRuleListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.client.migration.model.MigrationRule;
import org.apache.dubbo.registry.integration.RegistryProtocol;
import org.apache.dubbo.registry.integration.RegistryProtocolListener;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_THREAD_INTERRUPTED_EXCEPTION;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_EMPTY_ADDRESS;
import static org.apache.dubbo.common.constants.RegistryConstants.INIT;
/**
* Listens to {@MigrationRule} from Config Center.
* <p>
* - Migration rule is of consumer application scope.
* - Listener is shared among all invokers (interfaces), it keeps the relation between interface and handler.
* <p>
* There are two execution points:
* - Refer, invoker behaviour is determined with default rule.
* - Rule change, invoker behaviour is changed according to the newly received rule.
*/
@Activate
public class MigrationRuleListener implements RegistryProtocolListener, ConfigurationListener {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(MigrationRuleListener.class);
private static final String DUBBO_SERVICEDISCOVERY_MIGRATION = "DUBBO_SERVICEDISCOVERY_MIGRATION";
private static final String MIGRATION_DELAY_KEY = "dubbo.application.migration.delay";
private static final int MIGRATION_DEFAULT_DELAY_TIME = 60000;
private String ruleKey;
protected final ConcurrentMap<MigrationInvoker<?>, MigrationRuleHandler<?>> handlers = new ConcurrentHashMap<>();
protected final LinkedBlockingQueue<String> ruleQueue = new LinkedBlockingQueue<>();
private final AtomicBoolean executorSubmit = new AtomicBoolean(false);
private final ExecutorService ruleManageExecutor =
Executors.newFixedThreadPool(1, new NamedThreadFactory("Dubbo-Migration-Listener"));
protected ScheduledFuture<?> localRuleMigrationFuture;
protected Future<?> ruleMigrationFuture;
private DynamicConfiguration configuration;
private volatile String rawRule;
private volatile MigrationRule rule;
private final ModuleModel moduleModel;
public MigrationRuleListener(ModuleModel moduleModel) {
this.moduleModel = moduleModel;
init();
}
private void init() {
this.ruleKey = moduleModel.getApplicationModel().getApplicationName() + ".migration";
this.configuration =
moduleModel.modelEnvironment().getDynamicConfiguration().orElse(null);
if (this.configuration != null) {
logger.info("Listening for migration rules on dataId " + ruleKey + ", group "
+ DUBBO_SERVICEDISCOVERY_MIGRATION);
configuration.addListener(ruleKey, DUBBO_SERVICEDISCOVERY_MIGRATION, this);
String rawRule = configuration.getConfig(ruleKey, DUBBO_SERVICEDISCOVERY_MIGRATION);
if (StringUtils.isEmpty(rawRule)) {
rawRule = INIT;
}
setRawRule(rawRule);
} else {
if (logger.isWarnEnabled()) {
logger.warn(
REGISTRY_EMPTY_ADDRESS,
"",
"",
"Using default configuration rule because config center is not configured!");
}
setRawRule(INIT);
}
String localRawRule = moduleModel.modelEnvironment().getLocalMigrationRule();
if (!StringUtils.isEmpty(localRawRule)) {
localRuleMigrationFuture = moduleModel
.getApplicationModel()
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getSharedScheduledExecutor()
.schedule(
() -> {
if (this.rawRule.equals(INIT)) {
this.process(new ConfigChangedEvent(null, null, localRawRule));
}
},
getDelay(),
TimeUnit.MILLISECONDS);
}
}
private int getDelay() {
int delay = MIGRATION_DEFAULT_DELAY_TIME;
String delayStr = ConfigurationUtils.getProperty(moduleModel, MIGRATION_DELAY_KEY);
if (StringUtils.isEmpty(delayStr)) {
return delay;
}
try {
delay = Integer.parseInt(delayStr);
} catch (Exception e) {
logger.warn(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Invalid migration delay param " + delayStr);
}
return delay;
}
@Override
public synchronized void process(ConfigChangedEvent event) {
String rawRule = event.getContent();
if (StringUtils.isEmpty(rawRule)) {
// fail back to startup status
rawRule = INIT;
// logger.warn(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Received empty migration rule, will ignore.");
}
try {
ruleQueue.put(rawRule);
} catch (InterruptedException e) {
logger.error(
COMMON_THREAD_INTERRUPTED_EXCEPTION,
"",
"",
"Put rawRule to rule management queue failed. rawRule: " + rawRule,
e);
}
if (executorSubmit.compareAndSet(false, true)) {
ruleMigrationFuture = ruleManageExecutor.submit(() -> {
while (true) {
String rule = "";
try {
rule = ruleQueue.take();
if (StringUtils.isEmpty(rule)) {
Thread.sleep(1000);
}
} catch (InterruptedException e) {
logger.error(
COMMON_THREAD_INTERRUPTED_EXCEPTION, "", "", "Poll Rule from config center failed.", e);
}
if (StringUtils.isEmpty(rule)) {
continue;
}
if (Objects.equals(this.rawRule, rule)) {
logger.info("Ignore duplicated rule");
continue;
}
logger.info("Using the following migration rule to migrate:");
logger.info(rule);
setRawRule(rule);
if (CollectionUtils.isEmptyMap(handlers)) {
continue;
}
ExecutorService executorService = null;
try {
executorService = Executors.newFixedThreadPool(
Math.min(handlers.size(), 100), new NamedThreadFactory("Dubbo-Invoker-Migrate"));
List<Future<?>> migrationFutures = new ArrayList<>(handlers.size());
for (MigrationRuleHandler<?> handler : handlers.values()) {
Future<?> future = executorService.submit(() -> handler.doMigrate(this.rule));
migrationFutures.add(future);
}
for (Future<?> future : migrationFutures) {
try {
future.get();
} catch (InterruptedException ie) {
logger.warn(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Interrupted while waiting for migration async task to finish.");
} catch (ExecutionException ee) {
logger.error(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Migration async task failed.",
ee.getCause());
}
}
} catch (Throwable t) {
logger.error(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Error occurred when migration.",
t);
} finally {
if (executorService != null) {
executorService.shutdown();
}
}
}
});
}
}
public void setRawRule(String rawRule) {
this.rawRule = rawRule;
this.rule = parseRule(this.rawRule);
}
private MigrationRule parseRule(String rawRule) {
MigrationRule tmpRule = rule == null ? MigrationRule.getInitRule() : rule;
if (INIT.equals(rawRule)) {
tmpRule = MigrationRule.getInitRule();
} else {
try {
tmpRule = MigrationRule.parse(rawRule);
} catch (Exception e) {
logger.error(COMMON_PROPERTY_TYPE_MISMATCH, "", "", "Failed to parse migration rule...", e);
}
}
return tmpRule;
}
@Override
public void onExport(RegistryProtocol registryProtocol, Exporter<?> exporter) {}
@Override
public void onRefer(
RegistryProtocol registryProtocol, ClusterInvoker<?> invoker, URL consumerUrl, URL registryURL) {
MigrationRuleHandler<?> migrationRuleHandler =
ConcurrentHashMapUtils.computeIfAbsent(handlers, (MigrationInvoker<?>) invoker, _key -> {
((MigrationInvoker<?>) invoker).setMigrationRuleListener(this);
return new MigrationRuleHandler<>((MigrationInvoker<?>) invoker, consumerUrl);
});
migrationRuleHandler.doMigrate(rule);
}
@Override
public void onDestroy() {
if (configuration != null) {
configuration.removeListener(ruleKey, DUBBO_SERVICEDISCOVERY_MIGRATION, this);
}
if (ruleMigrationFuture != null) {
ruleMigrationFuture.cancel(true);
}
if (localRuleMigrationFuture != null) {
localRuleMigrationFuture.cancel(true);
}
ruleManageExecutor.shutdown();
ruleQueue.clear();
}
public Map<MigrationInvoker<?>, MigrationRuleHandler<?>> getHandlers() {
return handlers;
}
protected void removeMigrationInvoker(MigrationInvoker<?> migrationInvoker) {
handlers.remove(migrationInvoker);
}
public MigrationRule getRule() {
return rule;
}
}
| 5,520 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/MigrationRule.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration.model;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.ServiceNameMapping;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import static org.apache.dubbo.registry.Constants.MIGRATION_DELAY_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_FORCE_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_PROMOTION_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_APPLICATIONS_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_DELAY_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_FORCE_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_INTERFACES_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_PROPORTION_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_STEP_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_THRESHOLD_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_STEP_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_THRESHOLD_KEY;
import static org.apache.dubbo.registry.client.migration.MigrationRuleHandler.DUBBO_SERVICEDISCOVERY_MIGRATION;
/**
* # key = demo-consumer.migration
* # group = DUBBO_SERVICEDISCOVERY_MIGRATION
* # content
* key: demo-consumer
* step: APPLICATION_FIRST
* threshold: 1.0
* proportion: 60
* delay: 60
* force: false
* interfaces:
* - serviceKey: DemoService:1.0.0
* threshold: 0.5
* proportion: 30
* delay: 30
* force: true
* step: APPLICATION_FIRST
* - serviceKey: GreetingService:1.0.0
* step: FORCE_APPLICATION
* applications:
* - serviceKey: TestApplication
* threshold: 0.3
* proportion: 20
* delay: 10
* force: false
* step: FORCE_INTERFACE
*/
public class MigrationRule {
private String key;
private MigrationStep step;
private Float threshold;
private Integer proportion;
private Integer delay;
private Boolean force;
private List<SubMigrationRule> interfaces;
private List<SubMigrationRule> applications;
private transient Map<String, SubMigrationRule> interfaceRules;
private transient Map<String, SubMigrationRule> applicationRules;
public static MigrationRule getInitRule() {
return new MigrationRule();
}
@SuppressWarnings("unchecked")
private static MigrationRule parseFromMap(Map<String, Object> map) {
MigrationRule migrationRule = new MigrationRule();
migrationRule.setKey((String) map.get(MIGRATION_RULE_KEY));
Object step = map.get(MIGRATION_RULE_STEP_KEY);
if (step != null) {
migrationRule.setStep(MigrationStep.valueOf(step.toString()));
}
Object threshold = map.get(MIGRATION_RULE_THRESHOLD_KEY);
if (threshold != null) {
migrationRule.setThreshold(Float.valueOf(threshold.toString()));
}
Object proportion = map.get(MIGRATION_RULE_PROPORTION_KEY);
if (proportion != null) {
migrationRule.setProportion(Integer.valueOf(proportion.toString()));
}
Object delay = map.get(MIGRATION_RULE_DELAY_KEY);
if (delay != null) {
migrationRule.setDelay(Integer.valueOf(delay.toString()));
}
Object force = map.get(MIGRATION_RULE_FORCE_KEY);
if (force != null) {
migrationRule.setForce(Boolean.valueOf(force.toString()));
}
Object interfaces = map.get(MIGRATION_RULE_INTERFACES_KEY);
if (interfaces != null && List.class.isAssignableFrom(interfaces.getClass())) {
migrationRule.setInterfaces(((List<Map<String, Object>>) interfaces)
.stream().map(SubMigrationRule::parseFromMap).collect(Collectors.toList()));
}
Object applications = map.get(MIGRATION_RULE_APPLICATIONS_KEY);
if (applications != null && List.class.isAssignableFrom(applications.getClass())) {
migrationRule.setApplications(((List<Map<String, Object>>) applications)
.stream().map(SubMigrationRule::parseFromMap).collect(Collectors.toList()));
}
return migrationRule;
}
public MigrationRule() {}
public MigrationRule(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public MigrationStep getStep(URL consumerURL) {
MigrationStep value = getValue(consumerURL, SubMigrationRule::getStep);
if (value != null) {
return value;
}
/**
* FIXME, it's really hard to follow setting default values here.
*/
if (step == null) {
// initial step : APPLICATION_FIRST
return Enum.valueOf(
MigrationStep.class,
consumerURL.getParameter(
MIGRATION_STEP_KEY, getDefaultStep(consumerURL, MigrationStep.APPLICATION_FIRST.name())));
}
return step;
}
private String getDefaultStep(URL consumerURL, String defaultStep) {
String globalDefaultStep = ConfigurationUtils.getCachedDynamicProperty(
consumerURL.getScopeModel(), DUBBO_SERVICEDISCOVERY_MIGRATION, null);
if (StringUtils.isEmpty(globalDefaultStep)) {
// check 'dubbo.application.service-discovery.migration' for compatibility
globalDefaultStep = ConfigurationUtils.getCachedDynamicProperty(
consumerURL.getScopeModel(), "dubbo.application.service-discovery.migration", defaultStep);
}
return globalDefaultStep;
}
public MigrationStep getStep() {
return step;
}
public float getThreshold(URL consumerURL) {
Float value = getValue(consumerURL, SubMigrationRule::getThreshold);
if (value != null) {
return value;
}
return threshold == null ? consumerURL.getParameter(MIGRATION_THRESHOLD_KEY, -1f) : threshold;
}
public Float getThreshold() {
return threshold;
}
public void setThreshold(Float threshold) {
this.threshold = threshold;
}
public Integer getProportion() {
return proportion;
}
public int getProportion(URL consumerURL) {
Integer value = getValue(consumerURL, SubMigrationRule::getProportion);
if (value != null) {
return value;
}
return proportion == null ? consumerURL.getParameter(MIGRATION_PROMOTION_KEY, 100) : proportion;
}
public void setProportion(Integer proportion) {
this.proportion = proportion;
}
public Integer getDelay() {
return delay;
}
public int getDelay(URL consumerURL) {
Integer value = getValue(consumerURL, SubMigrationRule::getDelay);
if (value != null) {
return value;
}
return delay == null ? consumerURL.getParameter(MIGRATION_DELAY_KEY, 0) : delay;
}
public void setDelay(Integer delay) {
this.delay = delay;
}
public void setStep(MigrationStep step) {
this.step = step;
}
public Boolean getForce() {
return force;
}
public boolean getForce(URL consumerURL) {
Boolean value = getValue(consumerURL, SubMigrationRule::getForce);
if (value != null) {
return value;
}
return force == null ? consumerURL.getParameter(MIGRATION_FORCE_KEY, false) : force;
}
public <T> T getValue(URL consumerURL, Function<SubMigrationRule, T> function) {
if (interfaceRules != null) {
SubMigrationRule rule = interfaceRules.get(consumerURL.getDisplayServiceKey());
if (rule != null) {
T value = function.apply(rule);
if (value != null) {
return value;
}
}
}
if (applications != null) {
ServiceNameMapping serviceNameMapping = ServiceNameMapping.getDefaultExtension(consumerURL.getScopeModel());
Set<String> services = serviceNameMapping.getRemoteMapping(consumerURL);
if (CollectionUtils.isNotEmpty(services)) {
for (String service : services) {
SubMigrationRule rule = applicationRules.get(service);
if (rule != null) {
T value = function.apply(rule);
if (value != null) {
return value;
}
}
}
}
}
return null;
}
public void setForce(Boolean force) {
this.force = force;
}
public List<SubMigrationRule> getInterfaces() {
return interfaces;
}
public void setInterfaces(List<SubMigrationRule> interfaces) {
this.interfaces = interfaces;
if (interfaces != null) {
this.interfaceRules = new HashMap<>();
interfaces.forEach(rule -> {
interfaceRules.put(rule.getServiceKey(), rule);
});
}
}
public List<SubMigrationRule> getApplications() {
return applications;
}
public void setApplications(List<SubMigrationRule> applications) {
this.applications = applications;
if (applications != null) {
this.applicationRules = new HashMap<>();
applications.forEach(rule -> {
applicationRules.put(rule.getServiceKey(), rule);
});
}
}
public static MigrationRule parse(String rawRule) {
Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions()));
Map<String, Object> map = yaml.load(rawRule);
return parseFromMap(map);
}
public static String toYaml(MigrationRule rule) {
Constructor constructor = new Constructor(MigrationRule.class, new LoaderOptions());
Yaml yaml = new Yaml(constructor);
return yaml.dump(rule);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MigrationRule that = (MigrationRule) o;
return Objects.equals(key, that.key)
&& step == that.step
&& Objects.equals(threshold, that.threshold)
&& Objects.equals(proportion, that.proportion)
&& Objects.equals(delay, that.delay)
&& Objects.equals(force, that.force)
&& Objects.equals(interfaces, that.interfaces)
&& Objects.equals(applications, that.applications)
&& Objects.equals(interfaceRules, that.interfaceRules)
&& Objects.equals(applicationRules, that.applicationRules);
}
@Override
public int hashCode() {
return Objects.hash(
key,
step,
threshold,
proportion,
delay,
force,
interfaces,
applications,
interfaceRules,
applicationRules);
}
}
| 5,521 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/MigrationStep.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration.model;
public enum MigrationStep {
FORCE_INTERFACE,
APPLICATION_FIRST,
FORCE_APPLICATION
}
| 5,522 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/migration/model/SubMigrationRule.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.migration.model;
import java.util.Map;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_DELAY_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_FORCE_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_PROPORTION_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_STEP_KEY;
import static org.apache.dubbo.registry.Constants.MIGRATION_RULE_THRESHOLD_KEY;
public class SubMigrationRule {
private String serviceKey;
private MigrationStep step;
private Float threshold;
private Integer proportion;
private Integer delay;
private Boolean force;
public static SubMigrationRule parseFromMap(Map<String, Object> map) {
SubMigrationRule interfaceMigrationRule = new SubMigrationRule();
interfaceMigrationRule.setServiceKey((String) map.get("serviceKey"));
Object step = map.get(MIGRATION_RULE_STEP_KEY);
if (step != null) {
interfaceMigrationRule.setStep(MigrationStep.valueOf(step.toString()));
}
Object threshold = map.get(MIGRATION_RULE_THRESHOLD_KEY);
if (threshold != null) {
interfaceMigrationRule.setThreshold(Float.valueOf(threshold.toString()));
}
Object proportion = map.get(MIGRATION_RULE_PROPORTION_KEY);
if (proportion != null) {
interfaceMigrationRule.setProportion(Integer.valueOf(proportion.toString()));
}
Object delay = map.get(MIGRATION_RULE_DELAY_KEY);
if (delay != null) {
interfaceMigrationRule.setDelay(Integer.valueOf(delay.toString()));
}
Object force = map.get(MIGRATION_RULE_FORCE_KEY);
if (force != null) {
interfaceMigrationRule.setForce(Boolean.valueOf(force.toString()));
}
return interfaceMigrationRule;
}
public SubMigrationRule() {}
public SubMigrationRule(String serviceKey, MigrationStep step, Float threshold, Integer proportion) {
this.serviceKey = serviceKey;
this.step = step;
this.threshold = threshold;
this.proportion = proportion;
}
public String getServiceKey() {
return serviceKey;
}
public void setServiceKey(String serviceKey) {
this.serviceKey = serviceKey;
}
public MigrationStep getStep() {
return step;
}
public void setStep(MigrationStep step) {
this.step = step;
}
public Float getThreshold() {
return threshold;
}
public void setThreshold(Float threshold) {
this.threshold = threshold;
}
public Integer getProportion() {
return proportion;
}
public void setProportion(Integer proportion) {
this.proportion = proportion;
}
public Integer getDelay() {
return delay;
}
public void setDelay(Integer delay) {
this.delay = delay;
}
public Boolean getForce() {
return force;
}
public void setForce(Boolean force) {
this.force = force;
}
}
| 5,523 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/ServiceInstancesChangedEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.event;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import java.util.Collections;
import java.util.List;
import static java.util.Collections.unmodifiableList;
/**
* An event raised after the {@link ServiceInstance instances} of one service has been changed.
*
* @see ServiceInstancesChangedListener
* @since 2.7.5
*/
public class ServiceInstancesChangedEvent {
private final String serviceName;
private final List<ServiceInstance> serviceInstances;
/**
* @param serviceName The name of service that was changed
* @param serviceInstances all {@link ServiceInstance service instances}
* @throws IllegalArgumentException if source is null.
*/
public ServiceInstancesChangedEvent(String serviceName, List<ServiceInstance> serviceInstances) {
this.serviceName = serviceName;
this.serviceInstances = unmodifiableList(serviceInstances);
}
protected ServiceInstancesChangedEvent() {
this.serviceInstances = Collections.emptyList();
this.serviceName = "";
}
/**
* @return The name of service that was changed
*/
public String getServiceName() {
return serviceName;
}
/**
* @return all {@link ServiceInstance service instances}
*/
public List<ServiceInstance> getServiceInstances() {
return serviceInstances;
}
}
| 5,524 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/RetryServiceInstancesChangedEvent.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.event;
import java.util.Collections;
/**
* A retry task when is failed.
*/
public class RetryServiceInstancesChangedEvent extends ServiceInstancesChangedEvent {
private volatile long failureRecordTime;
public RetryServiceInstancesChangedEvent(String serviceName) {
super(serviceName, Collections.emptyList()); // instance list has been stored by ServiceInstancesChangedListener
this.failureRecordTime = System.currentTimeMillis();
}
public long getFailureRecordTime() {
return failureRecordTime;
}
}
| 5,525 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/event/listener/ServiceInstancesChangedListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.event.listener;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.threadpool.manager.FrameworkExecutorRepository;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashSet;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataInfo.ServiceInfo;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.registry.event.RegistryEvent;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.RetryServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils;
import org.apache.dubbo.registry.client.metadata.ServiceInstanceNotificationCustomizer;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_REFRESH_ADDRESS;
import static org.apache.dubbo.common.constants.RegistryConstants.DEFAULT_ENABLE_EMPTY_PROTECTION;
import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL;
import static org.apache.dubbo.common.constants.RegistryConstants.ENABLE_EMPTY_PROTECTION_KEY;
import static org.apache.dubbo.metadata.RevisionResolver.EMPTY_REVISION;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.getExportedServicesRevision;
/**
* TODO, refactor to move revision-metadata mapping to ServiceDiscovery. Instances should have already been mapped with metadata when reached here.
* <p>
* The operations of ServiceInstancesChangedListener should be synchronized.
*/
public class ServiceInstancesChangedListener {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ServiceInstancesChangedListener.class);
protected final Set<String> serviceNames;
protected final ServiceDiscovery serviceDiscovery;
protected Map<String, Set<NotifyListenerWithKey>> listeners;
protected AtomicBoolean destroyed = new AtomicBoolean(false);
protected Map<String, List<ServiceInstance>> allInstances;
protected Map<String, List<ProtocolServiceKeyWithUrls>> serviceUrls;
private volatile long lastRefreshTime;
private final Semaphore retryPermission;
private volatile ScheduledFuture<?> retryFuture;
private final ScheduledExecutorService scheduler;
private volatile boolean hasEmptyMetadata;
private final Set<ServiceInstanceNotificationCustomizer> serviceInstanceNotificationCustomizers;
private final ApplicationModel applicationModel;
public ServiceInstancesChangedListener(Set<String> serviceNames, ServiceDiscovery serviceDiscovery) {
this.serviceNames = serviceNames;
this.serviceDiscovery = serviceDiscovery;
this.listeners = new ConcurrentHashMap<>();
this.allInstances = new HashMap<>();
this.serviceUrls = new HashMap<>();
retryPermission = new Semaphore(1);
ApplicationModel applicationModel = ScopeModelUtil.getApplicationModel(
serviceDiscovery == null || serviceDiscovery.getUrl() == null
? null
: serviceDiscovery.getUrl().getScopeModel());
this.scheduler = applicationModel
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getMetadataRetryExecutor();
this.serviceInstanceNotificationCustomizers = applicationModel
.getExtensionLoader(ServiceInstanceNotificationCustomizer.class)
.getSupportedExtensionInstances();
this.applicationModel = applicationModel;
}
/**
* On {@link ServiceInstancesChangedEvent the service instances change event}
*
* @param event {@link ServiceInstancesChangedEvent}
*/
public void onEvent(ServiceInstancesChangedEvent event) {
if (destroyed.get() || !accept(event) || isRetryAndExpired(event)) {
return;
}
doOnEvent(event);
}
/**
* @param event
*/
private synchronized void doOnEvent(ServiceInstancesChangedEvent event) {
if (destroyed.get() || !accept(event) || isRetryAndExpired(event)) {
return;
}
refreshInstance(event);
if (logger.isDebugEnabled()) {
logger.debug(event.getServiceInstances().toString());
}
Map<String, List<ServiceInstance>> revisionToInstances = new HashMap<>();
Map<ServiceInfo, Set<String>> localServiceToRevisions = new HashMap<>();
// grouping all instances of this app(service name) by revision
for (Map.Entry<String, List<ServiceInstance>> entry : allInstances.entrySet()) {
List<ServiceInstance> instances = entry.getValue();
for (ServiceInstance instance : instances) {
String revision = getExportedServicesRevision(instance);
if (revision == null || EMPTY_REVISION.equals(revision)) {
if (logger.isDebugEnabled()) {
logger.debug("Find instance without valid service metadata: " + instance.getAddress());
}
continue;
}
List<ServiceInstance> subInstances =
revisionToInstances.computeIfAbsent(revision, r -> new LinkedList<>());
subInstances.add(instance);
}
}
// get MetadataInfo with revision
for (Map.Entry<String, List<ServiceInstance>> entry : revisionToInstances.entrySet()) {
String revision = entry.getKey();
List<ServiceInstance> subInstances = entry.getValue();
MetadataInfo metadata = subInstances.stream()
.map(ServiceInstance::getServiceMetadata)
.filter(Objects::nonNull)
.filter(m -> revision.equals(m.getRevision()))
.findFirst()
.orElseGet(() -> serviceDiscovery.getRemoteMetadata(revision, subInstances));
parseMetadata(revision, metadata, localServiceToRevisions);
// update metadata into each instance, in case new instance created.
for (ServiceInstance tmpInstance : subInstances) {
MetadataInfo originMetadata = tmpInstance.getServiceMetadata();
if (originMetadata == null || !Objects.equals(originMetadata.getRevision(), metadata.getRevision())) {
tmpInstance.setServiceMetadata(metadata);
}
}
}
int emptyNum = hasEmptyMetadata(revisionToInstances);
if (emptyNum != 0) { // retry every 10 seconds
hasEmptyMetadata = true;
if (retryPermission.tryAcquire()) {
if (retryFuture != null && !retryFuture.isDone()) {
// cancel last retryFuture because only one retryFuture will be canceled at destroy().
retryFuture.cancel(true);
}
try {
retryFuture = scheduler.schedule(
new AddressRefreshRetryTask(retryPermission, event.getServiceName()),
10_000L,
TimeUnit.MILLISECONDS);
} catch (Exception e) {
logger.error(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Error submitting async retry task.");
}
logger.warn(
INTERNAL_ERROR, "unknown error in registry module", "", "Address refresh try task submitted");
}
// return if all metadata is empty, this notification will not take effect.
if (emptyNum == revisionToInstances.size()) {
// 1-17 - Address refresh failed.
logger.error(
REGISTRY_FAILED_REFRESH_ADDRESS,
"metadata Server failure",
"",
"Address refresh failed because of Metadata Server failure, wait for retry or new address refresh event.");
return;
}
}
hasEmptyMetadata = false;
Map<String, Map<Integer, Map<Set<String>, Object>>> protocolRevisionsToUrls = new HashMap<>();
Map<String, List<ProtocolServiceKeyWithUrls>> newServiceUrls = new HashMap<>();
for (Map.Entry<ServiceInfo, Set<String>> entry : localServiceToRevisions.entrySet()) {
ServiceInfo serviceInfo = entry.getKey();
Set<String> revisions = entry.getValue();
Map<Integer, Map<Set<String>, Object>> portToRevisions =
protocolRevisionsToUrls.computeIfAbsent(serviceInfo.getProtocol(), k -> new HashMap<>());
Map<Set<String>, Object> revisionsToUrls =
portToRevisions.computeIfAbsent(serviceInfo.getPort(), k -> new HashMap<>());
Object urls = revisionsToUrls.computeIfAbsent(
revisions,
k -> getServiceUrlsCache(
revisionToInstances, revisions, serviceInfo.getProtocol(), serviceInfo.getPort()));
List<ProtocolServiceKeyWithUrls> list =
newServiceUrls.computeIfAbsent(serviceInfo.getPath(), k -> new LinkedList<>());
list.add(new ProtocolServiceKeyWithUrls(serviceInfo.getProtocolServiceKey(), (List<URL>) urls));
}
this.serviceUrls = newServiceUrls;
this.notifyAddressChanged();
}
public synchronized void addListenerAndNotify(URL url, NotifyListener listener) {
if (destroyed.get()) {
return;
}
Set<NotifyListenerWithKey> notifyListeners =
this.listeners.computeIfAbsent(url.getServiceKey(), _k -> new ConcurrentHashSet<>());
String protocol = listener.getConsumerUrl().getParameter(PROTOCOL_KEY, url.getProtocol());
ProtocolServiceKey protocolServiceKey = new ProtocolServiceKey(
url.getServiceInterface(),
url.getVersion(),
url.getGroup(),
!CommonConstants.CONSUMER.equals(protocol) ? protocol : null);
NotifyListenerWithKey listenerWithKey = new NotifyListenerWithKey(protocolServiceKey, listener);
notifyListeners.add(listenerWithKey);
// Aggregate address and notify on subscription.
List<URL> urls = getAddresses(protocolServiceKey, listener.getConsumerUrl());
if (CollectionUtils.isNotEmpty(urls)) {
logger.info(String.format(
"Notify serviceKey: %s, listener: %s with %s urls on subscription",
protocolServiceKey, listener, urls.size()));
listener.notify(urls);
}
}
public synchronized void removeListener(String serviceKey, NotifyListener notifyListener) {
if (destroyed.get()) {
return;
}
// synchronized method, no need to use DCL
Set<NotifyListenerWithKey> notifyListeners = this.listeners.get(serviceKey);
if (notifyListeners != null) {
notifyListeners.removeIf(listener -> listener.getNotifyListener().equals(notifyListener));
// ServiceKey has no listener, remove set
if (notifyListeners.isEmpty()) {
this.listeners.remove(serviceKey);
}
}
}
public boolean hasListeners() {
return CollectionUtils.isNotEmptyMap(listeners);
}
/**
* Get the correlative service name
*
* @return the correlative service name
*/
public final Set<String> getServiceNames() {
return serviceNames;
}
public Map<String, List<ServiceInstance>> getAllInstances() {
return allInstances;
}
/**
* @param event {@link ServiceInstancesChangedEvent event}
* @return If service name matches, return <code>true</code>, or <code>false</code>
*/
private boolean accept(ServiceInstancesChangedEvent event) {
return serviceNames.contains(event.getServiceName());
}
protected boolean isRetryAndExpired(ServiceInstancesChangedEvent event) {
if (event instanceof RetryServiceInstancesChangedEvent) {
RetryServiceInstancesChangedEvent retryEvent = (RetryServiceInstancesChangedEvent) event;
logger.warn(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Received address refresh retry event, " + retryEvent.getFailureRecordTime());
if (retryEvent.getFailureRecordTime() < lastRefreshTime && !hasEmptyMetadata) {
logger.warn(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Ignore retry event, event time: " + retryEvent.getFailureRecordTime() + ", last refresh time: "
+ lastRefreshTime);
return true;
}
logger.warn(INTERNAL_ERROR, "unknown error in registry module", "", "Retrying address notification...");
}
return false;
}
private void refreshInstance(ServiceInstancesChangedEvent event) {
if (event instanceof RetryServiceInstancesChangedEvent) {
return;
}
String appName = event.getServiceName();
List<ServiceInstance> appInstances = event.getServiceInstances();
logger.info("Received instance notification, serviceName: " + appName + ", instances: " + appInstances.size());
for (ServiceInstanceNotificationCustomizer serviceInstanceNotificationCustomizer :
serviceInstanceNotificationCustomizers) {
serviceInstanceNotificationCustomizer.customize(appInstances);
}
allInstances.put(appName, appInstances);
lastRefreshTime = System.currentTimeMillis();
}
/**
* Calculate the number of revisions that failed to find metadata info.
*
* @param revisionToInstances instance list classified by revisions
* @return the number of revisions that failed at fetching MetadataInfo
*/
protected int hasEmptyMetadata(Map<String, List<ServiceInstance>> revisionToInstances) {
if (revisionToInstances == null) {
return 0;
}
StringBuilder builder = new StringBuilder();
int emptyMetadataNum = 0;
for (Map.Entry<String, List<ServiceInstance>> entry : revisionToInstances.entrySet()) {
DefaultServiceInstance serviceInstance =
(DefaultServiceInstance) entry.getValue().get(0);
if (serviceInstance == null || serviceInstance.getServiceMetadata() == MetadataInfo.EMPTY) {
emptyMetadataNum++;
}
builder.append(entry.getKey());
builder.append(' ');
}
if (emptyMetadataNum > 0) {
builder.insert(
0,
emptyMetadataNum + "/" + revisionToInstances.size()
+ " revisions failed to get metadata from remote: ");
logger.error(INTERNAL_ERROR, "unknown error in registry module", "", builder.toString());
} else {
builder.insert(0, revisionToInstances.size() + " unique working revisions: ");
logger.info(builder.toString());
}
return emptyMetadataNum;
}
protected Map<ServiceInfo, Set<String>> parseMetadata(
String revision, MetadataInfo metadata, Map<ServiceInfo, Set<String>> localServiceToRevisions) {
Map<String, ServiceInfo> serviceInfos = metadata.getServices();
for (Map.Entry<String, ServiceInfo> entry : serviceInfos.entrySet()) {
Set<String> set = localServiceToRevisions.computeIfAbsent(entry.getValue(), _k -> new TreeSet<>());
set.add(revision);
}
return localServiceToRevisions;
}
protected Object getServiceUrlsCache(
Map<String, List<ServiceInstance>> revisionToInstances, Set<String> revisions, String protocol, int port) {
List<URL> urls = new ArrayList<>();
for (String r : revisions) {
for (ServiceInstance i : revisionToInstances.get(r)) {
if (port > 0) {
if (i.getPort() == port) {
urls.add(i.toURL(protocol).setScopeModel(i.getApplicationModel()));
} else {
urls.add(((DefaultServiceInstance) i)
.copyFrom(port)
.toURL(protocol)
.setScopeModel(i.getApplicationModel()));
}
continue;
}
// different protocols may have ports specified in meta
if (ServiceInstanceMetadataUtils.hasEndpoints(i)) {
DefaultServiceInstance.Endpoint endpoint = ServiceInstanceMetadataUtils.getEndpoint(i, protocol);
if (endpoint != null && endpoint.getPort() != i.getPort()) {
urls.add(((DefaultServiceInstance) i).copyFrom(endpoint).toURL(endpoint.getProtocol()));
continue;
}
}
urls.add(i.toURL(protocol).setScopeModel(i.getApplicationModel()));
}
}
return urls;
}
protected List<URL> getAddresses(ProtocolServiceKey protocolServiceKey, URL consumerURL) {
List<ProtocolServiceKeyWithUrls> protocolServiceKeyWithUrlsList =
serviceUrls.get(protocolServiceKey.getInterfaceName());
List<URL> urls = new ArrayList<>();
if (protocolServiceKeyWithUrlsList != null) {
for (ProtocolServiceKeyWithUrls protocolServiceKeyWithUrls : protocolServiceKeyWithUrlsList) {
if (ProtocolServiceKey.Matcher.isMatch(
protocolServiceKey, protocolServiceKeyWithUrls.getProtocolServiceKey())) {
urls.addAll(protocolServiceKeyWithUrls.getUrls());
}
}
}
if (serviceUrls.containsKey(CommonConstants.ANY_VALUE)) {
for (ProtocolServiceKeyWithUrls protocolServiceKeyWithUrls : serviceUrls.get(CommonConstants.ANY_VALUE)) {
urls.addAll(protocolServiceKeyWithUrls.getUrls());
}
}
return urls;
}
/**
* race condition is protected by onEvent/doOnEvent
*/
protected void notifyAddressChanged() {
MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), () -> {
Map<String, Integer> lastNumMap = new HashMap<>();
// 1 different services
listeners.forEach((serviceKey, listenerSet) -> {
// 2 multiple subscription listener of the same service
for (NotifyListenerWithKey listenerWithKey : listenerSet) {
NotifyListener notifyListener = listenerWithKey.getNotifyListener();
List<URL> urls = toUrlsWithEmpty(
getAddresses(listenerWithKey.getProtocolServiceKey(), notifyListener.getConsumerUrl()));
logger.info(
"Notify service " + listenerWithKey.getProtocolServiceKey() + " with urls " + urls.size());
notifyListener.notify(urls);
lastNumMap.put(serviceKey, urls.size());
}
});
return lastNumMap;
});
}
protected List<URL> toUrlsWithEmpty(List<URL> urls) {
boolean emptyProtectionEnabled =
serviceDiscovery.getUrl().getParameter(ENABLE_EMPTY_PROTECTION_KEY, DEFAULT_ENABLE_EMPTY_PROTECTION);
if (!emptyProtectionEnabled && urls == null) {
urls = new ArrayList<>();
} else if (emptyProtectionEnabled && urls == null) {
urls = Collections.emptyList();
}
if (CollectionUtils.isEmpty(urls) && !emptyProtectionEnabled) {
// notice that the service of this.url may not be the same as notify listener.
URL empty = URLBuilder.from(serviceDiscovery.getUrl())
.setProtocol(EMPTY_PROTOCOL)
.build();
urls.add(empty);
}
return urls;
}
/**
* Since this listener is shared among interfaces, destroy this listener only when all interface listener are unsubscribed
*/
public void destroy() {
if (destroyed.compareAndSet(false, true)) {
logger.info("Destroying instance listener of " + this.getServiceNames());
serviceDiscovery.removeServiceInstancesChangedListener(this);
synchronized (this) {
allInstances.clear();
serviceUrls.clear();
listeners.clear();
if (retryFuture != null && !retryFuture.isDone()) {
retryFuture.cancel(true);
}
}
}
}
public boolean isDestroyed() {
return destroyed.get();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ServiceInstancesChangedListener)) {
return false;
}
ServiceInstancesChangedListener that = (ServiceInstancesChangedListener) o;
return Objects.equals(getServiceNames(), that.getServiceNames()) && Objects.equals(listeners, that.listeners);
}
@Override
public int hashCode() {
return Objects.hash(getClass(), getServiceNames());
}
protected class AddressRefreshRetryTask implements Runnable {
private final RetryServiceInstancesChangedEvent retryEvent;
private final Semaphore retryPermission;
public AddressRefreshRetryTask(Semaphore semaphore, String serviceName) {
this.retryEvent = new RetryServiceInstancesChangedEvent(serviceName);
this.retryPermission = semaphore;
}
@Override
public void run() {
retryPermission.release();
ServiceInstancesChangedListener.this.onEvent(retryEvent);
}
}
public static class NotifyListenerWithKey {
private final ProtocolServiceKey protocolServiceKey;
private final NotifyListener notifyListener;
public NotifyListenerWithKey(ProtocolServiceKey protocolServiceKey, NotifyListener notifyListener) {
this.protocolServiceKey = protocolServiceKey;
this.notifyListener = notifyListener;
}
public ProtocolServiceKey getProtocolServiceKey() {
return protocolServiceKey;
}
public NotifyListener getNotifyListener() {
return notifyListener;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
NotifyListenerWithKey that = (NotifyListenerWithKey) o;
return Objects.equals(protocolServiceKey, that.protocolServiceKey)
&& Objects.equals(notifyListener, that.notifyListener);
}
@Override
public int hashCode() {
return Objects.hash(protocolServiceKey, notifyListener);
}
}
public static class ProtocolServiceKeyWithUrls {
private final ProtocolServiceKey protocolServiceKey;
private final List<URL> urls;
public ProtocolServiceKeyWithUrls(ProtocolServiceKey protocolServiceKey, List<URL> urls) {
this.protocolServiceKey = protocolServiceKey;
this.urls = urls;
}
public ProtocolServiceKey getProtocolServiceKey() {
return protocolServiceKey;
}
public List<URL> getUrls() {
return urls;
}
}
}
| 5,526 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudServiceInstanceNotificationCustomizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.ProtocolServiceKey;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.client.ServiceInstance;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
public class SpringCloudServiceInstanceNotificationCustomizer implements ServiceInstanceNotificationCustomizer {
@Override
public void customize(List<ServiceInstance> serviceInstance) {
if (serviceInstance.isEmpty()) {
return;
}
if (!serviceInstance.stream()
.allMatch(instance -> "SPRING_CLOUD".equals(instance.getMetadata("preserved.register.source")))) {
return;
}
for (ServiceInstance instance : serviceInstance) {
MetadataInfo.ServiceInfo serviceInfo =
new MetadataInfo.ServiceInfo("*", "*", "*", "rest", instance.getPort(), "*", new HashMap<>());
String revision = "SPRING_CLOUD-" + instance.getServiceName() + "-" + instance.getAddress() + "-"
+ instance.getPort();
MetadataInfo metadataInfo =
new MetadataInfo(
instance.getServiceName(),
revision,
new ConcurrentHashMap<>(Collections.singletonMap("*", serviceInfo))) {
@Override
public List<ServiceInfo> getMatchedServiceInfos(ProtocolServiceKey consumerProtocolServiceKey) {
getServices()
.putIfAbsent(
consumerProtocolServiceKey.getServiceKeyString(),
new MetadataInfo.ServiceInfo(
consumerProtocolServiceKey.getInterfaceName(),
consumerProtocolServiceKey.getGroup(),
consumerProtocolServiceKey.getVersion(),
consumerProtocolServiceKey.getProtocol(),
instance.getPort(),
consumerProtocolServiceKey.getInterfaceName(),
new HashMap<>()));
return super.getMatchedServiceInfos(consumerProtocolServiceKey);
}
};
instance.setServiceMetadata(metadataInfo);
}
}
}
| 5,527 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/SpringCloudMetadataServiceURLBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.client.ServiceInstance;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URLS_PROPERTY_NAME;
/**
* Supporting interaction with Dubbo Spring Cloud at https://github.com/alibaba/spring-cloud-alibaba
* Dubbo Spring Cloud is a Dubbo extension that favours a per instance registry model and exposes metadata service.
*
* @since 2.7.5
*/
public class SpringCloudMetadataServiceURLBuilder implements MetadataServiceURLBuilder {
public static final String NAME = "spring-cloud";
@Override
public List<URL> build(ServiceInstance serviceInstance) {
Map<String, String> metadata = serviceInstance.getMetadata();
String dubboUrlsForJson = metadata.get(METADATA_SERVICE_URLS_PROPERTY_NAME);
if (StringUtils.isBlank(dubboUrlsForJson)) {
return Collections.emptyList();
}
List<String> urlStrings = JsonUtils.toJavaList(dubboUrlsForJson, String.class);
return urlStrings.stream().map(URL::valueOf).collect(Collectors.toList());
}
}
| 5,528 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.definition.model.FullServiceDefinition;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.metadata.report.identifier.MetadataIdentifier;
import org.apache.dubbo.metadata.report.identifier.SubscriberMetadataIdentifier;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import org.apache.dubbo.rpc.model.ServiceDescriptor;
import org.apache.dubbo.rpc.service.Destroyable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.PROXY_CLASS_REF;
import static org.apache.dubbo.common.constants.CommonConstants.REMOTE_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_CREATE_INSTANCE;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_LOAD_METADATA;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_CLUSTER_KEY;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URLS_PROPERTY_NAME;
public class MetadataUtils {
public static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetadataUtils.class);
public static void publishServiceDefinition(
URL url, ServiceDescriptor serviceDescriptor, ApplicationModel applicationModel) {
if (getMetadataReports(applicationModel).size() == 0) {
String msg =
"Remote Metadata Report Server is not provided or unavailable, will stop registering service definition to remote center!";
logger.warn(REGISTRY_FAILED_LOAD_METADATA, "", "", msg);
return;
}
try {
String side = url.getSide();
if (PROVIDER_SIDE.equalsIgnoreCase(side)) {
String serviceKey = url.getServiceKey();
FullServiceDefinition serviceDefinition = serviceDescriptor.getFullServiceDefinition(serviceKey);
if (StringUtils.isNotEmpty(serviceKey) && serviceDefinition != null) {
serviceDefinition.setParameters(url.getParameters());
for (Map.Entry<String, MetadataReport> entry :
getMetadataReports(applicationModel).entrySet()) {
MetadataReport metadataReport = entry.getValue();
if (!metadataReport.shouldReportDefinition()) {
logger.info("Report of service definition is disabled for " + entry.getKey());
continue;
}
metadataReport.storeProviderMetadata(
new MetadataIdentifier(
url.getServiceInterface(),
url.getVersion() == null ? "" : url.getVersion(),
url.getGroup() == null ? "" : url.getGroup(),
PROVIDER_SIDE,
applicationModel.getApplicationName()),
serviceDefinition);
}
}
} else {
for (Map.Entry<String, MetadataReport> entry :
getMetadataReports(applicationModel).entrySet()) {
MetadataReport metadataReport = entry.getValue();
if (!metadataReport.shouldReportDefinition()) {
logger.info("Report of service definition is disabled for " + entry.getKey());
continue;
}
metadataReport.storeConsumerMetadata(
new MetadataIdentifier(
url.getServiceInterface(),
url.getVersion() == null ? "" : url.getVersion(),
url.getGroup() == null ? "" : url.getGroup(),
CONSUMER_SIDE,
applicationModel.getApplicationName()),
url.getParameters());
}
}
} catch (Exception e) {
// ignore error
logger.error(REGISTRY_FAILED_CREATE_INSTANCE, "", "", "publish service definition metadata error.", e);
}
}
public static ProxyHolder referProxy(ServiceInstance instance) {
MetadataServiceURLBuilder builder;
ExtensionLoader<MetadataServiceURLBuilder> loader =
instance.getApplicationModel().getExtensionLoader(MetadataServiceURLBuilder.class);
Map<String, String> metadata = instance.getMetadata();
// METADATA_SERVICE_URLS_PROPERTY_NAME is a unique key exists only on instances of spring-cloud-alibaba.
String dubboUrlsForJson = metadata.get(METADATA_SERVICE_URLS_PROPERTY_NAME);
if (metadata.isEmpty() || StringUtils.isEmpty(dubboUrlsForJson)) {
builder = loader.getExtension(StandardMetadataServiceURLBuilder.NAME);
} else {
builder = loader.getExtension(SpringCloudMetadataServiceURLBuilder.NAME);
}
List<URL> urls = builder.build(instance);
if (CollectionUtils.isEmpty(urls)) {
throw new IllegalStateException("Introspection service discovery mode is enabled " + instance
+ ", but no metadata service can build from it.");
}
URL url = urls.get(0);
// Simply rely on the first metadata url, as stated in MetadataServiceURLBuilder.
ApplicationModel applicationModel = instance.getApplicationModel();
ModuleModel internalModel = applicationModel.getInternalModule();
ConsumerModel consumerModel =
applicationModel.getInternalModule().registerInternalConsumer(MetadataService.class, url);
Protocol protocol = applicationModel.getExtensionLoader(Protocol.class).getExtension(url.getProtocol(), false);
url = url.setServiceModel(consumerModel);
Invoker<MetadataService> invoker = protocol.refer(MetadataService.class, url);
ProxyFactory proxyFactory =
applicationModel.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
MetadataService metadataService = proxyFactory.getProxy(invoker);
consumerModel.getServiceMetadata().setTarget(metadataService);
consumerModel.getServiceMetadata().addAttribute(PROXY_CLASS_REF, metadataService);
consumerModel.setProxyObject(metadataService);
consumerModel.initMethodModels();
return new ProxyHolder(consumerModel, metadataService, internalModel);
}
public static MetadataInfo getRemoteMetadata(
String revision, List<ServiceInstance> instances, MetadataReport metadataReport) {
ServiceInstance instance = selectInstance(instances);
String metadataType = ServiceInstanceMetadataUtils.getMetadataStorageType(instance);
MetadataInfo metadataInfo;
try {
if (logger.isDebugEnabled()) {
logger.debug("Instance " + instance.getAddress() + " is using metadata type " + metadataType);
}
if (REMOTE_METADATA_STORAGE_TYPE.equals(metadataType)) {
metadataInfo = MetadataUtils.getMetadata(revision, instance, metadataReport);
} else {
// change the instance used to communicate to avoid all requests route to the same instance
ProxyHolder proxyHolder = null;
try {
proxyHolder = MetadataUtils.referProxy(instance);
metadataInfo = proxyHolder
.getProxy()
.getMetadataInfo(ServiceInstanceMetadataUtils.getExportedServicesRevision(instance));
} finally {
MetadataUtils.destroyProxy(proxyHolder);
}
}
} catch (Exception e) {
logger.error(
REGISTRY_FAILED_LOAD_METADATA,
"",
"",
"Failed to get app metadata for revision " + revision + " for type " + metadataType
+ " from instance " + instance.getAddress(),
e);
metadataInfo = null;
}
if (metadataInfo == null) {
metadataInfo = MetadataInfo.EMPTY;
}
return metadataInfo;
}
public static void destroyProxy(ProxyHolder proxyHolder) {
if (proxyHolder != null) {
proxyHolder.destroy();
}
}
public static MetadataInfo getMetadata(String revision, ServiceInstance instance, MetadataReport metadataReport) {
SubscriberMetadataIdentifier identifier = new SubscriberMetadataIdentifier(instance.getServiceName(), revision);
if (metadataReport == null) {
throw new IllegalStateException("No valid remote metadata report specified.");
}
String registryCluster = instance.getRegistryCluster();
Map<String, String> params = new HashMap<>(instance.getExtendParams());
if (registryCluster != null && !registryCluster.equalsIgnoreCase(params.get(REGISTRY_CLUSTER_KEY))) {
params.put(REGISTRY_CLUSTER_KEY, registryCluster);
}
return metadataReport.getAppMetadata(identifier, params);
}
private static Map<String, MetadataReport> getMetadataReports(ApplicationModel applicationModel) {
return applicationModel
.getBeanFactory()
.getBean(MetadataReportInstance.class)
.getMetadataReports(false);
}
private static ServiceInstance selectInstance(List<ServiceInstance> instances) {
if (instances.size() == 1) {
return instances.get(0);
}
return instances.get(ThreadLocalRandom.current().nextInt(0, instances.size()));
}
public static class ProxyHolder {
private final ConsumerModel consumerModel;
private final MetadataService proxy;
private final ModuleModel internalModel;
public ProxyHolder(ConsumerModel consumerModel, MetadataService proxy, ModuleModel internalModel) {
this.consumerModel = consumerModel;
this.proxy = proxy;
this.internalModel = internalModel;
}
public void destroy() {
if (proxy instanceof Destroyable) {
((Destroyable) proxy).$destroy();
}
internalModel.getServiceRepository().unregisterConsumer(consumerModel);
}
public ConsumerModel getConsumerModel() {
return consumerModel;
}
public MetadataService getProxy() {
return proxy;
}
public ModuleModel getInternalModel() {
return internalModel;
}
}
}
| 5,529 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceHostPortCustomizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Set;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER;
/**
* The {@link ServiceInstanceCustomizer} to customize the {@link ServiceInstance#getPort() port} of service instance.
*/
public class ServiceInstanceHostPortCustomizer implements ServiceInstanceCustomizer {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ServiceInstanceHostPortCustomizer.class);
@Override
public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) {
if (serviceInstance.getPort() > 0) {
return;
}
MetadataInfo metadataInfo = serviceInstance.getServiceMetadata();
if (metadataInfo == null || CollectionUtils.isEmptyMap(metadataInfo.getExportedServiceURLs())) {
return;
}
String host = null;
int port = -1;
Set<URL> urls = metadataInfo.collectExportedURLSet();
if (CollectionUtils.isNotEmpty(urls)) {
String preferredProtocol = applicationModel.getCurrentConfig().getProtocol();
if (preferredProtocol != null) {
for (URL exportedURL : urls) {
if (preferredProtocol.equals(exportedURL.getProtocol())) {
host = exportedURL.getHost();
port = exportedURL.getPort();
break;
}
}
if (host == null || port == -1) {
// 4-2 - Can't find an instance URL using the default preferredProtocol.
logger.warn(
PROTOCOL_FAILED_INIT_SERIALIZATION_OPTIMIZER,
"typo in preferred protocol",
"",
"Can't find an instance URL using the default preferredProtocol \"" + preferredProtocol
+ "\", " + "falling back to the strategy that pick the first found protocol. "
+ "Please try modifying the config of dubbo.application.protocol");
URL url = urls.iterator().next();
host = url.getHost();
port = url.getPort();
}
} else {
URL url = urls.iterator().next();
host = url.getHost();
port = url.getPort();
}
if (serviceInstance instanceof DefaultServiceInstance) {
DefaultServiceInstance instance = (DefaultServiceInstance) serviceInstance;
instance.setHost(host);
instance.setPort(port);
}
}
}
}
| 5,530 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataUtils.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.metrics.registry.event.RegistryEvent;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.DefaultServiceInstance.Endpoint;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.registry.support.RegistryManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_METADATA_STORAGE_TYPE;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.RegistryConstants.REGISTRY_KEY;
import static org.apache.dubbo.common.utils.StringUtils.isBlank;
import static org.apache.dubbo.registry.integration.InterfaceCompatibleRegistryProtocol.DEFAULT_REGISTER_PROVIDER_KEYS;
import static org.apache.dubbo.rpc.Constants.DEPRECATED_KEY;
/**
* The Utilities class for the {@link ServiceInstance#getMetadata() metadata of the service instance}
*
* @see StandardMetadataServiceURLBuilder
* @see ServiceInstance#getMetadata()
* @see MetadataService
* @see URL
* @since 2.7.5
*/
public class ServiceInstanceMetadataUtils {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(ServiceInstanceMetadataUtils.class);
/**
* The prefix of {@link MetadataService} : "dubbo.metadata-service."
*/
public static final String METADATA_SERVICE_PREFIX = "dubbo.metadata-service.";
public static final String ENDPOINTS = "dubbo.endpoints";
/**
* The property name of metadata JSON of {@link MetadataService}'s {@link URL}
*/
public static final String METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME = METADATA_SERVICE_PREFIX + "url-params";
/**
* The {@link URL URLs} property name of {@link MetadataService} :
* "dubbo.metadata-service.urls", which is used to be compatible with Dubbo Spring Cloud and
* discovery the metadata of instance
*/
public static final String METADATA_SERVICE_URLS_PROPERTY_NAME = METADATA_SERVICE_PREFIX + "urls";
/**
* The property name of The revision for all exported Dubbo services.
*/
public static final String EXPORTED_SERVICES_REVISION_PROPERTY_NAME = "dubbo.metadata.revision";
/**
* The property name of metadata storage type.
*/
public static final String METADATA_STORAGE_TYPE_PROPERTY_NAME = "dubbo.metadata.storage-type";
public static final String METADATA_CLUSTER_PROPERTY_NAME = "dubbo.metadata.cluster";
public static String getMetadataServiceParameter(URL url) {
if (url == null) {
return "";
}
url = url.removeParameters(APPLICATION_KEY, GROUP_KEY, DEPRECATED_KEY, TIMESTAMP_KEY);
Map<String, String> params = getParams(url);
if (params.isEmpty()) {
return null;
}
return JsonUtils.toJson(params);
}
private static Map<String, String> getParams(URL providerURL) {
Map<String, String> params = new LinkedHashMap<>();
setDefaultParams(params, providerURL);
params.put(PORT_KEY, String.valueOf(providerURL.getPort()));
params.put(PROTOCOL_KEY, providerURL.getProtocol());
return params;
}
/**
* The revision for all exported Dubbo services from the specified {@link ServiceInstance}.
*
* @param serviceInstance the specified {@link ServiceInstance}
* @return <code>null</code> if not exits
*/
public static String getExportedServicesRevision(ServiceInstance serviceInstance) {
return Optional.ofNullable(serviceInstance.getServiceMetadata())
.map(MetadataInfo::getRevision)
.filter(StringUtils::isNotEmpty)
.orElse(serviceInstance.getMetadata(EXPORTED_SERVICES_REVISION_PROPERTY_NAME));
}
/**
* Get metadata's storage type
*
* @param registryURL the {@link URL} to connect the registry
* @return if not found in {@link URL#getParameters() parameters} of {@link URL registry URL}, return
*/
public static String getMetadataStorageType(URL registryURL) {
return registryURL.getParameter(METADATA_STORAGE_TYPE_PROPERTY_NAME, DEFAULT_METADATA_STORAGE_TYPE);
}
/**
* Get the metadata storage type specified by the peer instance.
*
* @return storage type, remote or local
*/
public static String getMetadataStorageType(ServiceInstance serviceInstance) {
Map<String, String> metadata = serviceInstance.getMetadata();
return metadata.getOrDefault(METADATA_STORAGE_TYPE_PROPERTY_NAME, DEFAULT_METADATA_STORAGE_TYPE);
}
/**
* Set the metadata storage type in specified {@link ServiceInstance service instance}
*
* @param serviceInstance {@link ServiceInstance service instance}
* @param metadataType remote or local
*/
public static void setMetadataStorageType(ServiceInstance serviceInstance, String metadataType) {
Map<String, String> metadata = serviceInstance.getMetadata();
metadata.put(METADATA_STORAGE_TYPE_PROPERTY_NAME, metadataType);
}
public static String getRemoteCluster(ServiceInstance serviceInstance) {
Map<String, String> metadata = serviceInstance.getMetadata();
return metadata.get(METADATA_CLUSTER_PROPERTY_NAME);
}
public static boolean hasEndpoints(ServiceInstance serviceInstance) {
return StringUtils.isNotEmpty(serviceInstance.getMetadata().get(ENDPOINTS));
}
public static void setEndpoints(ServiceInstance serviceInstance, Map<String, Integer> protocolPorts) {
Map<String, String> metadata = serviceInstance.getMetadata();
List<Endpoint> endpoints = new ArrayList<>();
protocolPorts.forEach((k, v) -> {
Endpoint endpoint = new Endpoint(v, k);
endpoints.add(endpoint);
});
metadata.put(ENDPOINTS, JsonUtils.toJson(endpoints));
}
/**
* Get the property value of port by the specified {@link ServiceInstance#getMetadata() the metadata of
* service instance} and protocol
*
* @param serviceInstance {@link ServiceInstance service instance}
* @param protocol the name of protocol, e.g, dubbo, rest, and so on
* @return if not found, return <code>null</code>
*/
public static Endpoint getEndpoint(ServiceInstance serviceInstance, String protocol) {
List<Endpoint> endpoints = ((DefaultServiceInstance) serviceInstance).getEndpoints();
if (endpoints != null) {
for (Endpoint endpoint : endpoints) {
if (endpoint.getProtocol().equals(protocol)) {
return endpoint;
}
}
}
return null;
}
public static void registerMetadataAndInstance(ApplicationModel applicationModel) {
LOGGER.info("Start registering instance address to registry.");
RegistryManager registryManager = applicationModel.getBeanFactory().getBean(RegistryManager.class);
// register service instance
List<ServiceDiscovery> serviceDiscoveries = registryManager.getServiceDiscoveries();
for (ServiceDiscovery serviceDiscovery : serviceDiscoveries) {
MetricsEventBus.post(
RegistryEvent.toRegisterEvent(
applicationModel, Collections.singletonList(getServiceDiscoveryName(serviceDiscovery))),
() -> {
// register service instance
serviceDiscoveries.forEach(ServiceDiscovery::register);
return null;
});
}
}
private static String getServiceDiscoveryName(ServiceDiscovery serviceDiscovery) {
return serviceDiscovery
.getUrl()
.getParameter(
RegistryConstants.REGISTRY_CLUSTER_KEY,
serviceDiscovery.getUrl().getParameter(REGISTRY_KEY));
}
public static void refreshMetadataAndInstance(ApplicationModel applicationModel) {
RegistryManager registryManager = applicationModel.getBeanFactory().getBean(RegistryManager.class);
// update service instance revision
registryManager.getServiceDiscoveries().forEach(ServiceDiscovery::update);
}
public static void unregisterMetadataAndInstance(ApplicationModel applicationModel) {
RegistryManager registryManager = applicationModel.getBeanFactory().getBean(RegistryManager.class);
registryManager.getServiceDiscoveries().forEach(serviceDiscovery -> {
try {
serviceDiscovery.unregister();
} catch (Exception ignored) {
// ignored
}
});
}
public static void customizeInstance(ServiceInstance instance, ApplicationModel applicationModel) {
ExtensionLoader<ServiceInstanceCustomizer> loader =
instance.getOrDefaultApplicationModel().getExtensionLoader(ServiceInstanceCustomizer.class);
// FIXME, sort customizer before apply
loader.getSupportedExtensionInstances().forEach(customizer -> {
// customize
customizer.customize(instance, applicationModel);
});
}
public static boolean isValidInstance(ServiceInstance instance) {
return instance != null && instance.getHost() != null && instance.getPort() != 0;
}
/**
* Set the default parameters via the specified {@link URL providerURL}
*
* @param params the parameters
* @param providerURL the provider's {@link URL}
*/
private static void setDefaultParams(Map<String, String> params, URL providerURL) {
for (String parameterName : DEFAULT_REGISTER_PROVIDER_KEYS) {
String parameterValue = providerURL.getParameter(parameterName);
if (!isBlank(parameterValue)) {
params.put(parameterName, parameterValue);
}
}
}
}
| 5,531 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceNotificationCustomizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.registry.client.ServiceInstance;
import java.util.List;
@SPI
public interface ServiceInstanceNotificationCustomizer {
void customize(List<ServiceInstance> serviceInstance);
}
| 5,532 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/StandardMetadataServiceURLBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.remoting.Constants;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static java.util.Collections.emptyMap;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.CORE_THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PORT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.RETRIES_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADPOOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.THREADS_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_MISSING_METADATA_CONFIG_PORT;
import static org.apache.dubbo.common.utils.StringUtils.isBlank;
import static org.apache.dubbo.metadata.MetadataConstants.DEFAULT_METADATA_TIMEOUT_VALUE;
import static org.apache.dubbo.metadata.MetadataConstants.METADATA_PROXY_TIMEOUT_KEY;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME;
import static org.apache.dubbo.remoting.Constants.CONNECTIONS_KEY;
/**
* Standard Dubbo provider enabling introspection service discovery mode.
*
* @see MetadataService
* @since 2.7.5
*/
public class StandardMetadataServiceURLBuilder implements MetadataServiceURLBuilder {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
public static final String NAME = "standard";
private ApplicationModel applicationModel;
private Integer metadataServicePort;
public StandardMetadataServiceURLBuilder(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
metadataServicePort = applicationModel.getCurrentConfig().getMetadataServicePort();
}
/**
* Build the {@link URL urls} from {@link ServiceInstance#getMetadata() the metadata} of {@link ServiceInstance}
*
* @param serviceInstance {@link ServiceInstance}
* @return the not-null {@link List}
*/
@Override
public List<URL> build(ServiceInstance serviceInstance) {
Map<String, String> paramsMap = getMetadataServiceURLsParams(serviceInstance);
String serviceName = serviceInstance.getServiceName();
String host = serviceInstance.getHost();
URL url;
if (paramsMap.isEmpty()) {
// ServiceInstance Metadata is empty. Happened when registry not support metadata write.
url = generateUrlWithoutMetadata(serviceName, host, serviceInstance.getPort());
} else {
url = generateWithMetadata(serviceName, host, paramsMap);
}
url = url.setScopeModel(serviceInstance.getApplicationModel().getInternalModule());
return Collections.singletonList(url);
}
private URL generateWithMetadata(String serviceName, String host, Map<String, String> params) {
String protocol = params.get(PROTOCOL_KEY);
int port = Integer.parseInt(params.get(PORT_KEY));
URLBuilder urlBuilder = new URLBuilder()
.setHost(host)
.setPort(port)
.setProtocol(protocol)
.setPath(MetadataService.class.getName())
.addParameter(
TIMEOUT_KEY,
ConfigurationUtils.get(
applicationModel, METADATA_PROXY_TIMEOUT_KEY, DEFAULT_METADATA_TIMEOUT_VALUE))
.addParameter(CONNECTIONS_KEY, 1)
.addParameter(THREADPOOL_KEY, "cached")
.addParameter(THREADS_KEY, "100")
.addParameter(CORE_THREADS_KEY, "2")
.addParameter(RETRIES_KEY, 0);
// add parameters
params.forEach(urlBuilder::addParameter);
// add the default parameters
urlBuilder.addParameter(GROUP_KEY, serviceName);
urlBuilder.addParameter(SIDE_KEY, CONSUMER);
return urlBuilder.build();
}
private URL generateUrlWithoutMetadata(String serviceName, String host, Integer instancePort) {
Integer port = metadataServicePort;
if (port == null || port < 1) {
// 1-18 - Metadata Service Port should be specified for consumer.
logger.warn(
REGISTRY_MISSING_METADATA_CONFIG_PORT,
"missing configuration of metadata service port",
"",
"Metadata Service Port is not provided. Since DNS is not able to negotiate the metadata port "
+ "between Provider and Consumer, Dubbo will try using instance port as the default metadata port.");
port = instancePort;
}
if (port == null || port < 1) {
// 1-18 - Metadata Service Port should be specified for consumer.
String message = "Metadata Service Port should be specified for consumer. "
+ "Please set dubbo.application.metadataServicePort and "
+ "make sure it has been set on provider side. "
+ "ServiceName: "
+ serviceName + " Host: " + host;
IllegalStateException illegalStateException = new IllegalStateException(message);
logger.error(
REGISTRY_MISSING_METADATA_CONFIG_PORT,
"missing configuration of metadata service port",
"",
message,
illegalStateException);
throw illegalStateException;
}
URLBuilder urlBuilder = new URLBuilder()
.setHost(host)
.setPort(port)
.setProtocol(DUBBO_PROTOCOL)
.setPath(MetadataService.class.getName())
.addParameter(
TIMEOUT_KEY,
ConfigurationUtils.get(
applicationModel, METADATA_PROXY_TIMEOUT_KEY, DEFAULT_METADATA_TIMEOUT_VALUE))
.addParameter(Constants.RECONNECT_KEY, false)
.addParameter(SIDE_KEY, CONSUMER)
.addParameter(GROUP_KEY, serviceName)
.addParameter(VERSION_KEY, MetadataService.VERSION)
.addParameter(RETRIES_KEY, 0);
// add ServiceInstance Metadata notify support
urlBuilder.addParameter("getAndListenInstanceMetadata.1.callback", true);
return urlBuilder.build();
}
/**
* Get the multiple {@link URL urls'} parameters of {@link MetadataService MetadataService's} Metadata
*
* @param serviceInstance the instance of {@link ServiceInstance}
* @return non-null {@link Map}, the key is {@link URL#getProtocol() the protocol of URL}, the value is
*/
private Map<String, String> getMetadataServiceURLsParams(ServiceInstance serviceInstance) {
Map<String, String> metadata = serviceInstance.getMetadata();
String param = metadata.get(METADATA_SERVICE_URL_PARAMS_PROPERTY_NAME);
return isBlank(param) ? emptyMap() : (Map) JsonUtils.toJavaObject(param, Map.class);
}
}
| 5,533 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ProtocolPortsMetadataCustomizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils.setEndpoints;
/**
* A Class to customize the ports of {@link Protocol protocols} into
* {@link ServiceInstance#getMetadata() the metadata of service instance}
*
* @since 2.7.5
*/
public class ProtocolPortsMetadataCustomizer implements ServiceInstanceCustomizer {
private static final ErrorTypeAwareLogger LOGGER =
LoggerFactory.getErrorTypeAwareLogger(ProtocolPortsMetadataCustomizer.class);
@Override
public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) {
MetadataInfo metadataInfo = serviceInstance.getServiceMetadata();
if (metadataInfo == null || CollectionUtils.isEmptyMap(metadataInfo.getExportedServiceURLs())) {
return;
}
Map<String, Integer> protocols = new HashMap<>();
Set<URL> urls = metadataInfo.collectExportedURLSet();
urls.forEach(url -> {
// TODO, same protocol listen on different ports will override with each other.
String protocol = url.getProtocol();
Integer oldPort = protocols.get(protocol);
int newPort = url.getPort();
if (oldPort != null && oldPort != newPort) {
LOGGER.warn(
LoggerCodeConstants.PROTOCOL_INCORRECT_PARAMETER_VALUES,
"the protocol is listening multiple ports",
"",
"Same protocol " + "[" + protocol + "]" + " listens on different ports " + "[" + oldPort + ","
+ newPort + "]" + " will override with each other" + ". The port [" + oldPort
+ "] is overridden with port [" + newPort + "].");
}
protocols.put(protocol, newPort);
});
if (protocols.size() > 0) { // set endpoints only for multi-protocol scenario
setEndpoints(serviceInstance, protocols);
}
}
}
| 5,534 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceNameMapping.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.ConfigurationUtils;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.AbstractServiceNameMapping;
import org.apache.dubbo.metadata.MappingListener;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.metadata.report.MetadataReport;
import org.apache.dubbo.metadata.report.MetadataReportInstance;
import org.apache.dubbo.registry.client.RegistryClusterIdentifier;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_PROPERTY_TYPE_MISMATCH;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_ERROR;
import static org.apache.dubbo.registry.Constants.CAS_RETRY_TIMES_KEY;
import static org.apache.dubbo.registry.Constants.CAS_RETRY_WAIT_TIME_KEY;
import static org.apache.dubbo.registry.Constants.DEFAULT_CAS_RETRY_TIMES;
import static org.apache.dubbo.registry.Constants.DEFAULT_CAS_RETRY_WAIT_TIME;
public class MetadataServiceNameMapping extends AbstractServiceNameMapping {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private static final List<String> IGNORED_SERVICE_INTERFACES =
Collections.singletonList(MetadataService.class.getName());
private final int casRetryTimes;
private final int casRetryWaitTime;
protected MetadataReportInstance metadataReportInstance;
public MetadataServiceNameMapping(ApplicationModel applicationModel) {
super(applicationModel);
metadataReportInstance = applicationModel.getBeanFactory().getBean(MetadataReportInstance.class);
casRetryTimes = ConfigurationUtils.getGlobalConfiguration(applicationModel)
.getInt(CAS_RETRY_TIMES_KEY, DEFAULT_CAS_RETRY_TIMES);
casRetryWaitTime = ConfigurationUtils.getGlobalConfiguration(applicationModel)
.getInt(CAS_RETRY_WAIT_TIME_KEY, DEFAULT_CAS_RETRY_WAIT_TIME);
}
@Override
public boolean hasValidMetadataCenter() {
return !CollectionUtils.isEmpty(
applicationModel.getApplicationConfigManager().getMetadataConfigs());
}
/**
* Simply register to all metadata center
*/
@Override
public boolean map(URL url) {
if (CollectionUtils.isEmpty(
applicationModel.getApplicationConfigManager().getMetadataConfigs())) {
logger.warn(
COMMON_PROPERTY_TYPE_MISMATCH, "", "", "No valid metadata config center found for mapping report.");
return false;
}
String serviceInterface = url.getServiceInterface();
if (IGNORED_SERVICE_INTERFACES.contains(serviceInterface)) {
return true;
}
boolean result = true;
for (Map.Entry<String, MetadataReport> entry :
metadataReportInstance.getMetadataReports(true).entrySet()) {
MetadataReport metadataReport = entry.getValue();
String appName = applicationModel.getApplicationName();
try {
if (metadataReport.registerServiceAppMapping(serviceInterface, appName, url)) {
// MetadataReport support directly register service-app mapping
continue;
}
boolean succeeded = false;
int currentRetryTimes = 1;
String newConfigContent = appName;
do {
ConfigItem configItem = metadataReport.getConfigItem(serviceInterface, DEFAULT_MAPPING_GROUP);
String oldConfigContent = configItem.getContent();
if (StringUtils.isNotEmpty(oldConfigContent)) {
String[] oldAppNames = oldConfigContent.split(",");
if (oldAppNames.length > 0) {
for (String oldAppName : oldAppNames) {
if (oldAppName.equals(appName)) {
succeeded = true;
break;
}
}
}
if (succeeded) {
break;
}
newConfigContent = oldConfigContent + COMMA_SEPARATOR + appName;
}
succeeded = metadataReport.registerServiceAppMapping(
serviceInterface, DEFAULT_MAPPING_GROUP, newConfigContent, configItem.getTicket());
if (!succeeded) {
int waitTime = ThreadLocalRandom.current().nextInt(casRetryWaitTime);
logger.info("Failed to publish service name mapping to metadata center by cas operation. "
+ "Times: "
+ currentRetryTimes + ". " + "Next retry delay: "
+ waitTime + ". " + "Service Interface: "
+ serviceInterface + ". " + "Origin Content: "
+ oldConfigContent + ". " + "Ticket: "
+ configItem.getTicket() + ". " + "Excepted context: "
+ newConfigContent);
Thread.sleep(waitTime);
}
} while (!succeeded && currentRetryTimes++ <= casRetryTimes);
if (!succeeded) {
result = false;
}
} catch (Exception e) {
result = false;
logger.warn(
INTERNAL_ERROR,
"unknown error in registry module",
"",
"Failed registering mapping to remote." + metadataReport,
e);
}
}
return result;
}
@Override
public Set<String> get(URL url) {
String serviceInterface = url.getServiceInterface();
String registryCluster = getRegistryCluster(url);
MetadataReport metadataReport = metadataReportInstance.getMetadataReport(registryCluster);
if (metadataReport == null) {
return Collections.emptySet();
}
return metadataReport.getServiceAppMapping(serviceInterface, url);
}
@Override
public Set<String> getAndListen(URL url, MappingListener mappingListener) {
String serviceInterface = url.getServiceInterface();
// randomly pick one metadata report is ok for it's guaranteed all metadata report will have the same mapping
// data.
String registryCluster = getRegistryCluster(url);
MetadataReport metadataReport = metadataReportInstance.getMetadataReport(registryCluster);
if (metadataReport == null) {
return Collections.emptySet();
}
return metadataReport.getServiceAppMapping(serviceInterface, mappingListener, url);
}
@Override
protected void removeListener(URL url, MappingListener mappingListener) {
String serviceInterface = url.getServiceInterface();
// randomly pick one metadata report is ok for it's guaranteed each metadata report will have the same mapping
// content.
String registryCluster = getRegistryCluster(url);
MetadataReport metadataReport = metadataReportInstance.getMetadataReport(registryCluster);
if (metadataReport == null) {
return;
}
metadataReport.removeServiceAppMappingListener(serviceInterface, mappingListener);
}
protected String getRegistryCluster(URL url) {
String registryCluster = RegistryClusterIdentifier.getExtension(url).providerKey(url);
if (registryCluster == null) {
registryCluster = DEFAULT_KEY;
}
int i = registryCluster.indexOf(",");
if (i > 0) {
registryCluster = registryCluster.substring(0, i);
}
return registryCluster;
}
}
| 5,535 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/ServiceInstanceMetadataCustomizer.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.infra.InfraAdapter;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstanceCustomizer;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
/**
* <p>Intercepting instance to load instance-level params from different sources before being registered into registry.</p>
*
* The sources can be one or both of the following:
* <ul>
* <li>os environment</li>
* <li>vm options</li>
* </ul>
*
* So, finally, the keys left in order will be:
* <ul>
* <li>all keys specified by sources above</li>
* <li>keys found in metadata info</li>
* </ul>
*
*
*/
public class ServiceInstanceMetadataCustomizer implements ServiceInstanceCustomizer {
@Override
public void customize(ServiceInstance serviceInstance, ApplicationModel applicationModel) {
MetadataInfo metadataInfo = serviceInstance.getServiceMetadata();
if (metadataInfo == null || CollectionUtils.isEmptyMap(metadataInfo.getServices())) {
return;
}
// try to load instance params that do not appear in service urls
// TODO, duplicate snippet in ApplicationConfig
Map<String, String> extraParameters = Collections.emptyMap();
Set<InfraAdapter> adapters =
applicationModel.getExtensionLoader(InfraAdapter.class).getSupportedExtensionInstances();
if (CollectionUtils.isNotEmpty(adapters)) {
Map<String, String> inputParameters = new HashMap<>();
inputParameters.put(APPLICATION_KEY, applicationModel.getApplicationName());
for (InfraAdapter adapter : adapters) {
extraParameters = adapter.getExtraAttributes(inputParameters);
}
}
serviceInstance.getMetadata().putAll(extraParameters);
if (CollectionUtils.isNotEmptyMap(metadataInfo.getInstanceParams())) {
serviceInstance.getMetadata().putAll(metadataInfo.getInstanceParams());
}
}
}
| 5,536 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceDelegation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.resource.Disposable;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.InstanceMetadataChangedListener;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.metadata.MetadataService;
import org.apache.dubbo.registry.client.ServiceDiscovery;
import org.apache.dubbo.registry.support.RegistryManager;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static java.util.Collections.emptySortedSet;
import static java.util.Collections.unmodifiableSortedSet;
import static org.apache.dubbo.common.URL.buildKey;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_FAILED_LOAD_METADATA;
import static org.apache.dubbo.common.utils.CollectionUtils.isEmpty;
/**
* Implementation providing remote RPC service to facilitate the query of metadata information.
*/
public class MetadataServiceDelegation implements MetadataService, Disposable {
ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private final ApplicationModel applicationModel;
private final RegistryManager registryManager;
private ConcurrentMap<String, InstanceMetadataChangedListener> instanceMetadataChangedListenerMap =
new ConcurrentHashMap<>();
private URL url;
// works only for DNS service discovery
private String instanceMetadata;
public MetadataServiceDelegation(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
registryManager = RegistryManager.getInstance(applicationModel);
}
/**
* Gets the current Dubbo Service name
*
* @return non-null
*/
@Override
public String serviceName() {
return ApplicationModel.ofNullable(applicationModel).getApplicationName();
}
@Override
public URL getMetadataURL() {
return url;
}
public void setMetadataURL(URL url) {
this.url = url;
}
@Override
public SortedSet<String> getSubscribedURLs() {
return getAllUnmodifiableSubscribedURLs();
}
private SortedSet<String> getAllUnmodifiableServiceURLs() {
SortedSet<URL> bizURLs = new TreeSet<>(URLComparator.INSTANCE);
List<ServiceDiscovery> serviceDiscoveries = registryManager.getServiceDiscoveries();
for (ServiceDiscovery sd : serviceDiscoveries) {
MetadataInfo metadataInfo = sd.getLocalMetadata();
Map<String, SortedSet<URL>> serviceURLs = metadataInfo.getExportedServiceURLs();
if (serviceURLs == null) {
continue;
}
for (Map.Entry<String, SortedSet<URL>> entry : serviceURLs.entrySet()) {
SortedSet<URL> urls = entry.getValue();
if (urls != null) {
for (URL url : urls) {
if (!MetadataService.class.getName().equals(url.getServiceInterface())) {
bizURLs.add(url);
}
}
}
}
}
return MetadataService.toSortedStrings(bizURLs);
}
private SortedSet<String> getAllUnmodifiableSubscribedURLs() {
SortedSet<URL> bizURLs = new TreeSet<>(URLComparator.INSTANCE);
List<ServiceDiscovery> serviceDiscoveries = registryManager.getServiceDiscoveries();
for (ServiceDiscovery sd : serviceDiscoveries) {
MetadataInfo metadataInfo = sd.getLocalMetadata();
Map<String, SortedSet<URL>> serviceURLs = metadataInfo.getSubscribedServiceURLs();
if (serviceURLs == null) {
continue;
}
for (Map.Entry<String, SortedSet<URL>> entry : serviceURLs.entrySet()) {
SortedSet<URL> urls = entry.getValue();
if (urls != null) {
for (URL url : urls) {
if (!MetadataService.class.getName().equals(url.getServiceInterface())) {
bizURLs.add(url);
}
}
}
}
}
return MetadataService.toSortedStrings(bizURLs);
}
@Override
public SortedSet<String> getExportedURLs(String serviceInterface, String group, String version, String protocol) {
if (ALL_SERVICE_INTERFACES.equals(serviceInterface)) {
return getAllUnmodifiableServiceURLs();
}
String serviceKey = buildKey(serviceInterface, group, version);
return unmodifiableSortedSet(getServiceURLs(getAllServiceURLs(), serviceKey, protocol));
}
private Map<String, SortedSet<URL>> getAllServiceURLs() {
List<ServiceDiscovery> serviceDiscoveries = registryManager.getServiceDiscoveries();
Map<String, SortedSet<URL>> allServiceURLs = new HashMap<>();
for (ServiceDiscovery sd : serviceDiscoveries) {
MetadataInfo metadataInfo = sd.getLocalMetadata();
Map<String, SortedSet<URL>> serviceURLs = metadataInfo.getExportedServiceURLs();
allServiceURLs.putAll(serviceURLs);
}
return allServiceURLs;
}
@Override
public Set<URL> getExportedServiceURLs() {
Set<URL> set = new HashSet<>();
registryManager.getRegistries();
for (Map.Entry<String, SortedSet<URL>> entry : getAllServiceURLs().entrySet()) {
set.addAll(entry.getValue());
}
return set;
}
@Override
public String getServiceDefinition(String interfaceName, String version, String group) {
return "";
}
@Override
public String getServiceDefinition(String serviceKey) {
return "";
}
@Override
public MetadataInfo getMetadataInfo(String revision) {
if (StringUtils.isEmpty(revision)) {
return null;
}
for (ServiceDiscovery sd : registryManager.getServiceDiscoveries()) {
MetadataInfo metadataInfo = sd.getLocalMetadata(revision);
if (metadataInfo != null && revision.equals(metadataInfo.getRevision())) {
return metadataInfo;
}
}
if (logger.isWarnEnabled()) {
logger.warn(REGISTRY_FAILED_LOAD_METADATA, "", "", "metadata not found for revision: " + revision);
}
return null;
}
@Override
public List<MetadataInfo> getMetadataInfos() {
List<MetadataInfo> metadataInfos = new ArrayList<>();
for (ServiceDiscovery sd : registryManager.getServiceDiscoveries()) {
metadataInfos.add(sd.getLocalMetadata());
}
return metadataInfos;
}
@Override
public void exportInstanceMetadata(String instanceMetadata) {
this.instanceMetadata = instanceMetadata;
}
@Override
public Map<String, InstanceMetadataChangedListener> getInstanceMetadataChangedListenerMap() {
return instanceMetadataChangedListenerMap;
}
@Override
public String getAndListenInstanceMetadata(String consumerId, InstanceMetadataChangedListener listener) {
instanceMetadataChangedListenerMap.put(consumerId, listener);
return instanceMetadata;
}
private SortedSet<String> getServiceURLs(
Map<String, SortedSet<URL>> exportedServiceURLs, String serviceKey, String protocol) {
SortedSet<URL> serviceURLs = exportedServiceURLs.get(serviceKey);
if (isEmpty(serviceURLs)) {
return emptySortedSet();
}
return MetadataService.toSortedStrings(serviceURLs.stream().filter(url -> isAcceptableProtocol(protocol, url)));
}
private boolean isAcceptableProtocol(String protocol, URL url) {
return protocol == null
|| protocol.equals(url.getParameter(PROTOCOL_KEY))
|| protocol.equals(url.getProtocol());
}
@Override
public void destroy() {}
static class URLComparator implements Comparator<URL> {
public static final URLComparator INSTANCE = new URLComparator();
@Override
public int compare(URL o1, URL o2) {
return o1.toFullString().compareTo(o2.toFullString());
}
}
}
| 5,537 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/MetadataServiceURLBuilder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.registry.client.ServiceInstance;
import java.util.List;
/**
* Used to build metadata service url from ServiceInstance.
*
* @since 2.7.5
*/
@SPI
public interface MetadataServiceURLBuilder {
/**
* Build the {@link URL URLs} from the specified {@link ServiceInstance}
*
* @param serviceInstance {@link ServiceInstance}
* @return TODO, usually, we generate one metadata url from one instance. There's no scenario to return a metadata url list.
*/
List<URL> build(ServiceInstance serviceInstance);
}
| 5,538 |
0 | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata | Create_ds/dubbo/dubbo-registry/dubbo-registry-api/src/main/java/org/apache/dubbo/registry/client/metadata/store/MetaCacheManager.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.client.metadata.store;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metadata.AbstractCacheManager;
import org.apache.dubbo.metadata.MetadataInfo;
import org.apache.dubbo.rpc.model.ScopeModel;
import java.util.concurrent.ScheduledExecutorService;
/**
* Metadata cache with limited size that uses LRU expiry policy.
*/
public class MetaCacheManager extends AbstractCacheManager<MetadataInfo> {
private static final String DEFAULT_FILE_NAME = ".metadata";
private static final int DEFAULT_ENTRY_SIZE = 100;
public static MetaCacheManager getInstance(ScopeModel scopeModel) {
return scopeModel.getBeanFactory().getOrRegisterBean(MetaCacheManager.class);
}
public MetaCacheManager(boolean enableFileCache, String registryName, ScheduledExecutorService executorService) {
String filePath = System.getProperty("dubbo.meta.cache.filePath");
String fileName = System.getProperty("dubbo.meta.cache.fileName");
if (StringUtils.isEmpty(fileName)) {
fileName = DEFAULT_FILE_NAME;
}
if (StringUtils.isNotEmpty(registryName)) {
fileName = fileName + "." + registryName;
}
String rawEntrySize = System.getProperty("dubbo.meta.cache.entrySize");
int entrySize = StringUtils.parseInteger(rawEntrySize);
entrySize = (entrySize == 0 ? DEFAULT_ENTRY_SIZE : entrySize);
String rawMaxFileSize = System.getProperty("dubbo.meta.cache.maxFileSize");
long maxFileSize = StringUtils.parseLong(rawMaxFileSize);
init(enableFileCache, filePath, fileName, entrySize, maxFileSize, 60, executorService);
}
// for unit test only
public MetaCacheManager() {
this(true, "", null);
}
@Override
protected MetadataInfo toValueType(String value) {
return JsonUtils.toJavaObject(value, MetadataInfo.class);
}
@Override
protected String getName() {
return "meta";
}
}
| 5,539 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidatorTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget;
import org.apache.dubbo.validation.support.jvalidation.mock.ValidationParameter;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
class JValidatorTest {
@Test
void testItWithNonExistMethod() {
Assertions.assertThrows(NoSuchMethodException.class, () -> {
URL url = URL.valueOf(
"test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate("nonExistingMethod", new Class<?>[] {String.class}, new Object[] {"arg1"});
});
}
@Test
void testItWithExistMethod() throws Exception {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate("someMethod1", new Class<?>[] {String.class}, new Object[] {"anything"});
}
@Test
void testItWhenItViolatedConstraint() {
Assertions.assertThrows(ValidationException.class, () -> {
URL url = URL.valueOf(
"test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate(
"someMethod2", new Class<?>[] {ValidationParameter.class}, new Object[] {new ValidationParameter()
});
});
}
@Test
void testItWhenItMeetsConstraint() throws Exception {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate("someMethod2", new Class<?>[] {ValidationParameter.class}, new Object[] {
new ValidationParameter("NotBeNull")
});
}
@Test
void testItWithArrayArg() throws Exception {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate("someMethod3", new Class<?>[] {ValidationParameter[].class}, new Object[] {
new ValidationParameter[] {new ValidationParameter("parameter")}
});
}
@Test
void testItWithCollectionArg() throws Exception {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate(
"someMethod4", new Class<?>[] {List.class}, new Object[] {Collections.singletonList("parameter")});
}
@Test
void testItWithMapArg() throws Exception {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
Map<String, String> map = new HashMap<>();
map.put("key", "value");
jValidator.validate("someMethod5", new Class<?>[] {Map.class}, new Object[] {map});
}
@Test
void testItWithPrimitiveArg() {
Assertions.assertThrows(ValidationException.class, () -> {
URL url = URL.valueOf(
"test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate("someMethod6", new Class<?>[] {Integer.class, String.class, Long.class}, new Object[] {
null, null, null
});
});
}
@Test
void testItWithPrimitiveArgWithProvidedMessage() {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
try {
jValidator.validate("someMethod6", new Class<?>[] {Integer.class, String.class, Long.class}, new Object[] {
null, "", null
});
Assertions.fail();
} catch (Exception e) {
assertThat(e.getMessage(), containsString("string must not be blank"));
assertThat(e.getMessage(), containsString("longValue must not be null"));
}
}
@Test
void testItWithPartialParameterValidation() {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
try {
jValidator.validate("someMethod6", new Class<?>[] {Integer.class, String.class, Long.class}, new Object[] {
null, "", null
});
Assertions.fail();
} catch (Exception e) {
assertThat(e, instanceOf(ConstraintViolationException.class));
ConstraintViolationException e1 = (ConstraintViolationException) e;
assertThat(e1.getConstraintViolations().size(), is(2));
}
}
@Test
void testItWithNestedParameterValidationWithNullParam() {
Assertions.assertThrows(ValidationException.class, () -> {
URL url = URL.valueOf(
"test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
jValidator.validate(
"someMethod7", new Class<?>[] {JValidatorTestTarget.BaseParam.class}, new Object[] {null});
});
}
@Test
void testItWithNestedParameterValidationWithNullNestedParam() {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
try {
JValidatorTestTarget.BaseParam<JValidatorTestTarget.Param> param = new JValidatorTestTarget.BaseParam<>();
jValidator.validate(
"someMethod7", new Class<?>[] {JValidatorTestTarget.BaseParam.class}, new Object[] {param});
Assertions.fail();
} catch (Exception e) {
assertThat(e, instanceOf(ConstraintViolationException.class));
ConstraintViolationException e1 = (ConstraintViolationException) e;
assertThat(e1.getConstraintViolations().size(), is(1));
assertThat(e1.getMessage(), containsString("body must not be null"));
}
}
@Test
void testItWithNestedParameterValidationWithNullNestedParams() {
URL url =
URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.mock.JValidatorTestTarget");
JValidator jValidator = new JValidator(url);
try {
JValidatorTestTarget.BaseParam<JValidatorTestTarget.Param> param = new JValidatorTestTarget.BaseParam<>();
param.setBody(new JValidatorTestTarget.Param());
jValidator.validate(
"someMethod7", new Class<?>[] {JValidatorTestTarget.BaseParam.class}, new Object[] {param});
Assertions.fail();
} catch (Exception e) {
assertThat(e, instanceOf(ConstraintViolationException.class));
ConstraintViolationException e1 = (ConstraintViolationException) e;
assertThat(e1.getConstraintViolations().size(), is(1));
assertThat(e1.getMessage(), containsString("name must not be null"));
}
}
}
| 5,540 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/JValidationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.validation.Validation;
import org.apache.dubbo.validation.Validator;
import javax.validation.ValidationException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
class JValidationTest {
@Test
void testReturnTypeWithInvalidValidationProvider() {
Assertions.assertThrows(ValidationException.class, () -> {
Validation jValidation = new JValidation();
URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.JValidation?"
+ "jvalidation=org.apache.dubbo.validation.Validation");
jValidation.getValidator(url);
});
}
@Test
void testReturnTypeWithDefaultValidatorProvider() {
Validation jValidation = new JValidation();
URL url = URL.valueOf("test://test:11/org.apache.dubbo.validation.support.jvalidation.JValidation");
Validator validator = jValidation.getValidator(url);
assertThat(validator instanceof JValidator, is(true));
}
}
| 5,541 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/ValidationParameter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation.mock;
import javax.validation.constraints.NotNull;
public class ValidationParameter {
@NotNull
private String parameter;
public ValidationParameter() {}
public ValidationParameter(String parameter) {
this.parameter = parameter;
}
}
| 5,542 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/support/jvalidation/mock/JValidatorTestTarget.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation.mock;
import org.apache.dubbo.validation.MethodValidated;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import org.hibernate.validator.constraints.NotBlank;
public interface JValidatorTestTarget {
@MethodValidated
void someMethod1(String anything);
@MethodValidated(Test2.class)
void someMethod2(@NotNull ValidationParameter validationParameter);
void someMethod3(ValidationParameter[] parameters);
void someMethod4(List<String> strings);
void someMethod5(Map<String, String> map);
void someMethod6(
Integer intValue,
@NotBlank(message = "string must not be blank") String string,
@NotNull(message = "longValue must not be null") Long longValue);
void someMethod7(@NotNull BaseParam<Param> baseParam);
@interface Test2 {}
class BaseParam<T> {
@Valid
@NotNull(message = "body must not be null")
private T body;
public T getBody() {
return body;
}
public void setBody(T body) {
this.body = body;
}
}
class Param {
@NotNull(message = "name must not be null")
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| 5,543 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/test/java/org/apache/dubbo/validation/filter/ValidationFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.validation.Validation;
import org.apache.dubbo.validation.Validator;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class ValidationFilterTest {
private Invoker<?> invoker = mock(Invoker.class);
private Validation validation = mock(Validation.class);
private Validator validator = mock(Validator.class);
private RpcInvocation invocation = mock(RpcInvocation.class);
private ValidationFilter validationFilter;
@BeforeEach
public void setUp() {
this.validationFilter = new ValidationFilter();
}
@Test
void testItWithNotExistClass() {
URL url = URL.valueOf("test://test:11/test?validation=true");
given(validation.getValidator(url)).willThrow(new IllegalStateException("Not found class test, cause: test"));
given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
given(invoker.getUrl()).willReturn(url);
given(invocation.getMethodName()).willReturn("echo1");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"arg1"});
validationFilter.setValidation(validation);
Result result = validationFilter.invoke(invoker, invocation);
assertThat(result.getException().getMessage(), is("Not found class test, cause: test"));
}
@Test
void testItWithExistClass() {
URL url = URL.valueOf("test://test:11/test?validation=true");
given(validation.getValidator(url)).willReturn(validator);
given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
given(invoker.getUrl()).willReturn(url);
given(invocation.getMethodName()).willReturn("echo1");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"arg1"});
validationFilter.setValidation(validation);
Result result = validationFilter.invoke(invoker, invocation);
assertThat(String.valueOf(result.getValue()), is("success"));
}
@Test
void testItWithoutUrlParameters() {
URL url = URL.valueOf("test://test:11/test");
given(validation.getValidator(url)).willReturn(validator);
given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
given(invoker.getUrl()).willReturn(url);
given(invocation.getMethodName()).willReturn("echo1");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"arg1"});
validationFilter.setValidation(validation);
Result result = validationFilter.invoke(invoker, invocation);
assertThat(String.valueOf(result.getValue()), is("success"));
}
@Test
void testItWhileMethodNameStartWithDollar() {
URL url = URL.valueOf("test://test:11/test");
given(validation.getValidator(url)).willReturn(validator);
given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
given(invoker.getUrl()).willReturn(url);
given(invocation.getMethodName()).willReturn("$echo1");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"arg1"});
validationFilter.setValidation(validation);
Result result = validationFilter.invoke(invoker, invocation);
assertThat(String.valueOf(result.getValue()), is("success"));
}
@Test
void testItWhileThrowoutRpcException() {
Assertions.assertThrows(RpcException.class, () -> {
URL url = URL.valueOf("test://test:11/test?validation=true");
given(validation.getValidator(url)).willThrow(new RpcException("rpc exception"));
given(invoker.invoke(invocation)).willReturn(new AppResponse("success"));
given(invoker.getUrl()).willReturn(url);
given(invocation.getMethodName()).willReturn("echo1");
given(invocation.getParameterTypes()).willReturn(new Class<?>[] {String.class});
given(invocation.getArguments()).willReturn(new Object[] {"arg1"});
validationFilter.setValidation(validation);
validationFilter.invoke(invoker, invocation);
});
}
}
| 5,544 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/MethodValidated.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Method grouping validation.
* <p>
* Scenario: this annotation can be used on interface's method when need to check against group before invoke the method
* For example: <pre> @MethodValidated({Save.class, Update.class})
* void relatedQuery(ValidationParameter parameter);
* </pre>
* It means both Save group and Update group are needed to check when method relatedQuery is invoked.
* </p>
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MethodValidated {
Class<?>[] value() default {};
}
| 5,545 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY;
/**
* Instance of Validation interface provide instance of {@link Validator} based on the value of <b>validation</b> attribute.
*/
@SPI("jvalidation")
public interface Validation {
/**
* Return the instance of {@link Validator} for a given url.
* @param url Invocation url
* @return Instance of {@link Validator}
*/
@Adaptive(VALIDATION_KEY)
Validator getValidator(URL url);
}
| 5,546 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/Validator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation;
/**
* Instance of validator class is an extension to perform validation on method input parameter before the actual method invocation.
*
*/
public interface Validator {
void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception;
}
| 5,547 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/AbstractValidation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.validation.Validation;
import org.apache.dubbo.validation.Validator;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* AbstractValidation is abstract class for Validation interface. It helps low level Validation implementation classes
* by performing common task e.g. key formation, storing instance of validation class to avoid creation of unnecessary
* copy of validation instance and faster execution.
*
* @see Validation
* @see Validator
*/
public abstract class AbstractValidation implements Validation {
private final ConcurrentMap<String, Validator> validators = new ConcurrentHashMap<>();
@Override
public Validator getValidator(URL url) {
String key = url.toFullString();
Validator validator = validators.get(key);
if (validator == null) {
validators.put(key, createValidator(url));
validator = validators.get(key);
}
return validator;
}
protected abstract Validator createValidator(URL url);
}
| 5,548 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidatorNew.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.bytecode.ClassGenerator;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.validation.MethodValidated;
import org.apache.dubbo.validation.Validator;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtNewConstructor;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.ArrayMemberValue;
import javassist.bytecode.annotation.BooleanMemberValue;
import javassist.bytecode.annotation.ByteMemberValue;
import javassist.bytecode.annotation.CharMemberValue;
import javassist.bytecode.annotation.ClassMemberValue;
import javassist.bytecode.annotation.DoubleMemberValue;
import javassist.bytecode.annotation.EnumMemberValue;
import javassist.bytecode.annotation.FloatMemberValue;
import javassist.bytecode.annotation.IntegerMemberValue;
import javassist.bytecode.annotation.LongMemberValue;
import javassist.bytecode.annotation.MemberValue;
import javassist.bytecode.annotation.ShortMemberValue;
import javassist.bytecode.annotation.StringMemberValue;
import jakarta.validation.Constraint;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import jakarta.validation.Validation;
import jakarta.validation.ValidatorFactory;
import jakarta.validation.groups.Default;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION;
/**
* Implementation of JValidationNew. JValidationNew is invoked if configuration validation attribute value is 'jvalidationNew'.
* <pre>
* e.g. <dubbo:method name="save" validation="jvalidationNew" />
* </pre>
*/
public class JValidatorNew implements Validator {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JValidatorNew.class);
private final Class<?> clazz;
private final Map<String, Class<?>> methodClassMap;
private final jakarta.validation.Validator validator;
@SuppressWarnings({"unchecked", "rawtypes"})
public JValidatorNew(URL url) {
this.clazz = ReflectUtils.forName(url.getServiceInterface());
String jvalidation = url.getParameter("jvalidationNew");
ValidatorFactory factory;
if (StringUtils.isNotEmpty(jvalidation)) {
factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation))
.configure()
.buildValidatorFactory();
} else {
factory = Validation.buildDefaultValidatorFactory();
}
this.validator = factory.getValidator();
this.methodClassMap = new ConcurrentHashMap<>();
}
private static Object getMethodParameterBean(Class<?> clazz, Method method, Object[] args) {
if (!hasConstraintParameter(method)) {
return null;
}
try {
String parameterClassName = generateMethodParameterClassName(clazz, method);
Class<?> parameterClass;
try {
parameterClass = Class.forName(parameterClassName, true, clazz.getClassLoader());
} catch (ClassNotFoundException e) {
parameterClass = generateMethodParameterClass(clazz, method, parameterClassName);
}
Object parameterBean = parameterClass.getDeclaredConstructor().newInstance();
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
Field field = parameterClass.getField(parameters[i].getName());
field.set(parameterBean, args[i]);
}
return parameterBean;
} catch (Throwable e) {
logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", e.getMessage(), e);
return null;
}
}
/**
* try to generate methodParameterClass.
*
* @param clazz interface class
* @param method invoke method
* @param parameterClassName generated parameterClassName
* @return Class<?> generated methodParameterClass
*/
private static Class<?> generateMethodParameterClass(Class<?> clazz, Method method, String parameterClassName)
throws Exception {
ClassPool pool = ClassGenerator.getClassPool(clazz.getClassLoader());
synchronized (parameterClassName.intern()) {
CtClass ctClass = null;
try {
ctClass = pool.getCtClass(parameterClassName);
} catch (NotFoundException ignore) {
}
if (null == ctClass) {
ctClass = pool.makeClass(parameterClassName);
ClassFile classFile = ctClass.getClassFile();
ctClass.addConstructor(CtNewConstructor.defaultConstructor(pool.getCtClass(parameterClassName)));
// parameter fields
Parameter[] parameters = method.getParameters();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameters.length; i++) {
Annotation[] annotations = parameterAnnotations[i];
AnnotationsAttribute attribute =
new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag);
for (Annotation annotation : annotations) {
if (annotation.annotationType().isAnnotationPresent(Constraint.class)) {
javassist.bytecode.annotation.Annotation ja = new javassist.bytecode.annotation.Annotation(
classFile.getConstPool(),
pool.getCtClass(annotation.annotationType().getName()));
Method[] members = annotation.annotationType().getMethods();
for (Method member : members) {
if (Modifier.isPublic(member.getModifiers())
&& member.getParameterTypes().length == 0
&& member.getDeclaringClass() == annotation.annotationType()) {
Object value = member.invoke(annotation);
if (null != value) {
MemberValue memberValue = createMemberValue(
classFile.getConstPool(),
pool.get(member.getReturnType().getName()),
value);
ja.addMemberValue(member.getName(), memberValue);
}
}
}
attribute.addAnnotation(ja);
}
}
Parameter parameter = parameters[i];
Class<?> type = parameter.getType();
String fieldName = parameter.getName();
CtField ctField = CtField.make(
"public " + type.getCanonicalName() + " " + fieldName + ";",
pool.getCtClass(parameterClassName));
ctField.getFieldInfo().addAttribute(attribute);
ctClass.addField(ctField);
}
return pool.toClass(ctClass, clazz, clazz.getClassLoader(), clazz.getProtectionDomain());
} else {
return Class.forName(parameterClassName, true, clazz.getClassLoader());
}
}
}
private static String generateMethodParameterClassName(Class<?> clazz, Method method) {
StringBuilder builder = new StringBuilder()
.append(clazz.getName())
.append('_')
.append(toUpperMethodName(method.getName()))
.append("Parameter");
Class<?>[] parameterTypes = method.getParameterTypes();
for (Class<?> parameterType : parameterTypes) {
// In order to ensure that the parameter class can be generated correctly,
// replace "." with "_" to make the package name of the generated parameter class
// consistent with the package name of the actual parameter class.
builder.append('_').append(parameterType.getName().replace(".", "_"));
}
return builder.toString();
}
private static boolean hasConstraintParameter(Method method) {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (Annotation[] annotations : parameterAnnotations) {
for (Annotation annotation : annotations) {
if (annotation.annotationType().isAnnotationPresent(Constraint.class)) {
return true;
}
}
}
return false;
}
private static String toUpperMethodName(String methodName) {
return methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
}
// Copy from javassist.bytecode.annotation.Annotation.createMemberValue(ConstPool, CtClass);
private static MemberValue createMemberValue(ConstPool cp, CtClass type, Object value) throws NotFoundException {
MemberValue memberValue = javassist.bytecode.annotation.Annotation.createMemberValue(cp, type);
if (memberValue instanceof BooleanMemberValue) {
((BooleanMemberValue) memberValue).setValue((Boolean) value);
} else if (memberValue instanceof ByteMemberValue) {
((ByteMemberValue) memberValue).setValue((Byte) value);
} else if (memberValue instanceof CharMemberValue) {
((CharMemberValue) memberValue).setValue((Character) value);
} else if (memberValue instanceof ShortMemberValue) {
((ShortMemberValue) memberValue).setValue((Short) value);
} else if (memberValue instanceof IntegerMemberValue) {
((IntegerMemberValue) memberValue).setValue((Integer) value);
} else if (memberValue instanceof LongMemberValue) {
((LongMemberValue) memberValue).setValue((Long) value);
} else if (memberValue instanceof FloatMemberValue) {
((FloatMemberValue) memberValue).setValue((Float) value);
} else if (memberValue instanceof DoubleMemberValue) {
((DoubleMemberValue) memberValue).setValue((Double) value);
} else if (memberValue instanceof ClassMemberValue) {
((ClassMemberValue) memberValue).setValue(((Class<?>) value).getName());
} else if (memberValue instanceof StringMemberValue) {
((StringMemberValue) memberValue).setValue((String) value);
} else if (memberValue instanceof EnumMemberValue) {
((EnumMemberValue) memberValue).setValue(((Enum<?>) value).name());
}
/* else if (memberValue instanceof AnnotationMemberValue) */
else if (memberValue instanceof ArrayMemberValue) {
CtClass arrayType = type.getComponentType();
int len = Array.getLength(value);
MemberValue[] members = new MemberValue[len];
for (int i = 0; i < len; i++) {
members[i] = createMemberValue(cp, arrayType, Array.get(value, i));
}
((ArrayMemberValue) memberValue).setValue(members);
}
return memberValue;
}
@Override
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
List<Class<?>> groups = new ArrayList<>();
Class<?> methodClass = methodClass(methodName);
if (methodClass != null) {
groups.add(methodClass);
}
Method method = clazz.getMethod(methodName, parameterTypes);
Class<?>[] methodClasses;
if (method.isAnnotationPresent(MethodValidated.class)) {
methodClasses = method.getAnnotation(MethodValidated.class).value();
groups.addAll(Arrays.asList(methodClasses));
}
// add into default group
groups.add(0, Default.class);
groups.add(1, clazz);
// convert list to array
Class<?>[] classGroups = groups.toArray(new Class[0]);
Set<ConstraintViolation<?>> violations = new HashSet<>();
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
violations.addAll(validator.validate(parameterBean, classGroups));
}
for (Object arg : arguments) {
validate(violations, arg, classGroups);
}
if (!violations.isEmpty()) {
logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: "
+ violations);
throw new ConstraintViolationException(
"Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: "
+ violations,
violations);
}
}
private Class<?> methodClass(String methodName) {
Class<?> methodClass = null;
String methodClassName = clazz.getName() + "$" + toUpperMethodName(methodName);
Class<?> cached = methodClassMap.get(methodClassName);
if (cached != null) {
return cached == clazz ? null : cached;
}
try {
methodClass =
Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
methodClassMap.put(methodClassName, methodClass);
} catch (ClassNotFoundException e) {
methodClassMap.put(methodClassName, clazz);
}
return methodClass;
}
private void validate(Set<ConstraintViolation<?>> violations, Object arg, Class<?>... groups) {
if (arg != null && !ReflectUtils.isPrimitives(arg.getClass())) {
if (arg instanceof Object[]) {
for (Object item : (Object[]) arg) {
validate(violations, item, groups);
}
} else if (arg instanceof Collection) {
for (Object item : (Collection<?>) arg) {
validate(violations, item, groups);
}
} else if (arg instanceof Map) {
for (Map.Entry<?, ?> entry : ((Map<?, ?>) arg).entrySet()) {
validate(violations, entry.getKey(), groups);
validate(violations, entry.getValue(), groups);
}
} else {
violations.addAll(validator.validate(arg, groups));
}
}
}
}
| 5,549 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidation.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.validation.Validator;
import org.apache.dubbo.validation.support.AbstractValidation;
/**
* Creates a new instance of {@link Validator} using input argument url.
* @see AbstractValidation
* @see Validator
*/
public class JValidation extends AbstractValidation {
/**
* Return new instance of {@link JValidator}
* @param url Valid URL instance
* @return Instance of JValidator
*/
@Override
protected Validator createValidator(URL url) {
return new JValidator(url);
}
}
| 5,550 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.bytecode.ClassGenerator;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.validation.MethodValidated;
import org.apache.dubbo.validation.Validator;
import javax.validation.Constraint;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import javax.validation.groups.Default;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtNewConstructor;
import javassist.Modifier;
import javassist.NotFoundException;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
import javassist.bytecode.ConstPool;
import javassist.bytecode.annotation.ArrayMemberValue;
import javassist.bytecode.annotation.BooleanMemberValue;
import javassist.bytecode.annotation.ByteMemberValue;
import javassist.bytecode.annotation.CharMemberValue;
import javassist.bytecode.annotation.ClassMemberValue;
import javassist.bytecode.annotation.DoubleMemberValue;
import javassist.bytecode.annotation.EnumMemberValue;
import javassist.bytecode.annotation.FloatMemberValue;
import javassist.bytecode.annotation.IntegerMemberValue;
import javassist.bytecode.annotation.LongMemberValue;
import javassist.bytecode.annotation.MemberValue;
import javassist.bytecode.annotation.ShortMemberValue;
import javassist.bytecode.annotation.StringMemberValue;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FILTER_VALIDATION_EXCEPTION;
/**
* Implementation of JValidation. JValidation is invoked if configuration validation attribute value is 'jvalidation'.
* <pre>
* e.g. <dubbo:method name="save" validation="jvalidation" />
* </pre>
*/
public class JValidator implements Validator {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(JValidator.class);
private final Class<?> clazz;
private final Map<String, Class<?>> methodClassMap;
private final javax.validation.Validator validator;
@SuppressWarnings({"unchecked", "rawtypes"})
public JValidator(URL url) {
this.clazz = ReflectUtils.forName(url.getServiceInterface());
String jvalidation = url.getParameter("jvalidation");
ValidatorFactory factory;
if (StringUtils.isNotEmpty(jvalidation)) {
factory = Validation.byProvider((Class) ReflectUtils.forName(jvalidation))
.configure()
.buildValidatorFactory();
} else {
factory = Validation.buildDefaultValidatorFactory();
}
this.validator = factory.getValidator();
this.methodClassMap = new ConcurrentHashMap<>();
}
private static Object getMethodParameterBean(Class<?> clazz, Method method, Object[] args) {
if (!hasConstraintParameter(method)) {
return null;
}
try {
String parameterClassName = generateMethodParameterClassName(clazz, method);
Class<?> parameterClass;
try {
parameterClass = Class.forName(parameterClassName, true, clazz.getClassLoader());
} catch (ClassNotFoundException e) {
parameterClass = generateMethodParameterClass(clazz, method, parameterClassName);
}
Object parameterBean = parameterClass.getDeclaredConstructor().newInstance();
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
Field field = parameterClass.getField(parameters[i].getName());
field.set(parameterBean, args[i]);
}
return parameterBean;
} catch (Throwable e) {
logger.warn(CONFIG_FILTER_VALIDATION_EXCEPTION, "", "", e.getMessage(), e);
return null;
}
}
/**
* try to generate methodParameterClass.
*
* @param clazz interface class
* @param method invoke method
* @param parameterClassName generated parameterClassName
* @return Class<?> generated methodParameterClass
*/
private static Class<?> generateMethodParameterClass(Class<?> clazz, Method method, String parameterClassName)
throws Exception {
ClassPool pool = ClassGenerator.getClassPool(clazz.getClassLoader());
synchronized (parameterClassName.intern()) {
CtClass ctClass = null;
try {
ctClass = pool.getCtClass(parameterClassName);
} catch (NotFoundException ignore) {
}
if (null == ctClass) {
ctClass = pool.makeClass(parameterClassName);
ClassFile classFile = ctClass.getClassFile();
ctClass.addConstructor(CtNewConstructor.defaultConstructor(pool.getCtClass(parameterClassName)));
// parameter fields
Parameter[] parameters = method.getParameters();
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (int i = 0; i < parameters.length; i++) {
Annotation[] annotations = parameterAnnotations[i];
AnnotationsAttribute attribute =
new AnnotationsAttribute(classFile.getConstPool(), AnnotationsAttribute.visibleTag);
for (Annotation annotation : annotations) {
if (annotation.annotationType().isAnnotationPresent(Constraint.class)) {
javassist.bytecode.annotation.Annotation ja = new javassist.bytecode.annotation.Annotation(
classFile.getConstPool(),
pool.getCtClass(annotation.annotationType().getName()));
Method[] members = annotation.annotationType().getMethods();
for (Method member : members) {
if (Modifier.isPublic(member.getModifiers())
&& member.getParameterTypes().length == 0
&& member.getDeclaringClass() == annotation.annotationType()) {
Object value = member.invoke(annotation);
if (null != value) {
MemberValue memberValue = createMemberValue(
classFile.getConstPool(),
pool.get(member.getReturnType().getName()),
value);
ja.addMemberValue(member.getName(), memberValue);
}
}
}
attribute.addAnnotation(ja);
}
}
Parameter parameter = parameters[i];
Class<?> type = parameter.getType();
String fieldName = parameter.getName();
CtField ctField = CtField.make(
"public " + type.getCanonicalName() + " " + fieldName + ";",
pool.getCtClass(parameterClassName));
ctField.getFieldInfo().addAttribute(attribute);
ctClass.addField(ctField);
}
return pool.toClass(ctClass, clazz, clazz.getClassLoader(), clazz.getProtectionDomain());
} else {
return Class.forName(parameterClassName, true, clazz.getClassLoader());
}
}
}
private static String generateMethodParameterClassName(Class<?> clazz, Method method) {
StringBuilder builder = new StringBuilder()
.append(clazz.getName())
.append('_')
.append(toUpperMethodName(method.getName()))
.append("Parameter");
Class<?>[] parameterTypes = method.getParameterTypes();
for (Class<?> parameterType : parameterTypes) {
// In order to ensure that the parameter class can be generated correctly,
// replace "." with "_" to make the package name of the generated parameter class
// consistent with the package name of the actual parameter class.
builder.append('_').append(parameterType.getName().replace(".", "_"));
}
return builder.toString();
}
private static boolean hasConstraintParameter(Method method) {
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
for (Annotation[] annotations : parameterAnnotations) {
for (Annotation annotation : annotations) {
if (annotation.annotationType().isAnnotationPresent(Constraint.class)) {
return true;
}
}
}
return false;
}
private static String toUpperMethodName(String methodName) {
return methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
}
// Copy from javassist.bytecode.annotation.Annotation.createMemberValue(ConstPool, CtClass);
private static MemberValue createMemberValue(ConstPool cp, CtClass type, Object value) throws NotFoundException {
MemberValue memberValue = javassist.bytecode.annotation.Annotation.createMemberValue(cp, type);
if (memberValue instanceof BooleanMemberValue) {
((BooleanMemberValue) memberValue).setValue((Boolean) value);
} else if (memberValue instanceof ByteMemberValue) {
((ByteMemberValue) memberValue).setValue((Byte) value);
} else if (memberValue instanceof CharMemberValue) {
((CharMemberValue) memberValue).setValue((Character) value);
} else if (memberValue instanceof ShortMemberValue) {
((ShortMemberValue) memberValue).setValue((Short) value);
} else if (memberValue instanceof IntegerMemberValue) {
((IntegerMemberValue) memberValue).setValue((Integer) value);
} else if (memberValue instanceof LongMemberValue) {
((LongMemberValue) memberValue).setValue((Long) value);
} else if (memberValue instanceof FloatMemberValue) {
((FloatMemberValue) memberValue).setValue((Float) value);
} else if (memberValue instanceof DoubleMemberValue) {
((DoubleMemberValue) memberValue).setValue((Double) value);
} else if (memberValue instanceof ClassMemberValue) {
((ClassMemberValue) memberValue).setValue(((Class<?>) value).getName());
} else if (memberValue instanceof StringMemberValue) {
((StringMemberValue) memberValue).setValue((String) value);
} else if (memberValue instanceof EnumMemberValue) {
((EnumMemberValue) memberValue).setValue(((Enum<?>) value).name());
}
/* else if (memberValue instanceof AnnotationMemberValue) */
else if (memberValue instanceof ArrayMemberValue) {
CtClass arrayType = type.getComponentType();
int len = Array.getLength(value);
MemberValue[] members = new MemberValue[len];
for (int i = 0; i < len; i++) {
members[i] = createMemberValue(cp, arrayType, Array.get(value, i));
}
((ArrayMemberValue) memberValue).setValue(members);
}
return memberValue;
}
@Override
public void validate(String methodName, Class<?>[] parameterTypes, Object[] arguments) throws Exception {
List<Class<?>> groups = new ArrayList<>();
Class<?> methodClass = methodClass(methodName);
if (methodClass != null) {
groups.add(methodClass);
}
Method method = clazz.getMethod(methodName, parameterTypes);
Class<?>[] methodClasses;
if (method.isAnnotationPresent(MethodValidated.class)) {
methodClasses = method.getAnnotation(MethodValidated.class).value();
groups.addAll(Arrays.asList(methodClasses));
}
// add into default group
groups.add(0, Default.class);
groups.add(1, clazz);
// convert list to array
Class<?>[] classGroups = groups.toArray(new Class[0]);
Set<ConstraintViolation<?>> violations = new HashSet<>();
Object parameterBean = getMethodParameterBean(clazz, method, arguments);
if (parameterBean != null) {
violations.addAll(validator.validate(parameterBean, classGroups));
}
for (Object arg : arguments) {
validate(violations, arg, classGroups);
}
if (!violations.isEmpty()) {
logger.info("Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: "
+ violations);
throw new ConstraintViolationException(
"Failed to validate service: " + clazz.getName() + ", method: " + methodName + ", cause: "
+ violations,
violations);
}
}
private Class<?> methodClass(String methodName) {
Class<?> methodClass = null;
String methodClassName = clazz.getName() + "$" + toUpperMethodName(methodName);
Class<?> cached = methodClassMap.get(methodClassName);
if (cached != null) {
return cached == clazz ? null : cached;
}
try {
methodClass =
Class.forName(methodClassName, false, Thread.currentThread().getContextClassLoader());
methodClassMap.put(methodClassName, methodClass);
} catch (ClassNotFoundException e) {
methodClassMap.put(methodClassName, clazz);
}
return methodClass;
}
private void validate(Set<ConstraintViolation<?>> violations, Object arg, Class<?>... groups) {
if (arg != null && !ReflectUtils.isPrimitives(arg.getClass())) {
if (arg instanceof Object[]) {
for (Object item : (Object[]) arg) {
validate(violations, item, groups);
}
} else if (arg instanceof Collection) {
for (Object item : (Collection<?>) arg) {
validate(violations, item, groups);
}
} else if (arg instanceof Map) {
for (Map.Entry<?, ?> entry : ((Map<?, ?>) arg).entrySet()) {
validate(violations, entry.getKey(), groups);
validate(violations, entry.getValue(), groups);
}
} else {
violations.addAll(validator.validate(arg, groups));
}
}
}
}
| 5,551 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/support/jvalidation/JValidationNew.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.support.jvalidation;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.validation.Validator;
import org.apache.dubbo.validation.support.AbstractValidation;
/**
* Creates a new instance of {@link Validator} using input argument url.
* @see AbstractValidation
* @see Validator
*/
public class JValidationNew extends AbstractValidation {
/**
* Return new instance of {@link JValidator}
* @param url Valid URL instance
* @return Instance of JValidator
*/
@Override
protected Validator createValidator(URL url) {
return new JValidatorNew(url);
}
}
| 5,552 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation | Create_ds/dubbo/dubbo-filter/dubbo-filter-validation/src/main/java/org/apache/dubbo/validation/filter/ValidationFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.validation.filter;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.validation.Validation;
import org.apache.dubbo.validation.Validator;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.FilterConstants.VALIDATION_KEY;
/**
* ValidationFilter invoke the validation by finding the right {@link Validator} instance based on the
* configured <b>validation</b> attribute value of invoker url before the actual method invocation.
*
* <pre>
* e.g. <dubbo:method name="save" validation="jvalidation" />
* In the above configuration a validation has been configured of type jvalidation. On invocation of method <b>save</b>
* dubbo will invoke {@link org.apache.dubbo.validation.support.jvalidation.JValidator}
* </pre>
* <p>
* To add a new type of validation
* <pre>
* e.g. <dubbo:method name="save" validation="special" />
* where "special" is representing a validator for special character.
* </pre>
* <p>
* developer needs to do
* <br/>
* 1)Implement a SpecialValidation.java class (package name xxx.yyy.zzz) either by implementing {@link Validation} or extending {@link org.apache.dubbo.validation.support.AbstractValidation} <br/>
* 2)Implement a SpecialValidator.java class (package name xxx.yyy.zzz) <br/>
* 3)Add an entry <b>special</b>=<b>xxx.yyy.zzz.SpecialValidation</b> under <b>META-INF folders org.apache.dubbo.validation.Validation file</b>.
*
* @see Validation
* @see Validator
* @see Filter
* @see org.apache.dubbo.validation.support.AbstractValidation
*/
@Activate(
group = {CONSUMER, PROVIDER},
value = VALIDATION_KEY,
order = 10000)
public class ValidationFilter implements Filter {
private Validation validation;
/**
* Sets the validation instance for ValidationFilter
*
* @param validation Validation instance injected by dubbo framework based on "validation" attribute value.
*/
public void setValidation(Validation validation) {
this.validation = validation;
}
/**
* Perform the validation of before invoking the actual method based on <b>validation</b> attribute value.
*
* @param invoker service
* @param invocation invocation.
* @return Method invocation result
* @throws RpcException Throws RpcException if validation failed or any other runtime exception occurred.
*/
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (needValidate(invoker.getUrl(), invocation.getMethodName())) {
try {
Validator validator = validation.getValidator(invoker.getUrl());
if (validator != null) {
validator.validate(
invocation.getMethodName(), invocation.getParameterTypes(), invocation.getArguments());
}
} catch (RpcException e) {
throw e;
} catch (Throwable t) {
return AsyncRpcResult.newDefaultAsyncResult(t, invocation);
}
}
return invoker.invoke(invocation);
}
private boolean needValidate(URL url, String methodName) {
return validation != null
&& !methodName.startsWith("$")
&& ConfigUtils.isNotEmpty(url.getMethodParameter(methodName, VALIDATION_KEY));
}
}
| 5,553 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/AbstractCacheFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.RpcInvocation;
public abstract class AbstractCacheFactoryTest {
protected Cache constructCache() {
URL url = URL.valueOf("test://test:11/test?cache=lru");
Invocation invocation = new RpcInvocation();
return getCacheFactory().getCache(url, invocation);
}
protected abstract AbstractCacheFactory getCacheFactory();
}
| 5,554 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/lru/LruCacheFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.lru;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.cache.support.AbstractCacheFactory;
import org.apache.dubbo.cache.support.AbstractCacheFactoryTest;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
class LruCacheFactoryTest extends AbstractCacheFactoryTest {
@Test
void testLruCacheFactory() throws Exception {
Cache cache = super.constructCache();
assertThat(cache instanceof LruCache, is(true));
}
@Override
protected AbstractCacheFactory getCacheFactory() {
return new LruCacheFactory();
}
}
| 5,555 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.threadlocal;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.cache.support.AbstractCacheFactory;
import org.apache.dubbo.cache.support.AbstractCacheFactoryTest;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
class ThreadLocalCacheFactoryTest extends AbstractCacheFactoryTest {
@Test
void testThreadLocalCacheFactory() throws Exception {
Cache cache = super.constructCache();
assertThat(cache instanceof ThreadLocalCache, is(true));
}
@Override
protected AbstractCacheFactory getCacheFactory() {
return new ThreadLocalCacheFactory();
}
}
| 5,556 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/jcache/JCacheFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.jcache;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.cache.support.AbstractCacheFactory;
import org.apache.dubbo.cache.support.AbstractCacheFactoryTest;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.RpcInvocation;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.assertNull;
class JCacheFactoryTest extends AbstractCacheFactoryTest {
@Test
void testJCacheFactory() {
Cache cache = super.constructCache();
assertThat(cache instanceof JCache, is(true));
}
@Test
void testJCacheGetExpired() throws Exception {
URL url = URL.valueOf("test://test:12/test?cache=jacache&cache.write.expire=1");
AbstractCacheFactory cacheFactory = getCacheFactory();
Invocation invocation = new RpcInvocation();
Cache cache = cacheFactory.getCache(url, invocation);
cache.put("testKey", "testValue");
Thread.sleep(10);
assertNull(cache.get("testKey"));
}
@Override
protected AbstractCacheFactory getCacheFactory() {
return new JCacheFactory();
}
}
| 5,557 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactoryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.expiring;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.cache.support.AbstractCacheFactory;
import org.apache.dubbo.cache.support.AbstractCacheFactoryTest;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.RpcInvocation;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
class ExpiringCacheFactoryTest extends AbstractCacheFactoryTest {
private static final String EXPIRING_CACHE_URL =
"test://test:12/test?cache=expiring&cache.seconds=1&cache.interval=1";
@Test
void testExpiringCacheFactory() throws Exception {
Cache cache = super.constructCache();
assertThat(cache instanceof ExpiringCache, is(true));
}
@Test
void testExpiringCacheGetExpired() throws Exception {
URL url = URL.valueOf("test://test:12/test?cache=expiring&cache.seconds=1&cache.interval=1");
AbstractCacheFactory cacheFactory = getCacheFactory();
Invocation invocation = new RpcInvocation();
Cache cache = cacheFactory.getCache(url, invocation);
cache.put("testKey", "testValue");
Thread.sleep(2100);
assertNull(cache.get("testKey"));
}
@Test
void testExpiringCacheUnExpired() throws Exception {
URL url = URL.valueOf("test://test:12/test?cache=expiring&cache.seconds=0&cache.interval=1");
AbstractCacheFactory cacheFactory = getCacheFactory();
Invocation invocation = new RpcInvocation();
Cache cache = cacheFactory.getCache(url, invocation);
cache.put("testKey", "testValue");
Thread.sleep(1100);
assertNotNull(cache.get("testKey"));
}
@Test
void testExpiringCache() throws Exception {
Cache cache = constructCache();
assertThat(cache instanceof ExpiringCache, is(true));
// 500ms
TimeUnit.MILLISECONDS.sleep(500);
cache.put("testKey", "testValue");
// 800ms
TimeUnit.MILLISECONDS.sleep(300);
assertNotNull(cache.get("testKey"));
// 1300ms
TimeUnit.MILLISECONDS.sleep(500);
assertNotNull(cache.get("testKey"));
}
@Test
void testExpiringCacheExpired() throws Exception {
Cache cache = constructCache();
assertThat(cache instanceof ExpiringCache, is(true));
// 500ms
TimeUnit.MILLISECONDS.sleep(500);
cache.put("testKey", "testValue");
// 1000ms ExpireThread clear all expire cache
TimeUnit.MILLISECONDS.sleep(500);
// 1700ms get should be null
TimeUnit.MILLISECONDS.sleep(700);
assertNull(cache.get("testKey"));
}
@Override
protected Cache constructCache() {
URL url = URL.valueOf(EXPIRING_CACHE_URL);
Invocation invocation = new RpcInvocation();
return getCacheFactory().getCache(url, invocation);
}
@Override
protected AbstractCacheFactory getCacheFactory() {
return new ExpiringCacheFactory();
}
}
| 5,558 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/test/java/org/apache/dubbo/cache/filter/CacheFilterTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.filter;
import org.apache.dubbo.cache.CacheFactory;
import org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory;
import org.apache.dubbo.cache.support.jcache.JCacheFactory;
import org.apache.dubbo.cache.support.lru.LruCacheFactory;
import org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcInvocation;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
class CacheFilterTest {
private RpcInvocation invocation;
private CacheFilter cacheFilter = new CacheFilter();
private Invoker<?> invoker = mock(Invoker.class);
private Invoker<?> invoker1 = mock(Invoker.class);
private Invoker<?> invoker2 = mock(Invoker.class);
private Invoker<?> invoker3 = mock(Invoker.class);
private Invoker<?> invoker4 = mock(Invoker.class);
static Stream<Arguments> cacheFactories() {
return Stream.of(
Arguments.of("lru", new LruCacheFactory()),
Arguments.of("jcache", new JCacheFactory()),
Arguments.of("threadlocal", new ThreadLocalCacheFactory()),
Arguments.of("expiring", new ExpiringCacheFactory()));
}
public void setUp(String cacheType, CacheFactory cacheFactory) {
invocation = new RpcInvocation();
cacheFilter.setCacheFactory(cacheFactory);
URL url = URL.valueOf("test://test:11/test?cache=" + cacheType);
given(invoker.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult("value", invocation));
given(invoker.getUrl()).willReturn(url);
given(invoker1.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult("value1", invocation));
given(invoker1.getUrl()).willReturn(url);
given(invoker2.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult("value2", invocation));
given(invoker2.getUrl()).willReturn(url);
given(invoker3.invoke(invocation))
.willReturn(AsyncRpcResult.newDefaultAsyncResult(new RuntimeException(), invocation));
given(invoker3.getUrl()).willReturn(url);
given(invoker4.invoke(invocation)).willReturn(AsyncRpcResult.newDefaultAsyncResult(invocation));
given(invoker4.getUrl()).willReturn(url);
}
@ParameterizedTest
@MethodSource("cacheFactories")
public void testNonArgsMethod(String cacheType, CacheFactory cacheFactory) {
setUp(cacheType, cacheFactory);
invocation.setMethodName("echo");
invocation.setParameterTypes(new Class<?>[] {});
invocation.setArguments(new Object[] {});
cacheFilter.invoke(invoker, invocation);
cacheFilter.invoke(invoker, invocation);
Result rpcResult1 = cacheFilter.invoke(invoker1, invocation);
Result rpcResult2 = cacheFilter.invoke(invoker2, invocation);
Assertions.assertEquals(rpcResult1.getValue(), rpcResult2.getValue());
Assertions.assertEquals(rpcResult1.getValue(), "value");
}
@ParameterizedTest
@MethodSource("cacheFactories")
public void testMethodWithArgs(String cacheType, CacheFactory cacheFactory) {
setUp(cacheType, cacheFactory);
invocation.setMethodName("echo1");
invocation.setParameterTypes(new Class<?>[] {String.class});
invocation.setArguments(new Object[] {"arg1"});
cacheFilter.invoke(invoker, invocation);
cacheFilter.invoke(invoker, invocation);
Result rpcResult1 = cacheFilter.invoke(invoker1, invocation);
Result rpcResult2 = cacheFilter.invoke(invoker2, invocation);
Assertions.assertEquals(rpcResult1.getValue(), rpcResult2.getValue());
Assertions.assertEquals(rpcResult1.getValue(), "value");
}
@ParameterizedTest
@MethodSource("cacheFactories")
public void testException(String cacheType, CacheFactory cacheFactory) {
setUp(cacheType, cacheFactory);
invocation.setMethodName("echo1");
invocation.setParameterTypes(new Class<?>[] {String.class});
invocation.setArguments(new Object[] {"arg2"});
cacheFilter.invoke(invoker3, invocation);
cacheFilter.invoke(invoker3, invocation);
Result rpcResult = cacheFilter.invoke(invoker2, invocation);
Assertions.assertEquals(rpcResult.getValue(), "value2");
}
@ParameterizedTest
@MethodSource("cacheFactories")
public void testNull(String cacheType, CacheFactory cacheFactory) {
setUp(cacheType, cacheFactory);
invocation.setMethodName("echo1");
invocation.setParameterTypes(new Class<?>[] {String.class});
invocation.setArguments(new Object[] {"arg3"});
cacheFilter.invoke(invoker4, invocation);
cacheFilter.invoke(invoker4, invocation);
Result result1 = cacheFilter.invoke(invoker1, invocation);
Result result2 = cacheFilter.invoke(invoker2, invocation);
Assertions.assertNull(result1.getValue());
Assertions.assertNull(result2.getValue());
}
}
| 5,559 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/Cache.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache;
/**
* Cache interface to support storing and retrieval of value against a lookup key. It has two operation <b>get</b> and <b>put</b>.
* <li><b>put</b>-Storing value against a key.</li>
* <li><b>get</b>-Retrieval of object.</li>
* @see org.apache.dubbo.cache.support.lru.LruCache
* @see org.apache.dubbo.cache.support.jcache.JCache
* @see org.apache.dubbo.cache.support.expiring.ExpiringCache
* @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache
*/
public interface Cache {
/**
* API to store value against a key
* @param key Unique identifier for the object being store.
* @param value Value getting store
*/
void put(Object key, Object value);
/**
* API to return stored value using a key.
* @param key Unique identifier for cache lookup
* @return Return stored object against key
*/
Object get(Object key);
}
| 5,560 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/CacheFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.rpc.Invocation;
/**
* Interface needs to be implemented by all the cache store provider.Along with implementing <b>CacheFactory</b> interface
* entry needs to be added in org.apache.dubbo.cache.CacheFactory file in a classpath META-INF sub directories.
*
* @see Cache
*/
@SPI("lru")
public interface CacheFactory {
/**
* CacheFactory implementation class needs to implement this return underlying cache instance for method against
* url and invocation.
* @param url
* @param invocation
* @return Instance of Cache containing cached value against method url and invocation.
*/
@Adaptive("cache")
Cache getCache(URL url, Invocation invocation);
}
| 5,561 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/AbstractCacheFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.cache.CacheFactory;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.Invocation;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY;
/**
* AbstractCacheFactory is a default implementation of {@link CacheFactory}. It abstract out the key formation from URL along with
* invocation method. It initially check if the value for key already present in own local in-memory store then it won't check underlying storage cache {@link Cache}.
* Internally it used {@link ConcurrentHashMap} to store do level-1 caching.
*
* @see CacheFactory
* @see org.apache.dubbo.cache.support.jcache.JCacheFactory
* @see org.apache.dubbo.cache.support.lru.LruCacheFactory
* @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory
* @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory
*/
public abstract class AbstractCacheFactory implements CacheFactory {
/**
* This is used to store factory level-1 cached data.
*/
private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();
private final Object MONITOR = new Object();
/**
* Takes URL and invocation instance and return cache instance for a given url.
*
* @param url url of the method
* @param invocation invocation context.
* @return Instance of cache store used as storage for caching return values.
*/
@Override
public Cache getCache(URL url, Invocation invocation) {
url = url.addParameter(METHOD_KEY, invocation.getMethodName());
String key = url.getServiceKey() + invocation.getMethodName();
Cache cache = caches.get(key);
// get from cache first.
if (null != cache) {
return cache;
}
synchronized (MONITOR) {
// double check.
cache = caches.get(key);
if (null != cache) {
return cache;
}
cache = createCache(url);
caches.put(key, cache);
}
return cache;
}
/**
* Takes url as an method argument and return new instance of cache store implemented by AbstractCacheFactory subclass.
*
* @param url url of the method
* @return Create and return new instance of cache store used as storage for caching return values.
*/
protected abstract Cache createCache(URL url);
}
| 5,562 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCacheFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.lru;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.cache.support.AbstractCacheFactory;
import org.apache.dubbo.common.URL;
/**
* Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide
* instance of new {@link LruCache}.
*
* @see AbstractCacheFactory
* @see LruCache
* @see Cache
*/
public class LruCacheFactory extends AbstractCacheFactory {
/**
* Takes url as an method argument and return new instance of cache store implemented by LruCache.
* @param url url of the method
* @return ThreadLocalCache instance of cache
*/
@Override
protected Cache createCache(URL url) {
return new LruCache(url);
}
}
| 5,563 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lru/LruCache.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.lru;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.LRU2Cache;
import java.util.Map;
/**
* This class store the cache value per thread. If a service,method,consumer or provided is configured with key <b>cache</b>
* with value <b>lru</b>, dubbo initialize the instance of this class using {@link LruCacheFactory} to store method's returns value
* to server from store without making method call.
* <pre>
* e.g. 1) <dubbo:service cache="lru" cache.size="5000"/>
* 2) <dubbo:consumer cache="lru" />
* </pre>
* <pre>
* LruCache uses url's <b>cache.size</b> value for its max store size, if nothing is provided then
* default value will be 1000
* </pre>
*
* @see Cache
* @see LruCacheFactory
* @see org.apache.dubbo.cache.support.AbstractCacheFactory
* @see org.apache.dubbo.cache.filter.CacheFilter
*/
public class LruCache implements Cache {
/**
* This is used to store cache records
*/
private final Map<Object, Object> store;
/**
* Initialize LruCache, it uses constructor argument <b>cache.size</b> value as its storage max size.
* If nothing is provided then it will use 1000 as default value.
* @param url A valid URL instance
*/
public LruCache(URL url) {
final int max = url.getParameter("cache.size", 1000);
this.store = new LRU2Cache<>(max);
}
/**
* API to store value against a key in the calling thread scope.
* @param key Unique identifier for the object being store.
* @param value Value getting store
*/
@Override
public void put(Object key, Object value) {
store.put(key, value);
}
/**
* API to return stored value using a key against the calling thread specific store.
* @param key Unique identifier for cache lookup
* @return Return stored object against key
*/
@Override
public Object get(Object key) {
return store.get(key);
}
}
| 5,564 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCacheFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.threadlocal;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.cache.support.AbstractCacheFactory;
import org.apache.dubbo.common.URL;
/**
* Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide
* instance of new {@link ThreadLocalCache}. Note about this class is, each thread does not have a local copy of factory.
*
* @see AbstractCacheFactory
* @see ThreadLocalCache
* @see Cache
*/
public class ThreadLocalCacheFactory extends AbstractCacheFactory {
/**
* Takes url as an method argument and return new instance of cache store implemented by ThreadLocalCache.
* @param url url of the method
* @return ThreadLocalCache instance of cache
*/
@Override
protected Cache createCache(URL url) {
return new ThreadLocalCache(url);
}
}
| 5,565 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/threadlocal/ThreadLocalCache.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.threadlocal;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.common.URL;
import java.util.HashMap;
import java.util.Map;
/**
* This class store the cache value per thread. If a service,method,consumer or provided is configured with key <b>cache</b>
* with value <b>threadlocal</b>, dubbo initialize the instance of this class using {@link ThreadLocalCacheFactory} to store method's returns value
* to server from store without making method call.
* <pre>
* e.g. <dubbo:service cache="threadlocal" />
* </pre>
* <pre>
* As this ThreadLocalCache stores key-value in memory without any expiry or delete support per thread wise, if number threads and number of key-value are high then jvm should be
* configured with appropriate memory.
* </pre>
*
* @see org.apache.dubbo.cache.support.AbstractCacheFactory
* @see org.apache.dubbo.cache.filter.CacheFilter
* @see Cache
*/
public class ThreadLocalCache implements Cache {
/**
* Thread local variable to store cached data.
*/
private final ThreadLocal<Map<Object, Object>> store;
/**
* Taken URL as an argument to create an instance of ThreadLocalCache. In this version of implementation constructor
* argument is not getting used in the scope of this class.
* @param url
*/
public ThreadLocalCache(URL url) {
this.store = ThreadLocal.withInitial(HashMap::new);
}
/**
* API to store value against a key in the calling thread scope.
* @param key Unique identifier for the object being store.
* @param value Value getting store
*/
@Override
public void put(Object key, Object value) {
store.get().put(key, value);
}
/**
* API to return stored value using a key against the calling thread specific store.
* @param key Unique identifier for cache lookup
* @return Return stored object against key
*/
@Override
public Object get(Object key) {
return store.get().get(key);
}
}
| 5,566 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCache.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.lfu;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.LFUCache;
/**
* This class store the cache value per thread. If a service,method,consumer or provided is configured with key <b>cache</b>
* with value <b>lfu</b>, dubbo initialize the instance of this class using {@link LfuCacheFactory} to store method's returns value
* to server from store without making method call.
* <pre>
* e.g. 1) <dubbo:service cache="lfu" cache.size="5000" cache.evictionFactor="0.3"/>
* 2) <dubbo:consumer cache="lfu" />
* </pre>
* <pre>
* LfuCache uses url's <b>cache.size</b> value for its max store size, url's <b>cache.evictionFactor</b> value for its eviction factor,
* default store size value will be 1000, default eviction factor will be 0.3
* </pre>
*
* @see Cache
* @see LfuCacheFactory
* @see org.apache.dubbo.cache.support.AbstractCacheFactory
* @see org.apache.dubbo.cache.filter.CacheFilter
*/
public class LfuCache implements Cache {
/**
* This is used to store cache records
*/
@SuppressWarnings("rawtypes")
private final LFUCache store;
/**
* Initialize LfuCache, it uses constructor argument <b>cache.size</b> value as its storage max size.
* If nothing is provided then it will use 1000 as default size value. <b>cache.evictionFactor</b> value as its eviction factor.
* If nothing is provided then it will use 0.3 as default value.
* @param url A valid URL instance
*/
@SuppressWarnings("rawtypes")
public LfuCache(URL url) {
final int max = url.getParameter("cache.size", 1000);
final float factor = url.getParameter("cache.evictionFactor", 0.75f);
this.store = new LFUCache(max, factor);
}
/**
* API to store value against a key in the calling thread scope.
* @param key Unique identifier for the object being store.
* @param value Value getting store
*/
@SuppressWarnings("unchecked")
@Override
public void put(Object key, Object value) {
store.put(key, value);
}
/**
* API to return stored value using a key against the calling thread specific store.
* @param key Unique identifier for cache lookup
* @return Return stored object against key
*/
@SuppressWarnings("unchecked")
@Override
public Object get(Object key) {
return store.get(key);
}
}
| 5,567 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCacheFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.lfu;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.cache.support.AbstractCacheFactory;
import org.apache.dubbo.common.URL;
/**
* Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide
* instance of new {@link LfuCache}.
*
* @see AbstractCacheFactory
* @see LfuCache
* @see Cache
*/
public class LfuCacheFactory extends AbstractCacheFactory {
/**
* Takes url as an method argument and return new instance of cache store implemented by LfuCache.
* @param url url of the method
* @return ThreadLocalCache instance of cache
*/
@Override
protected Cache createCache(URL url) {
return new LfuCache(url);
}
}
| 5,568 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCacheFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.jcache;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.cache.support.AbstractCacheFactory;
import org.apache.dubbo.common.URL;
import javax.cache.spi.CachingProvider;
/**
* JCacheFactory is factory class to provide instance of javax spi cache.Implement {@link org.apache.dubbo.cache.CacheFactory} by
* extending {@link AbstractCacheFactory} and provide
* @see AbstractCacheFactory
* @see JCache
* @see org.apache.dubbo.cache.filter.CacheFilter
* @see Cache
* @see CachingProvider
* @see javax.cache.Cache
* @see javax.cache.CacheManager
*/
public class JCacheFactory extends AbstractCacheFactory {
/**
* Takes url as an method argument and return new instance of cache store implemented by JCache.
* @param url url of the method
* @return JCache instance of cache
*/
@Override
protected Cache createCache(URL url) {
return new JCache(url);
}
}
| 5,569 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/jcache/JCache.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.jcache;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.expiry.CreatedExpiryPolicy;
import javax.cache.expiry.Duration;
import javax.cache.spi.CachingProvider;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY;
/**
* This class store the cache value per thread. If a service,method,consumer or provided is configured with key <b>cache</b>
* with value <b>jcache</b>, dubbo initialize the instance of this class using {@link JCacheFactory} to store method's returns value
* to server from store without making method call.
*
* @see Cache
* @see JCacheFactory
* @see org.apache.dubbo.cache.support.AbstractCacheFactory
* @see org.apache.dubbo.cache.filter.CacheFilter
*/
public class JCache implements org.apache.dubbo.cache.Cache {
private final Cache<Object, Object> store;
public JCache(URL url) {
String method = url.getParameter(METHOD_KEY, "");
String key = url.getAddress() + "." + url.getServiceKey() + "." + method;
// jcache parameter is the full-qualified class name of SPI implementation
String type = url.getParameter("jcache");
CachingProvider provider =
StringUtils.isEmpty(type) ? Caching.getCachingProvider() : Caching.getCachingProvider(type);
CacheManager cacheManager = provider.getCacheManager();
Cache<Object, Object> cache = cacheManager.getCache(key);
if (cache == null) {
try {
// configure the cache
MutableConfiguration config = new MutableConfiguration<>()
.setTypes(Object.class, Object.class)
.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(
TimeUnit.MILLISECONDS,
url.getMethodParameter(method, "cache.write.expire", 60 * 1000))))
.setStoreByValue(false)
.setManagementEnabled(true)
.setStatisticsEnabled(true);
cache = cacheManager.createCache(key, config);
} catch (CacheException e) {
// concurrent cache initialization
cache = cacheManager.getCache(key);
}
}
this.store = cache;
}
@Override
public void put(Object key, Object value) {
store.put(key, value);
}
@Override
public Object get(Object key) {
return store.get(key);
}
}
| 5,570 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCacheFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.expiring;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.cache.support.AbstractCacheFactory;
import org.apache.dubbo.common.URL;
/**
* Implement {@link org.apache.dubbo.cache.CacheFactory} by extending {@link AbstractCacheFactory} and provide
* instance of new {@link ExpiringCache}.
*
* @see AbstractCacheFactory
* @see ExpiringCache
* @see Cache
*/
public class ExpiringCacheFactory extends AbstractCacheFactory {
/**
* Takes url as an method argument and return new instance of cache store implemented by JCache.
* @param url url of the method
* @return ExpiringCache instance of cache
*/
@Override
protected Cache createCache(URL url) {
return new ExpiringCache(url);
}
}
| 5,571 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringMap.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.expiring;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/**
* can be expired map
* Contains a background thread that periodically checks if the data is out of date
*/
public class ExpiringMap<K, V> implements Map<K, V> {
/**
* default time to live (second)
*/
private static final int DEFAULT_TIME_TO_LIVE = 180;
/**
* default expire check interval (second)
*/
private static final int DEFAULT_EXPIRATION_INTERVAL = 1;
private static final AtomicInteger expireCount = new AtomicInteger(1);
private final ConcurrentHashMap<K, ExpiryObject> delegateMap;
private final ExpireThread expireThread;
public ExpiringMap() {
this(DEFAULT_TIME_TO_LIVE, DEFAULT_EXPIRATION_INTERVAL);
}
/**
* Constructor
*
* @param timeToLive time to live (second)
*/
public ExpiringMap(int timeToLive) {
this(timeToLive, DEFAULT_EXPIRATION_INTERVAL);
}
public ExpiringMap(int timeToLive, int expirationInterval) {
this(new ConcurrentHashMap<>(), timeToLive, expirationInterval);
}
private ExpiringMap(ConcurrentHashMap<K, ExpiryObject> delegateMap, int timeToLive, int expirationInterval) {
this.delegateMap = delegateMap;
this.expireThread = new ExpireThread();
expireThread.setTimeToLive(timeToLive);
expireThread.setExpirationInterval(expirationInterval);
}
@Override
public V put(K key, V value) {
ExpiryObject answer = delegateMap.put(key, new ExpiryObject(key, value, System.currentTimeMillis()));
if (answer == null) {
return null;
}
return answer.getValue();
}
@Override
public V get(Object key) {
ExpiryObject object = delegateMap.get(key);
if (object != null) {
long timeIdle = System.currentTimeMillis() - object.getLastAccessTime();
int timeToLive = expireThread.getTimeToLive();
if (timeToLive > 0 && timeIdle >= timeToLive * 1000L) {
delegateMap.remove(object.getKey());
return null;
}
object.setLastAccessTime(System.currentTimeMillis());
return object.getValue();
}
return null;
}
@Override
public V remove(Object key) {
ExpiryObject answer = delegateMap.remove(key);
if (answer == null) {
return null;
}
return answer.getValue();
}
@Override
public boolean containsKey(Object key) {
return delegateMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return delegateMap.containsValue(value);
}
@Override
public int size() {
return delegateMap.size();
}
@Override
public boolean isEmpty() {
return delegateMap.isEmpty();
}
@Override
public void clear() {
delegateMap.clear();
expireThread.stopExpiring();
}
@Override
public int hashCode() {
return delegateMap.hashCode();
}
@Override
public Set<K> keySet() {
return delegateMap.keySet();
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
return delegateMap.equals(obj);
}
@Override
public void putAll(Map<? extends K, ? extends V> inMap) {
for (Entry<? extends K, ? extends V> e : inMap.entrySet()) {
this.put(e.getKey(), e.getValue());
}
}
@Override
public Collection<V> values() {
List<V> list = new ArrayList<V>();
Set<Entry<K, ExpiryObject>> delegatedSet = delegateMap.entrySet();
for (Entry<K, ExpiryObject> entry : delegatedSet) {
ExpiryObject value = entry.getValue();
list.add(value.getValue());
}
return list;
}
@Override
public Set<Entry<K, V>> entrySet() {
throw new UnsupportedOperationException();
}
public ExpireThread getExpireThread() {
return expireThread;
}
public int getExpirationInterval() {
return expireThread.getExpirationInterval();
}
public void setExpirationInterval(int expirationInterval) {
expireThread.setExpirationInterval(expirationInterval);
}
public int getTimeToLive() {
return expireThread.getTimeToLive();
}
public void setTimeToLive(int timeToLive) {
expireThread.setTimeToLive(timeToLive);
}
@Override
public String toString() {
return "ExpiringMap{" + "delegateMap="
+ delegateMap.toString() + ", expireThread="
+ expireThread.toString() + '}';
}
/**
* can be expired object
*/
private class ExpiryObject {
private K key;
private V value;
private AtomicLong lastAccessTime;
ExpiryObject(K key, V value, long lastAccessTime) {
if (value == null) {
throw new IllegalArgumentException("An expiring object cannot be null.");
}
this.key = key;
this.value = value;
this.lastAccessTime = new AtomicLong(lastAccessTime);
}
public long getLastAccessTime() {
return lastAccessTime.get();
}
public void setLastAccessTime(long lastAccessTime) {
this.lastAccessTime.set(lastAccessTime);
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
return value.equals(obj);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public String toString() {
return "ExpiryObject{" + "key=" + key + ", value=" + value + ", lastAccessTime=" + lastAccessTime + '}';
}
}
/**
* Background thread, periodically checking if the data is out of date
*/
public class ExpireThread implements Runnable {
private long timeToLiveMillis;
private long expirationIntervalMillis;
private volatile boolean running = false;
private final Thread expirerThread;
@Override
public String toString() {
return "ExpireThread{" + ", timeToLiveMillis="
+ timeToLiveMillis + ", expirationIntervalMillis="
+ expirationIntervalMillis + ", running="
+ running + ", expirerThread="
+ expirerThread + '}';
}
public ExpireThread() {
expirerThread = new Thread(this, "ExpiryMapExpire-" + expireCount.getAndIncrement());
expirerThread.setDaemon(true);
}
@Override
public void run() {
while (running) {
processExpires();
try {
Thread.sleep(expirationIntervalMillis);
} catch (InterruptedException e) {
running = false;
}
}
}
private void processExpires() {
long timeNow = System.currentTimeMillis();
if (timeToLiveMillis <= 0) {
return;
}
for (ExpiryObject o : delegateMap.values()) {
long timeIdle = timeNow - o.getLastAccessTime();
if (timeIdle >= timeToLiveMillis) {
delegateMap.remove(o.getKey());
}
}
}
/**
* start expiring Thread
*/
public void startExpiring() {
if (!running) {
running = true;
expirerThread.start();
}
}
/**
* start thread
*/
public void startExpiryIfNotStarted() {
if (running && timeToLiveMillis <= 0) {
return;
}
startExpiring();
}
/**
* stop thread
*/
public void stopExpiring() {
if (running) {
running = false;
expirerThread.interrupt();
}
}
/**
* get thread state
*
* @return thread state
*/
public boolean isRunning() {
return running;
}
/**
* get time to live
*
* @return time to live
*/
public int getTimeToLive() {
return (int) timeToLiveMillis / 1000;
}
/**
* update time to live
*
* @param timeToLive time to live
*/
public void setTimeToLive(long timeToLive) {
this.timeToLiveMillis = timeToLive * 1000;
}
/**
* get expiration interval
*
* @return expiration interval (second)
*/
public int getExpirationInterval() {
return (int) expirationIntervalMillis / 1000;
}
/**
* set expiration interval
*
* @param expirationInterval expiration interval (second)
*/
public void setExpirationInterval(long expirationInterval) {
this.expirationIntervalMillis = expirationInterval * 1000;
}
}
}
| 5,572 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/expiring/ExpiringCache.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.support.expiring;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.common.URL;
import java.util.Map;
/**
* ExpiringCache - With the characteristic of expiration time.
*/
/**
* This class store the cache value with the characteristic of expiration time. If a service,method,consumer or provided is configured with key <b>cache</b>
* with value <b>expiring</b>, dubbo initialize the instance of this class using {@link ExpiringCacheFactory} to store method's returns value
* to server from store without making method call.
* <pre>
* e.g. 1) <dubbo:service cache="expiring" cache.seconds="60" cache.interval="10"/>
* 2) <dubbo:consumer cache="expiring" />
* </pre>
* <li>It used constructor argument url instance <b>cache.seconds</b> value to decide time to live of cached object.Default value of it is 180 second.</li>
* <li>It used constructor argument url instance <b>cache.interval</b> value for cache value expiration interval.Default value of this is 4 second</li>
* @see Cache
* @see ExpiringCacheFactory
* @see org.apache.dubbo.cache.support.AbstractCacheFactory
* @see org.apache.dubbo.cache.filter.CacheFilter
*/
public class ExpiringCache implements Cache {
private final Map<Object, Object> store;
public ExpiringCache(URL url) {
// cache time (second)
final int secondsToLive = url.getParameter("cache.seconds", 180);
// Cache check interval (second)
final int intervalSeconds = url.getParameter("cache.interval", 4);
ExpiringMap<Object, Object> expiringMap = new ExpiringMap<>(secondsToLive, intervalSeconds);
expiringMap.getExpireThread().startExpiryIfNotStarted();
this.store = expiringMap;
}
/**
* API to store value against a key in the calling thread scope.
* @param key Unique identifier for the object being store.
* @param value Value getting store
*/
@Override
public void put(Object key, Object value) {
store.put(key, value);
}
/**
* API to return stored value using a key against the calling thread specific store.
* @param key Unique identifier for cache lookup
* @return Return stored object against key
*/
@Override
public Object get(Object key) {
return store.get(key);
}
}
| 5,573 |
0 | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache | Create_ds/dubbo/dubbo-filter/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/filter/CacheFilter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.cache.filter;
import org.apache.dubbo.cache.Cache;
import org.apache.dubbo.cache.CacheFactory;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.common.utils.ConfigUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import java.io.Serializable;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.FilterConstants.CACHE_KEY;
/**
* CacheFilter is a core component of dubbo.Enabling <b>cache</b> key of service,method,consumer or provider dubbo will cache method return value.
* Along with cache key we need to configure cache type. Dubbo default implemented cache types are
* <li>lru</li>
* <li>threadlocal</li>
* <li>jcache</li>
* <li>expiring</li>
*
* <pre>
* e.g. 1)<dubbo:service cache="lru" />
* 2)<dubbo:service /> <dubbo:method name="method2" cache="threadlocal" /> <dubbo:service/>
* 3)<dubbo:provider cache="expiring" />
* 4)<dubbo:consumer cache="jcache" />
*
*If cache type is defined in method level then method level type will get precedence. According to above provided
*example, if service has two method, method1 and method2, method2 will have cache type as <b>threadlocal</b> where others will
*be backed by <b>lru</b>
*</pre>
*
* @see org.apache.dubbo.rpc.Filter
* @see org.apache.dubbo.cache.support.lru.LruCacheFactory
* @see org.apache.dubbo.cache.support.lru.LruCache
* @see org.apache.dubbo.cache.support.jcache.JCacheFactory
* @see org.apache.dubbo.cache.support.jcache.JCache
* @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCacheFactory
* @see org.apache.dubbo.cache.support.threadlocal.ThreadLocalCache
* @see org.apache.dubbo.cache.support.expiring.ExpiringCacheFactory
* @see org.apache.dubbo.cache.support.expiring.ExpiringCache
*
*/
@Activate(
group = {CONSUMER, PROVIDER},
value = CACHE_KEY)
public class CacheFilter implements Filter {
private CacheFactory cacheFactory;
/**
* Dubbo will populate and set the cache factory instance based on service/method/consumer/provider configured
* cache attribute value. Dubbo will search for the class name implementing configured <b>cache</b> in file org.apache.dubbo.cache.CacheFactory
* under META-INF sub folders.
*
* @param cacheFactory instance of CacheFactory based on <b>cache</b> type
*/
public void setCacheFactory(CacheFactory cacheFactory) {
this.cacheFactory = cacheFactory;
}
/**
* If cache is configured, dubbo will invoke method on each method call. If cache value is returned by cache store
* then it will return otherwise call the remote method and return value. If remote method's return value has error
* then it will not cache the value.
* @param invoker service
* @param invocation invocation.
* @return Cache returned value if found by the underlying cache store. If cache miss it will call target method.
* @throws RpcException
*/
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (cacheFactory == null
|| ConfigUtils.isEmpty(invoker.getUrl().getMethodParameter(invocation.getMethodName(), CACHE_KEY))) {
return invoker.invoke(invocation);
}
Cache cache = cacheFactory.getCache(invoker.getUrl(), invocation);
if (cache == null) {
return invoker.invoke(invocation);
}
String key = StringUtils.toArgumentString(invocation.getArguments());
Object value = cache.get(key);
return (value != null)
? onCacheValuePresent(invocation, value)
: onCacheValueNotPresent(invoker, invocation, cache, key);
}
private Result onCacheValuePresent(Invocation invocation, Object value) {
if (value instanceof ValueWrapper) {
return AsyncRpcResult.newDefaultAsyncResult(((ValueWrapper) value).get(), invocation);
}
return AsyncRpcResult.newDefaultAsyncResult(value, invocation);
}
private Result onCacheValueNotPresent(Invoker<?> invoker, Invocation invocation, Cache cache, String key) {
Result result = invoker.invoke(invocation);
if (!result.hasException()) {
cache.put(key, new ValueWrapper(result.getValue()));
}
return result;
}
/**
* Cache value wrapper.
*/
static class ValueWrapper implements Serializable {
private static final long serialVersionUID = -1777337318019193256L;
private final Object value;
public ValueWrapper(Object value) {
this.value = value;
}
public Object get() {
return this.value;
}
}
}
| 5,574 |
0 | Create_ds/dubbo/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven | Create_ds/dubbo/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/DubboNativeCodeGeneratorMojo.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.project.MavenProject;
/**
* generate related self-adaptive code (native image does not support dynamic code generation. Therefore, code needs to be generated before compilation)
*/
@Mojo(name = "generate")
public class DubboNativeCodeGeneratorMojo extends AbstractMojo {
@Override
public void execute() {
Log log = getLog();
log.info("dubbo native code generator mojo execute");
MavenProject project = (MavenProject) this.getPluginContext().get("project");
copyNativeConfigFile(log, project);
try {
generateCode(log, project);
} catch (Exception ignored) {
}
}
private void generateCode(Log log, MavenProject project) throws IOException {
String baseDir = project.getBasedir().getPath();
File source =
new File(baseDir + File.separator + "src" + File.separator + "main" + File.separator + "generated");
FileUtils.forceMkdir(source);
project.addCompileSourceRoot(source.getAbsolutePath());
log.info("Source directory: " + source + " added.");
List<String> list = project.getCompileSourceRoots();
log.info(list.toString());
CodeGenerator.execute(source.getPath(), log);
}
private void copyNativeConfigFile(Log log, MavenProject project) {
String[] nativeFiles = {
"META-INF/native-image/reflect-config.json",
"META-INF/native-image/jni-config.json",
"META-INF/native-image/proxy-config.json",
"META-INF/native-image/resource-config.json",
"META-INF/native-image/serialization-config.json"
};
Arrays.stream(nativeFiles).forEach(nativeFile -> {
InputStream is = DubboNativeCodeGeneratorMojo.class.getClassLoader().getResourceAsStream(nativeFile);
project.getResources().stream().findFirst().ifPresent(resource -> {
String directory = resource.getDirectory();
try {
FileUtils.forceMkdir(new File(directory + File.separator + "META-INF" + File.separator
+ "native-image" + File.separator));
File file = new File(directory + File.separator + nativeFile);
if (!file.exists()) {
FileUtils.copyInputStreamToFile(is, file);
log.info("Copy native config file:" + file);
} else {
log.info("Skip copy config file:" + file);
}
} catch (Throwable ex) {
log.error("Copy native config file error:" + ex.getMessage());
}
});
});
}
}
| 5,575 |
0 | Create_ds/dubbo/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven | Create_ds/dubbo/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/ClassFinder.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin;
import java.io.File;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
public class ClassFinder {
public Set<String> findClassSet(String packageName, Consumer<String> consumer) {
packageName = packageName.replace(".", "/");
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration resources = classLoader.getResources(packageName);
Set<String> result = new HashSet<>();
while (resources.hasMoreElements()) {
URL resource = (URL) resources.nextElement();
if (resource != null) {
String protocol = resource.getProtocol();
if ("file".equals(protocol)) {
findClassesByFile(packageName, resource.getPath(), result);
} else if ("jar".equals(protocol)) {
JarFile jar = ((JarURLConnection) resource.openConnection()).getJarFile();
consumer.accept("findClassSet jar:" + jar.getName());
findClassesByJar(packageName, jar, result);
}
}
}
return result;
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
private void findClassesByFile(String packageName, String resource, Set<String> result) {
File directory = new File(resource);
File[] listFiles = directory.listFiles();
// null check
if (listFiles != null) {
for (File file : listFiles) {
if (file.isDirectory()) {
findClassesByFile(packageName, file.getPath(), result);
} else {
String path = file.getPath();
if (path.endsWith(".class")) {
int packageIndex = path.indexOf(packageName.replace("/", File.separator));
String classPath = path.substring(packageIndex, path.length() - 6);
result.add(classPath.replace(File.separator, "."));
}
}
}
}
}
private static void findClassesByJar(String packageName, JarFile jar, Set<String> classes) {
Enumeration<JarEntry> entry = jar.entries();
JarEntry jarEntry;
String name;
while (entry.hasMoreElements()) {
jarEntry = entry.nextElement();
name = jarEntry.getName();
if (name.charAt(0) == '/') {
name = name.substring(1);
}
if (jarEntry.isDirectory() || !name.startsWith(packageName) || !name.endsWith(".class")) {
continue;
}
String className = name.substring(0, name.length() - 6);
classes.add(className.replace("/", "."));
}
}
}
| 5,576 |
0 | Create_ds/dubbo/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven | Create_ds/dubbo/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/Test.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin;
import java.util.Set;
public class Test {
public static void main(String[] args) {
ClassFinder finder = new ClassFinder();
Set<String> set = finder.findClassSet("org.apache.dubbo", msg -> {});
System.out.println(set.size());
}
}
| 5,577 |
0 | Create_ds/dubbo/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven | Create_ds/dubbo/dubbo-native-plugin/src/main/java/org/apache/dubbo/maven/plugin/CodeGenerator.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.maven.plugin;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.AdaptiveClassCodeGenerator;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.utils.StringUtils;
import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.plugin.logging.SystemStreamLog;
/**
* generate related self-adaptive code (native image does not support dynamic code generation. Therefore, code needs to be generated before compilation)
*/
public class CodeGenerator {
public static void execute(String p, Log log) {
log.info("Start generating code:" + p);
List<Class<?>> classes = new ClassFinder()
.findClassSet("org.apache.dubbo", msg -> {
log.info(msg);
})
.stream()
.map(it -> {
try {
return Class.forName(it);
} catch (Throwable e) {
}
return null;
})
.collect(Collectors.toList());
new ArrayList<>(classes)
.stream()
.filter(it -> {
if (null == it) {
return false;
}
Annotation anno = it.getAnnotation(SPI.class);
if (null == anno) {
return false;
}
try {
Optional<Method> optional = Arrays.stream(it.getMethods())
.filter(it2 -> it2.getAnnotation(Adaptive.class) != null)
.findAny();
return optional.isPresent();
} catch (Throwable ex) {
log.warn(ex.getMessage());
return false;
}
})
.forEach(it -> {
try {
SPI spi = it.getAnnotation(SPI.class);
String value = spi.value();
if (StringUtils.isEmpty(value)) {
value = "adaptive";
}
AdaptiveClassCodeGenerator codeGenerator = new AdaptiveClassCodeGenerator(it, value);
String code = codeGenerator.generate();
String file = p
+ File.separator
+ it.getName().replaceAll("\\.", Matcher.quoteReplacement(File.separator));
String dir = Paths.get(file).getParent().toString();
FileUtils.forceMkdir(new File(dir));
code = licensedStr + code + "\n";
File tmpFile = new File(file + "$Adaptive.java");
FileUtils.write(tmpFile, code, Charset.defaultCharset());
log.info("Generate file:" + tmpFile);
} catch (Throwable e) {
log.error("error:" + it.getPackage());
}
});
log.info("End of code generation");
}
public static void main(String[] args) {
URL r = Thread.currentThread().getContextClassLoader().getResource("");
String targetClassPath = new File(r.getFile()).getAbsolutePath();
String p = Paths.get(targetClassPath).getParent().getParent().toString() + File.separator + "src"
+ File.separator + "main" + File.separator + "java";
execute(p, new SystemStreamLog());
}
private static String licensedStr =
"/*\n" + " * Licensed to the Apache Software Foundation (ASF) under one or more\n"
+ " * contributor license agreements. See the NOTICE file distributed with\n"
+ " * this work for additional information regarding copyright ownership.\n"
+ " * The ASF licenses this file to You under the Apache License, Version 2.0\n"
+ " * (the \"License\"); you may not use this file except in compliance with\n"
+ " * the License. You may obtain a copy of the License at\n"
+ " *\n"
+ " * http://www.apache.org/licenses/LICENSE-2.0\n"
+ " *\n"
+ " * Unless required by applicable law or agreed to in writing, software\n"
+ " * distributed under the License is distributed on an \"AS IS\" BASIS,\n"
+ " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n"
+ " * See the License for the specific language governing permissions and\n"
+ " * limitations under the License.\n"
+ " */\n";
}
| 5,578 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.apollo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import com.google.common.util.concurrent.SettableFuture;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Apollo dynamic configuration mock test.
* Notice: EmbeddedApollo(apollo mock server) only support < junit5, please not upgrade the junit version in this UT,
* the junit version in this UT is junit4, and the dependency comes from apollo-mockserver.
*/
class ApolloDynamicConfigurationTest {
private static final String SESSION_TIMEOUT_KEY = "session";
private static final String DEFAULT_NAMESPACE = "dubbo";
private static ApolloDynamicConfiguration apolloDynamicConfiguration;
private static URL url;
private static ApplicationModel applicationModel;
/**
* The constant embeddedApollo.
*/
@RegisterExtension
public static EmbeddedApolloJunit5 embeddedApollo = new EmbeddedApolloJunit5();
/**
* Sets up.
*/
@BeforeEach
public void setUp() {
String apolloUrl = System.getProperty("apollo.configService");
String urlForDubbo = "apollo://" + apolloUrl.substring(apolloUrl.lastIndexOf("/") + 1)
+ "/org.apache.dubbo.apollo.testService?namespace=dubbo&check=true";
url = URL.valueOf(urlForDubbo).addParameter(SESSION_TIMEOUT_KEY, 15000);
applicationModel = ApplicationModel.defaultModel();
}
// /**
// * Embedded Apollo does not work as expected.
// */
// @Test
// public void testProperties() {
// URL url = this.url.addParameter(GROUP_KEY, "dubbo")
// .addParameter("namespace", "governance");
//
// apolloDynamicConfiguration = new ApolloDynamicConfiguration(url);
// putData("dubbo", "dubbo.registry.address", "zookeeper://127.0.0.1:2181");
// assertEquals("zookeeper://127.0.0.1:2181", apolloDynamicConfiguration.getProperties(null, "dubbo"));
//
// putData("governance", "router.tag", "router tag rule");
// assertEquals("router tag rule", apolloDynamicConfiguration.getConfig("router.tag", "governance"));
//
// }
/**
* Test get rule.
*/
@Test
void testGetRule() {
String mockKey = "mockKey1";
String mockValue = String.valueOf(new Random().nextInt());
putMockRuleData(mockKey, mockValue, DEFAULT_NAMESPACE);
apolloDynamicConfiguration = new ApolloDynamicConfiguration(url, applicationModel);
assertEquals(mockValue, apolloDynamicConfiguration.getConfig(mockKey, DEFAULT_NAMESPACE, 3000L));
mockKey = "notExistKey";
assertNull(apolloDynamicConfiguration.getConfig(mockKey, DEFAULT_NAMESPACE, 3000L));
}
/**
* Test get internal property.
*
* @throws InterruptedException the interrupted exception
*/
@Test
void testGetInternalProperty() throws InterruptedException {
String mockKey = "mockKey2";
String mockValue = String.valueOf(new Random().nextInt());
putMockRuleData(mockKey, mockValue, DEFAULT_NAMESPACE);
TimeUnit.MILLISECONDS.sleep(1000);
apolloDynamicConfiguration = new ApolloDynamicConfiguration(url, applicationModel);
assertEquals(mockValue, apolloDynamicConfiguration.getInternalProperty(mockKey));
mockValue = "mockValue2";
System.setProperty(mockKey, mockValue);
assertEquals(mockValue, apolloDynamicConfiguration.getInternalProperty(mockKey));
mockKey = "notExistKey";
assertNull(apolloDynamicConfiguration.getInternalProperty(mockKey));
}
/**
* Test add listener.
*
* @throws Exception the exception
*/
@Test
void testAddListener() throws Exception {
String mockKey = "mockKey3";
String mockValue = String.valueOf(new Random().nextInt());
final SettableFuture<org.apache.dubbo.common.config.configcenter.ConfigChangedEvent> future =
SettableFuture.create();
apolloDynamicConfiguration = new ApolloDynamicConfiguration(url, applicationModel);
apolloDynamicConfiguration.addListener(mockKey, DEFAULT_NAMESPACE, new ConfigurationListener() {
@Override
public void process(org.apache.dubbo.common.config.configcenter.ConfigChangedEvent event) {
future.set(event);
}
});
putData(mockKey, mockValue);
org.apache.dubbo.common.config.configcenter.ConfigChangedEvent result = future.get(3000, TimeUnit.MILLISECONDS);
assertEquals(mockValue, result.getContent());
assertEquals(mockKey, result.getKey());
assertEquals(ConfigChangeType.MODIFIED, result.getChangeType());
}
private static void putData(String namespace, String key, String value) {
embeddedApollo.addOrModifyProperty(namespace, key, value);
}
private static void putData(String key, String value) {
embeddedApollo.addOrModifyProperty(DEFAULT_NAMESPACE, key, value);
}
private static void putMockRuleData(String key, String value, String group) {
String fileName =
ApolloDynamicConfigurationTest.class.getResource("/").getPath() + "mockdata-" + group + ".properties";
putMockData(key, value, fileName);
}
private static void putMockData(String key, String value, String fileName) {
Properties pro = new Properties();
FileOutputStream oFile = null;
try {
oFile = new FileOutputStream(fileName);
pro.setProperty(key, value);
pro.store(oFile, "put mock data");
} catch (IOException exx) {
fail(exx.getMessage());
} finally {
if (null != oFile) {
try {
oFile.close();
} catch (IOException e) {
fail(e.getMessage());
}
}
}
}
/**
* Tear down.
*/
@AfterEach
public void tearDown() {}
}
| 5,579 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-apollo/src/test/java/org/apache/dubbo/configcenter/support/apollo/EmbeddedApolloJunit5.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.apollo;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.JsonUtils;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import com.ctrip.framework.apollo.build.ApolloInjector;
import com.ctrip.framework.apollo.core.dto.ApolloConfig;
import com.ctrip.framework.apollo.core.dto.ApolloConfigNotification;
import com.ctrip.framework.apollo.core.utils.ResourceUtils;
import com.ctrip.framework.apollo.internals.ConfigServiceLocator;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CLOSE_CONNECT_APOLLO;
public class EmbeddedApolloJunit5 implements BeforeAllCallback, AfterAllCallback {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(EmbeddedApolloJunit5.class);
private static Method CONFIG_SERVICE_LOCATOR_CLEAR;
private static ConfigServiceLocator CONFIG_SERVICE_LOCATOR;
private final Map<String, Map<String, String>> addedOrModifiedPropertiesOfNamespace = Maps.newConcurrentMap();
private final Map<String, Set<String>> deletedKeysOfNamespace = Maps.newConcurrentMap();
private MockWebServer server;
static {
try {
System.setProperty("apollo.longPollingInitialDelayInMills", "0");
CONFIG_SERVICE_LOCATOR = ApolloInjector.getInstance(ConfigServiceLocator.class);
CONFIG_SERVICE_LOCATOR_CLEAR = ConfigServiceLocator.class.getDeclaredMethod("initConfigServices");
CONFIG_SERVICE_LOCATOR_CLEAR.setAccessible(true);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
private void clear() throws Exception {
resetOverriddenProperties();
}
private void mockConfigServiceUrl(String url) throws Exception {
System.setProperty("apollo.configService", url);
CONFIG_SERVICE_LOCATOR_CLEAR.invoke(CONFIG_SERVICE_LOCATOR);
}
private String loadConfigFor(String namespace) {
String filename = String.format("mockdata-%s.properties", namespace);
final Properties prop = ResourceUtils.readConfigFile(filename, new Properties());
Map<String, String> configurations = Maps.newHashMap();
for (String propertyName : prop.stringPropertyNames()) {
configurations.put(propertyName, prop.getProperty(propertyName));
}
ApolloConfig apolloConfig = new ApolloConfig("someAppId", "someCluster", namespace, "someReleaseKey");
Map<String, String> mergedConfigurations = mergeOverriddenProperties(namespace, configurations);
apolloConfig.setConfigurations(mergedConfigurations);
return JsonUtils.toJson(apolloConfig);
}
private String mockLongPollBody(String notificationsStr) {
List<ApolloConfigNotification> oldNotifications =
JsonUtils.toJavaList(notificationsStr, ApolloConfigNotification.class);
List<ApolloConfigNotification> newNotifications = new ArrayList<>();
for (ApolloConfigNotification notification : oldNotifications) {
newNotifications.add(new ApolloConfigNotification(
notification.getNamespaceName(), notification.getNotificationId() + 1));
}
return JsonUtils.toJson(newNotifications);
}
/**
* Incorporate user modifications to namespace
*/
private Map<String, String> mergeOverriddenProperties(String namespace, Map<String, String> configurations) {
if (addedOrModifiedPropertiesOfNamespace.containsKey(namespace)) {
configurations.putAll(addedOrModifiedPropertiesOfNamespace.get(namespace));
}
if (deletedKeysOfNamespace.containsKey(namespace)) {
for (String k : deletedKeysOfNamespace.get(namespace)) {
configurations.remove(k);
}
}
return configurations;
}
/**
* Add new property or update existed property
*/
public void addOrModifyProperty(String namespace, String someKey, String someValue) {
if (addedOrModifiedPropertiesOfNamespace.containsKey(namespace)) {
addedOrModifiedPropertiesOfNamespace.get(namespace).put(someKey, someValue);
} else {
Map<String, String> m = Maps.newConcurrentMap();
m.put(someKey, someValue);
addedOrModifiedPropertiesOfNamespace.put(namespace, m);
}
}
/**
* Delete existed property
*/
public void deleteProperty(String namespace, String someKey) {
if (deletedKeysOfNamespace.containsKey(namespace)) {
deletedKeysOfNamespace.get(namespace).add(someKey);
} else {
Set<String> m = Sets.newConcurrentHashSet();
m.add(someKey);
deletedKeysOfNamespace.put(namespace, m);
}
}
/**
* reset overridden properties
*/
public void resetOverriddenProperties() {
addedOrModifiedPropertiesOfNamespace.clear();
deletedKeysOfNamespace.clear();
}
@Override
public void afterAll(ExtensionContext extensionContext) throws Exception {
try {
clear();
server.close();
} catch (Exception e) {
logger.error(CONFIG_FAILED_CLOSE_CONNECT_APOLLO, "", "", "stop apollo server error", e);
}
}
@Override
public void beforeAll(ExtensionContext extensionContext) throws Exception {
clear();
server = new MockWebServer();
final Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
if (request.getPath().startsWith("/notifications/v2")) {
String notifications = request.getRequestUrl().queryParameter("notifications");
return new MockResponse().setResponseCode(200).setBody(mockLongPollBody(notifications));
}
if (request.getPath().startsWith("/configs")) {
List<String> pathSegments = request.getRequestUrl().pathSegments();
// appId and cluster might be used in the future
String appId = pathSegments.get(1);
String cluster = pathSegments.get(2);
String namespace = pathSegments.get(3);
return new MockResponse().setResponseCode(200).setBody(loadConfigFor(namespace));
}
return new MockResponse().setResponseCode(404);
}
};
server.setDispatcher(dispatcher);
server.start();
mockConfigServiceUrl("http://localhost:" + server.getPort());
}
}
| 5,580 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfigurationFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.apollo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.rpc.model.ApplicationModel;
/**
*
*/
public class ApolloDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory {
private ApplicationModel applicationModel;
public ApolloDynamicConfigurationFactory(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
protected DynamicConfiguration createDynamicConfiguration(URL url) {
return new ApolloDynamicConfiguration(url, applicationModel);
}
}
| 5,581 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-apollo/src/main/java/org/apache/dubbo/configcenter/support/apollo/ApolloDynamicConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.apollo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metrics.config.event.ConfigCenterEvent;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigChangeListener;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import com.ctrip.framework.apollo.enums.ConfigSourceType;
import com.ctrip.framework.apollo.enums.PropertyChangeType;
import com.ctrip.framework.apollo.model.ConfigChange;
import static org.apache.dubbo.common.constants.CommonConstants.ANYHOST_VALUE;
import static org.apache.dubbo.common.constants.CommonConstants.CHECK_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CLUSTER_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.COMMA_SPLIT_PATTERN;
import static org.apache.dubbo.common.constants.CommonConstants.CONFIG_NAMESPACE_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CLOSE_CONNECT_APOLLO;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_NOT_EFFECT_EMPTY_RULE_APOLLO;
import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE;
/**
* Apollo implementation, https://github.com/ctripcorp/apollo
* <p>
* Apollo will be used for management of both governance rules and .properties files, by default, these two different
* kinds of data share the same namespace 'dubbo'. To gain better performance, we recommend separate them by giving
* namespace and group different values, for example:
* <p>
* <dubbo:config-center namespace="governance" group="dubbo" />, 'dubbo=governance' is for governance rules while
* 'group=dubbo' is for properties files.
* <p>
* Please see http://dubbo.apache.org/zh-cn/docs/user/configuration/config-center.html for details.
*/
public class ApolloDynamicConfiguration implements DynamicConfiguration {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(ApolloDynamicConfiguration.class);
private static final String APOLLO_ENV_KEY = "env";
private static final String APOLLO_ADDR_KEY = "apollo.meta";
private static final String APOLLO_CLUSTER_KEY = "apollo.cluster";
private static final String APOLLO_PROTOCOL_PREFIX = "http://";
private static final String APOLLO_APPLICATION_KEY = "application";
private static final String APOLLO_APPID_KEY = "app.id";
private final URL url;
private final Config dubboConfig;
private final ConfigFile dubboConfigFile;
private final ConcurrentMap<String, ApolloListener> listeners = new ConcurrentHashMap<>();
private final ApplicationModel applicationModel;
ApolloDynamicConfiguration(URL url, ApplicationModel applicationModel) {
this.url = url;
this.applicationModel = applicationModel;
// Instead of using Dubbo's configuration, I would suggest use the original configuration method Apollo
// provides.
String configEnv = url.getParameter(APOLLO_ENV_KEY);
String configAddr = getAddressWithProtocolPrefix(url);
String configCluster = url.getParameter(CLUSTER_KEY);
String configAppId = url.getParameter(APOLLO_APPID_KEY);
if (StringUtils.isEmpty(System.getProperty(APOLLO_ENV_KEY)) && configEnv != null) {
System.setProperty(APOLLO_ENV_KEY, configEnv);
}
if (StringUtils.isEmpty(System.getProperty(APOLLO_ADDR_KEY)) && !ANYHOST_VALUE.equals(url.getHost())) {
System.setProperty(APOLLO_ADDR_KEY, configAddr);
}
if (StringUtils.isEmpty(System.getProperty(APOLLO_CLUSTER_KEY)) && configCluster != null) {
System.setProperty(APOLLO_CLUSTER_KEY, configCluster);
}
if (StringUtils.isEmpty(System.getProperty(APOLLO_APPID_KEY)) && configAppId != null) {
System.setProperty(APOLLO_APPID_KEY, configAppId);
}
String namespace = url.getParameter(CONFIG_NAMESPACE_KEY, DEFAULT_GROUP);
String apolloNamespace = StringUtils.isEmpty(namespace) ? url.getGroup(DEFAULT_GROUP) : namespace;
dubboConfig = ConfigService.getConfig(apolloNamespace);
dubboConfigFile = ConfigService.getConfigFile(apolloNamespace, ConfigFileFormat.Properties);
// Decide to fail or to continue when failed to connect to remote server.
boolean check = url.getParameter(CHECK_KEY, true);
if (dubboConfig.getSourceType() != ConfigSourceType.REMOTE) {
if (check) {
throw new IllegalStateException("Failed to connect to config center, the config center is Apollo, "
+ "the address is: " + (StringUtils.isNotEmpty(configAddr) ? configAddr : configEnv));
} else {
// 5-1 Failed to connect to configuration center.
logger.warn(
CONFIG_FAILED_CONNECT_REGISTRY,
"configuration server offline",
"",
"Failed to connect to config center, the config center is Apollo, " + "the address is: "
+ (StringUtils.isNotEmpty(configAddr) ? configAddr : configEnv)
+ ", will use the local cache value instead before eventually the connection is established.");
}
}
}
@Override
public void close() {
try {
listeners.clear();
} catch (UnsupportedOperationException e) {
logger.warn(
CONFIG_FAILED_CLOSE_CONNECT_APOLLO,
"",
"",
"Failed to close connect from config center, the config center is Apollo");
}
}
private String getAddressWithProtocolPrefix(URL url) {
String address = url.getBackupAddress();
if (StringUtils.isNotEmpty(address)) {
address = Arrays.stream(COMMA_SPLIT_PATTERN.split(address))
.map(addr -> {
if (addr.startsWith(APOLLO_PROTOCOL_PREFIX)) {
return addr;
}
return APOLLO_PROTOCOL_PREFIX + addr;
})
.collect(Collectors.joining(","));
}
return address;
}
/**
* Since all governance rules will lay under dubbo group, this method now always uses the default dubboConfig and
* ignores the group parameter.
*/
@Override
public void addListener(String key, String group, ConfigurationListener listener) {
ApolloListener apolloListener = listeners.computeIfAbsent(group + key, k -> createTargetListener(key, group));
apolloListener.addListener(listener);
dubboConfig.addChangeListener(apolloListener, Collections.singleton(key));
}
@Override
public void removeListener(String key, String group, ConfigurationListener listener) {
ApolloListener apolloListener = listeners.get(group + key);
if (apolloListener != null) {
apolloListener.removeListener(listener);
if (!apolloListener.hasInternalListener()) {
dubboConfig.removeChangeListener(apolloListener);
}
}
}
@Override
public String getConfig(String key, String group, long timeout) throws IllegalStateException {
if (StringUtils.isNotEmpty(group)) {
if (group.equals(url.getApplication())) {
return ConfigService.getAppConfig().getProperty(key, null);
} else {
return ConfigService.getConfig(group).getProperty(key, null);
}
}
return dubboConfig.getProperty(key, null);
}
/**
* Recommend specify namespace and group when using Apollo.
* <p>
* <dubbo:config-center namespace="governance" group="dubbo" />, 'dubbo=governance' is for governance rules while
* 'group=dubbo' is for properties files.
*
* @param key default value is 'dubbo.properties', currently useless for Apollo.
* @param group
* @param timeout
* @return
* @throws IllegalStateException
*/
@Override
public String getProperties(String key, String group, long timeout) throws IllegalStateException {
if (StringUtils.isEmpty(group)) {
return dubboConfigFile.getContent();
}
if (group.equals(url.getApplication())) {
return ConfigService.getConfigFile(APOLLO_APPLICATION_KEY, ConfigFileFormat.Properties)
.getContent();
}
ConfigFile configFile = ConfigService.getConfigFile(group, ConfigFileFormat.Properties);
if (configFile == null) {
throw new IllegalStateException("There is no namespace named " + group + " in Apollo.");
}
return configFile.getContent();
}
/**
* This method will be used by Configuration to get valid value at runtime.
* The group is expected to be 'app level', which can be fetched from the 'config.appnamespace' in url if necessary.
* But I think Apollo's inheritance feature of namespace can solve the problem .
*/
@Override
public String getInternalProperty(String key) {
return dubboConfig.getProperty(key, null);
}
/**
* Ignores the group parameter.
*
* @param key property key the native listener will listen on
* @param group to distinguish different set of properties
* @return
*/
private ApolloListener createTargetListener(String key, String group) {
return new ApolloListener();
}
public class ApolloListener implements ConfigChangeListener {
private Set<ConfigurationListener> listeners = new CopyOnWriteArraySet<>();
ApolloListener() {}
@Override
public void onChange(com.ctrip.framework.apollo.model.ConfigChangeEvent changeEvent) {
for (String key : changeEvent.changedKeys()) {
ConfigChange change = changeEvent.getChange(key);
if ("".equals(change.getNewValue())) {
logger.warn(
CONFIG_NOT_EFFECT_EMPTY_RULE_APOLLO,
"",
"",
"an empty rule is received for " + key + ", the current working rule is "
+ change.getOldValue() + ", the empty rule will not take effect.");
return;
}
ConfigChangedEvent event =
new ConfigChangedEvent(key, change.getNamespace(), change.getNewValue(), getChangeType(change));
listeners.forEach(listener -> listener.process(event));
MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent(
applicationModel,
event.getKey(),
event.getGroup(),
ConfigCenterEvent.APOLLO_PROTOCOL,
ConfigChangeType.ADDED.name(),
SELF_INCREMENT_SIZE));
}
}
private ConfigChangeType getChangeType(ConfigChange change) {
if (change.getChangeType() == PropertyChangeType.DELETED) {
return ConfigChangeType.DELETED;
}
return ConfigChangeType.MODIFIED;
}
void addListener(ConfigurationListener configurationListener) {
this.listeners.add(configurationListener);
}
void removeListener(ConfigurationListener configurationListener) {
this.listeners.remove(configurationListener);
}
boolean hasInternalListener() {
return listeners != null && listeners.size() > 0;
}
}
}
| 5,582 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.nacos;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Unit test for nacos config center support
*/
// FIXME: waiting for embedded Nacos suport, then we can open the switch.
@Disabled("https://github.com/alibaba/nacos/issues/1188")
class NacosDynamicConfigurationTest {
private static final String SESSION_TIMEOUT_KEY = "session";
private static NacosDynamicConfiguration config;
/**
* A test client to put data to Nacos server for testing purpose
*/
private static ConfigService nacosClient;
@Test
void testGetConfig() throws Exception {
put("org.apache.dubbo.nacos.testService.configurators", "hello");
Thread.sleep(200);
put("dubbo.properties", "test", "aaa=bbb");
Thread.sleep(200);
put("org.apache.dubbo.demo.DemoService:1.0.0.test:xxxx.configurators", "helloworld");
Thread.sleep(200);
Assertions.assertEquals(
"hello",
config.getConfig(
"org.apache.dubbo.nacos.testService.configurators", DynamicConfiguration.DEFAULT_GROUP));
Assertions.assertEquals("aaa=bbb", config.getConfig("dubbo.properties", "test"));
Assertions.assertEquals(
"helloworld",
config.getConfig(
"org.apache.dubbo.demo.DemoService:1.0.0.test:xxxx.configurators",
DynamicConfiguration.DEFAULT_GROUP));
}
@Test
void testAddListener() throws Exception {
CountDownLatch latch = new CountDownLatch(4);
TestListener listener1 = new TestListener(latch);
TestListener listener2 = new TestListener(latch);
TestListener listener3 = new TestListener(latch);
TestListener listener4 = new TestListener(latch);
config.addListener("AService.configurators", listener1);
config.addListener("AService.configurators", listener2);
config.addListener("testapp.tag-router", listener3);
config.addListener("testapp.tag-router", listener4);
put("AService.configurators", "new value1");
Thread.sleep(200);
put("testapp.tag-router", "new value2");
Thread.sleep(200);
put("testapp", "new value3");
Thread.sleep(5000);
latch.await();
Assertions.assertEquals(1, listener1.getCount("AService.configurators"));
Assertions.assertEquals(1, listener2.getCount("AService.configurators"));
Assertions.assertEquals(1, listener3.getCount("testapp.tag-router"));
Assertions.assertEquals(1, listener4.getCount("testapp.tag-router"));
Assertions.assertEquals("new value1", listener1.getValue());
Assertions.assertEquals("new value1", listener2.getValue());
Assertions.assertEquals("new value2", listener3.getValue());
Assertions.assertEquals("new value2", listener4.getValue());
}
//
// @Test
// public void testGetConfigKeys() {
//
// put("key1", "a");
// put("key2", "b");
//
// SortedSet<String> keys = config.getConfigKeys(DynamicConfiguration.DEFAULT_GROUP);
//
// Assertions.assertFalse(keys.isEmpty());
//
// }
private void put(String key, String value) {
put(key, DynamicConfiguration.DEFAULT_GROUP, value);
}
private void put(String key, String group, String value) {
try {
nacosClient.publishConfig(key, group, value);
} catch (Exception e) {
System.out.println("Error put value to nacos.");
}
}
@BeforeAll
public static void setUp() {
String urlForDubbo = "nacos://" + "127.0.0.1:8848" + "/org.apache.dubbo.nacos.testService";
// timeout in 15 seconds.
URL url = URL.valueOf(urlForDubbo).addParameter(SESSION_TIMEOUT_KEY, 15000);
config = new NacosDynamicConfiguration(url, ApplicationModel.defaultModel());
try {
nacosClient = NacosFactory.createConfigService("127.0.0.1:8848");
} catch (NacosException e) {
e.printStackTrace();
}
}
@Test
void testPublishConfig() {
String key = "user-service";
String group = "org.apache.dubbo.service.UserService";
String content = "test";
assertTrue(config.publishConfig(key, group, content));
assertEquals("test", config.getProperties(key, group));
}
@AfterAll
public static void tearDown() {}
private class TestListener implements ConfigurationListener {
private CountDownLatch latch;
private String value;
private Map<String, Integer> countMap = new HashMap<>();
public TestListener(CountDownLatch latch) {
this.latch = latch;
}
@Override
public void process(ConfigChangedEvent event) {
System.out.println(this + ": " + event);
Integer count = countMap.computeIfAbsent(event.getKey(), k -> 0);
countMap.put(event.getKey(), ++count);
value = event.getContent();
latch.countDown();
}
public int getCount(String key) {
return countMap.get(key);
}
public String getValue() {
return value;
}
}
}
| 5,583 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/MockConfigService.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.nacos;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
public class MockConfigService implements ConfigService {
@Override
public String getConfig(String dataId, String group, long timeoutMs) throws NacosException {
return null;
}
@Override
public String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener)
throws NacosException {
return null;
}
@Override
public void addListener(String dataId, String group, Listener listener) throws NacosException {}
@Override
public boolean publishConfig(String dataId, String group, String content) throws NacosException {
return false;
}
@Override
public boolean publishConfig(String dataId, String group, String content, String type) throws NacosException {
return false;
}
@Override
public boolean publishConfigCas(String dataId, String group, String content, String casMd5) throws NacosException {
return false;
}
@Override
public boolean publishConfigCas(String dataId, String group, String content, String casMd5, String type)
throws NacosException {
return false;
}
@Override
public boolean removeConfig(String dataId, String group) throws NacosException {
return false;
}
@Override
public void removeListener(String dataId, String group, Listener listener) {}
@Override
public String getServerStatus() {
return null;
}
@Override
public void shutDown() throws NacosException {}
}
| 5,584 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/test/java/org/apache/dubbo/configcenter/support/nacos/RetryTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.nacos;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicInteger;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import static com.alibaba.nacos.client.constant.Constants.HealthCheck.DOWN;
import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP;
import static org.mockito.ArgumentMatchers.any;
class RetryTest {
private static ApplicationModel applicationModel = ApplicationModel.defaultModel();
@Test
void testRetryCreate() {
try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
AtomicInteger atomicInteger = new AtomicInteger(0);
ConfigService mock = new MockConfigService() {
@Override
public String getServerStatus() {
return atomicInteger.incrementAndGet() > 10 ? UP : DOWN;
}
};
nacosFactoryMockedStatic
.when(() -> NacosFactory.createConfigService((Properties) any()))
.thenReturn(mock);
URL url = URL.valueOf("nacos://127.0.0.1:8848")
.addParameter("nacos.retry", 5)
.addParameter("nacos.retry-wait", 10);
Assertions.assertThrows(
IllegalStateException.class, () -> new NacosDynamicConfiguration(url, applicationModel));
try {
new NacosDynamicConfiguration(url, applicationModel);
} catch (Throwable t) {
Assertions.fail(t);
}
}
}
@Test
void testDisable() {
try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
ConfigService mock = new MockConfigService() {
@Override
public String getServerStatus() {
return DOWN;
}
};
nacosFactoryMockedStatic
.when(() -> NacosFactory.createConfigService((Properties) any()))
.thenReturn(mock);
URL url = URL.valueOf("nacos://127.0.0.1:8848")
.addParameter("nacos.retry", 5)
.addParameter("nacos.retry-wait", 10)
.addParameter("nacos.check", "false");
try {
new NacosDynamicConfiguration(url, applicationModel);
} catch (Throwable t) {
Assertions.fail(t);
}
}
}
@Test
void testRequest() {
try (MockedStatic<NacosFactory> nacosFactoryMockedStatic = Mockito.mockStatic(NacosFactory.class)) {
AtomicInteger atomicInteger = new AtomicInteger(0);
ConfigService mock = new MockConfigService() {
@Override
public String getConfig(String dataId, String group, long timeoutMs) throws NacosException {
if (atomicInteger.incrementAndGet() > 10) {
return "";
} else {
throw new NacosException();
}
}
@Override
public String getServerStatus() {
return UP;
}
};
nacosFactoryMockedStatic
.when(() -> NacosFactory.createConfigService((Properties) any()))
.thenReturn(mock);
URL url = URL.valueOf("nacos://127.0.0.1:8848")
.addParameter("nacos.retry", 5)
.addParameter("nacos.retry-wait", 10);
Assertions.assertThrows(
IllegalStateException.class, () -> new NacosDynamicConfiguration(url, applicationModel));
try {
new NacosDynamicConfiguration(url, applicationModel);
} catch (Throwable t) {
Assertions.fail(t);
}
}
}
}
| 5,585 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.nacos;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.constants.LoggerCodeConstants;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.MD5Utils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.metrics.config.event.ConfigCenterEvent;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.Executor;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractSharedListener;
import com.alibaba.nacos.api.exception.NacosException;
import static com.alibaba.nacos.api.PropertyKeyConst.PASSWORD;
import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR;
import static com.alibaba.nacos.api.PropertyKeyConst.USERNAME;
import static com.alibaba.nacos.client.constant.Constants.HealthCheck.UP;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_ERROR_NACOS;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.INTERNAL_INTERRUPTED;
import static org.apache.dubbo.common.constants.RemotingConstants.BACKUP_KEY;
import static org.apache.dubbo.common.utils.StringConstantFieldValuePredicate.of;
import static org.apache.dubbo.common.utils.StringUtils.HYPHEN_CHAR;
import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE;
/**
* The nacos implementation of {@link DynamicConfiguration}
*/
public class NacosDynamicConfiguration implements DynamicConfiguration {
private static final String GET_CONFIG_KEYS_PATH = "/v1/cs/configs";
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
/**
* the default timeout in millis to get config from nacos
*/
private static final long DEFAULT_TIMEOUT = 5000L;
private final Properties nacosProperties;
private static final String NACOS_RETRY_KEY = "nacos.retry";
private static final String NACOS_RETRY_WAIT_KEY = "nacos.retry-wait";
private static final String NACOS_CHECK_KEY = "nacos.check";
/**
* The nacos configService
*/
private final NacosConfigServiceWrapper configService;
private ApplicationModel applicationModel;
/**
* The map store the key to {@link NacosConfigListener} mapping
*/
private final ConcurrentMap<String, NacosConfigListener> watchListenerMap;
private final MD5Utils md5Utils = new MD5Utils();
NacosDynamicConfiguration(URL url, ApplicationModel applicationModel) {
this.nacosProperties = buildNacosProperties(url);
this.configService = buildConfigService(url);
this.watchListenerMap = new ConcurrentHashMap<>();
this.applicationModel = applicationModel;
}
private NacosConfigServiceWrapper buildConfigService(URL url) {
int retryTimes = url.getPositiveParameter(NACOS_RETRY_KEY, 10);
int sleepMsBetweenRetries = url.getPositiveParameter(NACOS_RETRY_WAIT_KEY, 1000);
boolean check = url.getParameter(NACOS_CHECK_KEY, true);
ConfigService tmpConfigServices = null;
try {
for (int i = 0; i < retryTimes + 1; i++) {
tmpConfigServices = NacosFactory.createConfigService(nacosProperties);
String serverStatus = tmpConfigServices.getServerStatus();
boolean configServiceAvailable = testConfigService(tmpConfigServices);
if (!check || (UP.equals(serverStatus) && configServiceAvailable)) {
break;
} else {
logger.warn(
LoggerCodeConstants.CONFIG_ERROR_NACOS,
"",
"",
"Failed to connect to nacos config server. " + "Server status: "
+ serverStatus + ". " + "Config Service Available: "
+ configServiceAvailable + ". "
+ (i < retryTimes
? "Dubbo will try to retry in " + sleepMsBetweenRetries + ". "
: "Exceed retry max times.")
+ "Try times: "
+ (i + 1));
}
tmpConfigServices.shutDown();
tmpConfigServices = null;
Thread.sleep(sleepMsBetweenRetries);
}
} catch (NacosException e) {
logger.error(CONFIG_ERROR_NACOS, "", "", e.getErrMsg(), e);
throw new IllegalStateException(e);
} catch (InterruptedException e) {
logger.error(INTERNAL_INTERRUPTED, "", "", "Interrupted when creating nacos config service client.", e);
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
if (tmpConfigServices == null) {
logger.error(
CONFIG_ERROR_NACOS,
"",
"",
"Failed to create nacos config service client. Reason: server status check failed.");
throw new IllegalStateException(
"Failed to create nacos config service client. Reason: server status check failed.");
}
return new NacosConfigServiceWrapper(tmpConfigServices);
}
private boolean testConfigService(ConfigService configService) {
try {
configService.getConfig("Dubbo-Nacos-Test", "Dubbo-Nacos-Test", DEFAULT_TIMEOUT);
return true;
} catch (NacosException e) {
return false;
}
}
private Properties buildNacosProperties(URL url) {
Properties properties = new Properties();
setServerAddr(url, properties);
setProperties(url, properties);
return properties;
}
private void setServerAddr(URL url, Properties properties) {
StringBuilder serverAddrBuilder = new StringBuilder(url.getHost()) // Host
.append(':')
.append(url.getPort()); // Port
// Append backup parameter as other servers
String backup = url.getParameter(BACKUP_KEY);
if (backup != null) {
serverAddrBuilder.append(',').append(backup);
}
String serverAddr = serverAddrBuilder.toString();
properties.put(SERVER_ADDR, serverAddr);
}
private static void setProperties(URL url, Properties properties) {
// Get the parameters from constants
Map<String, String> parameters = url.getParameters(of(PropertyKeyConst.class));
// Put all parameters
properties.putAll(parameters);
if (StringUtils.isNotEmpty(url.getUsername())) {
properties.put(USERNAME, url.getUsername());
}
if (StringUtils.isNotEmpty(url.getPassword())) {
properties.put(PASSWORD, url.getPassword());
}
}
private static void putPropertyIfAbsent(URL url, Properties properties, String propertyName) {
String propertyValue = url.getParameter(propertyName);
if (StringUtils.isNotEmpty(propertyValue)) {
properties.setProperty(propertyName, propertyValue);
}
}
private static void putPropertyIfAbsent(URL url, Properties properties, String propertyName, String defaultValue) {
String propertyValue = url.getParameter(propertyName);
if (StringUtils.isNotEmpty(propertyValue)) {
properties.setProperty(propertyName, propertyValue);
} else {
properties.setProperty(propertyName, defaultValue);
}
}
/**
* Ignores the group parameter.
*
* @param key property key the native listener will listen on
* @param group to distinguish different set of properties
* @return
*/
private NacosConfigListener createTargetListener(String key, String group) {
NacosConfigListener configListener = new NacosConfigListener();
configListener.fillContext(key, group);
return configListener;
}
@Override
public void close() throws Exception {
configService.shutdown();
}
@Override
public void addListener(String key, String group, ConfigurationListener listener) {
String listenerKey = buildListenerKey(key, group);
NacosConfigListener nacosConfigListener = ConcurrentHashMapUtils.computeIfAbsent(
watchListenerMap, listenerKey, k -> createTargetListener(key, group));
nacosConfigListener.addListener(listener);
try {
configService.addListener(key, group, nacosConfigListener);
} catch (NacosException e) {
logger.error(CONFIG_ERROR_NACOS, "", "", e.getMessage(), e);
}
}
@Override
public void removeListener(String key, String group, ConfigurationListener listener) {
String listenerKey = buildListenerKey(key, group);
NacosConfigListener eventListener = watchListenerMap.get(listenerKey);
if (eventListener != null) {
eventListener.removeListener(listener);
}
}
@Override
public String getConfig(String key, String group, long timeout) throws IllegalStateException {
try {
long nacosTimeout = timeout < 0 ? getDefaultTimeout() : timeout;
if (StringUtils.isEmpty(group)) {
group = DEFAULT_GROUP;
}
return configService.getConfig(key, group, nacosTimeout);
} catch (NacosException e) {
logger.error(CONFIG_ERROR_NACOS, "", "", e.getMessage(), e);
}
return null;
}
@Override
public ConfigItem getConfigItem(String key, String group) {
String content = getConfig(key, group);
String casMd5 = "";
if (StringUtils.isNotEmpty(content)) {
casMd5 = md5Utils.getMd5(content);
}
return new ConfigItem(content, casMd5);
}
@Override
public Object getInternalProperty(String key) {
try {
return configService.getConfig(key, DEFAULT_GROUP, getDefaultTimeout());
} catch (NacosException e) {
logger.error(CONFIG_ERROR_NACOS, "", "", e.getMessage(), e);
}
return null;
}
@Override
public boolean publishConfig(String key, String group, String content) {
boolean published = false;
try {
published = configService.publishConfig(key, group, content);
} catch (NacosException e) {
logger.error(CONFIG_ERROR_NACOS, "", "", e.getMessage(), e);
}
return published;
}
@Override
public boolean publishConfigCas(String key, String group, String content, Object ticket) {
try {
if (!(ticket instanceof String)) {
throw new IllegalArgumentException("nacos publishConfigCas requires string type ticket");
}
return configService.publishConfigCas(key, group, content, (String) ticket);
} catch (NacosException e) {
logger.warn(CONFIG_ERROR_NACOS, "nacos publishConfigCas failed.", "", e.getMessage(), e);
return false;
}
}
@Override
public long getDefaultTimeout() {
return DEFAULT_TIMEOUT;
}
@Override
public boolean removeConfig(String key, String group) {
boolean removed = false;
try {
removed = configService.removeConfig(key, group);
} catch (NacosException e) {
if (logger.isErrorEnabled()) {
logger.error(CONFIG_ERROR_NACOS, "", "", e.getMessage(), e);
}
}
return removed;
}
private String getProperty(String name, String defaultValue) {
return nacosProperties.getProperty(name, defaultValue);
}
public class NacosConfigListener extends AbstractSharedListener {
private Set<ConfigurationListener> listeners = new CopyOnWriteArraySet<>();
/**
* cache data to store old value
*/
private Map<String, String> cacheData = new ConcurrentHashMap<>();
@Override
public Executor getExecutor() {
return null;
}
/**
* receive
*
* @param dataId data ID
* @param group group
* @param configInfo content
*/
@Override
public void innerReceive(String dataId, String group, String configInfo) {
String oldValue = cacheData.get(dataId);
ConfigChangedEvent event =
new ConfigChangedEvent(dataId, group, configInfo, getChangeType(configInfo, oldValue));
if (configInfo == null) {
cacheData.remove(dataId);
} else {
cacheData.put(dataId, configInfo);
}
listeners.forEach(listener -> listener.process(event));
MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent(
applicationModel,
event.getKey(),
event.getGroup(),
ConfigCenterEvent.NACOS_PROTOCOL,
ConfigChangeType.ADDED.name(),
SELF_INCREMENT_SIZE));
}
void addListener(ConfigurationListener configurationListener) {
this.listeners.add(configurationListener);
}
void removeListener(ConfigurationListener configurationListener) {
this.listeners.remove(configurationListener);
}
private ConfigChangeType getChangeType(String configInfo, String oldValue) {
if (StringUtils.isBlank(configInfo)) {
return ConfigChangeType.DELETED;
}
if (StringUtils.isBlank(oldValue)) {
return ConfigChangeType.ADDED;
}
return ConfigChangeType.MODIFIED;
}
}
protected String buildListenerKey(String key, String group) {
return key + HYPHEN_CHAR + group;
}
}
| 5,586 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosDynamicConfigurationFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.nacos;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.rpc.model.ApplicationModel;
import com.alibaba.nacos.api.PropertyKeyConst;
/**
* The nacos implementation of {@link AbstractDynamicConfigurationFactory}
*/
public class NacosDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory {
private ApplicationModel applicationModel;
public NacosDynamicConfigurationFactory(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
protected DynamicConfiguration createDynamicConfiguration(URL url) {
URL nacosURL = url;
if (CommonConstants.DUBBO.equals(url.getParameter(PropertyKeyConst.NAMESPACE))) {
// Nacos use empty string as default name space, replace default namespace "dubbo" to ""
nacosURL = url.removeParameter(PropertyKeyConst.NAMESPACE);
}
return new NacosDynamicConfiguration(nacosURL, applicationModel);
}
}
| 5,587 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-nacos/src/main/java/org/apache/dubbo/configcenter/support/nacos/NacosConfigServiceWrapper.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.nacos;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import static org.apache.dubbo.common.utils.StringUtils.HYPHEN_CHAR;
import static org.apache.dubbo.common.utils.StringUtils.SLASH_CHAR;
public class NacosConfigServiceWrapper {
private static final String INNERCLASS_SYMBOL = "$";
private static final String INNERCLASS_COMPATIBLE_SYMBOL = "___";
private static final long DEFAULT_TIMEOUT = 3000L;
private final ConfigService configService;
public NacosConfigServiceWrapper(ConfigService configService) {
this.configService = configService;
}
public ConfigService getConfigService() {
return configService;
}
public void addListener(String dataId, String group, Listener listener) throws NacosException {
configService.addListener(handleInnerSymbol(dataId), handleInnerSymbol(group), listener);
}
public String getConfig(String dataId, String group) throws NacosException {
return configService.getConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), DEFAULT_TIMEOUT);
}
public String getConfig(String dataId, String group, long timeout) throws NacosException {
return configService.getConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), timeout);
}
public boolean publishConfig(String dataId, String group, String content) throws NacosException {
return configService.publishConfig(handleInnerSymbol(dataId), handleInnerSymbol(group), content);
}
public boolean publishConfigCas(String dataId, String group, String content, String casMd5) throws NacosException {
return configService.publishConfigCas(handleInnerSymbol(dataId), handleInnerSymbol(group), content, casMd5);
}
public boolean removeConfig(String dataId, String group) throws NacosException {
return configService.removeConfig(handleInnerSymbol(dataId), handleInnerSymbol(group));
}
public void shutdown() throws NacosException {
configService.shutDown();
}
/**
* see {@link com.alibaba.nacos.client.config.utils.ParamUtils#isValid(java.lang.String)}
*/
private String handleInnerSymbol(String data) {
if (data == null) {
return null;
}
return data.replace(INNERCLASS_SYMBOL, INNERCLASS_COMPATIBLE_SYMBOL).replace(SLASH_CHAR, HYPHEN_CHAR);
}
}
| 5,588 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-zookeeper/src/test/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationTest.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.common.config.configcenter.DynamicConfigurationFactory;
import org.apache.dubbo.common.extension.ExtensionLoader;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* TODO refactor using mockito
*/
@Disabled("Disabled Due to Zookeeper in Github Actions")
class ZookeeperDynamicConfigurationTest {
private static CuratorFramework client;
private static URL configUrl;
private static DynamicConfiguration configuration;
private static int zookeeperServerPort1;
private static String zookeeperConnectionAddress1;
@BeforeAll
public static void setUp() throws Exception {
zookeeperConnectionAddress1 = System.getProperty("zookeeper.connection.address.1");
zookeeperServerPort1 = Integer.parseInt(
zookeeperConnectionAddress1.substring(zookeeperConnectionAddress1.lastIndexOf(":") + 1));
client = CuratorFrameworkFactory.newClient(
"127.0.0.1:" + zookeeperServerPort1, 60 * 1000, 60 * 1000, new ExponentialBackoffRetry(1000, 3));
client.start();
try {
setData("/dubbo/config/dubbo/dubbo.properties", "The content from dubbo.properties");
setData("/dubbo/config/dubbo/service:version:group.configurators", "The content from configurators");
setData("/dubbo/config/appname", "The content from higher level node");
setData("/dubbo/config/dubbo/appname.tag-router", "The content from appname tagrouters");
setData(
"/dubbo/config/dubbo/never.change.DemoService.configurators",
"Never change value from configurators");
} catch (Exception e) {
e.printStackTrace();
}
configUrl = URL.valueOf(zookeeperConnectionAddress1);
configuration = ExtensionLoader.getExtensionLoader(DynamicConfigurationFactory.class)
.getExtension(configUrl.getProtocol())
.getDynamicConfiguration(configUrl);
}
private static void setData(String path, String data) throws Exception {
if (client.checkExists().forPath(path) == null) {
client.create().creatingParentsIfNeeded().forPath(path);
}
client.setData().forPath(path, data.getBytes());
}
private ConfigurationListener mockListener(CountDownLatch latch, String[] value, Map<String, Integer> countMap) {
ConfigurationListener listener = Mockito.mock(ConfigurationListener.class);
Mockito.doAnswer(invoke -> {
ConfigChangedEvent event = invoke.getArgument(0);
Integer count = countMap.computeIfAbsent(event.getKey(), k -> 0);
countMap.put(event.getKey(), ++count);
value[0] = event.getContent();
latch.countDown();
return null;
})
.when(listener)
.process(Mockito.any());
return listener;
}
@Test
void testGetConfig() {
Assertions.assertEquals(
"The content from dubbo.properties", configuration.getConfig("dubbo.properties", "dubbo"));
}
@Test
void testAddListener() throws Exception {
CountDownLatch latch = new CountDownLatch(4);
String[] value1 = new String[1], value2 = new String[1], value3 = new String[1], value4 = new String[1];
Map<String, Integer> countMap1 = new HashMap<>(),
countMap2 = new HashMap<>(),
countMap3 = new HashMap<>(),
countMap4 = new HashMap<>();
ConfigurationListener listener1 = mockListener(latch, value1, countMap1);
ConfigurationListener listener2 = mockListener(latch, value2, countMap2);
ConfigurationListener listener3 = mockListener(latch, value3, countMap3);
ConfigurationListener listener4 = mockListener(latch, value4, countMap4);
configuration.addListener("service:version:group.configurators", listener1);
configuration.addListener("service:version:group.configurators", listener2);
configuration.addListener("appname.tag-router", listener3);
configuration.addListener("appname.tag-router", listener4);
Thread.sleep(100);
setData("/dubbo/config/dubbo/service:version:group.configurators", "new value1");
Thread.sleep(100);
setData("/dubbo/config/dubbo/appname.tag-router", "new value2");
Thread.sleep(100);
setData("/dubbo/config/appname", "new value3");
Thread.sleep(5000);
latch.await();
Assertions.assertEquals(1, countMap1.get("service:version:group.configurators"));
Assertions.assertEquals(1, countMap2.get("service:version:group.configurators"));
Assertions.assertEquals(1, countMap3.get("appname.tag-router"));
Assertions.assertEquals(1, countMap4.get("appname.tag-router"));
Assertions.assertEquals("new value1", value1[0]);
Assertions.assertEquals("new value1", value2[0]);
Assertions.assertEquals("new value2", value3[0]);
Assertions.assertEquals("new value2", value4[0]);
}
@Test
void testPublishConfig() {
String key = "user-service";
String group = "org.apache.dubbo.service.UserService";
String content = "test";
assertTrue(configuration.publishConfig(key, group, content));
assertEquals("test", configuration.getProperties(key, group));
}
@Test
void testPublishConfigCas() {
String key = "user-service-cas";
String group = "org.apache.dubbo.service.UserService";
String content = "test";
ConfigItem configItem = configuration.getConfigItem(key, group);
assertTrue(configuration.publishConfigCas(key, group, content, configItem.getTicket()));
configItem = configuration.getConfigItem(key, group);
assertEquals("test", configItem.getContent());
assertTrue(configuration.publishConfigCas(key, group, "newtest", configItem.getTicket()));
assertFalse(configuration.publishConfigCas(key, group, "newtest2", configItem.getTicket()));
assertEquals("newtest", configuration.getConfigItem(key, group).getContent());
}
//
// @Test
// public void testGetConfigKeysAndContents() {
//
// String group = "mapping";
// String key = "org.apache.dubbo.service.UserService";
// String content = "app1";
//
// String key2 = "org.apache.dubbo.service.UserService2";
//
// assertTrue(configuration.publishConfig(key, group, content));
// assertTrue(configuration.publishConfig(key2, group, content));
//
// Set<String> configKeys = configuration.getConfigKeys(group);
//
// assertEquals(new TreeSet(asList(key, key2)), configKeys);
// }
}
| 5,589 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDataListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.zookeeper;
import org.apache.dubbo.common.config.configcenter.ConfigChangeType;
import org.apache.dubbo.common.config.configcenter.ConfigChangedEvent;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.metrics.config.event.ConfigCenterEvent;
import org.apache.dubbo.metrics.event.MetricsEventBus;
import org.apache.dubbo.remoting.zookeeper.DataListener;
import org.apache.dubbo.remoting.zookeeper.EventType;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import static org.apache.dubbo.metrics.MetricsConstants.SELF_INCREMENT_SIZE;
/**
* one path has multi configurationListeners
*/
public class ZookeeperDataListener implements DataListener {
private String path;
private String key;
private String group;
private Set<ConfigurationListener> listeners;
private ApplicationModel applicationModel;
public ZookeeperDataListener(String path, String key, String group, ApplicationModel applicationModel) {
this.path = path;
this.key = key;
this.group = group;
this.listeners = new CopyOnWriteArraySet<>();
this.applicationModel = applicationModel;
}
public void addListener(ConfigurationListener configurationListener) {
listeners.add(configurationListener);
}
public void removeListener(ConfigurationListener configurationListener) {
listeners.remove(configurationListener);
}
public Set<ConfigurationListener> getListeners() {
return listeners;
}
@Override
public void dataChanged(String path, Object value, EventType eventType) {
if (!this.path.equals(path)) {
return;
}
ConfigChangeType changeType;
if (EventType.NodeCreated.equals(eventType)) {
changeType = ConfigChangeType.ADDED;
} else if (value == null) {
changeType = ConfigChangeType.DELETED;
} else {
changeType = ConfigChangeType.MODIFIED;
}
ConfigChangedEvent configChangeEvent = new ConfigChangedEvent(key, group, (String) value, changeType);
if (CollectionUtils.isNotEmpty(listeners)) {
listeners.forEach(listener -> listener.process(configChangeEvent));
}
MetricsEventBus.publish(ConfigCenterEvent.toChangeEvent(
applicationModel,
configChangeEvent.getKey(),
configChangeEvent.getGroup(),
ConfigCenterEvent.ZK_PROTOCOL,
ConfigChangeType.ADDED.name(),
SELF_INCREMENT_SIZE));
}
}
| 5,590 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfiguration.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.ConfigItem;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.config.configcenter.TreePathDynamicConfiguration;
import org.apache.dubbo.common.threadpool.support.AbortPolicyWithReport;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.NamedThreadFactory;
import org.apache.dubbo.remoting.zookeeper.ZookeeperClient;
import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.zookeeper.data.Stat;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_FAILED_CONNECT_REGISTRY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ZOOKEEPER_EXCEPTION;
public class ZookeeperDynamicConfiguration extends TreePathDynamicConfiguration {
private final Executor executor;
private ZookeeperClient zkClient;
private final CacheListener cacheListener;
private static final int DEFAULT_ZK_EXECUTOR_THREADS_NUM = 1;
private static final int DEFAULT_QUEUE = 10000;
private static final Long THREAD_KEEP_ALIVE_TIME = 0L;
private final ApplicationModel applicationModel;
ZookeeperDynamicConfiguration(
URL url, ZookeeperTransporter zookeeperTransporter, ApplicationModel applicationModel) {
super(url);
this.cacheListener = new CacheListener();
this.applicationModel = applicationModel;
final String threadName = this.getClass().getSimpleName();
this.executor = new ThreadPoolExecutor(
DEFAULT_ZK_EXECUTOR_THREADS_NUM,
DEFAULT_ZK_EXECUTOR_THREADS_NUM,
THREAD_KEEP_ALIVE_TIME,
TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<>(DEFAULT_QUEUE),
new NamedThreadFactory(threadName, true),
new AbortPolicyWithReport(threadName, url));
zkClient = zookeeperTransporter.connect(url);
boolean isConnected = zkClient.isConnected();
if (!isConnected) {
IllegalStateException illegalStateException = new IllegalStateException(
"Failed to connect with zookeeper, pls check if url " + url + " is correct.");
if (logger != null) {
logger.error(
CONFIG_FAILED_CONNECT_REGISTRY,
"configuration server offline",
"",
"Failed to connect with zookeeper",
illegalStateException);
}
throw illegalStateException;
}
}
/**
* @param key e.g., {service}.configurators, {service}.tagrouters, {group}.dubbo.properties
* @return
*/
@Override
public String getInternalProperty(String key) {
return zkClient.getContent(buildPathKey("", key));
}
@Override
protected void doClose() throws Exception {
// remove data listener
Map<String, ZookeeperDataListener> pathKeyListeners = cacheListener.getPathKeyListeners();
for (Map.Entry<String, ZookeeperDataListener> entry : pathKeyListeners.entrySet()) {
zkClient.removeDataListener(entry.getKey(), entry.getValue());
}
cacheListener.clear();
// zkClient is shared in framework, should not close it here
// zkClient.close();
// See: org.apache.dubbo.remoting.zookeeper.AbstractZookeeperTransporter#destroy()
// All zk clients is created and destroyed in ZookeeperTransporter.
zkClient = null;
}
@Override
protected boolean doPublishConfig(String pathKey, String content) throws Exception {
zkClient.createOrUpdate(pathKey, content, false);
return true;
}
@Override
public boolean publishConfigCas(String key, String group, String content, Object ticket) {
try {
if (ticket != null && !(ticket instanceof Stat)) {
throw new IllegalArgumentException("zookeeper publishConfigCas requires stat type ticket");
}
String pathKey = buildPathKey(group, key);
zkClient.createOrUpdate(pathKey, content, false, ticket == null ? 0 : ((Stat) ticket).getVersion());
return true;
} catch (Exception e) {
logger.warn(REGISTRY_ZOOKEEPER_EXCEPTION, "", "", "zookeeper publishConfigCas failed.", e);
return false;
}
}
@Override
protected String doGetConfig(String pathKey) throws Exception {
return zkClient.getContent(pathKey);
}
@Override
public ConfigItem getConfigItem(String key, String group) {
String pathKey = buildPathKey(group, key);
return zkClient.getConfigItem(pathKey);
}
@Override
protected boolean doRemoveConfig(String pathKey) throws Exception {
zkClient.delete(pathKey);
return true;
}
@Override
protected Collection<String> doGetConfigKeys(String groupPath) {
return zkClient.getChildren(groupPath);
}
@Override
protected void doAddListener(String pathKey, ConfigurationListener listener, String key, String group) {
ZookeeperDataListener cachedListener = cacheListener.getCachedListener(pathKey);
if (cachedListener != null) {
cachedListener.addListener(listener);
} else {
ZookeeperDataListener addedListener =
cacheListener.addListener(pathKey, listener, key, group, applicationModel);
zkClient.addDataListener(pathKey, addedListener, executor);
}
}
@Override
protected void doRemoveListener(String pathKey, ConfigurationListener listener) {
ZookeeperDataListener zookeeperDataListener = cacheListener.removeListener(pathKey, listener);
if (zookeeperDataListener != null && CollectionUtils.isEmpty(zookeeperDataListener.getListeners())) {
zkClient.removeDataListener(pathKey, zookeeperDataListener);
}
}
}
| 5,591 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/ZookeeperDynamicConfigurationFactory.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.zookeeper;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.config.configcenter.AbstractDynamicConfigurationFactory;
import org.apache.dubbo.common.config.configcenter.DynamicConfiguration;
import org.apache.dubbo.remoting.zookeeper.ZookeeperTransporter;
import org.apache.dubbo.rpc.model.ApplicationModel;
public class ZookeeperDynamicConfigurationFactory extends AbstractDynamicConfigurationFactory {
private final ZookeeperTransporter zookeeperTransporter;
private final ApplicationModel applicationModel;
public ZookeeperDynamicConfigurationFactory(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
this.zookeeperTransporter = ZookeeperTransporter.getExtension(applicationModel);
}
@Override
protected DynamicConfiguration createDynamicConfiguration(URL url) {
return new ZookeeperDynamicConfiguration(url, zookeeperTransporter, applicationModel);
}
}
| 5,592 |
0 | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support | Create_ds/dubbo/dubbo-configcenter/dubbo-configcenter-zookeeper/src/main/java/org/apache/dubbo/configcenter/support/zookeeper/CacheListener.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.configcenter.support.zookeeper;
import org.apache.dubbo.common.config.configcenter.ConfigurationListener;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* one path has one zookeeperDataListener
*/
public class CacheListener {
private final ConcurrentMap<String, ZookeeperDataListener> pathKeyListeners = new ConcurrentHashMap<>();
public CacheListener() {}
public ZookeeperDataListener addListener(
String pathKey,
ConfigurationListener configurationListener,
String key,
String group,
ApplicationModel applicationModel) {
ZookeeperDataListener zookeeperDataListener = ConcurrentHashMapUtils.computeIfAbsent(
pathKeyListeners,
pathKey,
_pathKey -> new ZookeeperDataListener(_pathKey, key, group, applicationModel));
zookeeperDataListener.addListener(configurationListener);
return zookeeperDataListener;
}
public ZookeeperDataListener removeListener(String pathKey, ConfigurationListener configurationListener) {
ZookeeperDataListener zookeeperDataListener = pathKeyListeners.get(pathKey);
if (zookeeperDataListener != null) {
zookeeperDataListener.removeListener(configurationListener);
if (CollectionUtils.isEmpty(zookeeperDataListener.getListeners())) {
pathKeyListeners.remove(pathKey);
}
}
return zookeeperDataListener;
}
public ZookeeperDataListener getCachedListener(String pathKey) {
return pathKeyListeners.get(pathKey);
}
public Map<String, ZookeeperDataListener> getPathKeyListeners() {
return pathKeyListeners;
}
public void clear() {
pathKeyListeners.clear();
}
}
| 5,593 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/AbstractDependencyFilterMojo.java | /*
* Copyright 2012-2022 the original author or authors.
*
* 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
*
* https://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 org.apache.dubbo.maven.plugin.aot;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.resolver.filter.ArtifactFilter;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.artifact.filter.collection.AbstractArtifactFeatureFilter;
import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException;
import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter;
import org.apache.maven.shared.artifact.filter.collection.FilterArtifacts;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
/**
* A base mojo filtering the dependencies of the project.
*
* @author Stephane Nicoll
* @author David Turanski
*/
public abstract class AbstractDependencyFilterMojo extends AbstractMojo {
/**
* The Maven project.
*/
@Parameter(defaultValue = "${project}", readonly = true, required = true)
protected MavenProject project;
/**
* Collection of artifact definitions to include. The {@link Include} element defines
* mandatory {@code groupId} and {@code artifactId} properties and an optional
* mandatory {@code groupId} and {@code artifactId} properties and an optional
* {@code classifier} property.
*/
@Parameter(property = "dubbo.includes")
private List<Include> includes;
/**
* Collection of artifact definitions to exclude. The {@link Exclude} element defines
* mandatory {@code groupId} and {@code artifactId} properties and an optional
* {@code classifier} property.
*/
@Parameter(property = "dubbo.excludes")
private List<Exclude> excludes;
/**
* Comma separated list of groupId names to exclude (exact match).
*/
@Parameter(property = "dubbo.excludeGroupIds", defaultValue = "")
private String excludeGroupIds;
protected void setExcludes(List<Exclude> excludes) {
this.excludes = excludes;
}
protected void setIncludes(List<Include> includes) {
this.includes = includes;
}
protected void setExcludeGroupIds(String excludeGroupIds) {
this.excludeGroupIds = excludeGroupIds;
}
protected List<URL> getDependencyURLs(ArtifactsFilter... additionalFilters) throws MojoExecutionException {
Set<Artifact> artifacts = filterDependencies(this.project.getArtifacts(), additionalFilters);
List<URL> urls = new ArrayList<>();
for (Artifact artifact : artifacts) {
if (artifact.getFile() != null) {
urls.add(toURL(artifact.getFile()));
}
}
return urls;
}
protected final Set<Artifact> filterDependencies(Set<Artifact> dependencies, ArtifactsFilter... additionalFilters)
throws MojoExecutionException {
try {
Set<Artifact> filtered = new LinkedHashSet<>(dependencies);
filtered.retainAll(getFilters(additionalFilters).filter(dependencies));
return filtered;
}
catch (ArtifactFilterException ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
}
protected URL toURL(File file) {
try {
return file.toURI().toURL();
}
catch (MalformedURLException ex) {
throw new IllegalStateException("Invalid URL for " + file, ex);
}
}
/**
* Return artifact filters configured for this MOJO.
* @param additionalFilters optional additional filters to apply
* @return the filters
*/
private FilterArtifacts getFilters(ArtifactsFilter... additionalFilters) {
FilterArtifacts filters = new FilterArtifacts();
for (ArtifactsFilter additionalFilter : additionalFilters) {
filters.addFilter(additionalFilter);
}
filters.addFilter(new MatchingGroupIdFilter(cleanFilterConfig(this.excludeGroupIds)));
if (this.includes != null && !this.includes.isEmpty()) {
filters.addFilter(new IncludeFilter(this.includes));
}
if (this.excludes != null && !this.excludes.isEmpty()) {
filters.addFilter(new ExcludeFilter(this.excludes));
}
return filters;
}
private String cleanFilterConfig(String content) {
if (content == null || content.trim().isEmpty()) {
return "";
}
StringBuilder cleaned = new StringBuilder();
StringTokenizer tokenizer = new StringTokenizer(content, ",");
while (tokenizer.hasMoreElements()) {
cleaned.append(tokenizer.nextToken().trim());
if (tokenizer.hasMoreElements()) {
cleaned.append(",");
}
}
return cleaned.toString();
}
/**
* {@link ArtifactFilter} to exclude test scope dependencies.
*/
protected static class ExcludeTestScopeArtifactFilter extends AbstractArtifactFeatureFilter {
ExcludeTestScopeArtifactFilter() {
super("", Artifact.SCOPE_TEST);
}
@Override
protected String getArtifactFeature(Artifact artifact) {
return artifact.getScope();
}
}
}
| 5,594 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/Exclude.java | /*
* Copyright 2012-2019 the original author or authors.
*
* 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
*
* https://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 org.apache.dubbo.maven.plugin.aot;
/**
* A model for a dependency to exclude.
*
* @author Stephane Nicoll
*/
public class Exclude extends FilterableDependency {
}
| 5,595 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/AbstractAotMojo.java | /*
* Copyright 2012-2022 the original author or authors.
*
* 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
*
* https://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 org.apache.dubbo.maven.plugin.aot;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter;
import org.apache.maven.toolchain.ToolchainManager;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Abstract base class for AOT processing MOJOs.
*
* @author Phillip Webb
* @author Scott Frederick
*/
public abstract class AbstractAotMojo extends AbstractDependencyFilterMojo {
/**
* The current Maven session. This is used for toolchain manager API calls.
*/
@Parameter(defaultValue = "${session}", readonly = true)
private MavenSession session;
/**
* The toolchain manager to use to locate a custom JDK.
*/
@Component
private ToolchainManager toolchainManager;
/**
* Skip the execution.
*/
@Parameter(property = "dubbo.aot.skip", defaultValue = "false")
private boolean skip;
/**
* List of JVM system properties to pass to the AOT process.
*/
@Parameter
private Map<String, String> systemPropertyVariables;
/**
* JVM arguments that should be associated with the AOT process. On command line, make
* sure to wrap multiple values between quotes.
*/
@Parameter(property = "dubbo.aot.jvmArguments")
private String jvmArguments;
/**
* Arguments that should be provided to the AOT compile process. On command line, make
* sure to wrap multiple values between quotes.
*/
@Parameter(property = "dubbo.aot.compilerArguments")
private String compilerArguments;
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
if (this.skip) {
getLog().debug("Skipping AOT execution as per configuration");
return;
}
try {
executeAot();
} catch (Exception ex) {
throw new MojoExecutionException(ex.getMessage(), ex);
}
}
protected abstract void executeAot() throws Exception;
protected void generateAotAssets(URL[] classPath, String processorClassName, String... arguments) throws Exception {
List<String> command = CommandLineBuilder.forMainClass(processorClassName)
.withSystemProperties(this.systemPropertyVariables)
.withJvmArguments(new RunArguments(this.jvmArguments).asArray()).withClasspath(classPath)
.withArguments(arguments).build();
if (getLog().isDebugEnabled()) {
getLog().debug("Generating AOT assets using command: " + command);
}
JavaProcessExecutor processExecutor = new JavaProcessExecutor(this.session, this.toolchainManager);
getLog().info("dir: " + this.project.getBasedir());
processExecutor.run(this.project.getBasedir(), command, Collections.emptyMap());
}
protected final void compileSourceFiles(URL[] classPath, File sourcesDirectory, File outputDirectory)
throws Exception {
List<File> sourceFiles;
try (Stream<Path> pathStream = Files.walk(sourcesDirectory.toPath())) {
sourceFiles = pathStream.filter(Files::isRegularFile).map(Path::toFile).collect(Collectors.toList());
}
if (sourceFiles.isEmpty()) {
return;
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
JavaCompilerPluginConfiguration compilerConfiguration = new JavaCompilerPluginConfiguration(this.project);
List<String> options = new ArrayList<>();
options.add("-cp");
options.add(CommandLineBuilder.ClasspathBuilder.build(Arrays.asList(classPath)));
options.add("-d");
options.add(outputDirectory.toPath().toAbsolutePath().toString());
String releaseVersion = compilerConfiguration.getReleaseVersion();
if (releaseVersion != null) {
options.add("--release");
options.add(releaseVersion);
}
else {
options.add("--source");
options.add(compilerConfiguration.getSourceMajorVersion());
options.add("--target");
options.add(compilerConfiguration.getTargetMajorVersion());
}
options.addAll(new RunArguments(this.compilerArguments).getArgs());
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFiles);
Errors errors = new Errors();
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, errors, options, null, compilationUnits);
boolean result = task.call();
if (!result || errors.hasReportedErrors()) {
throw new IllegalStateException("Unable to compile generated source" + errors);
}
}
}
protected final List<URL> getClassPath(File[] directories, ArtifactsFilter... artifactFilters)
throws MojoExecutionException {
List<URL> urls = new ArrayList<>();
Arrays.stream(directories).map(this::toURL).forEach(urls::add);
urls.addAll(getDependencyURLs(artifactFilters));
return urls;
}
protected final void copyAll(Path from, Path to) throws IOException {
if (!Files.exists(from)) {
return;
}
List<Path> files;
try (Stream<Path> pathStream = Files.walk(from)) {
files = pathStream.filter(Files::isRegularFile).collect(Collectors.toList());
}
for (Path file : files) {
String relativeFileName = file.subpath(from.getNameCount(), file.getNameCount()).toString();
getLog().debug("Copying '" + relativeFileName + "' to " + to);
Path target = to.resolve(relativeFileName);
Files.createDirectories(target.getParent());
Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING);
}
}
/**
* {@link DiagnosticListener} used to collect errors.
*/
protected static class Errors implements DiagnosticListener<JavaFileObject> {
private final StringBuilder message = new StringBuilder();
@Override
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
this.message.append("\n");
this.message.append(diagnostic.getMessage(Locale.getDefault()));
if (diagnostic.getSource() != null) {
this.message.append(" ");
this.message.append(diagnostic.getSource().getName());
this.message.append(" ");
this.message.append(diagnostic.getLineNumber()).append(":").append(diagnostic.getColumnNumber());
}
}
}
boolean hasReportedErrors() {
return this.message.length() > 0;
}
@Override
public String toString() {
return this.message.toString();
}
}
}
| 5,596 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/DependencyFilter.java | /*
* Copyright 2012-2020 the original author or authors.
*
* 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
*
* https://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 org.apache.dubbo.maven.plugin.aot;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.shared.artifact.filter.collection.AbstractArtifactsFilter;
import org.apache.maven.shared.artifact.filter.collection.ArtifactFilterException;
import org.apache.maven.shared.artifact.filter.collection.ArtifactsFilter;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Base class for {@link ArtifactsFilter} based on a {@link org.apache.dubbo.maven.plugin.aot.FilterableDependency} list.
*
* @author Stephane Nicoll
* @author David Turanski
*/
public abstract class DependencyFilter extends AbstractArtifactsFilter {
private final List<? extends FilterableDependency> filters;
/**
* Create a new instance with the list of {@link FilterableDependency} instance(s) to
* use.
* @param dependencies the source dependencies
*/
public DependencyFilter(List<? extends FilterableDependency> dependencies) {
this.filters = dependencies;
}
@Override
public Set<Artifact> filter(Set<Artifact> artifacts) throws ArtifactFilterException {
Set<Artifact> result = new HashSet<>();
for (Artifact artifact : artifacts) {
if (!filter(artifact)) {
result.add(artifact);
}
}
return result;
}
protected abstract boolean filter(Artifact artifact);
/**
* Check if the specified {@link Artifact} matches the
* specified {@link org.apache.dubbo.maven.plugin.aot.FilterableDependency}. Returns
* {@code true} if it should be excluded
* @param artifact the Maven {@link Artifact}
* @param dependency the {@link org.apache.dubbo.maven.plugin.aot.FilterableDependency}
* @return {@code true} if the artifact matches the dependency
*/
protected final boolean equals(Artifact artifact, FilterableDependency dependency) {
if (!dependency.getGroupId().equals(artifact.getGroupId())) {
return false;
}
if (!dependency.getArtifactId().equals(artifact.getArtifactId())) {
return false;
}
return (dependency.getClassifier() == null
|| artifact.getClassifier() != null && dependency.getClassifier().equals(artifact.getClassifier()));
}
protected final List<? extends FilterableDependency> getFilters() {
return this.filters;
}
}
| 5,597 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/RunProcess.java | /*
* Copyright 2012-2022 the original author or authors.
*
* 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
*
* https://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 org.apache.dubbo.maven.plugin.aot;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
/**
* Utility used to run a process.
*
* @author Phillip Webb
* @author Dave Syer
* @author Andy Wilkinson
* @author Stephane Nicoll
* @author Dmytro Nosan
*/
public class RunProcess {
private static final long JUST_ENDED_LIMIT = 500;
private final File workingDirectory;
private final String[] command;
private volatile Process process;
private volatile long endTime;
/**
* Creates new {@link RunProcess} instance for the specified command.
* @param command the program to execute and its arguments
*/
public RunProcess(String... command) {
this(null, command);
}
/**
* Creates new {@link RunProcess} instance for the specified working directory and
* command.
* @param workingDirectory the working directory of the child process or {@code null}
* to run in the working directory of the current Java process
* @param command the program to execute and its arguments
*/
public RunProcess(File workingDirectory, String... command) {
this.workingDirectory = workingDirectory;
this.command = command;
}
public int run(boolean waitForProcess, String... args) throws IOException {
return run(waitForProcess, Arrays.asList(args), Collections.emptyMap());
}
public int run(boolean waitForProcess, Collection<String> args, Map<String, String> environmentVariables)
throws IOException {
ProcessBuilder builder = new ProcessBuilder(this.command);
builder.directory(this.workingDirectory);
builder.command().addAll(args);
builder.environment().putAll(environmentVariables);
builder.redirectErrorStream(true);
builder.inheritIO();
try {
Process process = builder.start();
this.process = process;
if (waitForProcess) {
try {
return process.waitFor();
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return 1;
}
}
return 5;
}
finally {
if (waitForProcess) {
this.endTime = System.currentTimeMillis();
this.process = null;
}
}
}
/**
* Return the running process.
* @return the process or {@code null}
*/
public Process getRunningProcess() {
return this.process;
}
/**
* Return if the process was stopped.
* @return {@code true} if stopped
*/
public boolean handleSigInt() {
if (allowChildToHandleSigInt()) {
return true;
}
return doKill();
}
private boolean allowChildToHandleSigInt() {
Process process = this.process;
if (process == null) {
return true;
}
long end = System.currentTimeMillis() + 5000;
while (System.currentTimeMillis() < end) {
if (!process.isAlive()) {
return true;
}
try {
Thread.sleep(500);
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
return false;
}
}
return false;
}
/**
* Kill this process.
*/
public void kill() {
doKill();
}
private boolean doKill() {
// destroy the running process
Process process = this.process;
if (process != null) {
try {
process.destroy();
process.waitFor();
this.process = null;
return true;
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
return false;
}
public boolean hasJustEnded() {
return System.currentTimeMillis() < (this.endTime + JUST_ENDED_LIMIT);
}
}
| 5,598 |
0 | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin | Create_ds/dubbo/dubbo-maven-plugin/src/main/java/org/apache/dubbo/maven/plugin/aot/FilterableDependency.java | /*
* Copyright 2012-2019 the original author or authors.
*
* 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
*
* https://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 org.apache.dubbo.maven.plugin.aot;
import org.apache.maven.plugins.annotations.Parameter;
/**
* A model for a dependency to include or exclude.
*
* @author Stephane Nicoll
* @author David Turanski
*/
abstract class FilterableDependency {
/**
* The groupId of the artifact to exclude.
*/
@Parameter(required = true)
private String groupId;
/**
* The artifactId of the artifact to exclude.
*/
@Parameter(required = true)
private String artifactId;
/**
* The classifier of the artifact to exclude.
*/
@Parameter
private String classifier;
String getGroupId() {
return this.groupId;
}
void setGroupId(String groupId) {
this.groupId = groupId;
}
String getArtifactId() {
return this.artifactId;
}
void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
String getClassifier() {
return this.classifier;
}
void setClassifier(String classifier) {
this.classifier = classifier;
}
}
| 5,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.