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-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Help.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.qos.command.impl;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.util.CommandHelper;
import org.apache.dubbo.qos.textui.TTable;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
@Cmd(
name = "help",
summary = "help command",
example = {"help", "help online"})
public class Help implements BaseCommand {
private final CommandHelper commandHelper;
private static final String MAIN_HELP = "mainHelp";
private static final Map<String, String> processedTable = new WeakHashMap<>();
public Help(FrameworkModel frameworkModel) {
this.commandHelper = new CommandHelper(frameworkModel);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isNotEmpty(args)) {
return processedTable.computeIfAbsent(args[0], this::commandHelp);
} else {
return processedTable.computeIfAbsent(MAIN_HELP, commandName -> mainHelp());
}
}
private String commandHelp(String commandName) {
if (!commandHelper.hasCommand(commandName)) {
return "no such command:" + commandName;
}
Class<?> clazz = commandHelper.getCommandClass(commandName);
final Cmd cmd = clazz.getAnnotation(Cmd.class);
final TTable tTable = new TTable(new TTable.ColumnDefine[] {
new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(80, false, TTable.Align.LEFT)
});
tTable.addRow("COMMAND NAME", commandName);
if (null != cmd.example()) {
tTable.addRow("EXAMPLE", drawExample(cmd));
}
return tTable.padding(1).rendering();
}
private String drawExample(Cmd cmd) {
final StringBuilder drawExampleStringBuilder = new StringBuilder();
for (String example : cmd.example()) {
drawExampleStringBuilder.append(example).append('\n');
}
return drawExampleStringBuilder.toString();
}
/*
* output main help
*/
private String mainHelp() {
final TTable tTable = new TTable(new TTable.ColumnDefine[] {
new TTable.ColumnDefine(TTable.Align.RIGHT), new TTable.ColumnDefine(80, false, TTable.Align.LEFT)
});
final List<Class<?>> classes = commandHelper.getAllCommandClass();
Collections.sort(classes, new Comparator<Class<?>>() {
@Override
public int compare(Class<?> o1, Class<?> o2) {
final Integer o1s = o1.getAnnotation(Cmd.class).sort();
final Integer o2s = o2.getAnnotation(Cmd.class).sort();
return o1s.compareTo(o2s);
}
});
for (Class<?> clazz : classes) {
if (clazz.isAnnotationPresent(Cmd.class)) {
final Cmd cmd = clazz.getAnnotation(Cmd.class);
tTable.addRow(cmd.name(), cmd.summary());
}
}
return tTable.padding(1).rendering();
}
}
| 8,300 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineInterface.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.qos.command.impl;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ProviderModel;
@Cmd(
name = "onlineInterface",
summary = "online dubbo",
example = {"onlineInterface dubbo", "onlineInterface xx.xx.xxx.service"})
public class OnlineInterface extends BaseOnline {
public OnlineInterface(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected void doExport(ProviderModel.RegisterStatedURL statedURL) {
if (!UrlUtils.isServiceDiscoveryURL(statedURL.getRegistryUrl())) {
super.doExport(statedURL);
}
}
}
| 8,301 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PublishMetadata.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.qos.command.impl;
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.ArrayUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.registry.client.metadata.ServiceInstanceMetadataUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.CONFIG_PARAMETER_FORMAT_ERROR;
@Cmd(
name = "publishMetadata",
summary = "update service metadata and service instance",
example = {"publishMetadata", "publishMetadata 5"})
public class PublishMetadata implements BaseCommand {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(PublishMetadata.class);
private final FrameworkModel frameworkModel;
public PublishMetadata(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
logger.info("received publishMetadata command.");
StringBuilder stringBuilder = new StringBuilder();
List<ApplicationModel> applicationModels = frameworkModel.getApplicationModels();
for (ApplicationModel applicationModel : applicationModels) {
if (ArrayUtils.isEmpty(args)) {
ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel);
stringBuilder
.append("publish metadata succeeded. App:")
.append(applicationModel.getApplicationName())
.append("\n");
} else {
try {
int delay = Integer.parseInt(args[0]);
FrameworkExecutorRepository frameworkExecutorRepository = applicationModel
.getFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class);
frameworkExecutorRepository
.nextScheduledExecutor()
.schedule(
() -> ServiceInstanceMetadataUtils.refreshMetadataAndInstance(applicationModel),
delay,
TimeUnit.SECONDS);
} catch (NumberFormatException e) {
logger.error(CONFIG_PARAMETER_FORMAT_ERROR, "", "", "Wrong delay param", e);
return "publishMetadata failed! Wrong delay param!";
}
stringBuilder
.append("publish task submitted, will publish in ")
.append(args[0])
.append(" seconds. App:")
.append(applicationModel.getApplicationName())
.append("\n");
}
}
return stringBuilder.toString();
}
}
| 8,302 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogLevel.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.qos.command.impl;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import java.util.Locale;
@Cmd(
name = "switchLogLevel",
summary = "Switch log level",
example = {"switchLogLevel info"})
public class SwitchLogLevel implements BaseCommand {
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length != 1) {
return "Unexpected argument length.";
}
Level level;
switch (args[0]) {
case "0":
level = Level.ALL;
break;
case "1":
level = Level.TRACE;
break;
case "2":
level = Level.DEBUG;
break;
case "3":
level = Level.INFO;
break;
case "4":
level = Level.WARN;
break;
case "5":
level = Level.ERROR;
break;
case "6":
level = Level.OFF;
break;
default:
level = Level.valueOf(args[0].toUpperCase(Locale.ROOT));
break;
}
LoggerFactory.setLevel(level);
return "OK";
}
}
| 8,303 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableDetailProfiler.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.qos.command.impl;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_ENABLED;
@Cmd(name = "enableDetailProfiler", summary = "Enable Dubbo Invocation Profiler.")
public class EnableDetailProfiler implements BaseCommand {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(EnableDetailProfiler.class);
@Override
public String execute(CommandContext commandContext, String[] args) {
ProfilerSwitch.enableDetailProfiler();
logger.warn(QOS_PROFILER_ENABLED, "", "", "Dubbo Invocation Profiler has been enabled.");
return "OK. This will cause performance degradation, please be careful!";
}
}
| 8,304 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Quit.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.common.QosConstants;
@Cmd(name = "quit", summary = "quit telnet console", requiredPermissionLevel = PermissionLevel.PUBLIC)
public class Quit implements BaseCommand {
@Override
public String execute(CommandContext commandContext, String[] args) {
return QosConstants.CLOSE;
}
}
| 8,305 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableDetailProfiler.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.qos.command.impl;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_DISABLED;
@Cmd(name = "disableDetailProfiler", summary = "Disable Dubbo Invocation Profiler.")
public class DisableDetailProfiler implements BaseCommand {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(DisableDetailProfiler.class);
@Override
public String execute(CommandContext commandContext, String[] args) {
ProfilerSwitch.disableDetailProfiler();
logger.warn(QOS_PROFILER_DISABLED, "", "", "Dubbo Invocation Profiler has been disabled.");
return "OK";
}
}
| 8,306 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeWarnedClasses.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.qos.command.impl;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.util.SerializeCheckUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
@Cmd(name = "serializeWarnedClasses", summary = "get serialize warned classes")
public class SerializeWarnedClasses implements BaseCommand {
private final SerializeCheckUtils serializeCheckUtils;
public SerializeWarnedClasses(FrameworkModel frameworkModel) {
serializeCheckUtils = frameworkModel.getBeanFactory().getBean(SerializeCheckUtils.class);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (commandContext.isHttp()) {
Map<String, Object> result = new HashMap<>();
result.put("warnedClasses", serializeCheckUtils.getWarnedClasses());
return JsonUtils.toJson(result);
} else {
return "WarnedClasses: \n"
+ serializeCheckUtils.getWarnedClasses().stream().sorted().collect(Collectors.joining("\n"))
+ "\n\n";
}
}
}
| 8,307 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PortTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.remoting.exchange.ExchangeChannel;
import org.apache.dubbo.remoting.exchange.ExchangeServer;
import org.apache.dubbo.rpc.ProtocolServer;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import java.util.Collection;
@Cmd(
name = "ps",
summary = "Print server ports and connections.",
example = {"ps -l [port]", "ps", "ps -l", "ps -l 20880"})
public class PortTelnet implements BaseCommand {
private final DubboProtocol dubboProtocol;
public PortTelnet(FrameworkModel frameworkModel) {
this.dubboProtocol = DubboProtocol.getDubboProtocol(frameworkModel);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
StringBuilder buf = new StringBuilder();
String port = null;
boolean detail = false;
if (args.length > 0) {
for (String part : args) {
if ("-l".equals(part)) {
detail = true;
} else {
if (!StringUtils.isNumber(part)) {
return "Illegal port " + part + ", must be integer.";
}
port = part;
}
}
}
if (StringUtils.isEmpty(port)) {
for (ProtocolServer server : dubboProtocol.getServers()) {
if (buf.length() > 0) {
buf.append("\r\n");
}
if (detail) {
buf.append(server.getUrl().getProtocol())
.append("://")
.append(server.getUrl().getAddress());
} else {
buf.append(server.getUrl().getPort());
}
}
} else {
int p = Integer.parseInt(port);
ProtocolServer protocolServer = null;
for (ProtocolServer s : dubboProtocol.getServers()) {
if (p == s.getUrl().getPort()) {
protocolServer = s;
break;
}
}
if (protocolServer != null) {
ExchangeServer server = (ExchangeServer) protocolServer.getRemotingServer();
Collection<ExchangeChannel> channels = server.getExchangeChannels();
for (ExchangeChannel c : channels) {
if (buf.length() > 0) {
buf.append("\r\n");
}
if (detail) {
buf.append(c.getRemoteAddress()).append(" -> ").append(c.getLocalAddress());
} else {
buf.append(c.getRemoteAddress());
}
}
} else {
buf.append("No such port ").append(port);
}
}
return buf.toString();
}
}
| 8,308 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/CountTelnet.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.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.remoting.RemotingException;
import org.apache.dubbo.remoting.telnet.support.TelnetUtils;
import org.apache.dubbo.remoting.utils.PayloadDropper;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.RpcStatus;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_TIMEOUT;
import static org.apache.dubbo.qos.server.handler.QosProcessHandler.PROMPT;
@Cmd(
name = "count",
summary = "Count the service.",
example = {"count [service] [method] [times]"})
public class CountTelnet implements BaseCommand {
private final DubboProtocol dubboProtocol;
public CountTelnet(FrameworkModel frameworkModel) {
this.dubboProtocol = DubboProtocol.getDubboProtocol(frameworkModel);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
Channel channel = commandContext.getRemote();
String service = channel.attr(ChangeTelnet.SERVICE_KEY).get();
if ((service == null || service.length() == 0) && (args == null || args.length == 0)) {
return "Please input service name, eg: \r\ncount XxxService\r\ncount XxxService xxxMethod\r\ncount XxxService xxxMethod 10\r\nor \"cd XxxService\" firstly.";
}
StringBuilder buf = new StringBuilder();
if (service != null && service.length() > 0) {
buf.append("Use default service ").append(service).append(".\r\n");
}
String method;
String times;
if (service == null || service.length() == 0) {
service = args[0];
method = args.length > 1 ? args[1] : null;
} else {
method = args.length > 0 ? args[0] : null;
}
if (StringUtils.isNumber(method)) {
times = method;
method = null;
} else {
times = args.length > 2 ? args[2] : "1";
}
if (!StringUtils.isNumber(times)) {
return "Illegal times " + times + ", must be integer.";
}
final int t = Integer.parseInt(times);
Invoker<?> invoker = null;
for (Exporter<?> exporter : dubboProtocol.getExporters()) {
if (service.equals(exporter.getInvoker().getInterface().getSimpleName())
|| service.equals(exporter.getInvoker().getInterface().getName())
|| service.equals(exporter.getInvoker().getUrl().getPath())) {
invoker = exporter.getInvoker();
break;
}
}
if (invoker != null) {
if (t > 0) {
final String mtd = method;
final Invoker<?> inv = invoker;
Thread thread = new Thread(
() -> {
for (int i = 0; i < t; i++) {
String result = count(inv, mtd);
try {
send(channel, "\r\n" + result);
} catch (RemotingException e1) {
return;
}
if (i < t - 1) {
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}
try {
send(channel, "\r\n" + PROMPT);
} catch (RemotingException ignored) {
}
},
"TelnetCount");
thread.setDaemon(true);
thread.start();
}
} else {
buf.append("No such service ").append(service);
}
return buf.toString();
}
public void send(Channel channel, Object message) throws RemotingException {
boolean success;
int timeout = 0;
try {
ChannelFuture future = channel.writeAndFlush(message);
success = future.await(DEFAULT_TIMEOUT);
Throwable cause = future.cause();
if (cause != null) {
throw cause;
}
} catch (Throwable e) {
throw new RemotingException(
(InetSocketAddress) channel.localAddress(),
(InetSocketAddress) channel.remoteAddress(),
"Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to "
+ channel.remoteAddress().toString() + ", cause: " + e.getMessage(),
e);
}
if (!success) {
throw new RemotingException(
(InetSocketAddress) channel.localAddress(),
(InetSocketAddress) channel.remoteAddress(),
"Failed to send message " + PayloadDropper.getRequestWithoutData(message) + " to "
+ channel.remoteAddress().toString() + "in timeout(" + timeout + "ms) limit");
}
}
private String count(Invoker<?> invoker, String method) {
URL url = invoker.getUrl();
List<List<String>> table = new ArrayList<List<String>>();
List<String> header = new ArrayList<String>();
header.add("method");
header.add("total");
header.add("failed");
header.add("active");
header.add("average");
header.add("max");
if (method == null || method.length() == 0) {
for (Method m : invoker.getInterface().getMethods()) {
RpcStatus count = RpcStatus.getStatus(url, m.getName());
table.add(createRow(m.getName(), count));
}
} else {
boolean found = false;
for (Method m : invoker.getInterface().getMethods()) {
if (m.getName().equals(method)) {
found = true;
break;
}
}
if (found) {
RpcStatus count = RpcStatus.getStatus(url, method);
table.add(createRow(method, count));
} else {
return "No such method " + method + " in class "
+ invoker.getInterface().getName();
}
}
return TelnetUtils.toTable(header, table);
}
private List<String> createRow(String methodName, RpcStatus count) {
List<String> row = new ArrayList<String>();
row.add(methodName);
row.add(String.valueOf(count.getTotal()));
row.add(String.valueOf(count.getFailed()));
row.add(String.valueOf(count.getActive()));
row.add(count.getSucceededAverageElapsed() + "ms");
row.add(count.getSucceededMaxElapsed() + "ms");
return row;
}
}
| 8,309 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineApp.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.qos.command.impl;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ProviderModel;
@Cmd(
name = "offlineApp",
summary = "offline app addresses",
example = {"offlineApp", "offlineApp xx.xx.xxx.service"})
public class OfflineApp extends BaseOffline {
public OfflineApp(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected void doUnexport(ProviderModel.RegisterStatedURL statedURL) {
if (UrlUtils.isServiceDiscoveryURL(statedURL.getRegistryUrl())) {
super.doUnexport(statedURL);
}
}
}
| 8,310 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Ls.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.util.ServiceCheckUtils;
import org.apache.dubbo.qos.textui.TTable;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.util.Collection;
@Cmd(
name = "ls",
summary = "ls service",
example = {"ls"})
public class Ls implements BaseCommand {
private final FrameworkModel frameworkModel;
public Ls(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
StringBuilder result = new StringBuilder();
result.append(listProvider());
result.append(listConsumer());
return result.toString();
}
public String listProvider() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("As Provider side:" + System.lineSeparator());
Collection<ProviderModel> providerModelList =
frameworkModel.getServiceRepository().allProviderModels();
TTable tTable = new TTable(new TTable.ColumnDefine[] {
new TTable.ColumnDefine(TTable.Align.MIDDLE), new TTable.ColumnDefine(TTable.Align.MIDDLE)
});
// Header
tTable.addRow("Provider Service Name", "PUB");
// Content
for (ProviderModel providerModel : providerModelList) {
if (providerModel.getModuleModel().isInternal()) {
tTable.addRow(
"DubboInternal - " + providerModel.getServiceKey(),
ServiceCheckUtils.getRegisterStatus(providerModel));
} else {
tTable.addRow(providerModel.getServiceKey(), ServiceCheckUtils.getRegisterStatus(providerModel));
}
}
stringBuilder.append(tTable.rendering());
return stringBuilder.toString();
}
public String listConsumer() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("As Consumer side:" + System.lineSeparator());
Collection<ConsumerModel> consumerModelList =
frameworkModel.getServiceRepository().allConsumerModels();
TTable tTable = new TTable(new TTable.ColumnDefine[] {
new TTable.ColumnDefine(TTable.Align.MIDDLE), new TTable.ColumnDefine(TTable.Align.MIDDLE)
});
// Header
tTable.addRow("Consumer Service Name", "NUM");
// Content
// TODO to calculate consumerAddressNum
for (ConsumerModel consumerModel : consumerModelList) {
tTable.addRow(consumerModel.getServiceKey(), ServiceCheckUtils.getConsumerAddressNum(consumerModel));
}
stringBuilder.append(tTable.rendering());
return stringBuilder.toString();
}
}
| 8,311 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SerializeCheckStatus.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.qos.command.impl;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.util.SerializeCheckUtils;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
@Cmd(name = "serializeCheckStatus", summary = "get serialize check status")
public class SerializeCheckStatus implements BaseCommand {
private final SerializeCheckUtils serializeCheckUtils;
public SerializeCheckStatus(FrameworkModel frameworkModel) {
serializeCheckUtils = frameworkModel.getBeanFactory().getBean(SerializeCheckUtils.class);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (commandContext.isHttp()) {
Map<String, Object> result = new HashMap<>();
result.put("checkStatus", serializeCheckUtils.getStatus());
result.put("checkSerializable", serializeCheckUtils.isCheckSerializable());
result.put("allowedPrefix", serializeCheckUtils.getAllowedList());
result.put("disAllowedPrefix", serializeCheckUtils.getDisAllowedList());
return JsonUtils.toJson(result);
} else {
return "CheckStatus: " + serializeCheckUtils.getStatus() + "\n\n" + "CheckSerializable: "
+ serializeCheckUtils.isCheckSerializable() + "\n\n" + "AllowedPrefix:"
+ "\n"
+ serializeCheckUtils.getAllowedList().stream().sorted().collect(Collectors.joining("\n"))
+ "\n\n"
+ "DisAllowedPrefix:"
+ "\n"
+ serializeCheckUtils.getDisAllowedList().stream().sorted().collect(Collectors.joining("\n"))
+ "\n\n";
}
}
}
| 8,312 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OnlineApp.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.qos.command.impl;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ProviderModel;
@Cmd(
name = "onlineApp",
summary = "online app addresses",
example = {"onlineApp", "onlineApp xx.xx.xxx.service"})
public class OnlineApp extends BaseOnline {
public OnlineApp(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected void doExport(ProviderModel.RegisterStatedURL statedURL) {
if (UrlUtils.isServiceDiscoveryURL(statedURL.getRegistryUrl())) {
super.doExport(statedURL);
}
}
}
| 8,313 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Online.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.qos.command.impl;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.rpc.model.FrameworkModel;
@Cmd(
name = "online",
summary = "online app addresses",
example = {"online dubbo", "online xx.xx.xxx.service"})
public class Online extends BaseOnline {
public Online(FrameworkModel frameworkModel) {
super(frameworkModel);
}
}
| 8,314 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetEnabledRouterSnapshot.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher;
import org.apache.dubbo.rpc.model.FrameworkModel;
@Cmd(
name = "getEnabledRouterSnapshot",
summary = "Get enabled Dubbo invocation level router snapshot print service list")
public class GetEnabledRouterSnapshot implements BaseCommand {
private final RouterSnapshotSwitcher routerSnapshotSwitcher;
public GetEnabledRouterSnapshot(FrameworkModel frameworkModel) {
this.routerSnapshotSwitcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
return String.join("\n", routerSnapshotSwitcher.getEnabledService());
}
}
| 8,315 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Live.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.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.probe.LivenessProbe;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Cmd(name = "live", summary = "Judge if service is alive? ", requiredPermissionLevel = PermissionLevel.PUBLIC)
public class Live implements BaseCommand {
private final FrameworkModel frameworkModel;
public Live(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
String config = frameworkModel.getApplicationModels().stream()
.map(applicationModel ->
applicationModel.getApplicationConfigManager().getApplication())
.map(o -> o.orElse(null))
.filter(Objects::nonNull)
.map(ApplicationConfig::getLivenessProbe)
.filter(Objects::nonNull)
.collect(Collectors.joining(","));
URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_LIVE_PROBE_EXTENSION, config);
List<LivenessProbe> livenessProbes = frameworkModel
.getExtensionLoader(LivenessProbe.class)
.getActivateExtension(url, CommonConstants.QOS_LIVE_PROBE_EXTENSION);
if (!livenessProbes.isEmpty()) {
for (LivenessProbe livenessProbe : livenessProbes) {
if (!livenessProbe.check()) {
// 503 Service Unavailable
commandContext.setHttpCode(503);
return "false";
}
}
}
// 200 OK
commandContext.setHttpCode(200);
return "true";
}
}
| 8,316 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SwitchLogger.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.qos.command.impl;
import org.apache.dubbo.common.logger.Level;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
@Cmd(
name = "switchLogger",
summary = "Switch logger",
example = {"switchLogger slf4j"})
public class SwitchLogger implements BaseCommand {
private final FrameworkModel frameworkModel;
public SwitchLogger(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length != 1) {
return "Unexpected argument length.";
}
Level level = LoggerFactory.getLevel();
LoggerFactory.setLoggerAdapter(frameworkModel, args[0]);
LoggerFactory.setLevel(level);
return "OK";
}
}
| 8,317 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SelectTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.lang.reflect.Method;
import java.util.List;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
@Cmd(
name = "select",
summary = "Select the index of the method you want to invoke",
example = {"select [index]"})
public class SelectTelnet implements BaseCommand {
public static final AttributeKey<Boolean> SELECT_KEY = AttributeKey.valueOf("telnet.select");
public static final AttributeKey<Method> SELECT_METHOD_KEY = AttributeKey.valueOf("telnet.select.method");
private final InvokeTelnet invokeTelnet;
public SelectTelnet(FrameworkModel frameworkModel) {
this.invokeTelnet = new InvokeTelnet(frameworkModel);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isEmpty(args)) {
return "Please input the index of the method you want to invoke, eg: \r\n select 1";
}
Channel channel = commandContext.getRemote();
String message = args[0];
List<Method> methodList =
channel.attr(InvokeTelnet.INVOKE_METHOD_LIST_KEY).get();
if (CollectionUtils.isEmpty(methodList)) {
return "Please use the invoke command first.";
}
if (!StringUtils.isNumber(message)
|| Integer.parseInt(message) < 1
|| Integer.parseInt(message) > methodList.size()) {
return "Illegal index ,please input select 1~" + methodList.size();
}
Method method = methodList.get(Integer.parseInt(message) - 1);
channel.attr(SELECT_METHOD_KEY).set(method);
channel.attr(SELECT_KEY).set(Boolean.TRUE);
String invokeMessage = channel.attr(InvokeTelnet.INVOKE_MESSAGE_KEY).get();
return invokeTelnet.execute(commandContext, new String[] {invokeMessage});
}
}
| 8,318 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DisableRouterSnapshot.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ServiceMetadata;
@Cmd(
name = "disableRouterSnapshot",
summary = "Disable Dubbo Invocation Level Router Snapshot Print",
example = "disableRouterSnapshot xx.xx.xxx.service")
public class DisableRouterSnapshot implements BaseCommand {
private final RouterSnapshotSwitcher routerSnapshotSwitcher;
private final FrameworkModel frameworkModel;
public DisableRouterSnapshot(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
this.routerSnapshotSwitcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length != 1) {
return "args count should be 1. example disableRouterSnapshot xx.xx.xxx.service";
}
String servicePattern = args[0];
int count = 0;
for (ConsumerModel consumerModel : frameworkModel.getServiceRepository().allConsumerModels()) {
try {
ServiceMetadata metadata = consumerModel.getServiceMetadata();
if (metadata.getServiceKey().matches(servicePattern)
|| metadata.getDisplayServiceKey().matches(servicePattern)) {
routerSnapshotSwitcher.removeEnabledService(metadata.getServiceKey());
count += 1;
}
} catch (Throwable ignore) {
}
}
return "OK. Found service count: " + count;
}
}
| 8,319 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ShutdownTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
@Cmd(
name = "shutdown",
summary = "Shutdown Dubbo Application.",
example = {"shutdown -t <milliseconds>"})
public class ShutdownTelnet implements BaseCommand {
private final FrameworkModel frameworkModel;
public ShutdownTelnet(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
int sleepMilliseconds = 0;
if (args != null && args.length > 0) {
if (args.length == 2 && "-t".equals(args[0]) && StringUtils.isNumber(args[1])) {
sleepMilliseconds = Integer.parseInt(args[1]);
} else {
return "Invalid parameter,please input like shutdown -t 10000";
}
}
long start = System.currentTimeMillis();
if (sleepMilliseconds > 0) {
try {
Thread.sleep(sleepMilliseconds);
} catch (InterruptedException e) {
return "Failed to invoke shutdown command, cause: " + e.getMessage();
}
}
StringBuilder buf = new StringBuilder();
List<ApplicationModel> applicationModels = frameworkModel.getApplicationModels();
for (ApplicationModel applicationModel : new ArrayList<>(applicationModels)) {
applicationModel.destroy();
}
// TODO change to ApplicationDeployer.destroy() or ApplicationModel.destroy()
// DubboShutdownHook.getDubboShutdownHook().unregister();
// DubboShutdownHook.getDubboShutdownHook().doDestroy();
long end = System.currentTimeMillis();
buf.append("Application has shutdown successfully");
buf.append("\r\nelapsed: ");
buf.append(end - start);
buf.append(" ms.");
return buf.toString();
}
}
| 8,320 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/EnableRouterSnapshot.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.cluster.router.RouterSnapshotSwitcher;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ServiceMetadata;
@Cmd(
name = "enableRouterSnapshot",
summary = "Enable Dubbo Invocation Level Router Snapshot Print",
example = "enableRouterSnapshot xx.xx.xxx.service")
public class EnableRouterSnapshot implements BaseCommand {
private final RouterSnapshotSwitcher routerSnapshotSwitcher;
private final FrameworkModel frameworkModel;
public EnableRouterSnapshot(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
this.routerSnapshotSwitcher = frameworkModel.getBeanFactory().getBean(RouterSnapshotSwitcher.class);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length != 1) {
return "args count should be 1. example enableRouterSnapshot xx.xx.xxx.service";
}
String servicePattern = args[0];
int count = 0;
for (ConsumerModel consumerModel : frameworkModel.getServiceRepository().allConsumerModels()) {
try {
ServiceMetadata metadata = consumerModel.getServiceMetadata();
if (metadata.getServiceKey().matches(servicePattern)
|| metadata.getDisplayServiceKey().matches(servicePattern)) {
routerSnapshotSwitcher.addEnabledService(metadata.getServiceKey());
count += 1;
}
} catch (Throwable ignore) {
}
}
return "OK. Found service count: " + count + ". This will cause performance degradation, please be careful!";
}
}
| 8,321 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/OfflineInterface.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.qos.command.impl;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ProviderModel;
@Cmd(
name = "offlineInterface",
summary = "offline dubbo",
example = {"offlineInterface dubbo", "offlineInterface xx.xx.xxx.service"})
public class OfflineInterface extends BaseOffline {
public OfflineInterface(FrameworkModel frameworkModel) {
super(frameworkModel);
}
@Override
protected void doUnexport(ProviderModel.RegisterStatedURL statedURL) {
if (!UrlUtils.isServiceDiscoveryURL(statedURL.getRegistryUrl())) {
super.doUnexport(statedURL);
}
}
}
| 8,322 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/DefaultMetricsReporterCmd.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.qos.command.impl;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.metrics.report.DefaultMetricsReporter;
import org.apache.dubbo.metrics.report.MetricsReporter;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Cmd(name = "metrics_default", summary = "display metrics information")
public class DefaultMetricsReporterCmd implements BaseCommand {
public FrameworkModel frameworkModel;
public DefaultMetricsReporterCmd(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
List<ApplicationModel> models = frameworkModel.getApplicationModels();
String result = "There is no application with data";
if (notSpecifyApplication(args)) {
result = useFirst(models, result, null);
} else if (args.length == 1) {
result = specifyApplication(args[0], models, null);
} else if (args.length == 2) {
result = specifyApplication(args[0], models, args[1]);
}
return result;
}
private boolean notSpecifyApplication(String[] args) {
return args == null || args.length == 0;
}
private String useFirst(List<ApplicationModel> models, String result, String metricsName) {
for (ApplicationModel model : models) {
String current = getResponseByApplication(model, metricsName);
if (current != null && getLineNumber(current) > 0) {
result = current;
break;
}
}
return result;
}
private String specifyApplication(String appName, List<ApplicationModel> models, String metricsName) {
if ("application_all".equals(appName)) {
return allApplication(models);
} else {
return specifySingleApplication(appName, models, metricsName);
}
}
private String specifySingleApplication(String appName, List<ApplicationModel> models, String metricsName) {
Optional<ApplicationModel> modelOptional = models.stream()
.filter(applicationModel -> appName.equals(applicationModel.getApplicationName()))
.findFirst();
if (modelOptional.isPresent()) {
return getResponseByApplication(modelOptional.get(), metricsName);
} else {
return "Not exist application: " + appName;
}
}
private String allApplication(List<ApplicationModel> models) {
Map<String, String> appResultMap = new HashMap<>();
for (ApplicationModel model : models) {
appResultMap.put(model.getApplicationName(), getResponseByApplication(model, null));
}
return JsonUtils.toJson(appResultMap);
}
private String getResponseByApplication(ApplicationModel applicationModel, String metricsName) {
String response = "DefaultMetricsReporter not init";
MetricsReporter metricsReporter = applicationModel.getBeanFactory().getBean(DefaultMetricsReporter.class);
if (metricsReporter != null) {
metricsReporter.resetIfSamplesChanged();
response = metricsReporter.getResponseWithName(metricsName);
}
return response;
}
private static long getLineNumber(String content) {
LineNumberReader lnr = new LineNumberReader(new CharArrayReader(content.toCharArray()));
try {
lnr.skip(Long.MAX_VALUE);
lnr.close();
} catch (IOException ignore) {
}
return lnr.getLineNumber();
}
}
| 8,323 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/PwdTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import java.util.Arrays;
@Cmd(
name = "pwd",
summary = "Print working default service.",
example = {"pwd"})
public class PwdTelnet implements BaseCommand {
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length > 0) {
return "Unsupported parameter " + Arrays.toString(args) + " for pwd.";
}
String service =
commandContext.getRemote().attr(ChangeTelnet.SERVICE_KEY).get();
StringBuilder buf = new StringBuilder();
if (StringUtils.isEmpty(service)) {
buf.append('/');
} else {
buf.append(service);
}
return buf.toString();
}
}
| 8,324 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Startup.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.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.probe.StartupProbe;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Cmd(name = "startup", summary = "Judge if service has started? ", requiredPermissionLevel = PermissionLevel.PUBLIC)
public class Startup implements BaseCommand {
private final FrameworkModel frameworkModel;
public Startup(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
String config = frameworkModel.getApplicationModels().stream()
.map(applicationModel ->
applicationModel.getApplicationConfigManager().getApplication())
.map(o -> o.orElse(null))
.filter(Objects::nonNull)
.map(ApplicationConfig::getStartupProbe)
.filter(Objects::nonNull)
.collect(Collectors.joining(","));
URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_STARTUP_PROBE_EXTENSION, config);
List<StartupProbe> startupProbes = frameworkModel
.getExtensionLoader(StartupProbe.class)
.getActivateExtension(url, CommonConstants.QOS_STARTUP_PROBE_EXTENSION);
if (!startupProbes.isEmpty()) {
for (StartupProbe startupProbe : startupProbes) {
if (!startupProbe.check()) {
// 503 Service Unavailable
commandContext.setHttpCode(503);
return "false";
}
}
}
// 200 OK
commandContext.setHttpCode(200);
return "true";
}
}
| 8,325 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetRouterSnapshot.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.qos.command.impl;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.directory.AbstractDirectory;
import org.apache.dubbo.rpc.cluster.router.state.StateRouter;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ServiceMetadata;
import java.util.Map;
@Cmd(
name = "getRouterSnapshot",
summary = "Get State Router Snapshot.",
example = "getRouterSnapshot xx.xx.xxx.service")
public class GetRouterSnapshot implements BaseCommand {
private final FrameworkModel frameworkModel;
public GetRouterSnapshot(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args.length != 1) {
return "args count should be 1. example getRouterSnapshot xx.xx.xxx.service";
}
String servicePattern = args[0];
StringBuilder stringBuilder = new StringBuilder();
for (ConsumerModel consumerModel : frameworkModel.getServiceRepository().allConsumerModels()) {
try {
ServiceMetadata metadata = consumerModel.getServiceMetadata();
if (metadata.getServiceKey().matches(servicePattern)
|| metadata.getDisplayServiceKey().matches(servicePattern)) {
Object object = metadata.getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY);
Map<Registry, MigrationInvoker<?>> invokerMap;
if (object instanceof Map) {
invokerMap = (Map<Registry, MigrationInvoker<?>>) object;
for (Map.Entry<Registry, MigrationInvoker<?>> invokerEntry : invokerMap.entrySet()) {
Directory<?> directory = invokerEntry.getValue().getDirectory();
StateRouter<?> headStateRouter =
directory.getRouterChain().getHeadStateRouter();
stringBuilder
.append(metadata.getServiceKey())
.append('@')
.append(Integer.toHexString(System.identityHashCode(metadata)))
.append("\n")
.append("[ All Invokers:")
.append(directory.getAllInvokers().size())
.append(" ] ")
.append("[ Valid Invokers: ")
.append(((AbstractDirectory<?>) directory)
.getValidInvokers()
.size())
.append(" ]\n")
.append("\n")
.append(headStateRouter.buildSnapshot())
.append("\n\n");
}
}
}
} catch (Throwable ignore) {
}
}
return stringBuilder.toString();
}
}
| 8,326 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/SetProfilerWarnPercent.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.qos.command.impl;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.profiler.ProfilerSwitch;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.QOS_PROFILER_WARN_PERCENT;
@Cmd(
name = "setProfilerWarnPercent",
example = "setProfilerWarnPercent 0.75",
summary = "Disable Dubbo Invocation Profiler.")
public class SetProfilerWarnPercent implements BaseCommand {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(SetProfilerWarnPercent.class);
@Override
public String execute(CommandContext commandContext, String[] args) {
if (args == null || args.length != 1) {
return "args error. example: setProfilerWarnPercent 0.75";
}
ProfilerSwitch.setWarnPercent(Double.parseDouble(args[0]));
logger.warn(
QOS_PROFILER_WARN_PERCENT, "", "", "Dubbo Invocation Profiler warn percent has been set to " + args[0]);
return "OK";
}
}
| 8,327 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GetAddress.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.qos.command.impl;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.cluster.ClusterInvoker;
import org.apache.dubbo.rpc.cluster.Directory;
import org.apache.dubbo.rpc.cluster.directory.AbstractDirectory;
import org.apache.dubbo.rpc.model.ConsumerModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.FrameworkServiceRepository;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Cmd(
name = "getAddress",
summary = "Get service available address ",
example = {"getAddress com.example.DemoService", "getAddress group/com.example.DemoService"},
requiredPermissionLevel = PermissionLevel.PRIVATE)
public class GetAddress implements BaseCommand {
public final FrameworkServiceRepository serviceRepository;
public GetAddress(FrameworkModel frameworkModel) {
this.serviceRepository = frameworkModel.getServiceRepository();
}
@Override
@SuppressWarnings("unchecked")
public String execute(CommandContext commandContext, String[] args) {
if (args == null || args.length != 1) {
return "Invalid parameters, please input like getAddress com.example.DemoService";
}
String serviceName = args[0];
StringBuilder plainOutput = new StringBuilder();
Map<String, Object> jsonOutput = new HashMap<>();
for (ConsumerModel consumerModel : serviceRepository.allConsumerModels()) {
if (serviceName.equals(consumerModel.getServiceKey())) {
appendConsumer(plainOutput, jsonOutput, consumerModel);
}
}
if (commandContext.isHttp()) {
return JsonUtils.toJson(jsonOutput);
} else {
return plainOutput.toString();
}
}
private static void appendConsumer(
StringBuilder plainOutput, Map<String, Object> jsonOutput, ConsumerModel consumerModel) {
plainOutput
.append("ConsumerModel: ")
.append(consumerModel.getServiceKey())
.append("@")
.append(Integer.toHexString(System.identityHashCode(consumerModel)))
.append("\n\n");
Map<String, Object> consumerMap = new HashMap<>();
jsonOutput.put(
consumerModel.getServiceKey() + "@" + Integer.toHexString(System.identityHashCode(consumerModel)),
consumerMap);
Object object = consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY);
Map<Registry, MigrationInvoker<?>> invokerMap;
if (object instanceof Map) {
invokerMap = (Map<Registry, MigrationInvoker<?>>) object;
for (Map.Entry<Registry, MigrationInvoker<?>> entry : invokerMap.entrySet()) {
appendInvokers(plainOutput, consumerMap, entry);
}
}
}
private static void appendInvokers(
StringBuilder plainOutput,
Map<String, Object> consumerMap,
Map.Entry<Registry, MigrationInvoker<?>> entry) {
URL registryUrl = entry.getKey().getUrl();
plainOutput.append("Registry: ").append(registryUrl).append("\n");
Map<String, Object> registryMap = new HashMap<>();
consumerMap.put(registryUrl.toString(), registryMap);
MigrationInvoker<?> migrationInvoker = entry.getValue();
MigrationStep migrationStep = migrationInvoker.getMigrationStep();
plainOutput.append("MigrationStep: ").append(migrationStep).append("\n\n");
registryMap.put("MigrationStep", migrationStep);
Map<String, Object> invokersMap = new HashMap<>();
registryMap.put("Invokers", invokersMap);
URL originConsumerUrl = RpcContext.getServiceContext().getConsumerUrl();
RpcContext.getServiceContext().setConsumerUrl(migrationInvoker.getConsumerUrl());
appendInterfaceLevel(plainOutput, migrationInvoker, invokersMap);
appendAppLevel(plainOutput, migrationInvoker, invokersMap);
RpcContext.getServiceContext().setConsumerUrl(originConsumerUrl);
}
private static void appendAppLevel(
StringBuilder plainOutput, MigrationInvoker<?> migrationInvoker, Map<String, Object> invokersMap) {
Map<String, Object> appMap = new HashMap<>();
invokersMap.put("Application-Level", appMap);
Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker())
.ifPresent(i -> plainOutput.append("Application-Level: \n"));
Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker())
.map(ClusterInvoker::getDirectory)
.map(Directory::getAllInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("All Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
appMap.put("All", invokerUrls);
});
Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker())
.map(ClusterInvoker::getDirectory)
.map(s -> (AbstractDirectory<?>) s)
.map(AbstractDirectory::getValidInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("Valid Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
appMap.put("Valid", invokerUrls);
});
Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker())
.map(ClusterInvoker::getDirectory)
.map(s -> (AbstractDirectory<?>) s)
.map(AbstractDirectory::getDisabledInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("Disabled Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
appMap.put("Disabled", invokerUrls);
});
}
private static void appendInterfaceLevel(
StringBuilder plainOutput, MigrationInvoker<?> migrationInvoker, Map<String, Object> invokersMap) {
Map<String, Object> interfaceMap = new HashMap<>();
invokersMap.put("Interface-Level", interfaceMap);
Optional.ofNullable(migrationInvoker.getInvoker()).ifPresent(i -> plainOutput.append("Interface-Level: \n"));
Optional.ofNullable(migrationInvoker.getInvoker())
.map(ClusterInvoker::getDirectory)
.map(Directory::getAllInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("All Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
interfaceMap.put("All", invokerUrls);
});
Optional.ofNullable(migrationInvoker.getInvoker())
.map(ClusterInvoker::getDirectory)
.map(s -> (AbstractDirectory<?>) s)
.map(AbstractDirectory::getValidInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("Valid Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
interfaceMap.put("Valid", invokerUrls);
});
Optional.ofNullable(migrationInvoker.getInvoker())
.map(ClusterInvoker::getDirectory)
.map(s -> (AbstractDirectory<?>) s)
.map(AbstractDirectory::getDisabledInvokers)
.ifPresent(invokers -> {
List<String> invokerUrls = new LinkedList<>();
plainOutput.append("Disabled Invokers: \n");
for (org.apache.dubbo.rpc.Invoker<?> invoker : invokers) {
invokerUrls.add(invoker.getUrl().toFullString());
plainOutput.append(invoker.getUrl().toFullString()).append("\n");
}
plainOutput.append("\n");
interfaceMap.put("Disabled", invokerUrls);
});
}
}
| 8,328 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/ChangeTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
@Cmd(
name = "cd",
summary = "Change default service.",
example = {"cd [service]"})
public class ChangeTelnet implements BaseCommand {
public static final AttributeKey<String> SERVICE_KEY = AttributeKey.valueOf("telnet.service");
private final DubboProtocol dubboProtocol;
public ChangeTelnet(FrameworkModel frameworkModel) {
this.dubboProtocol = DubboProtocol.getDubboProtocol(frameworkModel);
}
@Override
public String execute(CommandContext commandContext, String[] args) {
Channel channel = commandContext.getRemote();
if (ArrayUtils.isEmpty(args)) {
return "Please input service name, eg: \r\ncd XxxService\r\ncd com.xxx.XxxService";
}
String message = args[0];
StringBuilder buf = new StringBuilder();
if ("/".equals(message) || "..".equals(message)) {
String service = channel.attr(SERVICE_KEY).getAndRemove();
buf.append("Cancelled default service ").append(service).append('.');
} else {
boolean found = false;
for (Exporter<?> exporter : dubboProtocol.getExporters()) {
if (message.equals(exporter.getInvoker().getInterface().getSimpleName())
|| message.equals(exporter.getInvoker().getInterface().getName())
|| message.equals(exporter.getInvoker().getUrl().getPath())) {
found = true;
break;
}
}
if (found) {
channel.attr(SERVICE_KEY).set(message);
buf.append("Used the ")
.append(message)
.append(" as default.\r\nYou can cancel default service by command: cd /");
} else {
buf.append("No such service ").append(message);
}
}
return buf.toString();
}
}
| 8,329 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/GracefulShutdown.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.rpc.model.FrameworkModel;
@Cmd(
name = "gracefulShutdown",
summary = "Gracefully shutdown servers",
example = {"gracefulShutdown"},
requiredPermissionLevel = PermissionLevel.PRIVATE)
public class GracefulShutdown implements BaseCommand {
private final Offline offline;
private final FrameworkModel frameworkModel;
public GracefulShutdown(FrameworkModel frameworkModel) {
this.offline = new Offline(frameworkModel);
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
for (org.apache.dubbo.rpc.GracefulShutdown gracefulShutdown :
org.apache.dubbo.rpc.GracefulShutdown.getGracefulShutdowns(frameworkModel)) {
gracefulShutdown.readonly();
}
offline.execute(commandContext, new String[0]);
return "OK";
}
}
| 8,330 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/Version.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.qos.command.impl;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
@Cmd(
name = "version",
summary = "version command(show dubbo version)",
example = {"version"})
public class Version implements BaseCommand {
@Override
public String execute(CommandContext commandContext, String[] args) {
StringBuilder versionDescBuilder = new StringBuilder();
versionDescBuilder.append("dubbo version \"");
versionDescBuilder.append(org.apache.dubbo.common.Version.getVersion());
versionDescBuilder.append('\"');
return versionDescBuilder.toString();
}
}
| 8,331 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/impl/InvokeTelnet.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.qos.command.impl;
import org.apache.dubbo.common.utils.ArrayUtils;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.qos.api.Cmd;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.AsyncContext;
import org.apache.dubbo.rpc.AsyncContextImpl;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.MethodDescriptor;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import static org.apache.dubbo.common.utils.PojoUtils.realize;
@Cmd(
name = "invoke",
summary = "Invoke the service method.",
example = {"invoke IHelloService.sayHello(\"xxxx\")", "invoke sayHello(\"xxxx\")"})
public class InvokeTelnet implements BaseCommand {
public static final AttributeKey<String> INVOKE_MESSAGE_KEY = AttributeKey.valueOf("telnet.invoke.method.message");
public static final AttributeKey<List<Method>> INVOKE_METHOD_LIST_KEY =
AttributeKey.valueOf("telnet.invoke.method.list");
public static final AttributeKey<ProviderModel> INVOKE_METHOD_PROVIDER_KEY =
AttributeKey.valueOf("telnet.invoke.method.provider");
private final FrameworkModel frameworkModel;
public InvokeTelnet(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public String execute(CommandContext commandContext, String[] args) {
if (ArrayUtils.isEmpty(args)) {
return "Please input method name, eg: \r\ninvoke xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n"
+ "invoke XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})\r\n"
+ "invoke com.xxx.XxxService.xxxMethod(1234, \"abcd\", {\"prop\" : \"value\"})";
}
Channel channel = commandContext.getRemote();
String service = channel.attr(ChangeTelnet.SERVICE_KEY) != null
? channel.attr(ChangeTelnet.SERVICE_KEY).get()
: null;
String message = args[0];
int i = message.indexOf("(");
if (i < 0 || !message.endsWith(")")) {
return "Invalid parameters, format: service.method(args)";
}
String method = message.substring(0, i).trim();
String param = message.substring(i + 1, message.length() - 1).trim();
i = method.lastIndexOf(".");
if (i >= 0) {
service = method.substring(0, i).trim();
method = method.substring(i + 1).trim();
}
if (StringUtils.isEmpty(service)) {
return "If you want to invoke like [invoke sayHello(\"xxxx\")], please execute cd command first,"
+ " or you can execute it like [invoke IHelloService.sayHello(\"xxxx\")]";
}
List<Object> list;
try {
list = JsonUtils.toJavaList("[" + param + "]", Object.class);
} catch (Throwable t) {
return "Invalid json argument, cause: " + t.getMessage();
}
StringBuilder buf = new StringBuilder();
Method invokeMethod = null;
ProviderModel selectedProvider = null;
if (isInvokedSelectCommand(channel)) {
selectedProvider = channel.attr(INVOKE_METHOD_PROVIDER_KEY).get();
invokeMethod = channel.attr(SelectTelnet.SELECT_METHOD_KEY).get();
} else {
for (ProviderModel provider : frameworkModel.getServiceRepository().allProviderModels()) {
if (!isServiceMatch(service, provider)) {
continue;
}
selectedProvider = provider;
List<Method> methodList = findSameSignatureMethod(provider.getAllMethods(), method, list);
if (CollectionUtils.isEmpty(methodList)) {
break;
}
if (methodList.size() == 1) {
invokeMethod = methodList.get(0);
} else {
List<Method> matchMethods = findMatchMethods(methodList, list);
if (CollectionUtils.isEmpty(matchMethods)) {
break;
}
if (matchMethods.size() == 1) {
invokeMethod = matchMethods.get(0);
} else { // exist overridden method
channel.attr(INVOKE_METHOD_PROVIDER_KEY).set(provider);
channel.attr(INVOKE_METHOD_LIST_KEY).set(matchMethods);
channel.attr(INVOKE_MESSAGE_KEY).set(message);
printSelectMessage(buf, matchMethods);
return buf.toString();
}
}
break;
}
}
if (!StringUtils.isEmpty(service)) {
buf.append("Use default service ").append(service).append('.');
}
if (selectedProvider == null) {
buf.append("\r\nNo such service ").append(service);
return buf.toString();
}
if (invokeMethod == null) {
buf.append("\r\nNo such method ")
.append(method)
.append(" in service ")
.append(service);
return buf.toString();
}
try {
Object[] array =
realize(list.toArray(), invokeMethod.getParameterTypes(), invokeMethod.getGenericParameterTypes());
long start = System.currentTimeMillis();
AppResponse result = new AppResponse();
try {
Object o = invokeMethod.invoke(selectedProvider.getServiceInstance(), array);
boolean setValueDone = false;
if (RpcContext.getServerAttachment().isAsyncStarted()) {
AsyncContext asyncContext = RpcContext.getServerAttachment().getAsyncContext();
if (asyncContext instanceof AsyncContextImpl) {
CompletableFuture<Object> internalFuture =
((AsyncContextImpl) asyncContext).getInternalFuture();
result.setValue(internalFuture.get());
setValueDone = true;
}
}
if (!setValueDone) {
result.setValue(o);
}
} catch (Throwable t) {
result.setException(t);
if (t instanceof InterruptedException) {
Thread.currentThread().interrupt();
}
} finally {
RpcContext.removeContext();
}
long end = System.currentTimeMillis();
buf.append("\r\nresult: ");
buf.append(JsonUtils.toJson(result.recreate()));
buf.append("\r\nelapsed: ");
buf.append(end - start);
buf.append(" ms.");
} catch (Throwable t) {
return "Failed to invoke method " + invokeMethod.getName() + ", cause: " + StringUtils.toString(t);
}
return buf.toString();
}
private boolean isServiceMatch(String service, ProviderModel provider) {
return provider.getServiceKey().equalsIgnoreCase(service)
|| provider.getServiceInterfaceClass().getSimpleName().equalsIgnoreCase(service)
|| provider.getServiceInterfaceClass().getName().equalsIgnoreCase(service)
|| StringUtils.isEmpty(service);
}
private List<Method> findSameSignatureMethod(
Set<MethodDescriptor> methods, String lookupMethodName, List<Object> args) {
List<Method> sameSignatureMethods = new ArrayList<>();
for (MethodDescriptor model : methods) {
Method method = model.getMethod();
if (method.getName().equals(lookupMethodName) && method.getParameterTypes().length == args.size()) {
sameSignatureMethods.add(method);
}
}
return sameSignatureMethods;
}
private List<Method> findMatchMethods(List<Method> methods, List<Object> args) {
List<Method> matchMethod = new ArrayList<>();
for (Method method : methods) {
if (isMatch(method, args)) {
matchMethod.add(method);
}
}
return matchMethod;
}
private static boolean isMatch(Method method, List<Object> args) {
Class<?>[] types = method.getParameterTypes();
if (types.length != args.size()) {
return false;
}
for (int i = 0; i < types.length; i++) {
Class<?> type = types[i];
Object arg = args.get(i);
if (arg == null) {
if (type.isPrimitive()) {
return false;
}
// if the type is not primitive, we choose to believe what the invoker want is a null value
continue;
}
if (ReflectUtils.isPrimitive(arg.getClass())) {
// allow string arg to enum type, @see PojoUtils.realize0()
if (arg instanceof String && type.isEnum()) {
continue;
}
if (!ReflectUtils.isPrimitive(type)) {
return false;
}
if (!ReflectUtils.isCompatible(type, arg)) {
return false;
}
} else if (arg instanceof Map) {
String name = (String) ((Map<?, ?>) arg).get("class");
if (StringUtils.isNotEmpty(name)) {
Class<?> cls = ReflectUtils.forName(name);
if (!type.isAssignableFrom(cls)) {
return false;
}
} else {
return true;
}
} else if (arg instanceof Collection) {
if (!type.isArray() && !type.isAssignableFrom(arg.getClass())) {
return false;
}
} else {
if (!type.isAssignableFrom(arg.getClass())) {
return false;
}
}
}
return true;
}
private void printSelectMessage(StringBuilder buf, List<Method> methods) {
buf.append("Methods:\r\n");
for (int i = 0; i < methods.size(); i++) {
Method method = methods.get(i);
buf.append(i + 1).append(". ").append(method.getName()).append('(');
Class<?>[] parameterTypes = method.getParameterTypes();
for (int n = 0; n < parameterTypes.length; n++) {
buf.append(parameterTypes[n].getSimpleName());
if (n != parameterTypes.length - 1) {
buf.append(',');
}
}
buf.append(")\r\n");
}
buf.append("Please use the select command to select the method you want to invoke. eg: select 1");
}
private boolean isInvokedSelectCommand(Channel channel) {
if (channel.attr(SelectTelnet.SELECT_KEY).get() != null) {
channel.attr(SelectTelnet.SELECT_KEY).remove();
return true;
}
return false;
}
}
| 8,332 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/SerializeCheckUtils.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.qos.command.util;
import org.apache.dubbo.common.utils.AllowClassNotifyListener;
import org.apache.dubbo.common.utils.SerializeCheckStatus;
import org.apache.dubbo.common.utils.SerializeSecurityManager;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.Collections;
import java.util.Set;
public class SerializeCheckUtils implements AllowClassNotifyListener {
private final SerializeSecurityManager manager;
private volatile Set<String> allowedList = Collections.emptySet();
private volatile Set<String> disAllowedList = Collections.emptySet();
private volatile SerializeCheckStatus status = AllowClassNotifyListener.DEFAULT_STATUS;
private volatile boolean checkSerializable = true;
public SerializeCheckUtils(FrameworkModel frameworkModel) {
manager = frameworkModel.getBeanFactory().getOrRegisterBean(SerializeSecurityManager.class);
manager.registerListener(this);
}
@Override
public void notifyPrefix(Set<String> allowedList, Set<String> disAllowedList) {
this.allowedList = allowedList;
this.disAllowedList = disAllowedList;
}
@Override
public void notifyCheckStatus(SerializeCheckStatus status) {
this.status = status;
}
@Override
public void notifyCheckSerializable(boolean checkSerializable) {
this.checkSerializable = checkSerializable;
}
public Set<String> getAllowedList() {
return allowedList;
}
public Set<String> getDisAllowedList() {
return disAllowedList;
}
public SerializeCheckStatus getStatus() {
return status;
}
public boolean isCheckSerializable() {
return checkSerializable;
}
public Set<String> getWarnedClasses() {
return manager.getWarnedClasses();
}
}
| 8,333 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/CommandHelper.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.qos.command.util;
import org.apache.dubbo.qos.api.BaseCommand;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class CommandHelper {
private final FrameworkModel frameworkModel;
public CommandHelper(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
public boolean hasCommand(String commandName) {
BaseCommand command;
try {
command = frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandName);
} catch (Throwable throwable) {
return false;
}
return command != null;
}
public List<Class<?>> getAllCommandClass() {
final Set<String> commandList =
frameworkModel.getExtensionLoader(BaseCommand.class).getSupportedExtensions();
final List<Class<?>> classes = new ArrayList<Class<?>>();
for (String commandName : commandList) {
BaseCommand command =
frameworkModel.getExtensionLoader(BaseCommand.class).getExtension(commandName);
classes.add(command.getClass());
}
return classes;
}
public Class<?> getCommandClass(String commandName) {
if (hasCommand(commandName)) {
return frameworkModel
.getExtensionLoader(BaseCommand.class)
.getExtension(commandName)
.getClass();
} else {
return null;
}
}
}
| 8,334 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/util/ServiceCheckUtils.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.qos.command.util;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.constants.RegistryConstants;
import org.apache.dubbo.common.utils.UrlUtils;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.client.migration.MigrationInvoker;
import org.apache.dubbo.registry.client.migration.model.MigrationStep;
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.ProviderModel;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class ServiceCheckUtils {
public static String getRegisterStatus(ProviderModel providerModel) {
// check all registries status
List<String> statuses = new LinkedList<>();
for (ProviderModel.RegisterStatedURL registerStatedURL : providerModel.getStatedUrl()) {
URL registryUrl = registerStatedURL.getRegistryUrl();
boolean isServiceDiscovery = UrlUtils.isServiceDiscoveryURL(registryUrl);
String protocol = isServiceDiscovery
? registryUrl.getParameter(RegistryConstants.REGISTRY_KEY)
: registryUrl.getProtocol();
// e.g. zookeeper-A(Y)
statuses.add(protocol + "-" + (isServiceDiscovery ? "A" : "I") + "("
+ (registerStatedURL.isRegistered() ? "Y" : "N") + ")");
}
// e.g. zookeeper-A(Y)/zookeeper-I(Y)
return String.join("/", statuses.toArray(new String[0]));
}
public static String getConsumerAddressNum(ConsumerModel consumerModel) {
int num = 0;
Object object = consumerModel.getServiceMetadata().getAttribute(CommonConstants.CURRENT_CLUSTER_INVOKER_KEY);
Map<Registry, MigrationInvoker<?>> invokerMap;
List<String> nums = new LinkedList<>();
if (object instanceof Map) {
invokerMap = (Map<Registry, MigrationInvoker<?>>) object;
for (Map.Entry<Registry, MigrationInvoker<?>> entry : invokerMap.entrySet()) {
URL registryUrl = entry.getKey().getUrl();
boolean isServiceDiscovery = UrlUtils.isServiceDiscoveryURL(registryUrl);
String protocol = isServiceDiscovery
? registryUrl.getParameter(RegistryConstants.REGISTRY_KEY)
: registryUrl.getProtocol();
MigrationInvoker<?> migrationInvoker = entry.getValue();
MigrationStep migrationStep = migrationInvoker.getMigrationStep();
String interfaceSize = Optional.ofNullable(migrationInvoker.getInvoker())
.map(ClusterInvoker::getDirectory)
.map(Directory::getAllInvokers)
.map(List::size)
.map(String::valueOf)
.orElse("-");
String applicationSize = Optional.ofNullable(migrationInvoker.getServiceDiscoveryInvoker())
.map(ClusterInvoker::getDirectory)
.map(Directory::getAllInvokers)
.map(List::size)
.map(String::valueOf)
.orElse("-");
String step;
String size;
switch (migrationStep) {
case APPLICATION_FIRST:
step = "AF";
size = "I-" + interfaceSize + ",A-" + applicationSize;
break;
case FORCE_INTERFACE:
step = "I";
size = interfaceSize;
break;
default:
step = "A";
size = applicationSize;
break;
}
// zookeeper-AF(I-10,A-0)
// zookeeper-I(10)
// zookeeper-A(10)
nums.add(protocol + "-" + step + "(" + size + ")");
}
}
// zookeeper-AF(I-10,A-0)/nacos-I(10)
return String.join("/", nums.toArray(new String[0]));
}
}
| 8,335 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/HttpCommandDecoder.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.qos.command.decoder;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.CommandContextFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.multipart.Attribute;
import io.netty.handler.codec.http.multipart.HttpPostRequestDecoder;
import io.netty.handler.codec.http.multipart.InterfaceHttpData;
public class HttpCommandDecoder {
public static CommandContext decode(HttpRequest request) {
CommandContext commandContext = null;
if (request != null) {
QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
String path = queryStringDecoder.path();
String[] array = path.split("/");
if (array.length == 2) {
String name = array[1];
// process GET request and POST request separately. Check url for GET, and check body for POST
if (request.method() == HttpMethod.GET) {
if (queryStringDecoder.parameters().isEmpty()) {
commandContext = CommandContextFactory.newInstance(name);
commandContext.setHttp(true);
} else {
List<String> valueList = new ArrayList<String>();
for (List<String> values :
queryStringDecoder.parameters().values()) {
valueList.addAll(values);
}
commandContext =
CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}), true);
}
} else if (request.method() == HttpMethod.POST) {
HttpPostRequestDecoder httpPostRequestDecoder = new HttpPostRequestDecoder(request);
List<String> valueList = new ArrayList<String>();
for (InterfaceHttpData interfaceHttpData : httpPostRequestDecoder.getBodyHttpDatas()) {
if (interfaceHttpData.getHttpDataType() == InterfaceHttpData.HttpDataType.Attribute) {
Attribute attribute = (Attribute) interfaceHttpData;
try {
valueList.add(attribute.getValue());
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
if (valueList.isEmpty()) {
commandContext = CommandContextFactory.newInstance(name);
commandContext.setHttp(true);
} else {
commandContext =
CommandContextFactory.newInstance(name, valueList.toArray(new String[] {}), true);
}
}
} else if (array.length == 3) {
String name = array[1];
String appName = array[2];
if (request.method() == HttpMethod.GET) {
commandContext = CommandContextFactory.newInstance(name, new String[] {appName}, true);
commandContext.setHttp(true);
}
}
}
return commandContext;
}
}
| 8,336 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/decoder/TelnetCommandDecoder.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.qos.command.decoder;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.command.CommandContextFactory;
public class TelnetCommandDecoder {
public static final CommandContext decode(String str) {
CommandContext commandContext = null;
if (!StringUtils.isBlank(str)) {
str = str.trim();
String[] array = str.split("(?<![\\\\]) ");
if (array.length > 0) {
String[] targetArgs = new String[array.length - 1];
System.arraycopy(array, 1, targetArgs, 0, array.length - 1);
String name = array[0].trim();
if (name.equals("invoke") && array.length > 2) {
targetArgs = reBuildInvokeCmdArgs(str);
}
commandContext = CommandContextFactory.newInstance(name, targetArgs, false);
commandContext.setOriginRequest(str);
}
}
return commandContext;
}
private static String[] reBuildInvokeCmdArgs(String cmd) {
return new String[] {cmd.substring(cmd.indexOf(" ") + 1).trim()};
}
}
| 8,337 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/exception/NoSuchCommandException.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.qos.command.exception;
public class NoSuchCommandException extends CommandException {
public NoSuchCommandException(String msg) {
super("NoSuchCommandException:" + msg);
}
}
| 8,338 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/exception/CommandException.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.qos.command.exception;
public class CommandException extends Exception {
public CommandException(String msg) {
super(msg);
}
}
| 8,339 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/command/exception/PermissionDenyException.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.qos.command.exception;
public class PermissionDenyException extends CommandException {
public PermissionDenyException(String msg) {
super("Permission Deny On Operation: " + msg);
}
}
| 8,340 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/permission/DefaultAnonymousAccessPermissionChecker.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.qos.permission;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
import org.apache.dubbo.qos.api.QosConfiguration;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.Optional;
import io.netty.channel.Channel;
public class DefaultAnonymousAccessPermissionChecker implements PermissionChecker {
public static final DefaultAnonymousAccessPermissionChecker INSTANCE =
new DefaultAnonymousAccessPermissionChecker();
@Override
public boolean access(CommandContext commandContext, PermissionLevel defaultCmdRequiredPermissionLevel) {
final InetAddress inetAddress = Optional.ofNullable(commandContext.getRemote())
.map(Channel::remoteAddress)
.map(InetSocketAddress.class::cast)
.map(InetSocketAddress::getAddress)
.orElse(null);
QosConfiguration qosConfiguration = commandContext.getQosConfiguration();
String anonymousAllowCommands = qosConfiguration.getAnonymousAllowCommands();
if (StringUtils.isNotEmpty(anonymousAllowCommands)
&& Arrays.stream(anonymousAllowCommands.split(","))
.filter(StringUtils::isNotEmpty)
.map(String::trim)
.anyMatch(cmd -> cmd.equals(commandContext.getCommandName()))) {
return true;
}
PermissionLevel currentLevel = qosConfiguration.getAnonymousAccessPermissionLevel();
// Local has private permission
if (inetAddress != null && inetAddress.isLoopbackAddress()) {
currentLevel = PermissionLevel.PRIVATE;
} else if (inetAddress != null
&& qosConfiguration.getAcceptForeignIpWhitelistPredicate().test(inetAddress.getHostAddress())) {
currentLevel = PermissionLevel.PROTECTED;
}
return currentLevel.getLevel() >= defaultCmdRequiredPermissionLevel.getLevel();
}
}
| 8,341 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/permission/PermissionChecker.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.qos.permission;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.qos.api.CommandContext;
import org.apache.dubbo.qos.api.PermissionLevel;
// qosPermissionChecker=xxx.xxx.xxxPermissionChecker
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface PermissionChecker {
boolean access(CommandContext commandContext, PermissionLevel defaultCmdPermissionLevel);
}
| 8,342 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/LivenessProbe.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.qos.probe;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* A probe to indicate whether program is alive
* </p>
* If one or more spi return false, 'live' command in dubbo-qos
* will return false. This can be extended with custom program and developers
* can implement this to customize life cycle.
*
* @since 3.0
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface LivenessProbe {
/**
* Check if program is alive
*
* @return {@link boolean} result of probe
*/
boolean check();
}
| 8,343 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/StartupProbe.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.qos.probe;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* A probe to indicate whether program is startup
* </p>
* If one or more spi return false, 'startup' command in dubbo-qos
* will return false. This can be extended with custom program and developers
* can implement this to customize life cycle.
*
* @since 3.0
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface StartupProbe {
/**
* Check if program has been startup
*
* @return {@link boolean} result of probe
*/
boolean check();
}
| 8,344 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/ReadinessProbe.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.qos.probe;
import org.apache.dubbo.common.extension.ExtensionScope;
import org.apache.dubbo.common.extension.SPI;
/**
* A probe to indicate whether program is ready
* </p>
* If one or more spi return false, 'ready' command in dubbo-qos
* will return false. This can be extended with custom program and developers
* can implement this to customize life cycle.
*
* @since 3.0
*/
@SPI(scope = ExtensionScope.FRAMEWORK)
public interface ReadinessProbe {
/**
* Check if program is Ready
*
* @return {@link boolean} result of probe
*/
boolean check();
}
| 8,345 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/DeployerStartupProbe.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.qos.probe.impl;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.qos.probe.StartupProbe;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
@Activate
public class DeployerStartupProbe implements StartupProbe {
private FrameworkModel frameworkModel;
public DeployerStartupProbe(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public boolean check() {
if (this.frameworkModel == null) {
this.frameworkModel = FrameworkModel.defaultModel();
}
List<ApplicationModel> applicationModels = frameworkModel.getApplicationModels();
for (ApplicationModel applicationModel : applicationModels) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
if (moduleModel.getDeployer().isRunning()) {
return true;
}
}
}
return false;
}
}
| 8,346 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/DeployerReadinessProbe.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.qos.probe.impl;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.qos.probe.ReadinessProbe;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.ModuleModel;
import java.util.List;
@Activate
public class DeployerReadinessProbe implements ReadinessProbe {
private FrameworkModel frameworkModel;
public DeployerReadinessProbe(FrameworkModel frameworkModel) {
this.frameworkModel = frameworkModel;
}
@Override
public boolean check() {
if (this.frameworkModel == null) {
this.frameworkModel = FrameworkModel.defaultModel();
}
List<ApplicationModel> applicationModels = frameworkModel.getApplicationModels();
for (ApplicationModel applicationModel : applicationModels) {
for (ModuleModel moduleModel : applicationModel.getModuleModels()) {
if (!moduleModel.getDeployer().isStarted()) {
return false;
}
}
}
return true;
}
}
| 8,347 |
0 |
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe
|
Create_ds/dubbo/dubbo-plugin/dubbo-qos/src/main/java/org/apache/dubbo/qos/probe/impl/ProviderReadinessProbe.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.qos.probe.impl;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.qos.probe.ReadinessProbe;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.model.FrameworkServiceRepository;
import org.apache.dubbo.rpc.model.ProviderModel;
import java.util.Collection;
@Activate
public class ProviderReadinessProbe implements ReadinessProbe {
private final FrameworkModel frameworkModel;
private final FrameworkServiceRepository serviceRepository;
public ProviderReadinessProbe(FrameworkModel frameworkModel) {
if (frameworkModel != null) {
this.frameworkModel = frameworkModel;
} else {
this.frameworkModel = FrameworkModel.defaultModel();
}
this.serviceRepository = this.frameworkModel.getServiceRepository();
}
@Override
public boolean check() {
Collection<ProviderModel> providerModelList = serviceRepository.allProviderModels();
if (providerModelList.isEmpty()) {
return true;
}
boolean hasService = false, anyOnline = false;
for (ProviderModel providerModel : providerModelList) {
if (providerModel.getModuleModel().isInternal()) {
continue;
}
hasService = true;
anyOnline = anyOnline
|| providerModel.getStatedUrl().isEmpty()
|| providerModel.getStatedUrl().stream().anyMatch(ProviderModel.RegisterStatedURL::isRegistered);
}
// no service => check pass
// has service and any online => check pass
// has service and none online => check fail
return !(hasService && !anyOnline);
}
}
| 8,348 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/AbstractMonitorFactoryTest.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.monitor.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.monitor.Monitor;
import org.apache.dubbo.monitor.MonitorFactory;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* AbstractMonitorFactoryTest
*/
class AbstractMonitorFactoryTest {
private MonitorFactory monitorFactory = new AbstractMonitorFactory() {
protected Monitor createMonitor(final URL url) {
return new Monitor() {
public URL getUrl() {
return url;
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public void destroy() {}
public void collect(URL statistics) {}
public List<URL> lookup(URL query) {
return null;
}
};
}
};
@Test
void testMonitorFactoryCache() throws Exception {
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":2233");
Monitor monitor1 = monitorFactory.getMonitor(url);
Monitor monitor2 = monitorFactory.getMonitor(url);
if (monitor1 == null || monitor2 == null) {
Thread.sleep(2000);
monitor1 = monitorFactory.getMonitor(url);
monitor2 = monitorFactory.getMonitor(url);
}
Assertions.assertEquals(monitor1, monitor2);
}
@Test
void testMonitorFactoryIpCache() throws Exception {
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostName() + ":2233");
Monitor monitor1 = monitorFactory.getMonitor(url);
Monitor monitor2 = monitorFactory.getMonitor(url);
if (monitor1 == null || monitor2 == null) {
Thread.sleep(2000);
monitor1 = monitorFactory.getMonitor(url);
monitor2 = monitorFactory.getMonitor(url);
}
Assertions.assertEquals(monitor1, monitor2);
}
@Test
void testMonitorFactoryGroupCache() throws Exception {
URL url1 = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=aaa");
URL url2 = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":2233?group=bbb");
Monitor monitor1 = monitorFactory.getMonitor(url1);
Monitor monitor2 = monitorFactory.getMonitor(url2);
if (monitor1 == null || monitor2 == null) {
Thread.sleep(2000);
monitor1 = monitorFactory.getMonitor(url1);
monitor2 = monitorFactory.getMonitor(url2);
}
Assertions.assertNotSame(monitor1, monitor2);
}
}
| 8,349 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/test/java/org/apache/dubbo/monitor/support/MonitorFilterTest.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.monitor.support;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.monitor.Monitor;
import org.apache.dubbo.monitor.MonitorFactory;
import org.apache.dubbo.monitor.MonitorService;
import org.apache.dubbo.rpc.AsyncRpcResult;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
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 java.util.Arrays;
import java.util.List;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
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.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.monitor.Constants.CONCURRENT_KEY;
import static org.apache.dubbo.monitor.Constants.FAILURE_KEY;
import static org.apache.dubbo.monitor.Constants.SUCCESS_KEY;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
/**
* MonitorFilterTest
*/
class MonitorFilterTest {
private volatile URL lastStatistics;
private volatile Invocation lastInvocation;
private final Invoker<MonitorService> serviceInvoker = new Invoker<MonitorService>() {
@Override
public Class<MonitorService> getInterface() {
return MonitorService.class;
}
public URL getUrl() {
return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&" + SIDE_KEY
+ "=" + CONSUMER_SIDE)
.putAttribute(MONITOR_KEY, URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":7070"));
}
@Override
public boolean isAvailable() {
return false;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
lastInvocation = invocation;
return AsyncRpcResult.newDefaultAsyncResult(invocation);
}
@Override
public void destroy() {}
};
private MonitorFactory monitorFactory = url -> new Monitor() {
public URL getUrl() {
return url;
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public void destroy() {}
public void collect(URL statistics) {
MonitorFilterTest.this.lastStatistics = statistics;
}
public List<URL> lookup(URL query) {
return Arrays.asList(MonitorFilterTest.this.lastStatistics);
}
};
@Test
void testFilter() throws Exception {
MonitorFilter monitorFilter = new MonitorFilter();
monitorFilter.setMonitorFactory(monitorFactory);
Invocation invocation =
new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]);
RpcContext.getServiceContext()
.setRemoteAddress(NetUtils.getLocalHost(), 20880)
.setLocalAddress(NetUtils.getLocalHost(), 2345);
Result result = monitorFilter.invoke(serviceInvoker, invocation);
result.whenCompleteWithContext((r, t) -> {
if (t == null) {
monitorFilter.onResponse(r, serviceInvoker, invocation);
} else {
monitorFilter.onError(t, serviceInvoker, invocation);
}
});
while (lastStatistics == null) {
Thread.sleep(10);
}
Assertions.assertEquals("abc", lastStatistics.getParameter(APPLICATION_KEY));
Assertions.assertEquals(MonitorService.class.getName(), lastStatistics.getParameter(INTERFACE_KEY));
Assertions.assertEquals("aaa", lastStatistics.getParameter(METHOD_KEY));
Assertions.assertEquals(NetUtils.getLocalHost() + ":20880", lastStatistics.getParameter(PROVIDER));
Assertions.assertEquals(NetUtils.getLocalHost(), lastStatistics.getAddress());
Assertions.assertNull(lastStatistics.getParameter(CONSUMER));
Assertions.assertEquals(1, lastStatistics.getParameter(SUCCESS_KEY, 0));
Assertions.assertEquals(0, lastStatistics.getParameter(FAILURE_KEY, 0));
Assertions.assertEquals(1, lastStatistics.getParameter(CONCURRENT_KEY, 0));
Assertions.assertEquals(invocation, lastInvocation);
}
@Test
void testSkipMonitorIfNotHasKey() {
MonitorFilter monitorFilter = new MonitorFilter();
MonitorFactory mockMonitorFactory = mock(MonitorFactory.class);
monitorFilter.setMonitorFactory(mockMonitorFactory);
Invocation invocation =
new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]);
Invoker invoker = mock(Invoker.class);
given(invoker.getUrl())
.willReturn(URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":20880?" + APPLICATION_KEY + "=abc&"
+ SIDE_KEY + "=" + CONSUMER_SIDE));
monitorFilter.invoke(invoker, invocation);
verify(mockMonitorFactory, never()).getMonitor(any(URL.class));
}
@Test
void testGenericFilter() throws Exception {
MonitorFilter monitorFilter = new MonitorFilter();
monitorFilter.setMonitorFactory(monitorFactory);
Invocation invocation = new RpcInvocation(
"$invoke",
MonitorService.class.getName(),
"",
new Class<?>[] {String.class, String[].class, Object[].class},
new Object[] {"xxx", new String[] {}, new Object[] {}});
RpcContext.getServiceContext()
.setRemoteAddress(NetUtils.getLocalHost(), 20880)
.setLocalAddress(NetUtils.getLocalHost(), 2345);
Result result = monitorFilter.invoke(serviceInvoker, invocation);
result.whenCompleteWithContext((r, t) -> {
if (t == null) {
monitorFilter.onResponse(r, serviceInvoker, invocation);
} else {
monitorFilter.onError(t, serviceInvoker, invocation);
}
});
while (lastStatistics == null) {
Thread.sleep(10);
}
Assertions.assertEquals("abc", lastStatistics.getParameter(APPLICATION_KEY));
Assertions.assertEquals(MonitorService.class.getName(), lastStatistics.getParameter(INTERFACE_KEY));
Assertions.assertEquals("xxx", lastStatistics.getParameter(METHOD_KEY));
Assertions.assertEquals(NetUtils.getLocalHost() + ":20880", lastStatistics.getParameter(PROVIDER));
Assertions.assertEquals(NetUtils.getLocalHost(), lastStatistics.getAddress());
Assertions.assertNull(lastStatistics.getParameter(CONSUMER));
Assertions.assertEquals(1, lastStatistics.getParameter(SUCCESS_KEY, 0));
Assertions.assertEquals(0, lastStatistics.getParameter(FAILURE_KEY, 0));
Assertions.assertEquals(1, lastStatistics.getParameter(CONCURRENT_KEY, 0));
Assertions.assertEquals(invocation, lastInvocation);
}
@Test
void testSafeFailForMonitorCollectFail() {
MonitorFilter monitorFilter = new MonitorFilter();
MonitorFactory mockMonitorFactory = mock(MonitorFactory.class);
Monitor mockMonitor = mock(Monitor.class);
Mockito.doThrow(new RuntimeException()).when(mockMonitor).collect(any(URL.class));
monitorFilter.setMonitorFactory(mockMonitorFactory);
given(mockMonitorFactory.getMonitor(any(URL.class))).willReturn(mockMonitor);
Invocation invocation =
new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]);
monitorFilter.invoke(serviceInvoker, invocation);
}
@Test
void testOnResponseWithoutStartTime() {
MonitorFilter monitorFilter = new MonitorFilter();
MonitorFactory mockMonitorFactory = mock(MonitorFactory.class);
Monitor mockMonitor = mock(Monitor.class);
monitorFilter.setMonitorFactory(mockMonitorFactory);
given(mockMonitorFactory.getMonitor(any(URL.class))).willReturn(mockMonitor);
Invocation invocation =
new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]);
Result result = monitorFilter.invoke(serviceInvoker, invocation);
invocation.getAttributes().remove("monitor_filter_start_time");
monitorFilter.onResponse(result, serviceInvoker, invocation);
}
@Test
void testOnErrorWithoutStartTime() {
MonitorFilter monitorFilter = new MonitorFilter();
MonitorFactory mockMonitorFactory = mock(MonitorFactory.class);
Monitor mockMonitor = mock(Monitor.class);
monitorFilter.setMonitorFactory(mockMonitorFactory);
given(mockMonitorFactory.getMonitor(any(URL.class))).willReturn(mockMonitor);
Invocation invocation =
new RpcInvocation("aaa", MonitorService.class.getName(), "", new Class<?>[0], new Object[0]);
Throwable rpcException = new RpcException();
monitorFilter.onError(rpcException, serviceInvoker, invocation);
}
}
| 8,350 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorService.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.monitor;
import org.apache.dubbo.common.URL;
import java.util.List;
/**
* MonitorService. (SPI, Prototype, ThreadSafe)
*/
public interface MonitorService {
/**
* Collect monitor data
* 1. support invocation count: count://host/interface?application=foo&method=foo&provider=10.20.153.11:20880&success=12&failure=2&elapsed=135423423
* 1.1 host,application,interface,group,version,method: record source host/application/interface/method
* 1.2 add provider address parameter if it's data sent from consumer, otherwise, add source consumer's address in parameters
* 1.3 success,failure,elapsed: record success count, failure count, and total cost for success invocations, average cost (total cost/success calls)
*
* @param statistics
*/
void collect(URL statistics);
/**
* Lookup monitor data
* 1. support lookup by day: count://host/interface?application=foo&method=foo&side=provider&view=chart&date=2012-07-03
* 1.1 host,application,interface,group,version,method: query criteria for looking up by host, application, interface, method. When one criterion is not present, it means ALL will be accepted, but 0.0.0.0 is ALL for host
* 1.2 side=consumer,provider: decide the data from which side, both provider and consumer are returned by default
* 1.3 default value is view=summary, to return the summarized data for the whole day. view=chart will return the URL address showing the whole day trend which is convenient for embedding in other web page
* 1.4 date=2012-07-03: specify the date to collect the data, today is the default value
*
* @param query
* @return statistics
*/
List<URL> lookup(URL query);
}
| 8,351 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MonitorFactory.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.monitor;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
/**
* MonitorFactory. (SPI, Singleton, ThreadSafe)
*/
@SPI("dubbo")
public interface MonitorFactory {
/**
* Create monitor.
*
* @param url
* @return monitor
*/
@Adaptive(CommonConstants.PROTOCOL_KEY)
Monitor getMonitor(URL url);
}
| 8,352 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/MetricsService.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.monitor;
/**
* @deprecated After metrics config is refactored.
* This class should no longer use and will be deleted in the future.
*/
@Deprecated
public interface MetricsService {
String getMetricsByGroup(String group);
}
| 8,353 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/Monitor.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.monitor;
import org.apache.dubbo.common.Node;
/**
* Monitor. (SPI, Prototype, ThreadSafe)
*
* @see org.apache.dubbo.monitor.MonitorFactory#getMonitor(org.apache.dubbo.common.URL)
*/
public interface Monitor extends Node, MonitorService {}
| 8,354 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/Constants.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.monitor;
public interface Constants {
String DUBBO_PROVIDER = "dubbo.provider";
String DUBBO_CONSUMER = "dubbo.consumer";
String DUBBO_PROVIDER_METHOD = "dubbo.provider.method";
String DUBBO_CONSUMER_METHOD = "dubbo.consumer.method";
String SERVICE = "service";
String DUBBO_GROUP = "dubbo";
String LOGSTAT_PROTOCOL = "logstat";
String COUNT_PROTOCOL = "count";
String MONITOR_SEND_DATA_INTERVAL_KEY = "interval";
int DEFAULT_MONITOR_SEND_DATA_INTERVAL = 60000;
String SUCCESS_KEY = "success";
String FAILURE_KEY = "failure";
String INPUT_KEY = "input";
String OUTPUT_KEY = "output";
String ELAPSED_KEY = "elapsed";
String CONCURRENT_KEY = "concurrent";
String MAX_INPUT_KEY = "max.input";
String MAX_OUTPUT_KEY = "max.output";
String MAX_ELAPSED_KEY = "max.elapsed";
String MAX_CONCURRENT_KEY = "max.concurrent";
}
| 8,355 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MetricsServiceDetector.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.monitor.support;
import org.apache.dubbo.monitor.MetricsService;
import org.apache.dubbo.rpc.model.BuiltinServiceDetector;
/**
* @deprecated After metrics config is refactored.
* This class should no longer use and will be deleted in the future.
*/
@Deprecated
public class MetricsServiceDetector implements BuiltinServiceDetector {
@Override
public Class<?> getService() {
return MetricsService.class;
}
}
| 8,356 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorFilter.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.monitor.support;
import org.apache.dubbo.common.URL;
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.url.component.ServiceConfigURL;
import org.apache.dubbo.common.utils.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.monitor.Monitor;
import org.apache.dubbo.monitor.MonitorFactory;
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.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ProviderModel;
import org.apache.dubbo.rpc.model.ServiceModel;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
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.GROUP_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.MONITOR_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PATH_SEPARATOR;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_MONITOR_EXCEPTION;
import static org.apache.dubbo.monitor.Constants.CONCURRENT_KEY;
import static org.apache.dubbo.monitor.Constants.COUNT_PROTOCOL;
import static org.apache.dubbo.monitor.Constants.ELAPSED_KEY;
import static org.apache.dubbo.monitor.Constants.FAILURE_KEY;
import static org.apache.dubbo.monitor.Constants.SUCCESS_KEY;
import static org.apache.dubbo.rpc.Constants.INPUT_KEY;
import static org.apache.dubbo.rpc.Constants.OUTPUT_KEY;
/**
* MonitorFilter. (SPI, Singleton, ThreadSafe)
*/
@Activate(group = {PROVIDER})
public class MonitorFilter implements Filter, Filter.Listener {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MonitorFilter.class);
private static final String MONITOR_FILTER_START_TIME = "monitor_filter_start_time";
private static final String MONITOR_REMOTE_HOST_STORE = "monitor_remote_host_store";
/**
* The Concurrent counter
*/
private final ConcurrentMap<String, AtomicInteger> concurrents = new ConcurrentHashMap<>();
/**
* The MonitorFactory
*/
private MonitorFactory monitorFactory;
public void setMonitorFactory(MonitorFactory monitorFactory) {
this.monitorFactory = monitorFactory;
}
/**
* The invocation interceptor,it will collect the invoke data about this invocation and send it to monitor center
*
* @param invoker service
* @param invocation invocation.
* @return {@link Result} the invoke result
* @throws RpcException
*/
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (invoker.getUrl().hasAttribute(MONITOR_KEY)) {
invocation.put(MONITOR_FILTER_START_TIME, System.currentTimeMillis());
invocation.put(
MONITOR_REMOTE_HOST_STORE, RpcContext.getServiceContext().getRemoteHost());
// count up
getConcurrent(invoker, invocation).incrementAndGet();
}
ServiceModel serviceModel = invoker.getUrl().getServiceModel();
if (serviceModel instanceof ProviderModel) {
((ProviderModel) serviceModel).updateLastInvokeTime();
}
// proceed invocation chain
return invoker.invoke(invocation);
}
/**
* concurrent counter
*
* @param invoker
* @param invocation
* @return
*/
private AtomicInteger getConcurrent(Invoker<?> invoker, Invocation invocation) {
String key = invoker.getInterface().getName() + "." + RpcUtils.getMethodName(invocation);
return ConcurrentHashMapUtils.computeIfAbsent(concurrents, key, k -> new AtomicInteger());
}
@Override
public void onResponse(Result result, Invoker<?> invoker, Invocation invocation) {
if (invoker.getUrl().hasAttribute(MONITOR_KEY)) {
Long startTime = (Long) invocation.get(MONITOR_FILTER_START_TIME);
if (startTime != null) {
collect(
invoker,
invocation,
result,
(String) invocation.get(MONITOR_REMOTE_HOST_STORE),
startTime,
false);
}
// count down
getConcurrent(invoker, invocation).decrementAndGet();
}
}
@Override
public void onError(Throwable t, Invoker<?> invoker, Invocation invocation) {
if (invoker.getUrl().hasAttribute(MONITOR_KEY)) {
Long startTime = (Long) invocation.get(MONITOR_FILTER_START_TIME);
if (startTime != null) {
collect(invoker, invocation, null, (String) invocation.get(MONITOR_REMOTE_HOST_STORE), startTime, true);
}
// count down
getConcurrent(invoker, invocation).decrementAndGet();
}
}
/**
* The collector logic, it will be handled by the default monitor
*
* @param invoker
* @param invocation
* @param result the invocation result
* @param remoteHost the remote host address
* @param start the timestamp the invocation begin
* @param error if there is an error on the invocation
*/
private void collect(
Invoker<?> invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) {
try {
Object monitorUrl;
monitorUrl = invoker.getUrl().getAttribute(MONITOR_KEY);
if (monitorUrl instanceof URL) {
Monitor monitor = monitorFactory.getMonitor((URL) monitorUrl);
if (monitor == null) {
return;
}
URL statisticsUrl = createStatisticsUrl(invoker, invocation, result, remoteHost, start, error);
monitor.collect(statisticsUrl.toSerializableURL());
}
} catch (Throwable t) {
logger.warn(
COMMON_MONITOR_EXCEPTION,
"",
"",
"Failed to monitor count service " + invoker.getUrl() + ", cause: " + t.getMessage(),
t);
}
}
/**
* Create statistics url
*
* @param invoker
* @param invocation
* @param result
* @param remoteHost
* @param start
* @param error
* @return
*/
private URL createStatisticsUrl(
Invoker<?> invoker, Invocation invocation, Result result, String remoteHost, long start, boolean error) {
// ---- service statistics ----
// invocation cost
long elapsed = System.currentTimeMillis() - start;
// current concurrent count
int concurrent = getConcurrent(invoker, invocation).get();
String application = invoker.getUrl().getApplication();
// service name
String service = invoker.getInterface().getName();
// method name
String method = RpcUtils.getMethodName(invocation);
String group = invoker.getUrl().getGroup();
String version = invoker.getUrl().getVersion();
int localPort;
String remoteKey, remoteValue;
if (CONSUMER_SIDE.equals(invoker.getUrl().getSide())) {
// ---- for service consumer ----
localPort = 0;
remoteKey = PROVIDER;
remoteValue = invoker.getUrl().getAddress();
} else {
// ---- for service provider ----
localPort = invoker.getUrl().getPort();
remoteKey = CONSUMER;
remoteValue = remoteHost;
}
String input = "", output = "";
if (invocation.getAttachment(INPUT_KEY) != null) {
input = invocation.getAttachment(INPUT_KEY);
}
if (result != null && result.getAttachment(OUTPUT_KEY) != null) {
output = result.getAttachment(OUTPUT_KEY);
}
return new ServiceConfigURL(
COUNT_PROTOCOL,
NetUtils.getLocalHost(),
localPort,
service + PATH_SEPARATOR + method,
APPLICATION_KEY,
application,
INTERFACE_KEY,
service,
METHOD_KEY,
method,
remoteKey,
remoteValue,
error ? FAILURE_KEY : SUCCESS_KEY,
"1",
ELAPSED_KEY,
String.valueOf(elapsed),
CONCURRENT_KEY,
String.valueOf(concurrent),
INPUT_KEY,
input,
OUTPUT_KEY,
output,
GROUP_KEY,
group,
VERSION_KEY,
version);
}
}
| 8,357 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorClusterFilter.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.monitor.support;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.cluster.filter.ClusterFilter;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
@Activate(group = {CONSUMER})
public class MonitorClusterFilter extends MonitorFilter implements ClusterFilter {}
| 8,358 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/AbstractMonitorFactory.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.monitor.support;
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.NamedThreadFactory;
import org.apache.dubbo.monitor.Monitor;
import org.apache.dubbo.monitor.MonitorFactory;
import org.apache.dubbo.monitor.MonitorService;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_MONITOR_EXCEPTION;
/**
* AbstractMonitorFactory. (SPI, Singleton, ThreadSafe)
*/
public abstract class AbstractMonitorFactory implements MonitorFactory {
private static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(AbstractMonitorFactory.class);
/**
* The lock for getting monitor center
*/
private static final ReentrantLock LOCK = new ReentrantLock();
/**
* The monitor centers Map<RegistryAddress, Registry>
*/
private static final Map<String, Monitor> MONITORS = new ConcurrentHashMap<String, Monitor>();
private static final Map<String, Future<Monitor>> FUTURES = new ConcurrentHashMap<String, Future<Monitor>>();
/**
* The monitor create executor
*/
private static final ExecutorService EXECUTOR = new ThreadPoolExecutor(
0,
10,
60L,
TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
new NamedThreadFactory("DubboMonitorCreator", true));
public static Collection<Monitor> getMonitors() {
return Collections.unmodifiableCollection(MONITORS.values());
}
@Override
public Monitor getMonitor(URL url) {
url = url.setPath(MonitorService.class.getName()).addParameter(INTERFACE_KEY, MonitorService.class.getName());
String key = url.toServiceStringWithoutResolving();
Monitor monitor = MONITORS.get(key);
Future<Monitor> future = FUTURES.get(key);
if (monitor != null || future != null) {
return monitor;
}
LOCK.lock();
try {
monitor = MONITORS.get(key);
future = FUTURES.get(key);
if (monitor != null || future != null) {
return monitor;
}
final URL monitorUrl = url;
future = EXECUTOR.submit(() -> {
try {
Monitor m = createMonitor(monitorUrl);
MONITORS.put(key, m);
FUTURES.remove(key);
return m;
} catch (Throwable e) {
logger.warn(
COMMON_MONITOR_EXCEPTION,
"",
"",
"Create monitor failed, monitor data will not be collected until you fix this problem. monitorUrl: "
+ monitorUrl,
e);
return null;
}
});
FUTURES.put(key, future);
return null;
} finally {
// unlock
LOCK.unlock();
}
}
protected abstract Monitor createMonitor(URL url);
}
| 8,359 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/CallbackConsumerContextFilter.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.monitor.support;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.cluster.filter.support.ConsumerContextFilter;
import org.apache.dubbo.rpc.model.ApplicationModel;
import static org.apache.dubbo.common.constants.CommonConstants.CALLBACK;
/**
* CallbackConsumerContextFilter set current RpcContext with invoker,invocation, local host, remote host and port
* for consumer callback invoker.It does it to make the requires info available to execution thread's RpcContext.
* @see ConsumerContextFilter
*/
@Activate(group = CALLBACK, order = Integer.MIN_VALUE)
public class CallbackConsumerContextFilter extends ConsumerContextFilter implements Filter {
public CallbackConsumerContextFilter(ApplicationModel applicationModel) {
super(applicationModel);
}
}
| 8,360 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-api/src/main/java/org/apache/dubbo/monitor/support/MonitorServiceDetector.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.monitor.support;
import org.apache.dubbo.monitor.MonitorService;
import org.apache.dubbo.rpc.model.BuiltinServiceDetector;
public class MonitorServiceDetector implements BuiltinServiceDetector {
@Override
public Class<?> getService() {
return MonitorService.class;
}
}
| 8,361 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactoryTest.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.monitor.dubbo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.monitor.Monitor;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
class DubboMonitorFactoryTest {
private DubboMonitorFactory dubboMonitorFactory;
@Mock
private ProxyFactory proxyFactory;
@BeforeEach
public void setUp() throws Exception {
initMocks(this);
this.dubboMonitorFactory = new DubboMonitorFactory();
this.dubboMonitorFactory.setProtocol(new DubboProtocol(FrameworkModel.defaultModel()));
this.dubboMonitorFactory.setProxyFactory(proxyFactory);
}
@Test
void testCreateMonitor() {
URL urlWithoutPath = URL.valueOf("http://10.10.10.11");
Monitor monitor = dubboMonitorFactory.createMonitor(urlWithoutPath);
assertThat(monitor, not(nullValue()));
URL urlWithFilterKey = URL.valueOf("http://10.10.10.11/").addParameter(REFERENCE_FILTER_KEY, "testFilter");
monitor = dubboMonitorFactory.createMonitor(urlWithFilterKey);
assertThat(monitor, not(nullValue()));
ArgumentCaptor<Invoker> invokerArgumentCaptor = ArgumentCaptor.forClass(Invoker.class);
verify(proxyFactory, atLeastOnce()).getProxy(invokerArgumentCaptor.capture());
Invoker invoker = invokerArgumentCaptor.getValue();
assertThat(invoker.getUrl().getParameter(REFERENCE_FILTER_KEY), containsString("testFilter"));
}
}
| 8,362 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/StatisticsTest.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.monitor.dubbo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.url.component.ServiceConfigURL;
import org.hamcrest.MatcherAssert;
import org.junit.jupiter.api.Test;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
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.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY;
import static org.apache.dubbo.monitor.Constants.CONCURRENT_KEY;
import static org.apache.dubbo.monitor.Constants.ELAPSED_KEY;
import static org.apache.dubbo.monitor.Constants.FAILURE_KEY;
import static org.apache.dubbo.monitor.Constants.MAX_CONCURRENT_KEY;
import static org.apache.dubbo.monitor.Constants.MAX_ELAPSED_KEY;
import static org.apache.dubbo.monitor.Constants.SUCCESS_KEY;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
class StatisticsTest {
@Test
void testEquals() {
URL statistics = new URLBuilder(DUBBO_PROTOCOL, "10.20.153.10", 0)
.addParameter(APPLICATION_KEY, "morgan")
.addParameter(INTERFACE_KEY, "MemberService")
.addParameter(METHOD_KEY, "findPerson")
.addParameter(CONSUMER, "10.20.153.11")
.addParameter(SUCCESS_KEY, 1)
.addParameter(FAILURE_KEY, 0)
.addParameter(ELAPSED_KEY, 3)
.addParameter(MAX_ELAPSED_KEY, 3)
.addParameter(CONCURRENT_KEY, 1)
.addParameter(MAX_CONCURRENT_KEY, 1)
.build();
Statistics statistics1 = new Statistics(statistics);
Statistics statistics2 = new Statistics(statistics);
MatcherAssert.assertThat(statistics1, equalTo(statistics1));
MatcherAssert.assertThat(statistics1, equalTo(statistics2));
statistics1.setVersion("2");
MatcherAssert.assertThat(statistics1, not(equalTo(statistics2)));
MatcherAssert.assertThat(statistics1.hashCode(), not(equalTo(statistics2.hashCode())));
statistics1.setMethod("anotherMethod");
MatcherAssert.assertThat(statistics1, not(equalTo(statistics2)));
MatcherAssert.assertThat(statistics1.hashCode(), not(equalTo(statistics2.hashCode())));
statistics1.setClient("anotherClient");
MatcherAssert.assertThat(statistics1, not(equalTo(statistics2)));
MatcherAssert.assertThat(statistics1.hashCode(), not(equalTo(statistics2.hashCode())));
}
@Test
void testToString() {
Statistics statistics = new Statistics(new ServiceConfigURL("dubbo", "10.20.153.10", 0));
statistics.setApplication("demo");
statistics.setMethod("findPerson");
statistics.setServer("10.20.153.10");
statistics.setGroup("unit-test");
statistics.setService("MemberService");
assertThat(statistics.toString(), is("dubbo://10.20.153.10"));
Statistics statisticsWithDetailInfo = new Statistics(new URLBuilder(DUBBO_PROTOCOL, "10.20.153.10", 0)
.addParameter(APPLICATION_KEY, "morgan")
.addParameter(INTERFACE_KEY, "MemberService")
.addParameter(METHOD_KEY, "findPerson")
.addParameter(CONSUMER, "10.20.153.11")
.addParameter(GROUP_KEY, "unit-test")
.addParameter(SUCCESS_KEY, 1)
.addParameter(FAILURE_KEY, 0)
.addParameter(ELAPSED_KEY, 3)
.addParameter(MAX_ELAPSED_KEY, 3)
.addParameter(CONCURRENT_KEY, 1)
.addParameter(MAX_CONCURRENT_KEY, 1)
.build());
MatcherAssert.assertThat(statisticsWithDetailInfo.getServer(), equalTo(statistics.getServer()));
MatcherAssert.assertThat(statisticsWithDetailInfo.getService(), equalTo(statistics.getService()));
MatcherAssert.assertThat(statisticsWithDetailInfo.getMethod(), equalTo(statistics.getMethod()));
MatcherAssert.assertThat(statisticsWithDetailInfo.getGroup(), equalTo(statistics.getGroup()));
MatcherAssert.assertThat(statisticsWithDetailInfo, not(equalTo(statistics)));
}
}
| 8,363 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/DubboMonitorTest.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.monitor.dubbo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.extension.ExtensionLoader;
import org.apache.dubbo.monitor.Monitor;
import org.apache.dubbo.monitor.MonitorFactory;
import org.apache.dubbo.monitor.MonitorService;
import org.apache.dubbo.rpc.Exporter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import org.hamcrest.CustomMatcher;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.INTERFACE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY;
import static org.apache.dubbo.monitor.Constants.CONCURRENT_KEY;
import static org.apache.dubbo.monitor.Constants.ELAPSED_KEY;
import static org.apache.dubbo.monitor.Constants.FAILURE_KEY;
import static org.apache.dubbo.monitor.Constants.INPUT_KEY;
import static org.apache.dubbo.monitor.Constants.MAX_CONCURRENT_KEY;
import static org.apache.dubbo.monitor.Constants.MAX_ELAPSED_KEY;
import static org.apache.dubbo.monitor.Constants.OUTPUT_KEY;
import static org.apache.dubbo.monitor.Constants.SUCCESS_KEY;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
/**
* DubboMonitorTest
*/
class DubboMonitorTest {
private final Invoker<MonitorService> monitorInvoker = new Invoker<MonitorService>() {
@Override
public Class<MonitorService> getInterface() {
return MonitorService.class;
}
public URL getUrl() {
return URL.valueOf("dubbo://127.0.0.1:7070?interval=1000");
}
@Override
public boolean isAvailable() {
return false;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
return null;
}
@Override
public void destroy() {}
};
private volatile URL lastStatistics;
private final MonitorService monitorService = new MonitorService() {
public void collect(URL statistics) {
DubboMonitorTest.this.lastStatistics = statistics;
}
public List<URL> lookup(URL query) {
return Arrays.asList(DubboMonitorTest.this.lastStatistics);
}
};
@Test
void testCount() {
DubboMonitor monitor = new DubboMonitor(monitorInvoker, monitorService);
URL statistics = new URLBuilder(DUBBO_PROTOCOL, "10.20.153.10", 0)
.addParameter(APPLICATION_KEY, "morgan")
.addParameter(INTERFACE_KEY, "MemberService")
.addParameter(METHOD_KEY, "findPerson")
.addParameter(CONSUMER, "10.20.153.11")
.addParameter(SUCCESS_KEY, 1)
.addParameter(FAILURE_KEY, 0)
.addParameter(ELAPSED_KEY, 3)
.addParameter(MAX_ELAPSED_KEY, 3)
.addParameter(CONCURRENT_KEY, 1)
.addParameter(MAX_CONCURRENT_KEY, 1)
.build();
monitor.collect(statistics.toSerializableURL());
monitor.send();
await().atMost(60, TimeUnit.SECONDS).until(() -> lastStatistics != null);
Assertions.assertEquals("morgan", lastStatistics.getParameter(APPLICATION_KEY));
Assertions.assertEquals("dubbo", lastStatistics.getProtocol());
Assertions.assertEquals("10.20.153.10", lastStatistics.getHost());
Assertions.assertEquals("morgan", lastStatistics.getParameter(APPLICATION_KEY));
Assertions.assertEquals("MemberService", lastStatistics.getParameter(INTERFACE_KEY));
Assertions.assertEquals("findPerson", lastStatistics.getParameter(METHOD_KEY));
Assertions.assertEquals("10.20.153.11", lastStatistics.getParameter(CONSUMER));
Assertions.assertEquals("1", lastStatistics.getParameter(SUCCESS_KEY));
Assertions.assertEquals("0", lastStatistics.getParameter(FAILURE_KEY));
Assertions.assertEquals("3", lastStatistics.getParameter(ELAPSED_KEY));
Assertions.assertEquals("3", lastStatistics.getParameter(MAX_ELAPSED_KEY));
Assertions.assertEquals("1", lastStatistics.getParameter(CONCURRENT_KEY));
Assertions.assertEquals("1", lastStatistics.getParameter(MAX_CONCURRENT_KEY));
monitor.destroy();
}
@Test
void testMonitorFactory() {
MockMonitorService monitorService = new MockMonitorService();
URL statistics = new URLBuilder(DUBBO_PROTOCOL, "10.20.153.10", 0)
.addParameter(APPLICATION_KEY, "morgan")
.addParameter(INTERFACE_KEY, "MemberService")
.addParameter(METHOD_KEY, "findPerson")
.addParameter(CONSUMER, "10.20.153.11")
.addParameter(SUCCESS_KEY, 1)
.addParameter(FAILURE_KEY, 0)
.addParameter(ELAPSED_KEY, 3)
.addParameter(MAX_ELAPSED_KEY, 3)
.addParameter(CONCURRENT_KEY, 1)
.addParameter(MAX_CONCURRENT_KEY, 1)
.build();
Protocol protocol = ExtensionLoader.getExtensionLoader(Protocol.class).getAdaptiveExtension();
ProxyFactory proxyFactory =
ExtensionLoader.getExtensionLoader(ProxyFactory.class).getAdaptiveExtension();
MonitorFactory monitorFactory =
ExtensionLoader.getExtensionLoader(MonitorFactory.class).getAdaptiveExtension();
Exporter<MonitorService> exporter = protocol.export(proxyFactory.getInvoker(
monitorService,
MonitorService.class,
URL.valueOf("dubbo://127.0.0.1:17979/" + MonitorService.class.getName())));
try {
Monitor monitor = null;
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < 60000) {
monitor = monitorFactory.getMonitor(URL.valueOf("dubbo://127.0.0.1:17979?interval=10"));
if (monitor == null) {
continue;
}
try {
monitor.collect(statistics.toSerializableURL());
await().atLeast(10, TimeUnit.MILLISECONDS)
.atMost(60, TimeUnit.SECONDS)
.until(() -> monitorService.getStatistics().stream()
.anyMatch(s -> s.getParameter(SUCCESS_KEY, 0) == 1));
List<URL> statisticsUrls = monitorService.getStatistics();
Optional<URL> url = statisticsUrls.stream()
.filter(s -> s.getParameter(SUCCESS_KEY, 0) == 1)
.findFirst();
Assertions.assertTrue(url.isPresent());
Assertions.assertEquals(1, url.get().getParameter(SUCCESS_KEY, 0));
Assertions.assertEquals(3, url.get().getParameter(ELAPSED_KEY, 0));
} finally {
monitor.destroy();
}
break;
}
Assertions.assertNotNull(monitor);
} finally {
exporter.unexport();
}
}
@Test
void testAvailable() {
Invoker invoker = mock(Invoker.class);
MonitorService monitorService = mock(MonitorService.class);
given(invoker.isAvailable()).willReturn(true);
given(invoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:7070?interval=20"));
DubboMonitor dubboMonitor = new DubboMonitor(invoker, monitorService);
assertThat(dubboMonitor.isAvailable(), is(true));
verify(invoker).isAvailable();
}
@Test
void testSum() {
URL statistics = new URLBuilder(DUBBO_PROTOCOL, "10.20.153.11", 0)
.addParameter(APPLICATION_KEY, "morgan")
.addParameter(INTERFACE_KEY, "MemberService")
.addParameter(METHOD_KEY, "findPerson")
.addParameter(CONSUMER, "10.20.153.11")
.addParameter(SUCCESS_KEY, 1)
.addParameter(FAILURE_KEY, 0)
.addParameter(ELAPSED_KEY, 3)
.addParameter(MAX_ELAPSED_KEY, 3)
.addParameter(CONCURRENT_KEY, 1)
.addParameter(MAX_CONCURRENT_KEY, 1)
.build();
Invoker invoker = mock(Invoker.class);
MonitorService monitorService = mock(MonitorService.class);
given(invoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:7070?interval=20"));
DubboMonitor dubboMonitor = new DubboMonitor(invoker, monitorService);
dubboMonitor.collect(statistics.toSerializableURL());
dubboMonitor.collect(statistics
.addParameter(SUCCESS_KEY, 3)
.addParameter(CONCURRENT_KEY, 2)
.addParameter(INPUT_KEY, 1)
.addParameter(OUTPUT_KEY, 2)
.toSerializableURL());
dubboMonitor.collect(statistics
.addParameter(SUCCESS_KEY, 6)
.addParameter(ELAPSED_KEY, 2)
.toSerializableURL());
dubboMonitor.send();
ArgumentCaptor<URL> summaryCaptor = ArgumentCaptor.forClass(URL.class);
verify(monitorService, atLeastOnce()).collect(summaryCaptor.capture());
List<URL> allValues = summaryCaptor.getAllValues();
assertThat(allValues, not(nullValue()));
assertThat(allValues, hasItem(new CustomMatcher<URL>("Monitor count should greater than 1") {
@Override
public boolean matches(Object item) {
URL url = (URL) item;
return Integer.valueOf(url.getParameter(SUCCESS_KEY)) > 1;
}
}));
}
@Test
void testLookUp() {
Invoker invoker = mock(Invoker.class);
MonitorService monitorService = mock(MonitorService.class);
URL queryUrl = URL.valueOf("dubbo://127.0.0.1:7070?interval=20");
given(invoker.getUrl()).willReturn(queryUrl);
DubboMonitor dubboMonitor = new DubboMonitor(invoker, monitorService);
dubboMonitor.lookup(queryUrl);
verify(monitorService).lookup(queryUrl);
}
}
| 8,364 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/AppResponseBuilder.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.monitor.dubbo;
import org.apache.dubbo.rpc.AppResponse;
import java.util.Map;
public class AppResponseBuilder {
private Object result;
private Throwable exception;
private Map<String, String> attachments;
private AppResponse appResponse;
private AppResponseBuilder() {
this.appResponse = new AppResponse();
}
public static AppResponseBuilder create() {
return new AppResponseBuilder();
}
public AppResponse build() {
return new AppResponse(this);
}
public AppResponseBuilder withResult(Object result) {
this.result = result;
return this;
}
public AppResponseBuilder withException(Throwable exception) {
this.exception = exception;
return this;
}
public AppResponseBuilder withAttachments(Map<String, String> attachments) {
this.attachments = attachments;
return this;
}
}
| 8,365 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MockMonitorService.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.monitor.dubbo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.monitor.MonitorService;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* MockMonitorService
*/
public class MockMonitorService implements MonitorService {
private List<URL> statistics = new CopyOnWriteArrayList<>();
public void collect(URL statistics) {
this.statistics.add(statistics);
}
public List<URL> getStatistics() {
return statistics;
}
public List<URL> lookup(URL query) {
return statistics;
}
}
| 8,366 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/MetricsFilterTest.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.monitor.dubbo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.monitor.MetricsService;
import org.apache.dubbo.monitor.dubbo.service.DemoService;
import org.apache.dubbo.rpc.AppResponse;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.RpcInvocation;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.FrameworkModel;
import org.apache.dubbo.rpc.protocol.dubbo.DubboProtocol;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.function.Function;
import com.alibaba.metrics.FastCompass;
import com.alibaba.metrics.IMetricManager;
import com.alibaba.metrics.MetricLevel;
import com.alibaba.metrics.MetricManager;
import com.alibaba.metrics.MetricName;
import com.alibaba.metrics.common.MetricObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER_SIDE;
import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.CommonConstants.SIDE_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.TIMEOUT_KEY;
import static org.apache.dubbo.monitor.Constants.DUBBO_CONSUMER;
import static org.apache.dubbo.monitor.Constants.DUBBO_CONSUMER_METHOD;
import static org.apache.dubbo.monitor.Constants.DUBBO_GROUP;
import static org.apache.dubbo.monitor.Constants.DUBBO_PROVIDER;
import static org.apache.dubbo.monitor.Constants.DUBBO_PROVIDER_METHOD;
import static org.apache.dubbo.monitor.Constants.SERVICE;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.mock;
class MetricsFilterTest {
private int port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000));
private final Function<URL, Invoker<DemoService>> invokerFunction = (url) -> {
Invoker<DemoService> serviceInvoker = mock(Invoker.class);
given(serviceInvoker.isAvailable()).willReturn(false);
given(serviceInvoker.getInterface()).willReturn(DemoService.class);
given(serviceInvoker.getUrl()).willReturn(url);
given(serviceInvoker.invoke(Mockito.any(Invocation.class))).willReturn(null);
doNothing().when(serviceInvoker).destroy();
return serviceInvoker;
};
private URL getUrl() {
return URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":" + port
+ "/org.apache.dubbo.monitor.dubbo.service.DemoService?" + "metrics.port" + "=" + port);
}
private void onInvokeReturns(Invoker<DemoService> invoker, AppResponse response) {
given(invoker.invoke(Mockito.any(Invocation.class))).willReturn(response);
}
public void onInvokerThrows(Invoker<DemoService> invoker) {
given(invoker.invoke(Mockito.any(Invocation.class)))
.willThrow(new RpcException(RpcException.TIMEOUT_EXCEPTION));
}
@Test
void testAll() {
List<Callable<Void>> testcases = new LinkedList<>();
testcases.add(() -> {
testConsumerSuccess();
return null;
});
testcases.add(() -> {
testConsumerTimeout();
return null;
});
testcases.add(() -> {
testProviderSuccess();
return null;
});
testcases.add(() -> {
testInvokeMetricsService();
return null;
});
testcases.add(() -> {
testInvokeMetricsMethodService();
return null;
});
for (Callable<Void> testcase : testcases) {
Throwable throwable = null;
for (int i = 0; i < 10; i++) {
try {
port = NetUtils.getAvailablePort(20880 + new Random().nextInt(10000));
testcase.call();
throwable = null;
break;
} catch (Throwable t) {
t.printStackTrace();
throwable = t;
} finally {
MetricsFilter.exported.set(false);
}
}
Assertions.assertNull(throwable);
}
}
private void testConsumerSuccess() {
IMetricManager metricManager = MetricManager.getIMetricManager();
metricManager.clear();
MetricsFilter metricsFilter = new MetricsFilter();
metricsFilter.setExtensionAccessor(ApplicationModel.defaultModel());
Invocation invocation = new RpcInvocation(
"sayName", DemoService.class.getName(), "", new Class<?>[] {Integer.class}, new Object[0]);
RpcContext.getServiceContext()
.setRemoteAddress(NetUtils.getLocalHost(), port)
.setLocalAddress(NetUtils.getLocalHost(), 2345);
URL url = getUrl().addParameter(SIDE_KEY, CONSUMER_SIDE);
Invoker<DemoService> invoker = invokerFunction.apply(url);
AppResponse response = AppResponseBuilder.create().build();
onInvokeReturns(invoker, response);
for (int i = 0; i < 100; i++) {
metricsFilter.invoke(invoker, invocation);
}
FastCompass dubboClient =
metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR));
FastCompass dubboMethod = metricManager.getFastCompass(
DUBBO_GROUP,
new MetricName(
DUBBO_CONSUMER_METHOD,
new HashMap<String, String>(4) {
{
put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService");
put(METHOD_KEY, "void sayName(Integer)");
}
},
MetricLevel.NORMAL));
long timestamp = System.currentTimeMillis() / 5000 * 5000;
Assertions.assertEquals(
100, dubboClient.getMethodCountPerCategory(0).get("success").get(timestamp));
timestamp = timestamp / 15000 * 15000;
Assertions.assertEquals(
100, dubboMethod.getMethodCountPerCategory(0).get("success").get(timestamp));
}
private void testConsumerTimeout() {
IMetricManager metricManager = MetricManager.getIMetricManager();
metricManager.clear();
MetricsFilter metricsFilter = new MetricsFilter();
metricsFilter.setExtensionAccessor(ApplicationModel.defaultModel());
Invocation invocation = new RpcInvocation("timeoutException", DemoService.class.getName(), "", null, null);
RpcContext.getServiceContext()
.setRemoteAddress(NetUtils.getLocalHost(), port)
.setLocalAddress(NetUtils.getLocalHost(), 2345);
URL url = getUrl().addParameter(SIDE_KEY, CONSUMER_SIDE).addParameter(TIMEOUT_KEY, 300);
Invoker<DemoService> invoker = invokerFunction.apply(url);
onInvokerThrows(invoker);
for (int i = 0; i < 10; i++) {
try {
metricsFilter.invoke(invoker, invocation);
} catch (RpcException e) {
// ignore
}
}
FastCompass dubboClient =
metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR));
FastCompass dubboMethod = metricManager.getFastCompass(
DUBBO_GROUP,
new MetricName(
DUBBO_CONSUMER_METHOD,
new HashMap<String, String>(4) {
{
put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService");
put(METHOD_KEY, "void timeoutException()");
}
},
MetricLevel.NORMAL));
long timestamp = System.currentTimeMillis() / 5000 * 5000;
Assertions.assertEquals(
10, dubboClient.getMethodCountPerCategory(0).get("timeoutError").get(timestamp));
timestamp = timestamp / 15000 * 15000;
Assertions.assertEquals(
10, dubboMethod.getMethodCountPerCategory(0).get("timeoutError").get(timestamp));
}
private void testProviderSuccess() {
IMetricManager metricManager = MetricManager.getIMetricManager();
metricManager.clear();
MetricsFilter metricsFilter = new MetricsFilter();
metricsFilter.setExtensionAccessor(ApplicationModel.defaultModel());
Invocation invocation =
new RpcInvocation("sayName", DemoService.class.getName(), "", new Class<?>[0], new Object[0]);
RpcContext.getServiceContext()
.setRemoteAddress(NetUtils.getLocalHost(), port)
.setLocalAddress(NetUtils.getLocalHost(), 2345);
URL url = getUrl().addParameter(SIDE_KEY, PROVIDER).addParameter(TIMEOUT_KEY, 300);
Invoker<DemoService> invoker = invokerFunction.apply(url);
AppResponse response = AppResponseBuilder.create().build();
onInvokeReturns(invoker, response);
for (int i = 0; i < 100; i++) {
metricsFilter.invoke(invoker, invocation);
}
FastCompass dubboClient =
metricManager.getFastCompass(DUBBO_GROUP, new MetricName(DUBBO_PROVIDER, MetricLevel.MAJOR));
FastCompass dubboMethod = metricManager.getFastCompass(
DUBBO_GROUP,
new MetricName(
DUBBO_PROVIDER_METHOD,
new HashMap<String, String>(4) {
{
put(SERVICE, "org.apache.dubbo.monitor.dubbo.service.DemoService");
put(METHOD_KEY, "void sayName()");
}
},
MetricLevel.NORMAL));
long timestamp = System.currentTimeMillis() / 5000 * 5000;
Assertions.assertEquals(
100, dubboClient.getMethodCountPerCategory(0).get("success").get(timestamp));
timestamp = timestamp / 15000 * 15000;
Assertions.assertEquals(
100, dubboMethod.getMethodCountPerCategory(0).get("success").get(timestamp));
}
private void testInvokeMetricsService() {
IMetricManager metricManager = MetricManager.getIMetricManager();
metricManager.clear();
MetricsFilter metricsFilter = new MetricsFilter();
metricsFilter.setExtensionAccessor(ApplicationModel.defaultModel());
Invocation invocation =
new RpcInvocation("sayName", DemoService.class.getName(), "", new Class<?>[0], new Object[0]);
RpcContext.getServiceContext()
.setRemoteAddress(NetUtils.getLocalHost(), port)
.setLocalAddress(NetUtils.getLocalHost(), 2345);
URL url = getUrl().addParameter(SIDE_KEY, PROVIDER).addParameter(TIMEOUT_KEY, 300);
Invoker<DemoService> serviceInvoker = invokerFunction.apply(url);
Invoker<DemoService> timeoutInvoker = invokerFunction.apply(url);
AppResponse response = AppResponseBuilder.create().build();
onInvokeReturns(serviceInvoker, response);
onInvokerThrows(timeoutInvoker);
for (int i = 0; i < 50; i++) {
try {
metricsFilter.invoke(serviceInvoker, invocation);
metricsFilter.invoke(timeoutInvoker, invocation);
} catch (RpcException e) {
// ignore
}
}
Protocol protocol = new DubboProtocol(FrameworkModel.defaultModel());
// using host name might cause connection failure because multiple addresses might be configured to the same
// name!
url = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":" + port + "/" + MetricsService.class.getName());
Invoker<MetricsService> invoker = protocol.refer(MetricsService.class, url);
invocation = new RpcInvocation(
"getMetricsByGroup", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {
DUBBO_GROUP
});
try {
Thread.sleep(5000);
} catch (Exception e) {
// ignore
}
String resStr = invoker.invoke(invocation).getValue().toString();
// MetricObject do not have setter, should use gson to parse
List<MetricObject> metricObjectList =
new Gson().fromJson(resStr, new TypeToken<List<MetricObject>>() {}.getType());
Map<String, Object> metricMap = new HashMap<>();
for (int i = 0; i < metricObjectList.size(); i++) {
MetricObject object = metricObjectList.get(i);
String metric = object.getMetric().substring(object.getMetric().lastIndexOf(".") + 1);
if ((double) object.getValue() > 0.0 && object.getMetricLevel().equals(MetricLevel.MAJOR))
metricMap.put(metric, object.getValue());
}
Assertions.assertEquals(50.0, metricMap.get("success_bucket_count"));
Assertions.assertEquals(50.0, metricMap.get("timeoutError_bucket_count"));
Assertions.assertEquals(100.0, metricMap.get("bucket_count"));
Assertions.assertEquals(100.0 / 5, metricMap.get("qps"));
Assertions.assertEquals(50.0 / 100.0, metricMap.get("success_rate"));
}
private void testInvokeMetricsMethodService() {
IMetricManager metricManager = MetricManager.getIMetricManager();
metricManager.clear();
MetricsFilter metricsFilter = new MetricsFilter();
metricsFilter.setExtensionAccessor(ApplicationModel.defaultModel());
Invocation sayNameInvocation =
new RpcInvocation("sayName", DemoService.class.getName(), "", new Class<?>[0], new Object[0]);
Invocation echoInvocation = new RpcInvocation(
"echo", DemoService.class.getName(), "", new Class<?>[] {Integer.class}, new Integer[] {1});
RpcContext.getServiceContext()
.setRemoteAddress(NetUtils.getLocalHost(), port)
.setLocalAddress(NetUtils.getLocalHost(), 2345);
URL url = getUrl().addParameter(SIDE_KEY, PROVIDER).addParameter(TIMEOUT_KEY, 300);
Invoker<DemoService> serviceInvoker = invokerFunction.apply(url);
Invoker<DemoService> timeoutInvoker = invokerFunction.apply(url);
AppResponse response = AppResponseBuilder.create().build();
onInvokeReturns(serviceInvoker, response);
onInvokerThrows(timeoutInvoker);
for (int i = 0; i < 50; i++) {
metricsFilter.invoke(serviceInvoker, sayNameInvocation);
metricsFilter.invoke(serviceInvoker, echoInvocation);
try {
metricsFilter.invoke(timeoutInvoker, sayNameInvocation);
} catch (RpcException e) {
// ignore
}
try {
metricsFilter.invoke(timeoutInvoker, echoInvocation);
} catch (RpcException e) {
// ignore
}
}
Protocol protocol = new DubboProtocol(FrameworkModel.defaultModel());
// using host name might cause connection failure because multiple addresses might be configured to the same
// name!
url = URL.valueOf("dubbo://" + NetUtils.getLocalHost() + ":" + port + "/" + MetricsService.class.getName());
Invoker<MetricsService> invoker = protocol.refer(MetricsService.class, url);
Invocation invocation = new RpcInvocation(
"getMetricsByGroup", DemoService.class.getName(), "", new Class<?>[] {String.class}, new Object[] {
DUBBO_GROUP
});
try {
Thread.sleep(15000);
} catch (Exception e) {
// ignore
}
String resStr = invoker.invoke(invocation).getValue().toString();
List<MetricObject> metricObjectList =
new Gson().fromJson(resStr, new TypeToken<List<MetricObject>>() {}.getType());
Map<String, Map<String, Object>> methodMetricMap = new HashMap<>();
for (int i = 0; i < metricObjectList.size(); i++) {
MetricObject object = metricObjectList.get(i);
String service = object.getTags().get("service");
String method = service + "." + object.getTags().get("method");
String metric = object.getMetric().substring(object.getMetric().lastIndexOf(".") + 1);
Map map = methodMetricMap.get(method);
if (map == null) {
map = new HashMap();
methodMetricMap.put(method, map);
}
map.put(metric, object.getValue());
}
Assertions.assertEquals(
50.0,
methodMetricMap
.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()")
.get("success_bucket_count"));
Assertions.assertEquals(
50.0,
methodMetricMap
.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)")
.get("success_bucket_count"));
Assertions.assertEquals(
50.0,
methodMetricMap
.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()")
.get("timeoutError_bucket_count"));
Assertions.assertEquals(
50.0,
methodMetricMap
.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)")
.get("timeoutError_bucket_count"));
Assertions.assertEquals(
100.0 / 15,
methodMetricMap
.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()")
.get("qps"));
Assertions.assertEquals(
100.0 / 15,
methodMetricMap
.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)")
.get("qps"));
Assertions.assertEquals(
50.0 / 100.0,
methodMetricMap
.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void sayName()")
.get("success_rate"));
Assertions.assertEquals(
50.0 / 100.0,
methodMetricMap
.get("org.apache.dubbo.monitor.dubbo.service.DemoService.void echo(Integer)")
.get("success_rate"));
}
}
| 8,367 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/test/java/org/apache/dubbo/monitor/dubbo/service/DemoService.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.monitor.dubbo.service;
public interface DemoService {
String sayName(String name);
void timeoutException();
void throwDemoException() throws Exception;
int echo(int i);
}
| 8,368 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/MetricsFilter.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.monitor.dubbo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.extension.ExtensionAccessor;
import org.apache.dubbo.common.extension.ExtensionAccessorAware;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.common.store.DataStore;
import org.apache.dubbo.common.utils.JsonUtils;
import org.apache.dubbo.common.utils.NetUtils;
import org.apache.dubbo.monitor.MetricsService;
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.Protocol;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcException;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelAware;
import org.apache.dubbo.rpc.support.RpcUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import com.alibaba.metrics.FastCompass;
import com.alibaba.metrics.MetricLevel;
import com.alibaba.metrics.MetricManager;
import com.alibaba.metrics.MetricName;
import com.alibaba.metrics.MetricRegistry;
import com.alibaba.metrics.common.CollectLevel;
import com.alibaba.metrics.common.MetricObject;
import com.alibaba.metrics.common.MetricsCollector;
import com.alibaba.metrics.common.MetricsCollectorFactory;
import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.EXECUTOR_SERVICE_COMPONENT_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.METHOD_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_METRICS_COLLECTOR_EXCEPTION;
import static org.apache.dubbo.monitor.Constants.DUBBO_CONSUMER;
import static org.apache.dubbo.monitor.Constants.DUBBO_CONSUMER_METHOD;
import static org.apache.dubbo.monitor.Constants.DUBBO_GROUP;
import static org.apache.dubbo.monitor.Constants.DUBBO_PROVIDER;
import static org.apache.dubbo.monitor.Constants.DUBBO_PROVIDER_METHOD;
import static org.apache.dubbo.monitor.Constants.SERVICE;
/**
* @deprecated After metrics config is refactored.
* This filter should no longer use and will be deleted in the future.
*/
@Deprecated
public class MetricsFilter implements Filter, ExtensionAccessorAware, ScopeModelAware {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(MetricsFilter.class);
protected static volatile AtomicBoolean exported = new AtomicBoolean(false);
private Integer port;
private String protocolName;
private ExtensionAccessor extensionAccessor;
private ApplicationModel applicationModel;
private static final String METRICS_PORT = "metrics.port";
private static final String METRICS_PROTOCOL = "metrics.protocol";
@Override
public void setApplicationModel(ApplicationModel applicationModel) {
this.applicationModel = applicationModel;
}
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
if (exported.compareAndSet(false, true)) {
this.protocolName = invoker.getUrl().getParameter(METRICS_PROTOCOL) == null
? DEFAULT_PROTOCOL
: invoker.getUrl().getParameter(METRICS_PROTOCOL);
Protocol protocol =
extensionAccessor.getExtensionLoader(Protocol.class).getExtension(protocolName);
this.port = invoker.getUrl().getParameter(METRICS_PORT) == null
? protocol.getDefaultPort()
: Integer.valueOf(invoker.getUrl().getParameter(METRICS_PORT));
Invoker<MetricsService> metricsInvoker = initMetricsInvoker();
try {
protocol.export(metricsInvoker);
} catch (RuntimeException e) {
logger.error(
COMMON_METRICS_COLLECTOR_EXCEPTION,
"",
"",
"Metrics Service need to be configured" + " when multiple processes are running on a host"
+ e.getMessage());
}
}
boolean isProvider = invoker.getUrl().getSide(PROVIDER).equalsIgnoreCase(PROVIDER);
long start = System.currentTimeMillis();
try {
Result result = invoker.invoke(invocation); // proceed invocation chain
long duration = System.currentTimeMillis() - start;
reportMetrics(invoker, invocation, duration, "success", isProvider);
return result;
} catch (RpcException e) {
long duration = System.currentTimeMillis() - start;
String result = "error";
if (e.isTimeout()) {
result = "timeoutError";
}
if (e.isBiz()) {
result = "bisError";
}
if (e.isNetwork()) {
result = "networkError";
}
if (e.isSerialization()) {
result = "serializationError";
}
reportMetrics(invoker, invocation, duration, result, isProvider);
throw e;
}
}
private String buildMethodName(Invocation invocation) {
String methodName = RpcUtils.getMethodName(invocation);
StringBuilder method = new StringBuilder(methodName);
Class<?>[] argTypes = RpcUtils.getParameterTypes(invocation);
method.append('(');
for (int i = 0; i < argTypes.length; i++) {
method.append((i == 0 ? "" : ", ") + argTypes[i].getSimpleName());
}
method.append(')');
Class<?> returnType = RpcUtils.getReturnType(invocation);
String typeName = null;
if (returnType != null) {
typeName = returnType.getTypeName();
typeName = typeName.substring(typeName.lastIndexOf(".") + 1);
}
return (typeName == null ? "void" : typeName) + " " + method;
}
private void reportMetrics(
Invoker<?> invoker, Invocation invocation, long duration, String result, boolean isProvider) {
String serviceName = invoker.getInterface().getName();
String methodName = buildMethodName(invocation);
MetricName global;
MetricName method;
if (isProvider) {
global = new MetricName(DUBBO_PROVIDER, MetricLevel.MAJOR);
method = new MetricName(
DUBBO_PROVIDER_METHOD,
new HashMap<String, String>(4) {
{
put(SERVICE, serviceName);
put(METHOD_KEY, methodName);
}
},
MetricLevel.NORMAL);
} else {
global = new MetricName(DUBBO_CONSUMER, MetricLevel.MAJOR);
method = new MetricName(
DUBBO_CONSUMER_METHOD,
new HashMap<String, String>(4) {
{
put(SERVICE, serviceName);
put(METHOD_KEY, methodName);
}
},
MetricLevel.NORMAL);
}
setCompassQuantity(DUBBO_GROUP, result, duration, global, method);
}
private void setCompassQuantity(String groupName, String result, long duration, MetricName... metricNames) {
for (MetricName metricName : metricNames) {
FastCompass compass = MetricManager.getFastCompass(groupName, metricName);
compass.record(duration, result);
}
}
private List<MetricObject> getThreadPoolMessage() {
DataStore dataStore =
extensionAccessor.getExtensionLoader(DataStore.class).getDefaultExtension();
Map<String, Object> executors = dataStore.get(EXECUTOR_SERVICE_COMPONENT_KEY);
List<MetricObject> threadPoolMtricList = new ArrayList<>();
for (Map.Entry<String, Object> entry : executors.entrySet()) {
String port = entry.getKey();
ExecutorService executor = (ExecutorService) entry.getValue();
if (executor instanceof ThreadPoolExecutor) {
ThreadPoolExecutor tp = (ThreadPoolExecutor) executor;
threadPoolMtricList.add(
value2MetricObject("threadPool.active", tp.getActiveCount(), MetricLevel.MAJOR));
threadPoolMtricList.add(value2MetricObject("threadPool.core", tp.getCorePoolSize(), MetricLevel.MAJOR));
threadPoolMtricList.add(
value2MetricObject("threadPool.max", tp.getMaximumPoolSize(), MetricLevel.MAJOR));
threadPoolMtricList.add(value2MetricObject("threadPool.current", tp.getPoolSize(), MetricLevel.MAJOR));
}
}
return threadPoolMtricList;
}
private MetricObject value2MetricObject(String metric, Integer value, MetricLevel level) {
if (metric == null || value == null || level == null) {
return null;
}
return new MetricObject.Builder(metric)
.withValue(value)
.withLevel(level)
.build();
}
private Invoker<MetricsService> initMetricsInvoker() {
Invoker<MetricsService> metricsInvoker = new Invoker<MetricsService>() {
@Override
public Class<MetricsService> getInterface() {
return MetricsService.class;
}
@Override
public Result invoke(Invocation invocation) throws RpcException {
String group = invocation.getArguments()[0].toString();
MetricRegistry registry = MetricManager.getIMetricManager().getMetricRegistryByGroup(group);
SortedMap<MetricName, FastCompass> fastCompasses = registry.getFastCompasses();
long timestamp = System.currentTimeMillis();
double rateFactor = TimeUnit.SECONDS.toSeconds(1);
double durationFactor = 1.0 / TimeUnit.MILLISECONDS.toNanos(1);
MetricsCollector collector = MetricsCollectorFactory.createNew(
CollectLevel.NORMAL, Collections.EMPTY_MAP, rateFactor, durationFactor, null);
for (Map.Entry<MetricName, FastCompass> entry : fastCompasses.entrySet()) {
collector.collect(entry.getKey(), entry.getValue(), timestamp);
}
List res = collector.build();
res.addAll(getThreadPoolMessage());
return AsyncRpcResult.newDefaultAsyncResult(JsonUtils.toJson(res), invocation);
}
@Override
public URL getUrl() {
return URL.valueOf(protocolName + "://" + NetUtils.getIpByConfig(applicationModel) + ":" + port + "/"
+ MetricsService.class.getName());
}
@Override
public boolean isAvailable() {
return false;
}
@Override
public void destroy() {}
};
return metricsInvoker;
}
@Override
public void setExtensionAccessor(ExtensionAccessor extensionAccessor) {
this.extensionAccessor = extensionAccessor;
}
}
| 8,369 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/StatisticsItem.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.monitor.dubbo;
public class StatisticsItem {
private long success;
private long failure;
private long input;
private long output;
private long elapsed;
private long concurrent;
private long maxInput;
private long maxOutput;
private long maxElapsed;
private long maxConcurrent;
public StatisticsItem() {}
public void setItems(long success, long failure, long input, long output, long elapsed, long concurrent) {
this.setItems(success, failure, input, output, elapsed, concurrent, 0, 0, 0, 0);
}
public void setItems(
long success,
long failure,
long input,
long output,
long elapsed,
long concurrent,
long maxInput,
long maxOutput,
long maxElapsed,
long maxConcurrent) {
this.success = success;
this.failure = failure;
this.input = input;
this.output = output;
this.elapsed = elapsed;
this.concurrent = concurrent;
this.maxInput = maxInput;
this.maxOutput = maxOutput;
this.maxElapsed = maxElapsed;
this.maxConcurrent = maxConcurrent;
}
public long getSuccess() {
return success;
}
public void setSuccess(long success) {
this.success = success;
}
public long getFailure() {
return failure;
}
public void setFailure(long failure) {
this.failure = failure;
}
public long getInput() {
return input;
}
public void setInput(long input) {
this.input = input;
}
public long getOutput() {
return output;
}
public void setOutput(long output) {
this.output = output;
}
public long getElapsed() {
return elapsed;
}
public void setElapsed(long elapsed) {
this.elapsed = elapsed;
}
public long getConcurrent() {
return concurrent;
}
public void setConcurrent(long concurrent) {
this.concurrent = concurrent;
}
public long getMaxInput() {
return maxInput;
}
public void setMaxInput(long maxInput) {
this.maxInput = maxInput;
}
public long getMaxOutput() {
return maxOutput;
}
public void setMaxOutput(long maxOutput) {
this.maxOutput = maxOutput;
}
public long getMaxElapsed() {
return maxElapsed;
}
public void setMaxElapsed(long maxElapsed) {
this.maxElapsed = maxElapsed;
}
public long getMaxConcurrent() {
return maxConcurrent;
}
public void setMaxConcurrent(long maxConcurrent) {
this.maxConcurrent = maxConcurrent;
}
}
| 8,370 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitorFactory.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.monitor.dubbo;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.monitor.Monitor;
import org.apache.dubbo.monitor.MonitorService;
import org.apache.dubbo.monitor.support.AbstractMonitorFactory;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Protocol;
import org.apache.dubbo.rpc.ProxyFactory;
import static org.apache.dubbo.common.constants.CommonConstants.DUBBO_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.PROTOCOL_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.REFERENCE_FILTER_KEY;
import static org.apache.dubbo.remoting.Constants.CHECK_KEY;
/**
* DefaultMonitorFactory
*/
public class DubboMonitorFactory extends AbstractMonitorFactory {
private Protocol protocol;
private ProxyFactory proxyFactory;
public void setProtocol(Protocol protocol) {
this.protocol = protocol;
}
public void setProxyFactory(ProxyFactory proxyFactory) {
this.proxyFactory = proxyFactory;
}
@Override
protected Monitor createMonitor(URL url) {
URLBuilder urlBuilder = URLBuilder.from(url);
urlBuilder.setProtocol(url.getParameter(PROTOCOL_KEY, DUBBO_PROTOCOL));
if (StringUtils.isEmpty(url.getPath())) {
urlBuilder.setPath(MonitorService.class.getName());
}
String filter = url.getParameter(REFERENCE_FILTER_KEY);
if (StringUtils.isEmpty(filter)) {
filter = "";
} else {
filter = filter + ",";
}
urlBuilder.addParameters(CHECK_KEY, String.valueOf(false), REFERENCE_FILTER_KEY, filter + "-monitor");
Invoker<MonitorService> monitorInvoker = protocol.refer(MonitorService.class, urlBuilder.build());
MonitorService monitorService = proxyFactory.getProxy(monitorInvoker);
return new DubboMonitor(monitorInvoker, monitorService);
}
}
| 8,371 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/DubboMonitor.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.monitor.dubbo;
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.ConcurrentHashMapUtils;
import org.apache.dubbo.common.utils.ExecutorUtil;
import org.apache.dubbo.monitor.Monitor;
import org.apache.dubbo.monitor.MonitorService;
import org.apache.dubbo.rpc.Invoker;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ScheduledExecutorService;
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_PROTOCOL;
import static org.apache.dubbo.common.constants.CommonConstants.TIMESTAMP_KEY;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.COMMON_MONITOR_EXCEPTION;
import static org.apache.dubbo.monitor.Constants.CONCURRENT_KEY;
import static org.apache.dubbo.monitor.Constants.DEFAULT_MONITOR_SEND_DATA_INTERVAL;
import static org.apache.dubbo.monitor.Constants.ELAPSED_KEY;
import static org.apache.dubbo.monitor.Constants.FAILURE_KEY;
import static org.apache.dubbo.monitor.Constants.INPUT_KEY;
import static org.apache.dubbo.monitor.Constants.MAX_CONCURRENT_KEY;
import static org.apache.dubbo.monitor.Constants.MAX_ELAPSED_KEY;
import static org.apache.dubbo.monitor.Constants.MAX_INPUT_KEY;
import static org.apache.dubbo.monitor.Constants.MAX_OUTPUT_KEY;
import static org.apache.dubbo.monitor.Constants.MONITOR_SEND_DATA_INTERVAL_KEY;
import static org.apache.dubbo.monitor.Constants.OUTPUT_KEY;
import static org.apache.dubbo.monitor.Constants.SUCCESS_KEY;
/**
* DubboMonitor
*/
public class DubboMonitor implements Monitor {
private static final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(DubboMonitor.class);
/**
* The timer for sending statistics
*/
private final ScheduledExecutorService scheduledExecutorService;
/**
* The future that can cancel the <b>scheduledExecutorService</b>
*/
private final ScheduledFuture<?> sendFuture;
private final Invoker<MonitorService> monitorInvoker;
private final MonitorService monitorService;
private final ConcurrentMap<Statistics, AtomicReference<StatisticsItem>> statisticsMap = new ConcurrentHashMap<>();
public DubboMonitor(Invoker<MonitorService> monitorInvoker, MonitorService monitorService) {
this.monitorInvoker = monitorInvoker;
this.monitorService = monitorService;
scheduledExecutorService = monitorInvoker
.getUrl()
.getOrDefaultFrameworkModel()
.getBeanFactory()
.getBean(FrameworkExecutorRepository.class)
.getSharedScheduledExecutor();
// The time interval for timer <b>scheduledExecutorService</b> to send data
final long monitorInterval = monitorInvoker
.getUrl()
.getPositiveParameter(MONITOR_SEND_DATA_INTERVAL_KEY, DEFAULT_MONITOR_SEND_DATA_INTERVAL);
// collect timer for collecting statistics data
sendFuture = scheduledExecutorService.scheduleWithFixedDelay(
() -> {
try {
// collect data
send();
} catch (Throwable t) {
logger.error(
COMMON_MONITOR_EXCEPTION,
"",
"",
"Unexpected error occur at send statistic, cause: " + t.getMessage(),
t);
}
},
monitorInterval,
monitorInterval,
TimeUnit.MILLISECONDS);
}
public void send() {
if (logger.isDebugEnabled()) {
logger.debug("Send statistics to monitor " + getUrl());
}
String timestamp = String.valueOf(System.currentTimeMillis());
for (Map.Entry<Statistics, AtomicReference<StatisticsItem>> entry : statisticsMap.entrySet()) {
// get statistics data
Statistics statistics = entry.getKey();
AtomicReference<StatisticsItem> reference = entry.getValue();
StatisticsItem statisticsItem = reference.get();
// send statistics data
URL url = statistics
.getUrl()
.addParameters(
TIMESTAMP_KEY,
timestamp,
SUCCESS_KEY,
String.valueOf(statisticsItem.getSuccess()),
FAILURE_KEY,
String.valueOf(statisticsItem.getFailure()),
INPUT_KEY,
String.valueOf(statisticsItem.getInput()),
OUTPUT_KEY,
String.valueOf(statisticsItem.getOutput()),
ELAPSED_KEY,
String.valueOf(statisticsItem.getElapsed()),
CONCURRENT_KEY,
String.valueOf(statisticsItem.getConcurrent()),
MAX_INPUT_KEY,
String.valueOf(statisticsItem.getMaxInput()),
MAX_OUTPUT_KEY,
String.valueOf(statisticsItem.getMaxOutput()),
MAX_ELAPSED_KEY,
String.valueOf(statisticsItem.getMaxElapsed()),
MAX_CONCURRENT_KEY,
String.valueOf(statisticsItem.getMaxConcurrent()),
DEFAULT_PROTOCOL,
getUrl().getParameter(DEFAULT_PROTOCOL));
monitorService.collect(url.toSerializableURL());
// reset
StatisticsItem current;
StatisticsItem update = new StatisticsItem();
do {
current = reference.get();
if (current == null) {
update.setItems(0, 0, 0, 0, 0, 0);
} else {
update.setItems(
current.getSuccess() - statisticsItem.getSuccess(),
current.getFailure() - statisticsItem.getFailure(),
current.getInput() - statisticsItem.getInput(),
current.getOutput() - statisticsItem.getOutput(),
current.getElapsed() - statisticsItem.getElapsed(),
current.getConcurrent() - statisticsItem.getConcurrent());
}
} while (!reference.compareAndSet(current, update));
}
}
@Override
public void collect(URL url) {
// data to collect from url
int success = url.getParameter(SUCCESS_KEY, 0);
int failure = url.getParameter(FAILURE_KEY, 0);
int input = url.getParameter(INPUT_KEY, 0);
int output = url.getParameter(OUTPUT_KEY, 0);
int elapsed = url.getParameter(ELAPSED_KEY, 0);
int concurrent = url.getParameter(CONCURRENT_KEY, 0);
// init atomic reference
Statistics statistics = new Statistics(url);
AtomicReference<StatisticsItem> reference =
ConcurrentHashMapUtils.computeIfAbsent(statisticsMap, statistics, k -> new AtomicReference<>());
// use CompareAndSet to sum
StatisticsItem current;
StatisticsItem update = new StatisticsItem();
do {
current = reference.get();
if (current == null) {
update.setItems(
success, failure, input, output, elapsed, concurrent, input, output, elapsed, concurrent);
} else {
update.setItems(
current.getSuccess() + success,
current.getFailure() + failure,
current.getInput() + input,
current.getOutput() + output,
current.getElapsed() + elapsed,
(current.getConcurrent() + concurrent) / 2,
current.getMaxInput() > input ? current.getMaxInput() : input,
current.getMaxOutput() > output ? current.getMaxOutput() : output,
current.getMaxElapsed() > elapsed ? current.getMaxElapsed() : elapsed,
current.getMaxConcurrent() > concurrent ? current.getMaxConcurrent() : concurrent);
}
} while (!reference.compareAndSet(current, update));
}
@Override
public List<URL> lookup(URL query) {
return monitorService.lookup(query);
}
@Override
public URL getUrl() {
return monitorInvoker.getUrl();
}
@Override
public boolean isAvailable() {
return monitorInvoker.isAvailable();
}
@Override
public void destroy() {
try {
ExecutorUtil.cancelScheduledFuture(sendFuture);
} catch (Throwable t) {
logger.error(
COMMON_MONITOR_EXCEPTION,
"",
"",
"Unexpected error occur at cancel sender timer, cause: " + t.getMessage(),
t);
}
monitorInvoker.destroy();
}
}
| 8,372 |
0 |
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor
|
Create_ds/dubbo/dubbo-monitor/dubbo-monitor-default/src/main/java/org/apache/dubbo/monitor/dubbo/Statistics.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.monitor.dubbo;
import org.apache.dubbo.common.URL;
import java.io.Serializable;
import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
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.METHOD_KEY;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;
import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY;
/**
* Statistics. (SPI, Prototype, ThreadSafe)
*/
public class Statistics implements Serializable {
private static final long serialVersionUID = -6921183057683641441L;
private URL url;
private String application;
private String service;
private String method;
private String group;
private String version;
private String client;
private String server;
public Statistics(URL url) {
this.url = url;
this.application = url.getParameter(APPLICATION_KEY);
this.service = url.getParameter(INTERFACE_KEY);
this.method = url.getParameter(METHOD_KEY);
this.group = url.getParameter(GROUP_KEY);
this.version = url.getParameter(VERSION_KEY);
this.client = url.getParameter(CONSUMER, url.getAddress());
this.server = url.getParameter(PROVIDER, url.getAddress());
}
public URL getUrl() {
return url;
}
public void setUrl(URL url) {
this.url = url;
}
public String getApplication() {
return application;
}
public Statistics setApplication(String application) {
this.application = application;
return this;
}
public String getService() {
return service;
}
public Statistics setService(String service) {
this.service = service;
return this;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getMethod() {
return method;
}
public Statistics setMethod(String method) {
this.method = method;
return this;
}
public String getClient() {
return client;
}
public Statistics setClient(String client) {
this.client = client;
return this;
}
public String getServer() {
return server;
}
public Statistics setServer(String server) {
this.server = server;
return this;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((application == null) ? 0 : application.hashCode());
result = prime * result + ((client == null) ? 0 : client.hashCode());
result = prime * result + ((group == null) ? 0 : group.hashCode());
result = prime * result + ((method == null) ? 0 : method.hashCode());
result = prime * result + ((server == null) ? 0 : server.hashCode());
result = prime * result + ((service == null) ? 0 : service.hashCode());
result = prime * result + ((version == null) ? 0 : version.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Statistics other = (Statistics) obj;
if (application == null) {
if (other.application != null) {
return false;
}
} else if (!application.equals(other.application)) {
return false;
}
if (client == null) {
if (other.client != null) {
return false;
}
} else if (!client.equals(other.client)) {
return false;
}
if (group == null) {
if (other.group != null) {
return false;
}
} else if (!group.equals(other.group)) {
return false;
}
if (method == null) {
if (other.method != null) {
return false;
}
} else if (!method.equals(other.method)) {
return false;
}
if (server == null) {
if (other.server != null) {
return false;
}
} else if (!server.equals(other.server)) {
return false;
}
if (service == null) {
if (other.service != null) {
return false;
}
} else if (!service.equals(other.service)) {
return false;
}
if (version == null) {
if (other.version != null) {
return false;
}
} else if (!version.equals(other.version)) {
return false;
}
return true;
}
@Override
public String toString() {
return url.toString();
}
}
| 8,373 |
0 |
Create_ds/dubbo/dubbo-kubernetes/src/test/java/org/apache/dubbo/registry
|
Create_ds/dubbo/dubbo-kubernetes/src/test/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscoveryTest.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.kubernetes;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import io.fabric8.kubernetes.api.model.Endpoints;
import io.fabric8.kubernetes.api.model.EndpointsBuilder;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceBuilder;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.NamespacedKubernetesClient;
import io.fabric8.kubernetes.client.server.mock.KubernetesServer;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.NAMESPACE;
import static org.awaitility.Awaitility.await;
@ExtendWith({MockitoExtension.class})
class KubernetesServiceDiscoveryTest {
private static final String SERVICE_NAME = "TestService";
private static final String POD_NAME = "TestServer";
public KubernetesServer mockServer = new KubernetesServer(false, true);
private NamespacedKubernetesClient mockClient;
private ServiceInstancesChangedListener mockListener = Mockito.mock(ServiceInstancesChangedListener.class);
private URL serverUrl;
private Map<String, String> selector;
private KubernetesServiceDiscovery serviceDiscovery;
@BeforeEach
public void setUp() {
mockServer.before();
mockClient = mockServer.getClient().inNamespace("dubbo-demo");
ApplicationModel applicationModel = ApplicationModel.defaultModel();
applicationModel.getApplicationConfigManager().setApplication(new ApplicationConfig());
serverUrl = URL.valueOf(mockClient.getConfiguration().getMasterUrl())
.setProtocol("kubernetes")
.addParameter(NAMESPACE, "dubbo-demo")
.addParameter(KubernetesClientConst.USE_HTTPS, "false")
.addParameter(KubernetesClientConst.HTTP2_DISABLE, "true");
serverUrl.setScopeModel(applicationModel);
this.serviceDiscovery = new KubernetesServiceDiscovery(applicationModel, serverUrl);
System.setProperty(Config.KUBERNETES_AUTH_TRYKUBECONFIG_SYSTEM_PROPERTY, "false");
System.setProperty(Config.KUBERNETES_AUTH_TRYSERVICEACCOUNT_SYSTEM_PROPERTY, "false");
selector = new HashMap<>(4);
selector.put("l", "v");
Pod pod = new PodBuilder()
.withNewMetadata()
.withName(POD_NAME)
.withLabels(selector)
.endMetadata()
.build();
Service service = new ServiceBuilder()
.withNewMetadata()
.withName(SERVICE_NAME)
.endMetadata()
.withNewSpec()
.withSelector(selector)
.endSpec()
.build();
Endpoints endPoints = new EndpointsBuilder()
.withNewMetadata()
.withName(SERVICE_NAME)
.endMetadata()
.addNewSubset()
.addNewAddress()
.withIp("ip1")
.withNewTargetRef()
.withUid("uid1")
.withName(POD_NAME)
.endTargetRef()
.endAddress()
.addNewPort("Test", "Test", 12345, "TCP")
.endSubset()
.build();
mockClient.pods().resource(pod).create();
mockClient.services().resource(service).create();
mockClient.endpoints().resource(endPoints).create();
}
@AfterEach
public void destroy() throws Exception {
serviceDiscovery.destroy();
mockClient.close();
mockServer.after();
}
@Test
void testEndpointsUpdate() {
serviceDiscovery.setCurrentHostname(POD_NAME);
serviceDiscovery.setKubernetesClient(mockClient);
ServiceInstance serviceInstance = new DefaultServiceInstance(
SERVICE_NAME,
"Test",
12345,
ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel()));
serviceDiscovery.doRegister(serviceInstance);
HashSet<String> serviceList = new HashSet<>(4);
serviceList.add(SERVICE_NAME);
Mockito.when(mockListener.getServiceNames()).thenReturn(serviceList);
Mockito.doNothing().when(mockListener).onEvent(Mockito.any());
serviceDiscovery.addServiceInstancesChangedListener(mockListener);
mockClient.endpoints().withName(SERVICE_NAME).edit(endpoints -> new EndpointsBuilder(endpoints)
.editFirstSubset()
.addNewAddress()
.withIp("ip2")
.withNewTargetRef()
.withUid("uid2")
.withName(POD_NAME)
.endTargetRef()
.endAddress()
.endSubset()
.build());
await().until(() -> {
ArgumentCaptor<ServiceInstancesChangedEvent> captor =
ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class);
Mockito.verify(mockListener, Mockito.atLeast(0)).onEvent(captor.capture());
return captor.getValue().getServiceInstances().size() == 2;
});
ArgumentCaptor<ServiceInstancesChangedEvent> eventArgumentCaptor =
ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class);
Mockito.verify(mockListener, Mockito.times(2)).onEvent(eventArgumentCaptor.capture());
Assertions.assertEquals(
2, eventArgumentCaptor.getValue().getServiceInstances().size());
serviceDiscovery.doUnregister(serviceInstance);
}
@Test
void testPodsUpdate() throws Exception {
serviceDiscovery.setCurrentHostname(POD_NAME);
serviceDiscovery.setKubernetesClient(mockClient);
ServiceInstance serviceInstance = new DefaultServiceInstance(
SERVICE_NAME,
"Test",
12345,
ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel()));
serviceDiscovery.doRegister(serviceInstance);
HashSet<String> serviceList = new HashSet<>(4);
serviceList.add(SERVICE_NAME);
Mockito.when(mockListener.getServiceNames()).thenReturn(serviceList);
Mockito.doNothing().when(mockListener).onEvent(Mockito.any());
serviceDiscovery.addServiceInstancesChangedListener(mockListener);
serviceInstance = new DefaultServiceInstance(
SERVICE_NAME,
"Test12345",
12345,
ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel()));
serviceDiscovery.doUpdate(serviceInstance, serviceInstance);
await().until(() -> {
ArgumentCaptor<ServiceInstancesChangedEvent> captor =
ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class);
Mockito.verify(mockListener, Mockito.atLeast(0)).onEvent(captor.capture());
return captor.getValue().getServiceInstances().size() == 1;
});
ArgumentCaptor<ServiceInstancesChangedEvent> eventArgumentCaptor =
ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class);
Mockito.verify(mockListener, Mockito.times(1)).onEvent(eventArgumentCaptor.capture());
Assertions.assertEquals(
1, eventArgumentCaptor.getValue().getServiceInstances().size());
serviceDiscovery.doUnregister(serviceInstance);
}
@Test
void testServiceUpdate() {
serviceDiscovery.setCurrentHostname(POD_NAME);
serviceDiscovery.setKubernetesClient(mockClient);
ServiceInstance serviceInstance = new DefaultServiceInstance(
SERVICE_NAME,
"Test",
12345,
ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel()));
serviceDiscovery.doRegister(serviceInstance);
HashSet<String> serviceList = new HashSet<>(4);
serviceList.add(SERVICE_NAME);
Mockito.when(mockListener.getServiceNames()).thenReturn(serviceList);
Mockito.doNothing().when(mockListener).onEvent(Mockito.any());
serviceDiscovery.addServiceInstancesChangedListener(mockListener);
selector.put("app", "test");
mockClient.services().withName(SERVICE_NAME).edit(service -> new ServiceBuilder(service)
.editSpec()
.addToSelector(selector)
.endSpec()
.build());
await().until(() -> {
ArgumentCaptor<ServiceInstancesChangedEvent> captor =
ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class);
Mockito.verify(mockListener, Mockito.atLeast(0)).onEvent(captor.capture());
return captor.getValue().getServiceInstances().size() == 1;
});
ArgumentCaptor<ServiceInstancesChangedEvent> eventArgumentCaptor =
ArgumentCaptor.forClass(ServiceInstancesChangedEvent.class);
Mockito.verify(mockListener, Mockito.times(1)).onEvent(eventArgumentCaptor.capture());
Assertions.assertEquals(
1, eventArgumentCaptor.getValue().getServiceInstances().size());
serviceDiscovery.doUnregister(serviceInstance);
}
@Test
void testGetInstance() {
serviceDiscovery.setCurrentHostname(POD_NAME);
serviceDiscovery.setKubernetesClient(mockClient);
ServiceInstance serviceInstance = new DefaultServiceInstance(
SERVICE_NAME,
"Test",
12345,
ScopeModelUtil.getApplicationModel(serviceDiscovery.getUrl().getScopeModel()));
serviceDiscovery.doRegister(serviceInstance);
serviceDiscovery.doUpdate(serviceInstance, serviceInstance);
Assertions.assertEquals(1, serviceDiscovery.getServices().size());
Assertions.assertEquals(1, serviceDiscovery.getInstances(SERVICE_NAME).size());
serviceDiscovery.doUnregister(serviceInstance);
}
}
| 8,374 |
0 |
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry
|
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesRegistryFactory.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.kubernetes;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.Registry;
import org.apache.dubbo.registry.support.AbstractRegistryFactory;
public class KubernetesRegistryFactory extends AbstractRegistryFactory {
@Override
protected String createRegistryCacheKey(URL url) {
return url.toFullString();
}
@Override
protected Registry createRegistry(URL url) {
return new KubernetesRegistry(url);
}
}
| 8,375 |
0 |
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry
|
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesRegistry.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.kubernetes;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.NotifyListener;
import org.apache.dubbo.registry.support.FailbackRegistry;
/**
* Empty implements for Kubernetes <br/>
* Kubernetes only support `Service Discovery` mode register <br/>
* Used to compat past version like 2.6.x, 2.7.x with interface level register <br/>
* {@link KubernetesServiceDiscovery} is the real implementation of Kubernetes
*/
public class KubernetesRegistry extends FailbackRegistry {
public KubernetesRegistry(URL url) {
super(url);
}
@Override
public boolean isAvailable() {
return true;
}
@Override
public void doRegister(URL url) {}
@Override
public void doUnregister(URL url) {}
@Override
public void doSubscribe(URL url, NotifyListener listener) {}
@Override
public void doUnsubscribe(URL url, NotifyListener listener) {}
}
| 8,376 |
0 |
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry
|
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesMeshEnvListenerFactory.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.kubernetes;
import org.apache.dubbo.common.logger.Logger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshEnvListener;
import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshEnvListenerFactory;
import java.util.concurrent.atomic.AtomicBoolean;
public class KubernetesMeshEnvListenerFactory implements MeshEnvListenerFactory {
public static final Logger logger = LoggerFactory.getLogger(KubernetesMeshEnvListenerFactory.class);
private final AtomicBoolean initialized = new AtomicBoolean(false);
private MeshEnvListener listener = null;
@Override
public MeshEnvListener getListener() {
try {
if (initialized.compareAndSet(false, true)) {
listener = new NopKubernetesMeshEnvListener();
}
} catch (Throwable t) {
logger.info("Current Env not support Kubernetes.");
}
return listener;
}
}
| 8,377 |
0 |
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry
|
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscovery.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.kubernetes;
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.JsonUtils;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.registry.client.AbstractServiceDiscovery;
import org.apache.dubbo.registry.client.DefaultServiceInstance;
import org.apache.dubbo.registry.client.ServiceInstance;
import org.apache.dubbo.registry.client.event.ServiceInstancesChangedEvent;
import org.apache.dubbo.registry.client.event.listener.ServiceInstancesChangedListener;
import org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst;
import org.apache.dubbo.registry.kubernetes.util.KubernetesConfigUtils;
import org.apache.dubbo.rpc.model.ApplicationModel;
import org.apache.dubbo.rpc.model.ScopeModelUtil;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import io.fabric8.kubernetes.api.model.EndpointAddress;
import io.fabric8.kubernetes.api.model.EndpointPort;
import io.fabric8.kubernetes.api.model.EndpointSubset;
import io.fabric8.kubernetes.api.model.Endpoints;
import io.fabric8.kubernetes.api.model.Pod;
import io.fabric8.kubernetes.api.model.PodBuilder;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClientBuilder;
import io.fabric8.kubernetes.client.informers.ResourceEventHandler;
import io.fabric8.kubernetes.client.informers.SharedIndexInformer;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNABLE_ACCESS_KUBERNETES;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNABLE_FIND_SERVICE_KUBERNETES;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_UNABLE_MATCH_KUBERNETES;
public class KubernetesServiceDiscovery extends AbstractServiceDiscovery {
private final ErrorTypeAwareLogger logger = LoggerFactory.getErrorTypeAwareLogger(getClass());
private KubernetesClient kubernetesClient;
private String currentHostname;
private final URL registryURL;
private final String namespace;
private final boolean enableRegister;
public static final String KUBERNETES_PROPERTIES_KEY = "io.dubbo/metadata";
private static final ConcurrentHashMap<String, AtomicLong> SERVICE_UPDATE_TIME = new ConcurrentHashMap<>(64);
private static final ConcurrentHashMap<String, SharedIndexInformer<Service>> SERVICE_INFORMER =
new ConcurrentHashMap<>(64);
private static final ConcurrentHashMap<String, SharedIndexInformer<Pod>> PODS_INFORMER =
new ConcurrentHashMap<>(64);
private static final ConcurrentHashMap<String, SharedIndexInformer<Endpoints>> ENDPOINTS_INFORMER =
new ConcurrentHashMap<>(64);
public KubernetesServiceDiscovery(ApplicationModel applicationModel, URL registryURL) {
super(applicationModel, registryURL);
Config config = KubernetesConfigUtils.createKubernetesConfig(registryURL);
this.kubernetesClient = new KubernetesClientBuilder().withConfig(config).build();
this.currentHostname = System.getenv("HOSTNAME");
this.registryURL = registryURL;
this.namespace = config.getNamespace();
this.enableRegister = registryURL.getParameter(KubernetesClientConst.ENABLE_REGISTER, true);
boolean availableAccess;
try {
availableAccess = kubernetesClient.pods().withName(currentHostname).get() != null;
} catch (Throwable e) {
availableAccess = false;
}
if (!availableAccess) {
String message = "Unable to access api server. " + "Please check your url config."
+ " Master URL: "
+ config.getMasterUrl() + " Hostname: "
+ currentHostname;
logger.error(REGISTRY_UNABLE_ACCESS_KUBERNETES, "", "", message);
} else {
KubernetesMeshEnvListener.injectKubernetesEnv(kubernetesClient, namespace);
}
}
@Override
public void doDestroy() {
SERVICE_INFORMER.forEach((k, v) -> v.close());
SERVICE_INFORMER.clear();
PODS_INFORMER.forEach((k, v) -> v.close());
PODS_INFORMER.clear();
ENDPOINTS_INFORMER.forEach((k, v) -> v.close());
ENDPOINTS_INFORMER.clear();
kubernetesClient.close();
}
@Override
public void doRegister(ServiceInstance serviceInstance) throws RuntimeException {
if (enableRegister) {
kubernetesClient
.pods()
.inNamespace(namespace)
.withName(currentHostname)
.edit(pod -> new PodBuilder(pod)
.editOrNewMetadata()
.addToAnnotations(
KUBERNETES_PROPERTIES_KEY, JsonUtils.toJson(serviceInstance.getMetadata()))
.endMetadata()
.build());
if (logger.isInfoEnabled()) {
logger.info("Write Current Service Instance Metadata to Kubernetes pod. " + "Current pod name: "
+ currentHostname);
}
}
}
/**
* Comparing to {@link AbstractServiceDiscovery#doUpdate(ServiceInstance, ServiceInstance)}, unregister() is unnecessary here.
*/
@Override
public void doUpdate(ServiceInstance oldServiceInstance, ServiceInstance newServiceInstance)
throws RuntimeException {
reportMetadata(newServiceInstance.getServiceMetadata());
this.doRegister(newServiceInstance);
}
@Override
public void doUnregister(ServiceInstance serviceInstance) throws RuntimeException {
if (enableRegister) {
kubernetesClient
.pods()
.inNamespace(namespace)
.withName(currentHostname)
.edit(pod -> new PodBuilder(pod)
.editOrNewMetadata()
.removeFromAnnotations(KUBERNETES_PROPERTIES_KEY)
.endMetadata()
.build());
if (logger.isInfoEnabled()) {
logger.info(
"Remove Current Service Instance from Kubernetes pod. Current pod name: " + currentHostname);
}
}
}
@Override
public Set<String> getServices() {
return kubernetesClient.services().inNamespace(namespace).list().getItems().stream()
.map(service -> service.getMetadata().getName())
.collect(Collectors.toSet());
}
@Override
public List<ServiceInstance> getInstances(String serviceName) throws NullPointerException {
Endpoints endpoints = null;
SharedIndexInformer<Endpoints> endInformer = ENDPOINTS_INFORMER.get(serviceName);
if (endInformer != null) {
// get endpoints directly from informer local store
List<Endpoints> endpointsList = endInformer.getStore().list();
if (endpointsList.size() > 0) {
endpoints = endpointsList.get(0);
}
}
if (endpoints == null) {
endpoints = kubernetesClient
.endpoints()
.inNamespace(namespace)
.withName(serviceName)
.get();
}
return toServiceInstance(endpoints, serviceName);
}
@Override
public void addServiceInstancesChangedListener(ServiceInstancesChangedListener listener)
throws NullPointerException, IllegalArgumentException {
listener.getServiceNames().forEach(serviceName -> {
SERVICE_UPDATE_TIME.put(serviceName, new AtomicLong(0L));
// Watch Service Endpoint Modification
watchEndpoints(listener, serviceName);
// Watch Pods Modification, happens when ServiceInstance updated
watchPods(listener, serviceName);
// Watch Service Modification, happens when Service Selector updated, used to update pods watcher
watchService(listener, serviceName);
});
}
private void watchEndpoints(ServiceInstancesChangedListener listener, String serviceName) {
SharedIndexInformer<Endpoints> endInformer = kubernetesClient
.endpoints()
.inNamespace(namespace)
.withName(serviceName)
.inform(new ResourceEventHandler<Endpoints>() {
@Override
public void onAdd(Endpoints endpoints) {
if (logger.isDebugEnabled()) {
logger.debug("Received Endpoint Event. Event type: added. Current pod name: "
+ currentHostname + ". Endpoints is: " + endpoints);
}
notifyServiceChanged(serviceName, listener, toServiceInstance(endpoints, serviceName));
}
@Override
public void onUpdate(Endpoints oldEndpoints, Endpoints newEndpoints) {
if (logger.isDebugEnabled()) {
logger.debug("Received Endpoint Event. Event type: updated. Current pod name: "
+ currentHostname + ". The new Endpoints is: " + newEndpoints);
}
notifyServiceChanged(serviceName, listener, toServiceInstance(newEndpoints, serviceName));
}
@Override
public void onDelete(Endpoints endpoints, boolean deletedFinalStateUnknown) {
if (logger.isDebugEnabled()) {
logger.debug("Received Endpoint Event. Event type: deleted. Current pod name: "
+ currentHostname + ". Endpoints is: " + endpoints);
}
notifyServiceChanged(serviceName, listener, toServiceInstance(endpoints, serviceName));
}
});
ENDPOINTS_INFORMER.put(serviceName, endInformer);
}
private void watchPods(ServiceInstancesChangedListener listener, String serviceName) {
Map<String, String> serviceSelector = getServiceSelector(serviceName);
if (serviceSelector == null) {
return;
}
SharedIndexInformer<Pod> podInformer = kubernetesClient
.pods()
.inNamespace(namespace)
.withLabels(serviceSelector)
.inform(new ResourceEventHandler<Pod>() {
@Override
public void onAdd(Pod pod) {
if (logger.isDebugEnabled()) {
logger.debug("Received Pods Event. Event type: added. Current pod name: " + currentHostname
+ ". Pod is: " + pod);
}
}
@Override
public void onUpdate(Pod oldPod, Pod newPod) {
if (logger.isDebugEnabled()) {
logger.debug("Received Pods Event. Event type: updated. Current pod name: "
+ currentHostname + ". new Pod is: " + newPod);
}
notifyServiceChanged(serviceName, listener, getInstances(serviceName));
}
@Override
public void onDelete(Pod pod, boolean deletedFinalStateUnknown) {
if (logger.isDebugEnabled()) {
logger.debug("Received Pods Event. Event type: deleted. Current pod name: "
+ currentHostname + ". Pod is: " + pod);
}
}
});
PODS_INFORMER.put(serviceName, podInformer);
}
private void watchService(ServiceInstancesChangedListener listener, String serviceName) {
SharedIndexInformer<Service> serviceInformer = kubernetesClient
.services()
.inNamespace(namespace)
.withName(serviceName)
.inform(new ResourceEventHandler<Service>() {
@Override
public void onAdd(Service service) {
if (logger.isDebugEnabled()) {
logger.debug("Received Service Added Event. " + "Current pod name: " + currentHostname);
}
}
@Override
public void onUpdate(Service oldService, Service newService) {
if (logger.isDebugEnabled()) {
logger.debug("Received Service Update Event. Update Pods Watcher. Current pod name: "
+ currentHostname + ". The new Service is: " + newService);
}
if (PODS_INFORMER.containsKey(serviceName)) {
PODS_INFORMER.get(serviceName).close();
PODS_INFORMER.remove(serviceName);
}
watchPods(listener, serviceName);
}
@Override
public void onDelete(Service service, boolean deletedFinalStateUnknown) {
if (logger.isDebugEnabled()) {
logger.debug("Received Service Delete Event. " + "Current pod name: " + currentHostname);
}
}
});
SERVICE_INFORMER.put(serviceName, serviceInformer);
}
private void notifyServiceChanged(
String serviceName, ServiceInstancesChangedListener listener, List<ServiceInstance> serviceInstanceList) {
long receivedTime = System.nanoTime();
ServiceInstancesChangedEvent event;
event = new ServiceInstancesChangedEvent(serviceName, serviceInstanceList);
AtomicLong updateTime = SERVICE_UPDATE_TIME.get(serviceName);
long lastUpdateTime = updateTime.get();
if (lastUpdateTime <= receivedTime) {
if (updateTime.compareAndSet(lastUpdateTime, receivedTime)) {
listener.onEvent(event);
return;
}
}
if (logger.isInfoEnabled()) {
logger.info("Discard Service Instance Data. "
+ "Possible Cause: Newer message has been processed or Failed to update time record by CAS. "
+ "Current Data received time: "
+ receivedTime + ". " + "Newer Data received time: "
+ lastUpdateTime + ".");
}
}
@Override
public URL getUrl() {
return registryURL;
}
private Map<String, String> getServiceSelector(String serviceName) {
Service service = kubernetesClient
.services()
.inNamespace(namespace)
.withName(serviceName)
.get();
if (service == null) {
return null;
}
return service.getSpec().getSelector();
}
private List<ServiceInstance> toServiceInstance(Endpoints endpoints, String serviceName) {
Map<String, String> serviceSelector = getServiceSelector(serviceName);
if (serviceSelector == null) {
return new LinkedList<>();
}
Map<String, Pod> pods =
kubernetesClient.pods().inNamespace(namespace).withLabels(serviceSelector).list().getItems().stream()
.collect(Collectors.toMap(pod -> pod.getMetadata().getName(), pod -> pod));
List<ServiceInstance> instances = new LinkedList<>();
Set<Integer> instancePorts = new HashSet<>();
for (EndpointSubset endpointSubset : endpoints.getSubsets()) {
instancePorts.addAll(endpointSubset.getPorts().stream()
.map(EndpointPort::getPort)
.collect(Collectors.toSet()));
}
for (EndpointSubset endpointSubset : endpoints.getSubsets()) {
for (EndpointAddress address : endpointSubset.getAddresses()) {
Pod pod = pods.get(address.getTargetRef().getName());
String ip = address.getIp();
if (pod == null) {
logger.warn(
REGISTRY_UNABLE_MATCH_KUBERNETES,
"",
"",
"Unable to match Kubernetes Endpoint address with Pod. " + "EndpointAddress Hostname: "
+ address.getTargetRef().getName());
continue;
}
instancePorts.forEach(port -> {
ServiceInstance serviceInstance = new DefaultServiceInstance(
serviceName, ip, port, ScopeModelUtil.getApplicationModel(getUrl().getScopeModel()));
String properties = pod.getMetadata().getAnnotations().get(KUBERNETES_PROPERTIES_KEY);
if (StringUtils.isNotEmpty(properties)) {
serviceInstance.getMetadata().putAll(JsonUtils.toJavaObject(properties, Map.class));
instances.add(serviceInstance);
} else {
logger.warn(
REGISTRY_UNABLE_FIND_SERVICE_KUBERNETES,
"",
"",
"Unable to find Service Instance metadata in Pod Annotations. "
+ "Possibly cause: provider has not been initialized successfully. "
+ "EndpointAddress Hostname: "
+ address.getTargetRef().getName());
}
});
}
}
return instances;
}
/**
* UT used only
*/
@Deprecated
public void setCurrentHostname(String currentHostname) {
this.currentHostname = currentHostname;
}
/**
* UT used only
*/
@Deprecated
public void setKubernetesClient(KubernetesClient kubernetesClient) {
this.kubernetesClient = kubernetesClient;
}
}
| 8,378 |
0 |
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry
|
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/NopKubernetesMeshEnvListener.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.kubernetes;
import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshAppRuleListener;
import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshEnvListener;
public class NopKubernetesMeshEnvListener implements MeshEnvListener {
@Override
public boolean isEnable() {
return false;
}
@Override
public void onSubscribe(String appName, MeshAppRuleListener listener) {}
@Override
public void onUnSubscribe(String appName) {}
}
| 8,379 |
0 |
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry
|
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesMeshEnvListener.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.kubernetes;
import org.apache.dubbo.common.logger.ErrorTypeAwareLogger;
import org.apache.dubbo.common.logger.LoggerFactory;
import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshAppRuleListener;
import org.apache.dubbo.rpc.cluster.router.mesh.route.MeshEnvListener;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import io.fabric8.kubernetes.api.model.GenericKubernetesResource;
import io.fabric8.kubernetes.client.KubernetesClient;
import io.fabric8.kubernetes.client.Watch;
import io.fabric8.kubernetes.client.Watcher;
import io.fabric8.kubernetes.client.WatcherException;
import org.yaml.snakeyaml.LoaderOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import static org.apache.dubbo.common.constants.LoggerCodeConstants.REGISTRY_ERROR_LISTEN_KUBERNETES;
public class KubernetesMeshEnvListener implements MeshEnvListener {
public static final ErrorTypeAwareLogger logger =
LoggerFactory.getErrorTypeAwareLogger(KubernetesMeshEnvListener.class);
private static volatile boolean usingApiServer = false;
private static volatile KubernetesClient kubernetesClient;
private static volatile String namespace;
private final Map<String, MeshAppRuleListener> appRuleListenerMap = new ConcurrentHashMap<>();
private final Map<String, Watch> vsAppWatch = new ConcurrentHashMap<>();
private final Map<String, Watch> drAppWatch = new ConcurrentHashMap<>();
private final Map<String, String> vsAppCache = new ConcurrentHashMap<>();
private final Map<String, String> drAppCache = new ConcurrentHashMap<>();
public static void injectKubernetesEnv(KubernetesClient client, String configuredNamespace) {
usingApiServer = true;
kubernetesClient = client;
namespace = configuredNamespace;
}
@Override
public boolean isEnable() {
return usingApiServer;
}
@Override
public void onSubscribe(String appName, MeshAppRuleListener listener) {
appRuleListenerMap.put(appName, listener);
logger.info("Subscribe Mesh Rule in Kubernetes. AppName: " + appName);
// subscribe VisualService
subscribeVs(appName);
// subscribe DestinationRule
subscribeDr(appName);
// notify for start
notifyOnce(appName);
}
private void subscribeVs(String appName) {
if (vsAppWatch.containsKey(appName)) {
return;
}
try {
Watch watch = kubernetesClient
.genericKubernetesResources(MeshConstant.getVsDefinition())
.inNamespace(namespace)
.withName(appName)
.watch(new Watcher<GenericKubernetesResource>() {
@Override
public void eventReceived(Action action, GenericKubernetesResource resource) {
if (logger.isInfoEnabled()) {
logger.info("Received VS Rule notification. AppName: " + appName + " Action:" + action
+ " Resource:" + resource);
}
if (action == Action.ADDED || action == Action.MODIFIED) {
String vsRule = new Yaml(new SafeConstructor(new LoaderOptions())).dump(resource);
vsAppCache.put(appName, vsRule);
if (drAppCache.containsKey(appName)) {
notifyListener(vsRule, appName, drAppCache.get(appName));
}
} else {
appRuleListenerMap.get(appName).receiveConfigInfo("");
}
}
@Override
public void onClose(WatcherException cause) {
// ignore
}
});
vsAppWatch.put(appName, watch);
try {
GenericKubernetesResource vsRule = kubernetesClient
.genericKubernetesResources(MeshConstant.getVsDefinition())
.inNamespace(namespace)
.withName(appName)
.get();
vsAppCache.put(appName, new Yaml(new SafeConstructor(new LoaderOptions())).dump(vsRule));
} catch (Throwable ignore) {
}
} catch (Exception e) {
logger.error(REGISTRY_ERROR_LISTEN_KUBERNETES, "", "", "Error occurred when listen kubernetes crd.", e);
}
}
private void notifyListener(String vsRule, String appName, String drRule) {
String rule = vsRule + "\n---\n" + drRule;
logger.info("Notify App Rule Listener. AppName: " + appName + " Rule:" + rule);
appRuleListenerMap.get(appName).receiveConfigInfo(rule);
}
private void subscribeDr(String appName) {
if (drAppWatch.containsKey(appName)) {
return;
}
try {
Watch watch = kubernetesClient
.genericKubernetesResources(MeshConstant.getDrDefinition())
.inNamespace(namespace)
.withName(appName)
.watch(new Watcher<GenericKubernetesResource>() {
@Override
public void eventReceived(Action action, GenericKubernetesResource resource) {
if (logger.isInfoEnabled()) {
logger.info("Received VS Rule notification. AppName: " + appName + " Action:" + action
+ " Resource:" + resource);
}
if (action == Action.ADDED || action == Action.MODIFIED) {
String drRule = new Yaml(new SafeConstructor(new LoaderOptions())).dump(resource);
drAppCache.put(appName, drRule);
if (vsAppCache.containsKey(appName)) {
notifyListener(vsAppCache.get(appName), appName, drRule);
}
} else {
appRuleListenerMap.get(appName).receiveConfigInfo("");
}
}
@Override
public void onClose(WatcherException cause) {
// ignore
}
});
drAppWatch.put(appName, watch);
try {
GenericKubernetesResource drRule = kubernetesClient
.genericKubernetesResources(MeshConstant.getDrDefinition())
.inNamespace(namespace)
.withName(appName)
.get();
drAppCache.put(appName, new Yaml(new SafeConstructor(new LoaderOptions())).dump(drRule));
} catch (Throwable ignore) {
}
} catch (Exception e) {
logger.error(REGISTRY_ERROR_LISTEN_KUBERNETES, "", "", "Error occurred when listen kubernetes crd.", e);
}
}
private void notifyOnce(String appName) {
if (vsAppCache.containsKey(appName) && drAppCache.containsKey(appName)) {
notifyListener(vsAppCache.get(appName), appName, drAppCache.get(appName));
}
}
@Override
public void onUnSubscribe(String appName) {
appRuleListenerMap.remove(appName);
if (vsAppWatch.containsKey(appName)) {
vsAppWatch.remove(appName).close();
}
vsAppCache.remove(appName);
if (drAppWatch.containsKey(appName)) {
drAppWatch.remove(appName).close();
}
drAppCache.remove(appName);
}
}
| 8,380 |
0 |
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry
|
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/KubernetesServiceDiscoveryFactory.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.kubernetes;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.registry.client.AbstractServiceDiscoveryFactory;
import org.apache.dubbo.registry.client.ServiceDiscovery;
public class KubernetesServiceDiscoveryFactory extends AbstractServiceDiscoveryFactory {
@Override
protected ServiceDiscovery createDiscovery(URL registryURL) {
return new KubernetesServiceDiscovery(applicationModel, registryURL);
}
}
| 8,381 |
0 |
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry
|
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/MeshConstant.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.kubernetes;
import io.fabric8.kubernetes.client.dsl.base.CustomResourceDefinitionContext;
public class MeshConstant {
public static CustomResourceDefinitionContext getVsDefinition() {
// TODO cache
return new CustomResourceDefinitionContext.Builder()
.withGroup("service.dubbo.apache.org")
.withVersion("v1alpha1")
.withScope("Namespaced")
.withName("virtualservices.service.dubbo.apache.org")
.withPlural("virtualservices")
.withKind("VirtualService")
.build();
}
public static CustomResourceDefinitionContext getDrDefinition() {
// TODO cache
return new CustomResourceDefinitionContext.Builder()
.withGroup("service.dubbo.apache.org")
.withVersion("v1alpha1")
.withScope("Namespaced")
.withName("destinationrules.service.dubbo.apache.org")
.withPlural("destinationrules")
.withKind("DestinationRule")
.build();
}
}
| 8,382 |
0 |
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes
|
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/util/KubernetesClientConst.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.kubernetes.util;
public class KubernetesClientConst {
public static final String DEFAULT_MASTER_PLACEHOLDER = "DEFAULT_MASTER_HOST";
public static final String DEFAULT_MASTER_URL = "https://kubernetes.default.svc";
public static final String ENABLE_REGISTER = "enableRegister";
public static final String TRUST_CERTS = "trustCerts";
public static final String USE_HTTPS = "useHttps";
public static final String HTTP2_DISABLE = "http2Disable";
public static final String NAMESPACE = "namespace";
public static final String API_VERSION = "apiVersion";
public static final String CA_CERT_FILE = "caCertFile";
public static final String CA_CERT_DATA = "caCertData";
public static final String CLIENT_CERT_FILE = "clientCertFile";
public static final String CLIENT_CERT_DATA = "clientCertData";
public static final String CLIENT_KEY_FILE = "clientKeyFile";
public static final String CLIENT_KEY_DATA = "clientKeyData";
public static final String CLIENT_KEY_ALGO = "clientKeyAlgo";
public static final String CLIENT_KEY_PASSPHRASE = "clientKeyPassphrase";
public static final String OAUTH_TOKEN = "oauthToken";
public static final String USERNAME = "username";
public static final String PASSWORD = "password";
public static final String WATCH_RECONNECT_INTERVAL = "watchReconnectInterval";
public static final String WATCH_RECONNECT_LIMIT = "watchReconnectLimit";
public static final String CONNECTION_TIMEOUT = "connectionTimeout";
public static final String REQUEST_TIMEOUT = "requestTimeout";
public static final String ROLLING_TIMEOUT = "rollingTimeout";
public static final String LOGGING_INTERVAL = "loggingInterval";
public static final String HTTP_PROXY = "httpProxy";
public static final String HTTPS_PROXY = "httpsProxy";
public static final String PROXY_USERNAME = "proxyUsername";
public static final String PROXY_PASSWORD = "proxyPassword";
public static final String NO_PROXY = "noProxy";
}
| 8,383 |
0 |
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes
|
Create_ds/dubbo/dubbo-kubernetes/src/main/java/org/apache/dubbo/registry/kubernetes/util/KubernetesConfigUtils.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.kubernetes.util;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.StringUtils;
import java.util.Base64;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.ConfigBuilder;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.API_VERSION;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.CA_CERT_DATA;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.CA_CERT_FILE;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.CLIENT_CERT_DATA;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.CLIENT_CERT_FILE;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.CLIENT_KEY_ALGO;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.CLIENT_KEY_DATA;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.CLIENT_KEY_FILE;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.CLIENT_KEY_PASSPHRASE;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.CONNECTION_TIMEOUT;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.DEFAULT_MASTER_PLACEHOLDER;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.DEFAULT_MASTER_URL;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.HTTP2_DISABLE;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.HTTPS_PROXY;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.HTTP_PROXY;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.LOGGING_INTERVAL;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.NAMESPACE;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.NO_PROXY;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.OAUTH_TOKEN;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.PASSWORD;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.PROXY_PASSWORD;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.PROXY_USERNAME;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.REQUEST_TIMEOUT;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.TRUST_CERTS;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.USERNAME;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.USE_HTTPS;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.WATCH_RECONNECT_INTERVAL;
import static org.apache.dubbo.registry.kubernetes.util.KubernetesClientConst.WATCH_RECONNECT_LIMIT;
public class KubernetesConfigUtils {
public static Config createKubernetesConfig(URL url) {
// Init default config
Config base = Config.autoConfigure(null);
// replace config with parameters if presents
return new ConfigBuilder(base) //
.withMasterUrl(buildMasterUrl(url)) //
.withApiVersion(url.getParameter(API_VERSION, base.getApiVersion())) //
.withNamespace(url.getParameter(NAMESPACE, base.getNamespace())) //
.withUsername(url.getParameter(USERNAME, base.getUsername())) //
.withPassword(url.getParameter(PASSWORD, base.getPassword())) //
.withOauthToken(url.getParameter(OAUTH_TOKEN, base.getOauthToken())) //
.withCaCertFile(url.getParameter(CA_CERT_FILE, base.getCaCertFile())) //
.withCaCertData(url.getParameter(CA_CERT_DATA, decodeBase64(base.getCaCertData()))) //
.withClientKeyFile(url.getParameter(CLIENT_KEY_FILE, base.getClientKeyFile())) //
.withClientKeyData(url.getParameter(CLIENT_KEY_DATA, decodeBase64(base.getClientKeyData()))) //
.withClientCertFile(url.getParameter(CLIENT_CERT_FILE, base.getClientCertFile())) //
.withClientCertData(url.getParameter(CLIENT_CERT_DATA, decodeBase64(base.getClientCertData()))) //
.withClientKeyAlgo(url.getParameter(CLIENT_KEY_ALGO, base.getClientKeyAlgo())) //
.withClientKeyPassphrase(url.getParameter(CLIENT_KEY_PASSPHRASE, base.getClientKeyPassphrase())) //
.withConnectionTimeout(url.getParameter(CONNECTION_TIMEOUT, base.getConnectionTimeout())) //
.withRequestTimeout(url.getParameter(REQUEST_TIMEOUT, base.getRequestTimeout())) //
.withWatchReconnectInterval(
url.getParameter(WATCH_RECONNECT_INTERVAL, base.getWatchReconnectInterval())) //
.withWatchReconnectLimit(url.getParameter(WATCH_RECONNECT_LIMIT, base.getWatchReconnectLimit())) //
.withLoggingInterval(url.getParameter(LOGGING_INTERVAL, base.getLoggingInterval())) //
.withTrustCerts(url.getParameter(TRUST_CERTS, base.isTrustCerts())) //
.withHttp2Disable(url.getParameter(HTTP2_DISABLE, base.isHttp2Disable())) //
.withHttpProxy(url.getParameter(HTTP_PROXY, base.getHttpProxy())) //
.withHttpsProxy(url.getParameter(HTTPS_PROXY, base.getHttpsProxy())) //
.withProxyUsername(url.getParameter(PROXY_USERNAME, base.getProxyUsername())) //
.withProxyPassword(url.getParameter(PROXY_PASSWORD, base.getProxyPassword())) //
.withNoProxy(url.getParameter(NO_PROXY, base.getNoProxy())) //
.build();
}
private static String buildMasterUrl(URL url) {
if (DEFAULT_MASTER_PLACEHOLDER.equalsIgnoreCase(url.getHost())) {
return DEFAULT_MASTER_URL;
}
return (url.getParameter(USE_HTTPS, true) ? "https://" : "http://") + url.getHost() + ":" + url.getPort();
}
private static String decodeBase64(String str) {
return StringUtils.isNotEmpty(str) ? new String(Base64.getDecoder().decode(str)) : null;
}
}
| 8,384 |
0 |
Create_ds/dubbo/dubbo-native/src/test/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/test/java/org/apache/dubbo/aot/generate/ResourcePatternDescriberTest.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.aot.generate;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class ResourcePatternDescriberTest {
@Test
public void testToRegex() {
ResourcePatternDescriber describer = new ResourcePatternDescriber(
"META-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionInjector", null);
Assertions.assertEquals(
"\\QMETA-INF/dubbo/internal/org.apache.dubbo.common.extension.ExtensionInjector\\E",
describer.toRegex().toString());
}
}
| 8,385 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/MemberDescriber.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.aot.generate;
import java.lang.reflect.Member;
/**
* Base describer that describes the need for reflection on a {@link Member}.
*
*/
public class MemberDescriber {
private final String name;
protected MemberDescriber(String name) {
this.name = name;
}
/**
* Return the name of the member.
* @return the name
*/
public String getName() {
return this.name;
}
}
| 8,386 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeClassSourceWriter.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.aot.generate;
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.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Paths;
import java.util.List;
import java.util.regex.Matcher;
import org.apache.commons.io.FileUtils;
/**
* Write the Adaptive bytecode class dynamically generated.
*/
public class NativeClassSourceWriter {
public static final NativeClassSourceWriter INSTANCE = new NativeClassSourceWriter();
public void writeTo(List<Class<?>> classes, String generatedSources) {
classes.forEach(it -> {
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(true);
try {
String file = generatedSources
+ File.separator
+ it.getName().replaceAll("\\.", Matcher.quoteReplacement(File.separator));
String dir = Paths.get(file).getParent().toString();
FileUtils.forceMkdir(new File(dir));
code = LICENSED_STR + code + "\n";
String fileName = file + "$Adaptive.java";
FileUtils.write(new File(fileName), code, Charset.defaultCharset());
} catch (IOException e) {
throw new IllegalStateException("Failed to generated adaptive class sources", e);
}
});
}
private static final String LICENSED_STR =
"/*\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";
}
| 8,387 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/NativeConfigurationWriter.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.aot.generate;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Path;
import java.util.function.Consumer;
/**
* Write Write configuration metadata information in
* {@link ResourceConfigMetadataRepository} and {@link ReflectConfigMetadataRepository}
* as GraalVM native configuration.
* @see <a href="https://www.graalvm.org/latest/reference-manual/native-image/overview/BuildConfiguration/">Native Image Build Configuration</a>
*/
public class NativeConfigurationWriter {
private final Path basePath;
private final String groupId;
private final String artifactId;
public NativeConfigurationWriter(Path basePath, String groupId, String artifactId) {
this.basePath = basePath;
this.groupId = groupId;
this.artifactId = artifactId;
}
protected void writeTo(String fileName, Consumer<BasicJsonWriter> writer) {
try {
File file = createIfNecessary(fileName);
try (FileWriter out = new FileWriter(file)) {
writer.accept(createJsonWriter(out));
}
} catch (IOException ex) {
throw new IllegalStateException("Failed to write native configuration for " + fileName, ex);
}
}
private File createIfNecessary(String filename) throws IOException {
Path outputDirectory = this.basePath.resolve("META-INF").resolve("native-image");
if (this.groupId != null && this.artifactId != null) {
outputDirectory = outputDirectory.resolve(this.groupId).resolve(this.artifactId);
}
outputDirectory.toFile().mkdirs();
File file = outputDirectory.resolve(filename).toFile();
file.createNewFile();
return file;
}
public void writeReflectionConfig(ReflectConfigMetadataRepository repository) {
writeTo("reflect-config.json", writer -> ReflectionConfigWriter.INSTANCE.write(writer, repository));
}
public void writeResourceConfig(ResourceConfigMetadataRepository repository) {
writeTo("resource-config.json", writer -> ResourceConfigWriter.INSTANCE.write(writer, repository));
}
private BasicJsonWriter createJsonWriter(Writer out) {
return new BasicJsonWriter(out);
}
}
| 8,388 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ClassSourceScanner.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.aot.generate;
import org.apache.dubbo.common.extension.Adaptive;
import org.apache.dubbo.common.extension.SPI;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.AbstractConfig;
import org.apache.dubbo.rpc.model.FrameworkModel;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A scanner for processing and filtering specific types of classes
*/
public class ClassSourceScanner extends JarScanner {
public static final ClassSourceScanner INSTANCE = new ClassSourceScanner();
/**
* Filter out the spi classes with adaptive annotations
* from all the class collections that can be loaded.
* @return All spi classes with adaptive annotations
*/
public List<Class<?>> spiClassesWithAdaptive() {
Map<String, Class<?>> allClasses = getClasses();
List<Class<?>> spiClasses = new ArrayList<>(allClasses.values())
.stream()
.filter(it -> {
if (null == it) {
return false;
}
Annotation anno = it.getAnnotation(SPI.class);
if (null == anno) {
return false;
}
Optional<Method> optional = Arrays.stream(it.getMethods())
.filter(it2 -> it2.getAnnotation(Adaptive.class) != null)
.findAny();
return optional.isPresent();
})
.collect(Collectors.toList());
return spiClasses;
}
/**
* The required adaptive class.
* For example: LoadBalance$Adaptive.class
* @return adaptive class
*/
public Map<String, Class<?>> adaptiveClasses() {
List<String> res = spiClassesWithAdaptive().stream()
.map((c) -> c.getName() + "$Adaptive")
.collect(Collectors.toList());
return forNames(res);
}
/**
* The required configuration class, which is a subclass of AbstractConfig,
* but which excludes abstract classes.
* @return configuration class
*/
public List<Class<?>> configClasses() {
return getClasses().values().stream()
.filter(c -> AbstractConfig.class.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers()))
.collect(Collectors.toList());
}
public Map<String, Class<?>> distinctSpiExtensionClasses(Set<String> spiResource) {
Map<String, Class<?>> extensionClasses = new HashMap<>();
spiResource.forEach((fileName) -> {
Enumeration<URL> resources;
try {
resources = ClassLoader.getSystemResources(fileName);
if (resources != null) {
while (resources.hasMoreElements()) {
extensionClasses.putAll(loadResource(resources.nextElement()));
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
});
return extensionClasses;
}
/**
* Beans that need to be injected in advance in different ScopeModels.
* For example, the RouterSnapshotSwitcher that needs to be injected when ClusterScopeModelInitializer executes initializeFrameworkModel
* @return Beans that need to be injected in advance
*/
public List<Class<?>> scopeModelInitializer() {
List<Class<?>> classes = new ArrayList<>();
classes.addAll(FrameworkModel.defaultModel().getBeanFactory().getRegisteredClasses());
classes.addAll(FrameworkModel.defaultModel()
.defaultApplication()
.getBeanFactory()
.getRegisteredClasses());
classes.addAll(FrameworkModel.defaultModel()
.defaultApplication()
.getDefaultModule()
.getBeanFactory()
.getRegisteredClasses());
return classes.stream().distinct().collect(Collectors.toList());
}
private Map<String, Class<?>> loadResource(URL resourceUrl) {
Map<String, Class<?>> extensionClasses = new HashMap<>();
try {
List<String> newContentList = getResourceContent(resourceUrl);
String clazz;
for (String line : newContentList) {
try {
int i = line.indexOf('=');
if (i > 0) {
clazz = line.substring(i + 1).trim();
} else {
clazz = line;
}
if (StringUtils.isNotEmpty(clazz)) {
extensionClasses.put(clazz, getClasses().get(clazz));
}
} catch (Throwable t) {
}
}
} catch (Throwable t) {
}
return extensionClasses;
}
private List<String> getResourceContent(URL resourceUrl) throws IOException {
List<String> newContentList = new ArrayList<>();
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(resourceUrl.openStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
final int ci = line.indexOf('#');
if (ci >= 0) {
line = line.substring(0, ci);
}
line = line.trim();
if (line.length() > 0) {
newContentList.add(line);
}
}
} catch (IOException e) {
throw new RuntimeException(e.getMessage(), e);
}
return newContentList;
}
}
| 8,389 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/BasicJsonWriter.java
|
/*
* Copyright 2002-2023 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.aot.generate;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
/**
* Very basic json writer for the purposes of translating runtime hints to native
* configuration.
*
* @author Stephane Nicoll
*/
class BasicJsonWriter {
private final IndentingWriter writer;
/**
* Create a new instance with the specified indent value.
*
* @param writer the writer to use
* @param singleIndent the value of one indent
*/
public BasicJsonWriter(Writer writer, String singleIndent) {
this.writer = new IndentingWriter(writer, singleIndent);
}
/**
* Create a new instance using two whitespaces for the indent.
*
* @param writer the writer to use
*/
public BasicJsonWriter(Writer writer) {
this(writer, " ");
}
/**
* Write an object with the specified attributes. Each attribute is
* written according to its value type:
* <ul>
* <li>Map: write the value as a nested object</li>
* <li>List: write the value as a nested array</li>
* <li>Otherwise, write a single value</li>
* </ul>
*
* @param attributes the attributes of the object
*/
public void writeObject(Map<String, Object> attributes) {
writeObject(attributes, true);
}
/**
* Write an array with the specified items. Each item in the
* list is written either as a nested object or as an attribute
* depending on its type.
*
* @param items the items to write
* @see #writeObject(Map)
*/
public void writeArray(List<?> items) {
writeArray(items, true);
}
private void writeObject(Map<String, Object> attributes, boolean newLine) {
if (attributes.isEmpty()) {
this.writer.print("{ }");
} else {
this.writer.println("{").indented(writeAll(attributes.entrySet().iterator(),
entry -> writeAttribute(entry.getKey(), entry.getValue()))).print("}");
}
if (newLine) {
this.writer.println();
}
}
private void writeArray(List<?> items, boolean newLine) {
if (items.isEmpty()) {
this.writer.print("[ ]");
} else {
this.writer.println("[")
.indented(writeAll(items.iterator(), this::writeValue)).print("]");
}
if (newLine) {
this.writer.println();
}
}
private <T> Runnable writeAll(Iterator<T> it, Consumer<T> writer) {
return () -> {
while (it.hasNext()) {
writer.accept(it.next());
if (it.hasNext()) {
this.writer.println(",");
} else {
this.writer.println();
}
}
};
}
private void writeAttribute(String name, Object value) {
this.writer.print(quote(name) + ": ");
writeValue(value);
}
@SuppressWarnings("unchecked")
private void writeValue(Object value) {
if (value instanceof Map<?, ?>) {
writeObject((Map<String, Object>) value, false);
} else if (value instanceof List<?>) {
writeArray((List<?>) value, false);
} else if (value instanceof CharSequence) {
this.writer.print(quote(escape((CharSequence) value)));
} else if (value instanceof Boolean) {
this.writer.print(Boolean.toString((Boolean) value));
} else {
throw new IllegalStateException("unsupported type: " + value.getClass());
}
}
private String quote(String name) {
return "\"" + name + "\"";
}
private static String escape(CharSequence input) {
StringBuilder builder = new StringBuilder();
input.chars().forEach(c -> {
if (c == '"') {
builder.append("\\\"");
} else if (c == '\\') {
builder.append("\\\\");
} else if (c == '\b') {
builder.append("\\b");
} else if (c == '\f') {
builder.append("\\f");
} else if (c == '\n') {
builder.append("\\n");
} else if (c == '\r') {
builder.append("\\r");
} else if (c == '\t') {
builder.append("\\t");
} else if (c <= 0x1F) {
builder.append(String.format("\\u%04x", c));
} else {
builder.append((char) c);
}
});
return builder.toString();
}
static class IndentingWriter extends Writer {
private final Writer out;
private final String singleIndent;
private int level = 0;
private String currentIndent = "";
private boolean prependIndent = false;
IndentingWriter(Writer out, String singleIndent) {
this.out = out;
this.singleIndent = singleIndent;
}
/**
* Write the specified text.
*
* @param string the content to write
*/
public IndentingWriter print(String string) {
write(string.toCharArray(), 0, string.length());
return this;
}
/**
* Write the specified text and append a new line.
*
* @param string the content to write
*/
public IndentingWriter println(String string) {
write(string.toCharArray(), 0, string.length());
return println();
}
/**
* Write a new line.
*/
public IndentingWriter println() {
String separator = System.lineSeparator();
try {
this.out.write(separator.toCharArray(), 0, separator.length());
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
this.prependIndent = true;
return this;
}
/**
* Increase the indentation level and execute the {@link Runnable}. Decrease the
* indentation level on completion.
*
* @param runnable the code to execute within an extra indentation level
*/
public IndentingWriter indented(Runnable runnable) {
indent();
runnable.run();
return outdent();
}
/**
* Increase the indentation level.
*/
private IndentingWriter indent() {
this.level++;
return refreshIndent();
}
/**
* Decrease the indentation level.
*/
private IndentingWriter outdent() {
this.level--;
return refreshIndent();
}
private IndentingWriter refreshIndent() {
int count = Math.max(0, this.level);
StringBuilder str = new StringBuilder();
for (int i = 0; i < count; i++) {
str.append(this.singleIndent);
}
this.currentIndent = str.toString();
return this;
}
@Override
public void write(char[] chars, int offset, int length) {
try {
if (this.prependIndent) {
this.out.write(this.currentIndent.toCharArray(), 0, this.currentIndent.length());
this.prependIndent = false;
}
this.out.write(chars, offset, length);
} catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public void flush() throws IOException {
this.out.flush();
}
@Override
public void close() throws IOException {
this.out.close();
}
}
}
| 8,390 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigMetadataRepository.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.aot.generate;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class ResourceConfigMetadataRepository {
private final List<ResourcePatternDescriber> includes;
private final List<ResourcePatternDescriber> excludes;
private final Set<ResourceBundleDescriber> resourceBundles;
public ResourceConfigMetadataRepository() {
this.includes = new ArrayList<>();
this.excludes = new ArrayList<>();
this.resourceBundles = new LinkedHashSet<>();
}
public ResourceConfigMetadataRepository registerIncludesPatterns(String... patterns) {
for (String pattern : patterns) {
registerIncludesPattern(new ResourcePatternDescriber(pattern, null));
}
return this;
}
public ResourceConfigMetadataRepository registerIncludesPattern(ResourcePatternDescriber describer) {
this.includes.add(describer);
return this;
}
public ResourceConfigMetadataRepository registerExcludesPattern(ResourcePatternDescriber describer) {
this.excludes.add(describer);
return this;
}
public ResourceConfigMetadataRepository registerBundles(ResourceBundleDescriber describer) {
this.resourceBundles.add(describer);
return this;
}
public List<ResourcePatternDescriber> getIncludes() {
return includes;
}
public List<ResourcePatternDescriber> getExcludes() {
return excludes;
}
public Set<ResourceBundleDescriber> getResourceBundles() {
return resourceBundles;
}
}
| 8,391 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/JarScanner.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.aot.generate;
import java.io.File;
import java.net.JarURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* A scanner that scan the dependent jar packages
* to obtain the classes source and resources in them.
*/
public class JarScanner {
private static final String PACKAGE_NAME_PREFIX = "org/apache/dubbo";
private final Map<String, String> classNameCache;
private Map<String, Class<?>> classesCache;
private final List<String> resourcePathCache;
protected Map<String, Class<?>> getClasses() {
if (classesCache == null || classesCache.size() == 0) {
this.classesCache = forNames(classNameCache.values());
}
return classesCache;
}
public JarScanner() {
classNameCache = new HashMap<>();
resourcePathCache = new ArrayList<>();
scanURL(PACKAGE_NAME_PREFIX);
}
protected Map<String, Class<?>> forNames(Collection<String> classNames) {
Map<String, Class<?>> classes = new HashMap<>();
classNames.forEach((it) -> {
try {
Class<?> c = Class.forName(it);
classes.put(it, c);
} catch (Throwable ignored) {
}
});
return classes;
}
private void scanURL(String prefixName) {
try {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
Enumeration<URL> resources = classLoader.getResources(prefixName);
while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
String protocol = resource.getProtocol();
if ("file".equals(protocol)) {
scanFile(resource.getPath());
} else if ("jar".equals(protocol)) {
JarFile jar = ((JarURLConnection) resource.openConnection()).getJarFile();
scanJar(jar);
}
}
} catch (Throwable ex) {
throw new RuntimeException(ex);
}
}
private void scanFile(String resource) {
File directory = new File(resource);
File[] listFiles = directory.listFiles();
if (listFiles != null) {
for (File file : listFiles) {
System.out.println("scanFile: " + file.getPath());
if (file.isDirectory()) {
scanFile(file.getPath());
} else {
String path = file.getPath();
if (matchedDubboClasses(path)) {
classNameCache.put(path, toClassName(path));
}
}
}
}
}
private void scanJar(JarFile jar) {
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()) {
continue;
}
if (matchedDubboClasses(name)) {
classNameCache.put(name, toClassName(name));
} else {
resourcePathCache.add(name);
}
}
}
protected List<String> getResourcePath() {
return resourcePathCache;
}
private boolean matchedDubboClasses(String path) {
return path.startsWith(PACKAGE_NAME_PREFIX) && path.endsWith(".class");
}
private String toClassName(String path) {
return path.substring(0, path.length() - 6).replace(File.separator, ".");
}
}
| 8,392 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ExecutableMode.java
|
/*
* Copyright 2002-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.aot.generate;
import java.lang.reflect.Executable;
/**
* Represent the need of reflection for a given {@link Executable}.
*
* @author Stephane Nicoll
*/
public enum ExecutableMode {
/**
* Only retrieving the {@link Executable} and its metadata is required.
*/
INTROSPECT,
/**
* Full reflection support is required, including the ability to invoke
* the {@link Executable}.
*/
INVOKE;
/**
* Specify if this mode already includes the specified {@code other} mode.
* @param other the other mode to check
* @return {@code true} if this mode includes the other mode
*/
boolean includes(ExecutableMode other) {
return (other == null || this.ordinal() >= other.ordinal());
}
}
| 8,393 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/MemberCategory.java
|
/*
* Copyright 2002-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.aot.generate;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
/**
* Represent predefined {@linkplain Member members} groups.
*
* @author Andy Clement
* @author Sebastien Deleuze
* @author Stephane Nicoll
*/
public enum MemberCategory {
/**
* A category that represents public {@linkplain Field fields}.
* @see Class#getFields()
*/
PUBLIC_FIELDS,
/**
* A category that represents {@linkplain Class#getDeclaredFields() declared
* fields}, that is all fields defined by the class, but not inherited ones.
* @see Class#getDeclaredFields()
*/
DECLARED_FIELDS,
/**
* A category that defines public {@linkplain Constructor constructors} can
* be introspected, but not invoked.
* @see Class#getConstructors()
* @see ExecutableMode#INTROSPECT
*/
INTROSPECT_PUBLIC_CONSTRUCTORS,
/**
* A category that defines {@linkplain Class#getDeclaredConstructors() all
* constructors} can be introspected, but not invoked.
* @see Class#getDeclaredConstructors()
* @see ExecutableMode#INTROSPECT
*/
INTROSPECT_DECLARED_CONSTRUCTORS,
/**
* A category that defines public {@linkplain Constructor constructors} can
* be invoked.
* @see Class#getConstructors()
* @see ExecutableMode#INVOKE
*/
INVOKE_PUBLIC_CONSTRUCTORS,
/**
* A category that defines {@linkplain Class#getDeclaredConstructors() all
* constructors} can be invoked.
* @see Class#getDeclaredConstructors()
* @see ExecutableMode#INVOKE
*/
INVOKE_DECLARED_CONSTRUCTORS,
/**
* A category that defines public {@linkplain Method methods}, including
* inherited ones can be introspect, but not invoked.
* @see Class#getMethods()
* @see ExecutableMode#INTROSPECT
*/
INTROSPECT_PUBLIC_METHODS,
/**
* A category that defines {@linkplain Class#getDeclaredMethods() all
* methods}, excluding inherited ones can be introspected, but not invoked.
* @see Class#getDeclaredMethods()
* @see ExecutableMode#INTROSPECT
*/
INTROSPECT_DECLARED_METHODS,
/**
* A category that defines public {@linkplain Method methods}, including
* inherited ones can be invoked.
* @see Class#getMethods()
* @see ExecutableMode#INVOKE
*/
INVOKE_PUBLIC_METHODS,
/**
* A category that defines {@linkplain Class#getDeclaredMethods() all
* methods}, excluding inherited ones can be invoked.
* @see Class#getDeclaredMethods()
* @see ExecutableMode#INVOKE
*/
INVOKE_DECLARED_METHODS,
/**
* A category that represents public {@linkplain Class#getClasses() inner
* classes}. Contrary to other categories, this does not register any
* particular reflection for them but rather make sure they are available
* via a call to {@link Class#getClasses}.
*/
PUBLIC_CLASSES,
/**
* A category that represents all {@linkplain Class#getDeclaredClasses()
* inner classes}. Contrary to other categories, this does not register any
* particular reflection for them but rather make sure they are available
* via a call to {@link Class#getDeclaredClasses}.
*/
DECLARED_CLASSES;
}
| 8,394 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/TypeDescriber.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.aot.generate;
import java.util.Set;
/**
* A describer that describes the need for reflection on a type.
*/
public class TypeDescriber implements ConditionalDescriber {
private final String name;
private final String reachableType;
private final Set<FieldDescriber> fields;
private final Set<ExecutableDescriber> constructors;
private final Set<ExecutableDescriber> methods;
private final Set<MemberCategory> memberCategories;
public TypeDescriber(
String name,
String reachableType,
Set<FieldDescriber> fields,
Set<ExecutableDescriber> constructors,
Set<ExecutableDescriber> methods,
Set<MemberCategory> memberCategories) {
this.name = name;
this.reachableType = reachableType;
this.fields = fields;
this.constructors = constructors;
this.methods = methods;
this.memberCategories = memberCategories;
}
public String getName() {
return name;
}
public Set<MemberCategory> getMemberCategories() {
return memberCategories;
}
public Set<FieldDescriber> getFields() {
return fields;
}
public Set<ExecutableDescriber> getConstructors() {
return constructors;
}
public Set<ExecutableDescriber> getMethods() {
return methods;
}
@Override
public String getReachableType() {
return reachableType;
}
}
| 8,395 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ReflectConfigMetadataRepository.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.aot.generate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import static org.apache.dubbo.aot.generate.ExecutableMode.INVOKE;
public class ReflectConfigMetadataRepository {
List<TypeDescriber> types;
public ReflectConfigMetadataRepository() {
this.types = new ArrayList<>();
}
public ReflectConfigMetadataRepository registerSpiExtensionType(List<Class<?>> classes) {
types.addAll(classes.stream()
.filter(Objects::nonNull)
.map(this::buildTypeDescriberWithConstructor)
.collect(Collectors.toList()));
return this;
}
public ReflectConfigMetadataRepository registerAdaptiveType(List<Class<?>> classes) {
types.addAll(classes.stream()
.filter(Objects::nonNull)
.map(this::buildTypeDescriberWithConstructor)
.collect(Collectors.toList()));
return this;
}
public ReflectConfigMetadataRepository registerBeanType(List<Class<?>> classes) {
types.addAll(classes.stream()
.filter(Objects::nonNull)
.map(this::buildTypeDescriberWithConstructor)
.collect(Collectors.toList()));
return this;
}
public ReflectConfigMetadataRepository registerConfigType(List<Class<?>> classes) {
types.addAll(classes.stream()
.filter(Objects::nonNull)
.map(this::buildTypeDescriberWithConstructor)
.collect(Collectors.toList()));
return this;
}
private TypeDescriber buildTypeDescriberWithConstructor(Class<?> c) {
Set<ExecutableDescriber> constructors = Arrays.stream(c.getConstructors())
.map((constructor) -> new ExecutableDescriber(constructor, INVOKE))
.collect(Collectors.toSet());
Set<MemberCategory> memberCategories = new HashSet<>();
memberCategories.add(MemberCategory.INVOKE_PUBLIC_METHODS);
return new TypeDescriber(c.getName(), null, new HashSet<>(), constructors, new HashSet<>(), memberCategories);
}
public List<TypeDescriber> getTypes() {
return types;
}
}
| 8,396 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/AotProcessor.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.aot.generate;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
/**
* generate related self-adaptive code (native image does not support dynamic code generation. Therefore, code needs to be generated before compilation)
*/
public class AotProcessor {
public static void main(String[] args) {
String generatedSources = args[1];
List<Class<?>> classes = ClassSourceScanner.INSTANCE.spiClassesWithAdaptive();
NativeClassSourceWriter.INSTANCE.writeTo(classes, generatedSources);
NativeConfigurationWriter writer = new NativeConfigurationWriter(Paths.get(args[2]), args[4], args[5]);
ResourceConfigMetadataRepository resourceRepository = new ResourceConfigMetadataRepository();
resourceRepository.registerIncludesPatterns(
ResourceScanner.INSTANCE.distinctSpiResource().toArray(new String[] {}));
resourceRepository.registerIncludesPatterns(
ResourceScanner.INSTANCE.distinctSecurityResource().toArray(new String[] {}));
writer.writeResourceConfig(resourceRepository);
ReflectConfigMetadataRepository reflectRepository = new ReflectConfigMetadataRepository();
reflectRepository
.registerSpiExtensionType(new ArrayList<>(ClassSourceScanner.INSTANCE
.distinctSpiExtensionClasses(ResourceScanner.INSTANCE.distinctSpiResource())
.values()))
.registerAdaptiveType(new ArrayList<>(
ClassSourceScanner.INSTANCE.adaptiveClasses().values()))
.registerBeanType(ClassSourceScanner.INSTANCE.scopeModelInitializer())
.registerConfigType(ClassSourceScanner.INSTANCE.configClasses());
writer.writeReflectionConfig(reflectRepository);
}
}
| 8,397 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceScanner.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.aot.generate;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A scanner for processing and filtering specific resource.
*/
public class ResourceScanner extends JarScanner {
private static final String DUBBO_INTERNAL_RESOURCE_DIRECTORY = "META-INF/dubbo/internal/";
private static final String DUBBO_RESOURCE_DIRECTORY = "META-INF/dubbo/";
private static final String SERVICES_RESOURCE_DIRECTORY = "META-INF/services/";
private static final String SECURITY_RESOURCE_DIRECTORY = "security/";
public static final ResourceScanner INSTANCE = new ResourceScanner();
public Set<String> distinctSpiResource() {
return getResourcePath().stream()
.distinct()
.filter(this::matchedSpiResource)
.collect(Collectors.toSet());
}
public Set<String> distinctSecurityResource() {
return getResourcePath().stream()
.distinct()
.filter(this::matchedSecurityResource)
.collect(Collectors.toSet());
}
private boolean matchedSecurityResource(String path) {
return path.startsWith(SECURITY_RESOURCE_DIRECTORY);
}
private boolean matchedSpiResource(String path) {
return path.startsWith(DUBBO_INTERNAL_RESOURCE_DIRECTORY)
|| path.startsWith(DUBBO_RESOURCE_DIRECTORY)
|| path.startsWith(SERVICES_RESOURCE_DIRECTORY);
}
}
| 8,398 |
0 |
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot
|
Create_ds/dubbo/dubbo-native/src/main/java/org/apache/dubbo/aot/generate/ResourceConfigWriter.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.aot.generate;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Write a {@link ResourceConfigMetadataRepository} to the JSON output expected by the GraalVM
* {@code native-image} compiler, typically named {@code resource-config.json}.
*/
public class ResourceConfigWriter {
public static final ResourceConfigWriter INSTANCE = new ResourceConfigWriter();
public void write(BasicJsonWriter writer, ResourceConfigMetadataRepository repository) {
Map<String, Object> attributes = new LinkedHashMap<>();
addIfNotEmpty(attributes, "resources", toAttributes(repository.getIncludes(), repository.getExcludes()));
handleResourceBundles(attributes, repository.getResourceBundles());
writer.writeObject(attributes);
}
private Map<String, Object> toAttributes(
List<ResourcePatternDescriber> includes, List<ResourcePatternDescriber> excludes) {
Map<String, Object> attributes = new LinkedHashMap<>();
addIfNotEmpty(
attributes,
"includes",
includes.stream().distinct().map(this::toAttributes).collect(Collectors.toList()));
addIfNotEmpty(
attributes,
"excludes",
excludes.stream().distinct().map(this::toAttributes).collect(Collectors.toList()));
return attributes;
}
private void handleResourceBundles(
Map<String, Object> attributes, Set<ResourceBundleDescriber> resourceBundleDescribers) {
addIfNotEmpty(
attributes,
"bundles",
resourceBundleDescribers.stream().map(this::toAttributes).collect(Collectors.toList()));
}
private Map<String, Object> toAttributes(ResourceBundleDescriber describer) {
Map<String, Object> attributes = new LinkedHashMap<>();
handleCondition(attributes, describer);
attributes.put("name", describer.getName());
return attributes;
}
private Map<String, Object> toAttributes(ResourcePatternDescriber describer) {
Map<String, Object> attributes = new LinkedHashMap<>();
handleCondition(attributes, describer);
attributes.put("pattern", describer.toRegex().toString());
return attributes;
}
private void addIfNotEmpty(Map<String, Object> attributes, String name, Object value) {
if (value instanceof Collection<?>) {
if (!((Collection<?>) value).isEmpty()) {
attributes.put(name, value);
}
} else if (value instanceof Map<?, ?>) {
if (!((Map<?, ?>) value).isEmpty()) {
attributes.put(name, value);
}
} else if (value != null) {
attributes.put(name, value);
}
}
private void handleCondition(Map<String, Object> attributes, ConditionalDescriber conditionalDescriber) {
if (conditionalDescriber.getReachableType() != null) {
Map<String, Object> conditionAttributes = new LinkedHashMap<>();
conditionAttributes.put("typeReachable", conditionalDescriber.getReachableType());
attributes.put("condition", conditionAttributes);
}
}
}
| 8,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.