repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/router/RouterService.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/router/RouterService.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.router;
import com.webank.ai.fate.register.loadbalance.LoadBalanceModel;
import com.webank.ai.fate.register.url.URL;
import java.util.List;
public interface RouterService {
List<URL> router(URL url, LoadBalanceModel loadBalanceModel);
List<URL> router(URL url);
List<URL> router(String project, String environment, String serviceName);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/router/AbstractRouterService.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/router/AbstractRouterService.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.router;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.webank.ai.fate.register.common.AbstractRegistry;
import com.webank.ai.fate.register.common.Constants;
import com.webank.ai.fate.register.common.RouterMode;
import com.webank.ai.fate.register.interfaces.Registry;
import com.webank.ai.fate.register.loadbalance.DefaultLoadBalanceFactory;
import com.webank.ai.fate.register.loadbalance.LoadBalanceModel;
import com.webank.ai.fate.register.loadbalance.LoadBalancer;
import com.webank.ai.fate.register.loadbalance.LoadBalancerFactory;
import com.webank.ai.fate.register.url.CollectionUtils;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public abstract class AbstractRouterService implements RouterService {
protected LoadBalancerFactory loadBalancerFactory = new DefaultLoadBalanceFactory();
protected AbstractRegistry registry;
Logger logger = LoggerFactory.getLogger(AbstractRouterService.class);
public Registry getRegistry() {
return registry;
}
public void setRegistry(AbstractRegistry registry) {
this.registry = registry;
}
@Override
public List<URL> router(URL url, LoadBalanceModel loadBalanceModel) {
LoadBalancer loadBalancer = loadBalancerFactory.getLoaderBalancer(loadBalanceModel);
return doRouter(url, loadBalancer);
}
@Override
public List<URL> router(String project, String environment, String serviceName) {
Preconditions.checkArgument(StringUtils.isNotEmpty(project));
Preconditions.checkArgument(StringUtils.isNotEmpty(environment));
Preconditions.checkArgument(StringUtils.isNotEmpty(serviceName));
LoadBalancer loadBalancer = loadBalancerFactory.getLoaderBalancer(LoadBalanceModel.random_with_weight);
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(project).append("/").append(environment).append("/").append(serviceName);
URL paramUrl = URL.valueOf(stringBuilder.toString());
return doRouter(paramUrl, loadBalancer);
}
public abstract List<URL> doRouter(URL url, LoadBalancer loadBalancer);
@Override
public List<URL> router(URL url) {
return this.router(url, LoadBalanceModel.random);
}
protected List<URL> filterVersion(List<URL> urls, long version) {
/*if (StringUtils.isEmpty(version)) {
return urls;
}*/
final List<URL> resultUrls = Lists.newArrayList();
if (CollectionUtils.isNotEmpty(urls)) {
urls.forEach(url -> {
String routerMode = url.getParameter(Constants.ROUTER_MODE);
try {
if (RouterMode.ALL_ALLOWED.name().equals(routerMode)) {
resultUrls.add(url);
return;
}
String targetVersion = url.getParameter(Constants.VERSION_KEY);
if (StringUtils.isBlank(targetVersion)) {
return;
}
long targetVersionValue = Long.parseLong(targetVersion);
long versionValue = version;
if (targetVersionValue != 0 && versionValue != 0) {
if (String.valueOf(RouterMode.VERSION_BIGER).equalsIgnoreCase(routerMode)) {
if (versionValue > targetVersionValue) {
resultUrls.add(url);
}
} else if (String.valueOf(RouterMode.VERSION_BIGTHAN_OR_EQUAL).equalsIgnoreCase(routerMode)) {
if (versionValue >= targetVersionValue) {
resultUrls.add(url);
}
} else if (String.valueOf(RouterMode.VERSION_SMALLER).equalsIgnoreCase(routerMode)) {
if (versionValue < targetVersionValue) {
resultUrls.add(url);
}
} else if (String.valueOf(RouterMode.VERSION_EQUALS).equalsIgnoreCase(routerMode)) {
if (versionValue == targetVersionValue) {
resultUrls.add(url);
}
} else {
resultUrls.add(url);
}
}
} catch (Exception e) {
throw new IllegalArgumentException("parse version error");
}
});
}
return resultUrls;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/router/DefaultRouterService.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/router/DefaultRouterService.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.router;
import com.webank.ai.fate.register.common.Constants;
import com.webank.ai.fate.register.loadbalance.LoadBalancer;
import com.webank.ai.fate.register.url.CollectionUtils;
import com.webank.ai.fate.register.url.URL;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class DefaultRouterService extends AbstractRouterService {
@Override
public List<URL> doRouter(URL url, LoadBalancer loadBalancer) {
List<URL> urls = registry.getCacheUrls(url);
if (CollectionUtils.isEmpty(urls)) {
return null;
}
urls = filterEmpty(urls);
String version = url.getParameter(Constants.VERSION_KEY);
if (CollectionUtils.isNotEmpty(urls) && StringUtils.isNotBlank(version)) {
urls = filterVersion(urls, Long.parseLong(version));
}
List<URL> resultUrls = loadBalancer.select(urls);
if (logger.isDebugEnabled()) {
logger.debug("router service return urls {}", resultUrls);
}
return resultUrls;
}
private List<URL> filterEmpty(List<URL> urls) {
List<URL> resultList = new ArrayList<>();
if (urls != null) {
urls.forEach(url -> {
if (!url.getProtocol().equalsIgnoreCase(Constants.EMPTY_PROTOCOL)) {
resultList.add(url);
}
});
}
return resultList;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedUnsubscribedTask.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedUnsubscribedTask.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.task;
import com.webank.ai.fate.register.common.FailbackRegistry;
import com.webank.ai.fate.register.interfaces.NotifyListener;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.serving.core.timer.Timeout;
/**
* FailedUnsubscribedTask
*/
public final class FailedUnsubscribedTask extends AbstractRetryTask {
private static final String NAME = "retry unsubscribe";
private final NotifyListener listener;
public FailedUnsubscribedTask(URL url, FailbackRegistry registry, NotifyListener listener) {
super(url, registry, NAME);
if (listener == null) {
throw new IllegalArgumentException();
}
this.listener = listener;
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.unsubscribe(url, listener);
registry.removeFailedUnsubscribedTask(url, listener);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedSubProjectTask.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedSubProjectTask.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.task;
import com.webank.ai.fate.register.common.FailbackRegistry;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.serving.core.timer.Timeout;
public class FailedSubProjectTask extends AbstractRetryTask {
private static final String NAME = "retry subscribe project";
public FailedSubProjectTask(URL url, FailbackRegistry registry) {
super(url, registry, NAME);
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.subProject(url.getProject());
registry.removeFailedSubscribedProjectTask(url.getProject());
}
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/task/AbstractRetryTask.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/task/AbstractRetryTask.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.task;
import com.webank.ai.fate.register.common.Constants;
import com.webank.ai.fate.register.common.FailbackRegistry;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.serving.core.timer.Timeout;
import com.webank.ai.fate.serving.core.timer.Timer;
import com.webank.ai.fate.serving.core.timer.TimerTask;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.TimeUnit;
public abstract class AbstractRetryTask implements TimerTask {
public static final Logger logger = LoggerFactory.getLogger(AbstractRetryTask.class);
private static int DEFAULT_REGISTRY_RETRY_PERIOD = 5 * 1000;
private static String REGISTRY_RETRY_TIMES_KEY = "retry.times";
/**
* url for retry task
*/
protected final URL url;
/**
* registry for this task
*/
protected final FailbackRegistry registry;
/**
* retry period
*/
final long retryPeriod;
/**
* define the most retry times
*/
private final int retryTimes;
/**
* task name for this task
*/
private final String taskName;
/**
* times of retry.
* retry task is execute in single thread so that the times is not need volatile.
*/
private int times = 1;
private volatile boolean cancel;
AbstractRetryTask(URL url, FailbackRegistry registry, String taskName) {
if (url == null || StringUtils.isBlank(taskName)) {
throw new IllegalArgumentException();
}
this.url = url;
this.registry = registry;
this.taskName = taskName;
cancel = false;
this.retryPeriod = url.getParameter(Constants.REGISTRY_FILESAVE_SYNC_KEY, DEFAULT_REGISTRY_RETRY_PERIOD);
this.retryTimes = url.getParameter(REGISTRY_RETRY_TIMES_KEY, Integer.MAX_VALUE);
}
public void cancel() {
cancel = true;
}
public boolean isCancel() {
return cancel;
}
protected void reput(Timeout timeout, long tick) {
if (timeout == null) {
throw new IllegalArgumentException();
}
Timer timer = timeout.timer();
if (timer.isStop() || timeout.isCancelled() || isCancel()) {
return;
}
times++;
timer.newTimeout(timeout.task(), tick, TimeUnit.MILLISECONDS);
}
@Override
public void run(Timeout timeout) throws Exception {
if (logger.isDebugEnabled()) {
logger.debug("retry task begin");
}
long begin = System.currentTimeMillis();
if (timeout.isCancelled() || timeout.timer().isStop() || isCancel()) {
// other thread cancel this timeout or stop the timer.
return;
}
if (times > retryTimes) {
// reach the most times of retry.
logger.error("Final failed to execute task " + taskName + ", url: " + url + ", retry " + retryTimes + " times.");
return;
}
if (logger.isDebugEnabled()) {
logger.debug(taskName + " : " + url.getProject());
}
try {
doRetry(url, registry, timeout);
} catch (Throwable t) { // Ignore all the exceptions and wait for the next retry
logger.error("Failed to execute task " + taskName + ", url: " + url + ", waiting for again, cause:" + t.getMessage(), t);
// reput this task when catch exception.
reput(timeout, retryPeriod);
} finally {
long end = System.currentTimeMillis();
if (logger.isDebugEnabled()) {
logger.debug("retry task cost " + (end - begin));
}
}
}
/**
* doRetry
*
* @param url
* @param registry
* @param timeout
*/
protected abstract void doRetry(URL url, FailbackRegistry registry, Timeout timeout);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedUnregisteredTask.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedUnregisteredTask.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.task;
import com.webank.ai.fate.register.common.FailbackRegistry;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.serving.core.timer.Timeout;
/**
* FailedUnregisteredTask
*/
public final class FailedUnregisteredTask extends AbstractRetryTask {
private static final String NAME = "retry unregister";
public FailedUnregisteredTask(URL url, FailbackRegistry registry) {
super(url, registry, NAME);
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doUnregister(url);
registry.removeFailedUnregisteredTask(url);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedSubscribedTask.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedSubscribedTask.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.task;
import com.webank.ai.fate.register.common.FailbackRegistry;
import com.webank.ai.fate.register.interfaces.NotifyListener;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.serving.core.timer.Timeout;
/**
* FailedSubscribedTask
*/
public final class FailedSubscribedTask extends AbstractRetryTask {
private static final String NAME = "retry subscribe";
private final NotifyListener listener;
public FailedSubscribedTask(URL url, FailbackRegistry registry, NotifyListener listener) {
super(url, registry, NAME);
if (listener == null) {
throw new IllegalArgumentException();
}
this.listener = listener;
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doSubscribe(url, listener);
registry.removeFailedSubscribedTask(url, listener);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedNotifiedTask.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedNotifiedTask.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.task;
import com.webank.ai.fate.register.common.FailbackRegistry;
import com.webank.ai.fate.register.interfaces.NotifyListener;
import com.webank.ai.fate.register.url.CollectionUtils;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.serving.core.timer.Timeout;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* FailedNotifiedTask
*/
public final class FailedNotifiedTask extends AbstractRetryTask {
private static final String NAME = "retry subscribe";
private final NotifyListener listener;
private final List<URL> urls = new CopyOnWriteArrayList<>();
public FailedNotifiedTask(URL url, NotifyListener listener) {
super(url, null, NAME);
if (listener == null) {
throw new IllegalArgumentException();
}
this.listener = listener;
}
public void addUrlToRetry(List<URL> urls) {
if (CollectionUtils.isEmpty(urls)) {
return;
}
this.urls.addAll(urls);
}
public void removeRetryUrl(List<URL> urls) {
this.urls.removeAll(urls);
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
if (CollectionUtils.isNotEmpty(urls)) {
listener.notify(urls);
urls.clear();
}
reput(timeout, retryPeriod);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedRegisteredTask.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedRegisteredTask.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.task;
import com.webank.ai.fate.register.common.FailbackRegistry;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.serving.core.timer.Timeout;
/**
* FailedRegisteredTask
*/
public final class FailedRegisteredTask extends AbstractRetryTask {
private static final String NAME = "retry register";
public FailedRegisteredTask(URL url, FailbackRegistry registry) {
super(url, registry, NAME);
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doRegister(url);
registry.removeFailedRegisteredTask(url);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedRegisterComponentTask.java | fate-serving-register/src/main/java/com/webank/ai/fate/register/task/FailedRegisterComponentTask.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.register.task;
import com.webank.ai.fate.register.common.FailbackRegistry;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.serving.core.timer.Timeout;
public class FailedRegisterComponentTask extends AbstractRetryTask {
private static final String NAME = "retry register component";
public FailedRegisterComponentTask(URL url, FailbackRegistry registry) {
super(url, registry, NAME);
}
@Override
protected void doRetry(URL url, FailbackRegistry registry, Timeout timeout) {
registry.doRegisterComponent(url);
registry.removeFailedRegisterComponentTask(url);
}
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-sdk/src/main/java/com/webank/ai/fate/serving/sdk/client/RegistedClient.java | fate-serving-sdk/src/main/java/com/webank/ai/fate/serving/sdk/client/RegistedClient.java | package com.webank.ai.fate.serving.sdk.client;
import com.google.common.base.Preconditions;
import com.google.protobuf.ByteString;
import com.webank.ai.fate.api.serving.InferenceServiceGrpc;
import com.webank.ai.fate.api.serving.InferenceServiceProto;
import com.webank.ai.fate.register.router.DefaultRouterService;
import com.webank.ai.fate.register.router.RouterService;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.core.bean.BatchInferenceRequest;
import com.webank.ai.fate.serving.core.bean.BatchInferenceResult;
import com.webank.ai.fate.serving.core.bean.InferenceRequest;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.List;
public class RegistedClient extends SimpleClient{
protected RouterService routerService;
private String registerAddress;
public RegistedClient(String address){
Preconditions.checkArgument(StringUtils.isNotBlank(address), "register address is blank");
this.registerAddress= address;
ZookeeperRegistry zookeeperRegistry = ZookeeperRegistry.createRegistry(address, ClIENT_PROJECT, ENVIRONMENT, port);
zookeeperRegistry.subProject(PROJECT);
DefaultRouterService defaultRouterService = new DefaultRouterService();
defaultRouterService.setRegistry(zookeeperRegistry);
this.routerService = defaultRouterService;
}
public ReturnResult singleInference(InferenceRequest inferenceRequest, int timeout) throws Exception {
Preconditions.checkArgument(inferenceRequest != null, "inferenceRequest is null");
Preconditions.checkArgument(this.routerService != null, "router service is null, please call setRegistryAddress(String address) to config registry");
Preconditions.checkArgument(StringUtils.isNotEmpty(inferenceRequest.getServiceId()));
List<URL> urls = routerService.router(PROJECT, inferenceRequest.getServiceId(), SINGLE_INFERENCE);
Preconditions.checkArgument(CollectionUtils.isNotEmpty(urls), "serviceId " + inferenceRequest.getServiceId() + " found no url in zk");
URL url = urls.get(0);
InferenceServiceProto.InferenceMessage.Builder inferenceMessageBuilder = InferenceServiceProto.InferenceMessage.newBuilder();
inferenceMessageBuilder.setBody(ByteString.copyFrom(JsonUtil.object2Json(inferenceRequest), "UTF-8"));
InferenceServiceProto.InferenceMessage inferenceMessage = inferenceMessageBuilder.build();
InferenceServiceGrpc.InferenceServiceBlockingStub blockingStub = this.getInferenceServiceBlockingStub(url.getHost(), url.getPort(),timeout);
InferenceServiceProto.InferenceMessage result = blockingStub.inference(inferenceMessage);
Preconditions.checkArgument(result != null && result.getBody() != null);
return JsonUtil.json2Object(result.getBody().toByteArray(), ReturnResult.class);
}
public BatchInferenceResult batchInference(BatchInferenceRequest batchInferenceRequest) throws Exception {
return batchInference(batchInferenceRequest,timeout);
}
public BatchInferenceResult batchInference(BatchInferenceRequest batchInferenceRequest,int timeout) throws Exception {
Preconditions.checkArgument(batchInferenceRequest != null, "batchInferenceRequest is null");
Preconditions.checkArgument(this.routerService != null, "router service is null, please call setRegistryAddress(String address) to config registry");
Preconditions.checkArgument(StringUtils.isNotEmpty(batchInferenceRequest.getServiceId()));
List<URL> urls = routerService.router(PROJECT, batchInferenceRequest.getServiceId(), BATCH_INFERENCE);
Preconditions.checkArgument(CollectionUtils.isNotEmpty(urls), "serviceId " + batchInferenceRequest.getServiceId() + " found no url in zk");
URL url = urls.get(0);
InferenceServiceProto.InferenceMessage.Builder inferenceMessageBuilder = InferenceServiceProto.InferenceMessage.newBuilder();
inferenceMessageBuilder.setBody(ByteString.copyFrom(JsonUtil.object2Json(batchInferenceRequest), "UTF-8"));
InferenceServiceGrpc.InferenceServiceBlockingStub blockingStub = this.getInferenceServiceBlockingStub(url.getHost(), url.getPort(),timeout);
InferenceServiceProto.InferenceMessage result = blockingStub.batchInference(inferenceMessageBuilder.build());
Preconditions.checkArgument(result != null && result.getBody() != null);
return JsonUtil.json2Object(result.getBody().toByteArray(), BatchInferenceResult.class);
}
public ReturnResult singleInference(InferenceRequest inferenceRequest) throws Exception {
return singleInference(inferenceRequest,timeout);
}
public String getRegisterAddress() {
return registerAddress;
}
public void setRegisterAddress(String registerAddress) {
this.registerAddress = registerAddress;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-sdk/src/main/java/com/webank/ai/fate/serving/sdk/client/SimpleClient.java | fate-serving-sdk/src/main/java/com/webank/ai/fate/serving/sdk/client/SimpleClient.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.sdk.client;
import com.google.common.base.Preconditions;
import com.google.protobuf.ByteString;
import com.webank.ai.fate.api.serving.InferenceServiceGrpc;
import com.webank.ai.fate.api.serving.InferenceServiceProto;
import com.webank.ai.fate.serving.core.bean.*;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import io.grpc.ManagedChannel;
import org.apache.commons.lang3.StringUtils;
import java.util.concurrent.TimeUnit;
public class SimpleClient {
static final String PROJECT = "serving";
static final String SINGLE_INFERENCE = "inference";
static final String BATCH_INFERENCE = "batchInference";
static final String ClIENT_PROJECT = "client";
static final int port = 36578;
static final String ENVIRONMENT = "online";
int timeout = 3000;
protected GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
public SimpleClient setTimeout(int timeoutMs){
Preconditions.checkArgument(this.timeout>0, "timeout must bigger than 0 ms");
this.timeout = timeoutMs;
return this;
}
public ReturnResult singleInference(String host, int port, InferenceRequest inferenceRequest) throws Exception {
return singleInference(host,port,inferenceRequest,timeout);
}
public ReturnResult singleInference(String host, int port, InferenceRequest inferenceRequest,int timeout) throws Exception {
Preconditions.checkArgument(inferenceRequest != null, "inferenceRequest is null");
Preconditions.checkArgument(StringUtils.isNotEmpty(inferenceRequest.getServiceId()));
InferenceServiceProto.InferenceMessage.Builder inferenceMessageBuilder = InferenceServiceProto.InferenceMessage.newBuilder();
inferenceMessageBuilder.setBody(ByteString.copyFrom(JsonUtil.object2Json(inferenceRequest), "UTF-8"));
InferenceServiceProto.InferenceMessage inferenceMessage = inferenceMessageBuilder.build();
InferenceServiceGrpc.InferenceServiceBlockingStub blockingStub = this.getInferenceServiceBlockingStub(host, port,timeout);
InferenceServiceProto.InferenceMessage result = blockingStub.inference(inferenceMessage);
Preconditions.checkArgument(result != null && result.getBody() != null);
return JsonUtil.json2Object(result.getBody().toByteArray(), ReturnResult.class);
}
public BatchInferenceResult batchInference(String host, int port, BatchInferenceRequest batchInferenceRequest) throws Exception {
return batchInference( host, port, batchInferenceRequest, timeout);
}
public BatchInferenceResult batchInference(String host, int port, BatchInferenceRequest batchInferenceRequest,int timeout) throws Exception {
Preconditions.checkArgument(batchInferenceRequest != null, "batchInferenceRequest is null");
Preconditions.checkArgument(StringUtils.isNotEmpty(batchInferenceRequest.getServiceId()));
InferenceServiceProto.InferenceMessage.Builder inferenceMessageBuilder = InferenceServiceProto.InferenceMessage.newBuilder();
inferenceMessageBuilder.setBody(ByteString.copyFrom(JsonUtil.object2Json(batchInferenceRequest), "UTF-8"));
InferenceServiceGrpc.InferenceServiceBlockingStub blockingStub = this.getInferenceServiceBlockingStub(host, port, timeout);
InferenceServiceProto.InferenceMessage result = blockingStub.batchInference(inferenceMessageBuilder.build());
Preconditions.checkArgument(result != null && result.getBody() != null);
return JsonUtil.json2Object(result.getBody().toByteArray(), BatchInferenceResult.class);
}
protected InferenceServiceGrpc.InferenceServiceBlockingStub getInferenceServiceBlockingStub(String host, int port,int timeout) throws Exception {
Preconditions.checkArgument(StringUtils.isNotBlank(host), "host is blank");
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
InferenceServiceGrpc.InferenceServiceBlockingStub blockingStub = InferenceServiceGrpc.newBlockingStub(managedChannel);
return blockingStub.withDeadlineAfter(timeout, TimeUnit.MILLISECONDS);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-sdk/src/main/java/com/webank/ai/fate/serving/sdk/client/SimpleClientExample.java | fate-serving-sdk/src/main/java/com/webank/ai/fate/serving/sdk/client/SimpleClientExample.java | package com.webank.ai.fate.serving.sdk.client;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.webank.ai.fate.serving.core.bean.BatchInferenceRequest;
import com.webank.ai.fate.serving.core.bean.BatchInferenceResult;
import com.webank.ai.fate.serving.core.bean.InferenceRequest;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* 该类主要演示不带注册中心的客户端如何使用
*/
public class SimpleClientExample {
static SimpleClient client =ClientBuilder.getClientWithoutRegister();
/**
* 构建单笔预测请求
* @return
*/
static InferenceRequest buildInferenceRequest(){
InferenceRequest inferenceRequest = new InferenceRequest();
inferenceRequest.setServiceId("lr-test");
Map<String,Object> featureData = Maps.newHashMap();
featureData.put("x0", 0.100016);
featureData.put("x1", 1.210);
featureData.put("x2", 2.321);
featureData.put("x3", 3.432);
featureData.put("x4", 4.543);
featureData.put("x5", 5.654);
featureData.put("x6", 5.654);
featureData.put("x7", 0.102345);
inferenceRequest.setFeatureData(featureData);
Map<String,Object> sendToRemote = Maps.newHashMap();
sendToRemote.put("device_id","helloworld");
/**
* sendToRemote 数据会发送到host ,需要谨慎检查是否是敏感数据
*/
inferenceRequest.setSendToRemoteFeatureData(sendToRemote);
return inferenceRequest;
}
/**
* 构建批量预测请求
* @return
*/
static BatchInferenceRequest buildBatchInferenceRequest(){
BatchInferenceRequest batchInferenceRequest = new BatchInferenceRequest();
batchInferenceRequest.setServiceId("lr-test");
List<BatchInferenceRequest.SingleInferenceData> singleInferenceDataList = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
BatchInferenceRequest.SingleInferenceData singleInferenceData = new BatchInferenceRequest.SingleInferenceData();
singleInferenceData.getFeatureData().put("x0", 0.100016);
singleInferenceData.getFeatureData().put("x1", 1.210);
singleInferenceData.getFeatureData().put("x2", 2.321);
singleInferenceData.getFeatureData().put("x3", 3.432);
singleInferenceData.getFeatureData().put("x4", 4.543);
singleInferenceData.getFeatureData().put("x5", 5.654);
singleInferenceData.getFeatureData().put("x6", 5.654);
singleInferenceData.getFeatureData().put("x7", 0.102345);
/**
* sendToRemote 数据会发送到host ,需要谨慎检查是否是敏感数据
*/
singleInferenceData.getSendToRemoteFeatureData().put("device_id","helloworld");
/**
* 这里的序号从0开始 ,序号很重要,不可以重复
*/
singleInferenceData.setIndex(i);
singleInferenceDataList.add(singleInferenceData);
}
batchInferenceRequest.setBatchDataList(singleInferenceDataList);
batchInferenceRequest.setServiceId("lr-test");
return batchInferenceRequest;
}
public static void main(String[] args) throws IOException, InterruptedException {
InferenceRequest inferenceRequest = buildInferenceRequest();
BatchInferenceRequest batchInferenceRequest = buildBatchInferenceRequest();
try {
/**
* 使用ip端口的方式进行rpc调用
*/
ReturnResult returnResult2 = client.singleInference("localhost",8000,inferenceRequest);
System.err.println(returnResult2);
/**
* 指定ip端口批量预测
*/
BatchInferenceResult BatchInferenceResult2 = client.batchInference("localhost",8000,batchInferenceRequest);
System.err.println(BatchInferenceResult2);
} catch (Exception e) {
e.printStackTrace();
}
System.err.println("over");
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-sdk/src/main/java/com/webank/ai/fate/serving/sdk/client/RegisterClientExample.java | fate-serving-sdk/src/main/java/com/webank/ai/fate/serving/sdk/client/RegisterClientExample.java | package com.webank.ai.fate.serving.sdk.client;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.webank.ai.fate.serving.core.bean.BatchInferenceRequest;
import com.webank.ai.fate.serving.core.bean.BatchInferenceResult;
import com.webank.ai.fate.serving.core.bean.InferenceRequest;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import java.io.IOException;
import java.util.List;
import java.util.Map;
/**
* 该类主要演示如何使用带有注册中心的客户端
*/
public class RegisterClientExample {
/**
* 只能实例化一次 ,全局维护一个单例。 若是有多个ip ,则使用逗号分隔. 在调用前先检查zk是否正常,ip端口是否填写正确
* 若是连接不上,客户端会每隔5秒一次重连
*/
static RegistedClient client =ClientBuilder.getClientUseRegister("localhost:2181");
/**
* 构建单笔预测请求
* @return
*/
static InferenceRequest buildInferenceRequest(){
InferenceRequest inferenceRequest = new InferenceRequest();
inferenceRequest.setServiceId("lr-test");
Map<String,Object> featureData = Maps.newHashMap();
featureData.put("x0", 0.100016);
featureData.put("x1", 1.210);
featureData.put("x2", 2.321);
featureData.put("x3", 3.432);
featureData.put("x4", 4.543);
featureData.put("x5", 5.654);
featureData.put("x6", 5.654);
featureData.put("x7", 0.102345);
inferenceRequest.setFeatureData(featureData);
Map<String,Object> sendToRemote = Maps.newHashMap();
sendToRemote.put("device_id","helloworld");
/**
* sendToRemote 数据会发送到host ,需要谨慎检查是否是敏感数据
*/
inferenceRequest.setSendToRemoteFeatureData(sendToRemote);
return inferenceRequest;
}
/**
* 构建批量预测请求
* @return
*/
static BatchInferenceRequest buildBatchInferenceRequest(){
BatchInferenceRequest batchInferenceRequest = new BatchInferenceRequest();
batchInferenceRequest.setServiceId("lr-test");
List<BatchInferenceRequest.SingleInferenceData> singleInferenceDataList = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
BatchInferenceRequest.SingleInferenceData singleInferenceData = new BatchInferenceRequest.SingleInferenceData();
singleInferenceData.getFeatureData().put("x0", 0.100016);
singleInferenceData.getFeatureData().put("x1", 1.210);
singleInferenceData.getFeatureData().put("x2", 2.321);
singleInferenceData.getFeatureData().put("x3", 3.432);
singleInferenceData.getFeatureData().put("x4", 4.543);
singleInferenceData.getFeatureData().put("x5", 5.654);
singleInferenceData.getFeatureData().put("x6", 5.654);
singleInferenceData.getFeatureData().put("x7", 0.102345);
/**
* sendToRemote 数据会发送到host ,需要谨慎检查是否是敏感数据
*/
singleInferenceData.getSendToRemoteFeatureData().put("device_id","helloworld");
/**
* 这里的序号从0开始 ,序号很重要,不可以重复
*/
singleInferenceData.setIndex(i);
singleInferenceDataList.add(singleInferenceData);
}
batchInferenceRequest.setBatchDataList(singleInferenceDataList);
batchInferenceRequest.setServiceId("lr-test");
return batchInferenceRequest;
}
public static void main(String[] args) throws IOException, InterruptedException {
InferenceRequest inferenceRequest = buildInferenceRequest();
BatchInferenceRequest batchInferenceRequest = buildBatchInferenceRequest();
try {
/**
* 测试单笔预测
*/
ReturnResult returnResult1 = client.singleInference(inferenceRequest);
System.err.println(returnResult1);
/**
* 使用注册中心的同时也可以绕过注册中心,使用ip端口的方式进行rpc调用
*/
ReturnResult returnResult2 = client.singleInference("localhost",8000,inferenceRequest);
System.err.println(returnResult2);
/**
* 测试批量预测
*/
BatchInferenceResult BatchInferenceResult1 = client.batchInference(batchInferenceRequest);
System.err.println(BatchInferenceResult1);
/**
* 指定ip端口批量预测
*/
BatchInferenceResult BatchInferenceResult2 = client.batchInference("localhost",8000,batchInferenceRequest);
System.err.println(BatchInferenceResult2);
} catch (Exception e) {
e.printStackTrace();
}
System.err.println("over");
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-sdk/src/main/java/com/webank/ai/fate/serving/sdk/client/ClientBuilder.java | fate-serving-sdk/src/main/java/com/webank/ai/fate/serving/sdk/client/ClientBuilder.java | package com.webank.ai.fate.serving.sdk.client;
import com.google.common.base.Preconditions;
import com.webank.ai.fate.register.utils.StringUtils;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.utils.NetUtils;
public class ClientBuilder {
/**
* without Register
* @return
*/
public static synchronized SimpleClient getClientWithoutRegister() {
return new SimpleClient();
}
/**
*
* @param zkAddress eg: 127.0.0.1:2181,127.0.0.2:2181,127.0.0.3:2181
* @return
*/
public static synchronized RegistedClient getClientUseRegister(String zkAddress) {
return getClientUseRegister(zkAddress,false);
}
/**
sigleton
*/
private static RegistedClient registedClient;
private static synchronized RegistedClient getClientUseRegister(String zkAddress,boolean useAcl) {
Preconditions.checkArgument(StringUtils.isNotEmpty(zkAddress));
MetaInfo.PROPERTY_ACL_ENABLE=useAcl;
String[] addresses = zkAddress.split(",");
for(String address:addresses){
Preconditions.checkArgument(NetUtils.isValidAddress(address)||NetUtils.isLocalhostAddress(address),"register address is invalid");
}
if (registedClient == null) {
RegistedClient client = new RegistedClient(zkAddress);
registedClient= client;
}else{
throw new RuntimeException("register is already exist ,register address is "+ registedClient.getRegisterAddress());
}
return registedClient;
}
/**
*
* @param zkAddress eg: 127.0.0.1:2181,127.0.0.2:2181,127.0.0.3:2181
* @param useAcl
* @param aclUserName
* @param aclPassword
* @return
*/
public static synchronized RegistedClient getClientUseRegister(String zkAddress, boolean useAcl, String aclUserName, String aclPassword) {
MetaInfo.PROPERTY_ACL_ENABLE = useAcl;
MetaInfo.PROPERTY_ACL_USERNAME = aclUserName;
MetaInfo.PROPERTY_ACL_PASSWORD = aclPassword;
return getClientUseRegister(zkAddress,useAcl);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/adaptor/AdaptorDescriptor.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/adaptor/AdaptorDescriptor.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.adaptor;
import java.util.List;
public interface AdaptorDescriptor {
public List<ParamDescriptor> desc();
public static class ParamDescriptor {
String keyName;
String keyType;
boolean isRequired;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/adaptor/BatchFeatureDataAdaptor.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/adaptor/BatchFeatureDataAdaptor.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.adaptor;
import com.webank.ai.fate.serving.core.bean.BatchHostFeatureAdaptorResult;
import com.webank.ai.fate.serving.core.bean.BatchHostFederatedParams;
import com.webank.ai.fate.serving.core.bean.Context;
import java.util.List;
public interface BatchFeatureDataAdaptor extends AdaptorDescriptor {
void init();
BatchHostFeatureAdaptorResult getFeatures(Context context, List<BatchHostFederatedParams.SingleInferenceData> featureIdList);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/adaptor/SingleFeatureDataAdaptor.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/adaptor/SingleFeatureDataAdaptor.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.adaptor;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import java.util.Map;
public interface SingleFeatureDataAdaptor {
void init();
ReturnResult getData(Context context, Map<String, Object> featureIds);
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/constant/StatusCode.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/constant/StatusCode.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an AS IS BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.constant;
public class StatusCode {
public static final int SUCCESS = 0;
public static final int GUEST_PARAM_ERROR = 100;
public static final int HOST_PARAM_ERROR = 100;
public static final int GUEST_FEATURE_ERROR = 102;
public static final int HOST_FEATURE_ERROR = 102;
public static final int MODEL_NULL = 104;
public static final int HOST_MODEL_NULL = 104;
public static final int NET_ERROR = 105;
public static final int GUEST_ROUTER_ERROR = 106;
public static final int GUEST_LOAD_MODEL_ERROR = 107;
public static final int HOST_LOAD_MODEL_ERROR = 107;
public static final int GUEST_MERGE_ERROR = 108;
public static final int GUEST_BIND_MODEL_ERROR = 109;
public static final int HOST_BIND_MODEL_ERROR = 109;
public static final int SYSTEM_ERROR = 110;
public static final int SHUTDOWN_ERROR = 111;
public static final int HOST_FEATURE_NOT_EXIST = 113;
public static final int FEATURE_DATA_ADAPTOR_ERROR = 116;
public static final int PARAM_ERROR = 120;
public static final int INVALID_ROLE_ERROR = 121;
public static final int SERVICE_NOT_FOUND = 122;
public static final int MODEL_INIT_ERROR = 123;
public static final int OVER_LOAD_ERROR = 124;
public static final int HOST_UNSUPPORTED_COMMAND_ERROR = 125;
public static final int UNREGISTER_ERROR = 126;
public static final int INVALID_TOKEN = 127;
public static final int PROXY_ROUTER_ERROR = 128;
public static final int PROXY_AUTH_ERROR = 129;
public static final int MODEL_SYNC_ERROR = 130;
public static final int Fill_RATE_ERROR = 131; // 填充率异常
public static final int PROXY_LOAD_ROUTER_TABLE_ERROR = 132;
public static final int PROXY_UPDATE_ROUTER_TABLE_ERROR = 133;
public static final int PROXY_PARAM_ERROR = 134;
public static final int INVALID_RESPONSE = 135;
public static final int SBT_DATA_ERROR = 136;
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/GuestMergeException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/GuestMergeException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class GuestMergeException extends BaseException {
public GuestMergeException(String message) {
super(StatusCode.GUEST_MERGE_ERROR, message);
}
public GuestMergeException(int retCode, String message) {
super(retCode, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/RouterInfoOperateException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/RouterInfoOperateException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class RouterInfoOperateException extends BaseException {
public RouterInfoOperateException(String message) {
super(StatusCode.PROXY_UPDATE_ROUTER_TABLE_ERROR, message);
}
public RouterInfoOperateException(int retCode, String message) {
super(retCode, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/HostGetFeatureErrorException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/HostGetFeatureErrorException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class HostGetFeatureErrorException extends BaseException {
public HostGetFeatureErrorException(String message) {
super(StatusCode.HOST_FEATURE_NOT_EXIST, message);
}
public HostGetFeatureErrorException(int retCode, String message) {
super(retCode, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/InvalidRoleInfoException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/InvalidRoleInfoException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class InvalidRoleInfoException extends BaseException {
public InvalidRoleInfoException(String message) {
super(StatusCode.INVALID_ROLE_ERROR, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/AsyncMessageException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/AsyncMessageException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
public class AsyncMessageException extends RuntimeException {
public AsyncMessageException(String message) {
super(message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/NoRouterInfoException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/NoRouterInfoException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
public class NoRouterInfoException extends BaseException {
public NoRouterInfoException(int retCode, String message) {
super(retCode, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ShowDownRejectException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ShowDownRejectException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
public class ShowDownRejectException extends RuntimeException {
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/BaseException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/BaseException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
//public class InferenceRetCode {
// public static final int OK = 0;
// public static final int EMPTY_DATA = 100;
// public static final int NUMERICAL_ERROR = 101;
// public static final int INVALID_FEATURE = 102;
// public static final int GET_FEATURE_FAILED = 103;
// public static final int LOAD_MODEL_FAILED = 104;
// public static final int NETWORK_ERROR = 105;
// public static final int DISK_ERROR = 106;
// public static final int STORAGE_ERROR = 107;
// public static final int COMPUTE_ERROR = 108;
// public static final int NO_RESULT = 109;
// public static final int SYSTEM_ERROR = 110;
// public static final int ADAPTER_ERROR = 111;
// public static final int DEAL_FEATURE_FAILED = 112;
// public static final int NO_FEATURE = 113;
//}
/**
* guest 参数错误 1100 异常 GuestInvalidParamException
* host 参数错误 2100 异常 HostInvalidParamException
* guest 特征错误 1102 异常 GuestInvalidFeatureException
* host 特征错误 2102 异常 HostInvalidFeatureException
* host 特征不存在 2113 异常 HostNoFeatureException
* <p>
* guest 加载模型失败 1107 异常 GuestLoadModelException
* host 加载模型失败 1107 异常 HostLoadModelException
* <p>
* guest 模型不存在 1104 异常 GuestModelNullException
* host 模型不存在 2104 异常 HostModelNullException
* guest 通信异常 1105 异常 GuestNetErrorExcetpion
* guest 通讯路由不存在 4115 异常 NoRouterInfoException
* guest host返回数据异常 1115 HostReturnErrorException
*/
public class BaseException extends RuntimeException {
protected int retcode;
public BaseException(int retCode, String message) {
super(message);
this.retcode = retCode;
}
public BaseException() {
}
public int getRetcode() {
return retcode;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ModelProcessorInitException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ModelProcessorInitException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class ModelProcessorInitException extends BaseException {
public ModelProcessorInitException(String message) {
super(StatusCode.MODEL_INIT_ERROR, message);
}
public ModelProcessorInitException(int retCode, String message) {
super(retCode, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/InvalidResponseException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/InvalidResponseException.java | package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class InvalidResponseException extends BaseException{
public InvalidResponseException(String message) {
super(StatusCode.INVALID_ROLE_ERROR, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/HostInvalidParamException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/HostInvalidParamException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class HostInvalidParamException extends BaseException {
public HostInvalidParamException(int retCode, String message) {
super(retCode, message);
}
public HostInvalidParamException(String message) {
super(StatusCode.HOST_PARAM_ERROR, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/SbtDataException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/SbtDataException.java | package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class SbtDataException extends BaseException{
public SbtDataException(){
super(StatusCode.SBT_DATA_ERROR,"sbt model data error");
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ModelLoadException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ModelLoadException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class ModelLoadException extends BaseException {
public ModelLoadException(String message) {
super(StatusCode.MODEL_NULL, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/OverLoadException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/OverLoadException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class OverLoadException extends BaseException {
public OverLoadException(int retCode, String message) {
super(retCode, message);
}
public OverLoadException(String message) {
super(StatusCode.OVER_LOAD_ERROR, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ModelSerializeException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ModelSerializeException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
public class ModelSerializeException extends RuntimeException {
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ModelNullException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ModelNullException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class ModelNullException extends BaseException {
public ModelNullException(String message) {
super(StatusCode.MODEL_NULL, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/NoResultException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/NoResultException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
public class NoResultException extends RuntimeException {
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/GuestLoadModelException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/GuestLoadModelException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class GuestLoadModelException extends BaseException {
public GuestLoadModelException(int retCode, String message) {
super(retCode, message);
}
public GuestLoadModelException(String message) {
super(StatusCode.GUEST_LOAD_MODEL_ERROR, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/FeatureDataAdaptorException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/FeatureDataAdaptorException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class FeatureDataAdaptorException extends BaseException {
public FeatureDataAdaptorException(String message) {
super(StatusCode.FEATURE_DATA_ADAPTOR_ERROR, message);
}
public FeatureDataAdaptorException(int retCode, String message) {
super(retCode, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/RemoteRpcException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/RemoteRpcException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class RemoteRpcException extends BaseException {
public RemoteRpcException(int retCode, String message) {
super(retCode, message);
}
public RemoteRpcException(String message) {
super(StatusCode.NET_ERROR, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/HostModelNullException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/HostModelNullException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class HostModelNullException extends BaseException {
public HostModelNullException(String message) {
super(StatusCode.HOST_MODEL_NULL, message);
}
public HostModelNullException(int retCode, String message) {
super(retCode, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ProxyAuthException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ProxyAuthException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class ProxyAuthException extends BaseException {
public ProxyAuthException(int retCode, String message) {
super(retCode, message);
}
public ProxyAuthException(String message) {
super(StatusCode.PROXY_AUTH_ERROR, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/UnSupportMethodException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/UnSupportMethodException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
public class UnSupportMethodException extends RuntimeException {
public UnSupportMethodException() {
super("UnSupportMethod");
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/SysException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/SysException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class SysException extends BaseException {
public SysException(int retCode, String message) {
super(retCode, message);
}
public SysException(String message) {
super(StatusCode.SYSTEM_ERROR, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ParameterException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/ParameterException.java | package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
/**
* @auther Xiongli
* @date 2021/7/30
* @remark
*/
public class ParameterException extends BaseException {
public ParameterException(int retCode, String message) {
super(retCode, message);
}
public ParameterException(String message) {
super(StatusCode.OVER_LOAD_ERROR, message);
}
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/GuestInvalidParamException.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/exceptions/GuestInvalidParamException.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.exceptions;
import com.webank.ai.fate.serving.core.constant.StatusCode;
public class GuestInvalidParamException extends BaseException {
public GuestInvalidParamException(int retCode, String message) {
super(retCode, message);
}
public GuestInvalidParamException(String message) {
super(StatusCode.GUEST_PARAM_ERROR, message);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/rpc/grpc/GrpcType.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/rpc/grpc/GrpcType.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.rpc.grpc;
/**
* @Description TODO
* @Author
**/
public enum GrpcType {
/**
* INTRA_GRPC
*/
INTRA_GRPC,
/**
* INTRA_GRPC
*/
INTER_GRPC
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/rpc/router/RouteTypeConvertor.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/rpc/router/RouteTypeConvertor.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.rpc.router;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @Description TODO
* @Author
**/
public class RouteTypeConvertor {
private static final String ROUTE_TYPE_RANDOM = "random";
private static final String ROUTE_TYPE_CONSISTENT_HASH = "consistent";
private static final Logger logger = LoggerFactory.getLogger(RouteTypeConvertor.class);
public static RouteType string2RouteType(String routeTypeString) {
RouteType routeType = RouteType.RANDOM_ROUTE;
if (StringUtils.isNotEmpty(routeTypeString)) {
if (routeTypeString.equalsIgnoreCase(ROUTE_TYPE_RANDOM)) {
routeType = RouteType.RANDOM_ROUTE;
} else if (routeTypeString.equalsIgnoreCase(ROUTE_TYPE_CONSISTENT_HASH)) {
routeType = RouteType.CONSISTENT_HASH_ROUTE;
} else {
routeType = RouteType.RANDOM_ROUTE;
logger.error("unknown routeType{}, will use {} instead.", routeTypeString, ROUTE_TYPE_RANDOM);
}
}
return routeType;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/rpc/router/Protocol.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/rpc/router/Protocol.java | package com.webank.ai.fate.serving.core.rpc.router;
public enum Protocol {
GRPC ,HTTP
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/rpc/router/RouterInfo.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/rpc/router/RouterInfo.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.rpc.router;
public class RouterInfo {
public Protocol getProtocol() {
return protocol;
}
public void setProtocol(Protocol protocol) {
this.protocol = protocol;
}
private Protocol protocol;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
private String url;
private String host;
private Integer port;
private boolean useSSL;
private String negotiationType;
private String certChainFile;
private String privateKeyFile;
private String caFile;
public boolean isUseSSL() {
return useSSL;
}
public void setUseSSL(boolean useSSL) {
this.useSSL = useSSL;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host == null ? null : host.trim();
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getCaFile() {
return caFile;
}
public String getCertChainFile() {
return certChainFile;
}
public String getNegotiationType() {
return negotiationType;
}
public String getPrivateKeyFile() {
return privateKeyFile;
}
public void setCaFile(String caFile) {
this.caFile = caFile;
}
public void setCertChainFile(String certChainFile) {
this.certChainFile = certChainFile;
}
public void setNegotiationType(String negotiationType) {
this.negotiationType = negotiationType;
}
public void setPrivateKeyFile(String privateKeyFile) {
this.privateKeyFile = privateKeyFile;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(host).append(":").append(port);
return sb.toString();
}
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/rpc/router/RouteType.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/rpc/router/RouteType.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.rpc.router;
/**
* @Description TODO
* @Author
**/
public enum RouteType {
/**
* RANDOM_ROUTE
*/
RANDOM_ROUTE,
/**
* CONSISTENT_HASH_ROUTE
*/
CONSISTENT_HASH_ROUTE
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/ParameterUtils.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/ParameterUtils.java | package com.webank.ai.fate.serving.core.utils;
import com.webank.ai.fate.serving.core.exceptions.ParameterException;
import org.checkerframework.checker.nullness.qual.Nullable;
/**
* @auther Xiongli
* @date 2021/7/30
* @remark
*/
public class ParameterUtils {
public static void checkArgument(boolean expression, @Nullable String errorMessage) {
if (!expression) {
throw new ParameterException(errorMessage);
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/ObjectTransform.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/ObjectTransform.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.utils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
public class ObjectTransform {
public ObjectTransform() {
}
public static String bean2Json(Object object) {
if (object == null) {
return "";
} else {
try {
return (new ObjectMapper()).writeValueAsString(object);
} catch (JsonProcessingException var2) {
return "";
}
}
}
public static Object json2Bean(String json, Class objectType) {
if (StringUtils.isEmpty(json)) {
return null;
} else {
try {
return (new ObjectMapper()).readValue(json, objectType);
} catch (Exception var3) {
return null;
}
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/ProtobufUtils.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/ProtobufUtils.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ProtobufUtils {
private static final Logger logger = LoggerFactory.getLogger(ProtobufUtils.class);
public static <T> T parseProtoObject(com.google.protobuf.Parser<T> protoParser, byte[] protoString) throws com.google.protobuf.InvalidProtocolBufferException {
T messageV3;
try {
messageV3 = protoParser.parseFrom(protoString);
if (logger.isDebugEnabled()) {
logger.debug("parse {} proto object normal", messageV3.getClass().getSimpleName());
}
return messageV3;
} catch (Exception ex1) {
try {
messageV3 = protoParser.parseFrom(new byte[0]);
if (logger.isDebugEnabled()) {
logger.debug("parse {} proto object with default values", messageV3.getClass().getSimpleName());
}
return messageV3;
} catch (Exception ex2) {
throw ex1;
}
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/InferenceUtils.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/InferenceUtils.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.UUID;
public class InferenceUtils {
private static final Logger logger = LoggerFactory.getLogger(InferenceUtils.class);
public static String generateCaseid() {
return UUID.randomUUID().toString().replace("-", "");
}
public static String generateSeqno() {
return UUID.randomUUID().toString().replace("-", "");
}
public static Object getClassByName(String classPath) {
try {
Class thisClass = Class.forName(classPath);
return thisClass.getConstructor().newInstance();
} catch (ClassNotFoundException ex) {
logger.error("Can not found this class: {}.", classPath);
} catch (NoSuchMethodException ex) {
logger.error("Can not get this class({}) constructor.", classPath);
} catch (Exception ex) {
logger.error(ex.getMessage());
logger.error("Can not create class({}) instance.", classPath);
}
return null;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/EncryptUtils.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/EncryptUtils.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.utils;
import com.webank.ai.fate.serving.core.bean.EncryptMethod;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
public class EncryptUtils {
public static final String UTF8 = "UTF-8";
private static final String HMAC_SHA1 = "HmacSHA1";
public static String encrypt(String originString, EncryptMethod encryptMethod) {
try {
MessageDigest m = MessageDigest.getInstance(getEncryptMethodString(encryptMethod));
m.update(originString.getBytes("UTF8"));
byte[] s = m.digest();
String result = "";
for (int i = 0; i < s.length; i++) {
result += Integer.toHexString((0x000000FF & s[i]) | 0xFFFFFF00).substring(6);
}
return result;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static byte[] hmacSha1Encrypt(String encryptText, String encryptKey) throws Exception {
byte[] data = encryptKey.getBytes(UTF8);
SecretKey secretKey = new SecretKeySpec(data, HMAC_SHA1);
Mac mac = Mac.getInstance(HMAC_SHA1);
mac.init(secretKey);
byte[] text = encryptText.getBytes(UTF8);
return mac.doFinal(text);
}
private static String getEncryptMethodString(EncryptMethod encryptMethod) {
String methodString = "";
switch (encryptMethod) {
case MD5:
methodString = "MD5";
break;
case SHA256:
methodString = "SHA-256";
break;
default:
break;
}
return methodString;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/NetUtils.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/NetUtils.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.*;
import java.util.Enumeration;
import java.util.Optional;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
/**
* IP and Port Helper for RPC
*/
public class NetUtils {
private static final Logger logger = LoggerFactory.getLogger(NetUtils.class);
//LoggerFactory.getLogger(NetUtils.class);
// returned port range is [30000, 39999]
private static final int RND_PORT_START = 30000;
private static final int RND_PORT_RANGE = 10000;
// valid port range is (0, 65535]
private static final int MIN_PORT = 0;
private static final int MAX_PORT = 65535;
private static final Pattern ADDRESS_PATTERN = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}\\:\\d{1,5}$");
private static final Pattern LOCALHOST_PATTERN = Pattern.compile("localhost\\:\\d{1,5}$");
private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$");
private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
private static final String SPLIT_IPV4_CHARECTER = "\\.";
private static final String SPLIT_IPV6_CHARECTER = ":";
private static String ANYHOST_VALUE = "0.0.0.0";
private static String LOCALHOST_KEY = "localhost";
private static String LOCALHOST_VALUE = "127.0.0.1";
private static volatile InetAddress LOCAL_ADDRESS = null;
public static void main(String[] args) {
// System.out.println(NetUtils.getLocalHost());
// System.out.println(NetUtils.getAvailablePort());
// System.out.println(NetUtils.getLocalAddress());
// System.out.println(NetUtils.getLocalIp());
// System.out.println(NetUtils.getIpByHost("127.0.0.1"));
// System.out.println(NetUtils.getLocalAddress0(""));
}
public static int getRandomPort() {
return RND_PORT_START + ThreadLocalRandom.current().nextInt(RND_PORT_RANGE);
}
public static boolean isLocalhostAddress(String address){
return LOCALHOST_PATTERN.matcher(address).matches();
}
public static int getAvailablePort() {
try (ServerSocket ss = new ServerSocket()) {
ss.bind(null);
return ss.getLocalPort();
} catch (IOException e) {
return getRandomPort();
}
}
public static int getAvailablePort(int port) {
if (port <= 0) {
return getAvailablePort();
}
for (int i = port; i < MAX_PORT; i++) {
try (ServerSocket ss = new ServerSocket(i)) {
return i;
} catch (IOException e) {
// continue
}
}
return port;
}
public static boolean isInvalidPort(int port) {
return port <= MIN_PORT || port > MAX_PORT;
}
public static boolean isValidAddress(String address) {
return ADDRESS_PATTERN.matcher(address).matches();
}
public static boolean isLocalHost(String host) {
return host != null
&& (LOCAL_IP_PATTERN.matcher(host).matches()
|| host.equalsIgnoreCase(LOCALHOST_KEY));
}
public static boolean isAnyHost(String host) {
return ANYHOST_VALUE.equals(host);
}
public static boolean isInvalidLocalHost(String host) {
return host == null
|| host.length() == 0
|| host.equalsIgnoreCase(LOCALHOST_KEY)
|| host.equals(ANYHOST_VALUE)
|| (LOCAL_IP_PATTERN.matcher(host).matches());
}
public static boolean isValidLocalHost(String host) {
return !isInvalidLocalHost(host);
}
public static InetSocketAddress getLocalSocketAddress(String host, int port) {
return isInvalidLocalHost(host) ?
new InetSocketAddress(port) : new InetSocketAddress(host, port);
}
static boolean isValidV4Address(InetAddress address) {
if (address == null || address.isLoopbackAddress()) {
return false;
}
String name = address.getHostAddress();
boolean result = (name != null
&& IP_PATTERN.matcher(name).matches()
&& !ANYHOST_VALUE.equals(name)
&& !LOCALHOST_VALUE.equals(name));
return result;
}
/**
* Check if an ipv6 address
*
* @return true if it is reachable
*/
static boolean isPreferIpv6Address() {
boolean preferIpv6 = Boolean.getBoolean("java.net.preferIPv6Addresses");
return preferIpv6;
}
/**
* normalize the ipv6 Address, convert scope name to scope id.
* e.g.
* convert
* fe80:0:0:0:894:aeec:f37d:23e1%en0
* to
* fe80:0:0:0:894:aeec:f37d:23e1%5
* <p>
* The %5 after ipv6 address is called scope id.
* see java doc of {@link Inet6Address} for more details.
*
* @param address the input address
* @return the normalized address, with scope id converted to int
*/
static InetAddress normalizeV6Address(Inet6Address address) {
String addr = address.getHostAddress();
int i = addr.lastIndexOf('%');
if (i > 0) {
try {
return InetAddress.getByName(addr.substring(0, i) + '%' + address.getScopeId());
} catch (UnknownHostException e) {
// ignore
logger.debug("Unknown IPV6 address: ", e);
}
}
return address;
}
public static String getLocalHost() {
InetAddress address = getLocalAddress();
return address == null ? LOCALHOST_VALUE : address.getHostAddress();
}
public static InetAddress getLocalAddress() {
if (LOCAL_ADDRESS != null) {
return LOCAL_ADDRESS;
}
InetAddress localAddress = getLocalAddress0("");
LOCAL_ADDRESS = localAddress;
return localAddress;
}
private static Optional<InetAddress> toValidAddress(InetAddress address) {
if (address instanceof Inet6Address) {
Inet6Address v6Address = (Inet6Address) address;
if (isPreferIpv6Address()) {
return Optional.ofNullable(normalizeV6Address(v6Address));
}
}
if (isValidV4Address(address)) {
return Optional.of(address);
}
return Optional.empty();
}
public static String getLocalIp() {
try {
InetAddress inetAddress = getLocalAddress0("eth0");
if (inetAddress != null) {
return inetAddress.getHostAddress();
} else {
inetAddress = getLocalAddress0("");
}
if (inetAddress != null) {
return inetAddress.getHostAddress();
} else {
throw new RuntimeException("can not get local ip");
}
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
return "";
}
private static String getIpByEthNum(String ethNum) {
try {
Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (ethNum.equals(netInterface.getName())) {
Enumeration addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = (InetAddress) addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
} catch (SocketException e) {
logger.error(e.getMessage(), e);
}
return "";
}
public static String getOsName() {
String osName = System.getProperty("os.name");
return osName;
}
private static InetAddress getLocalAddress0(String name) {
InetAddress localAddress = null;
try {
localAddress = InetAddress.getLocalHost();
Optional<InetAddress> addressOp = toValidAddress(localAddress);
if (addressOp.isPresent()) {
return addressOp.get();
} else {
localAddress = null;
}
} catch (Throwable e) {
logger.warn(e.getMessage());
}
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
if (null == interfaces) {
return localAddress;
}
while (interfaces.hasMoreElements()) {
try {
NetworkInterface network = interfaces.nextElement();
if (network.isLoopback() || network.isVirtual() || !network.isUp()) {
continue;
}
if (StringUtils.isNotEmpty(name)) {
if (!network.getName().equals(name)) {
continue;
}
}
Enumeration<InetAddress> addresses = network.getInetAddresses();
while (addresses.hasMoreElements()) {
try {
Optional<InetAddress> addressOp = toValidAddress(addresses.nextElement());
if (addressOp.isPresent()) {
try {
if (addressOp.get().isReachable(10000)) {
return addressOp.get();
}
} catch (IOException e) {
// ignore
}
}
} catch (Throwable e) {
logger.warn(e.getMessage());
}
}
} catch (Throwable e) {
logger.warn(e.getMessage());
}
}
} catch (Throwable e) {
logger.warn(e.getMessage());
}
return localAddress;
}
/**
* @param hostName
* @return ip address or hostName if UnknownHostException
*/
public static String getIpByHost(String hostName) {
try {
return InetAddress.getByName(hostName).getHostAddress();
} catch (UnknownHostException e) {
return hostName;
}
}
public static String toAddressString(InetSocketAddress address) {
return address.getAddress().getHostAddress() + ":" + address.getPort();
}
public static InetSocketAddress toAddress(String address) {
int i = address.indexOf(':');
String host;
int port;
if (i > -1) {
host = address.substring(0, i);
port = Integer.parseInt(address.substring(i + 1));
} else {
host = address;
port = 0;
}
return new InetSocketAddress(host, port);
}
public static String toUrl(String protocol, String host, int port, String path) {
StringBuilder sb = new StringBuilder();
sb.append(protocol).append("://");
sb.append(host).append(':').append(port);
if (path.charAt(0) != '/') {
sb.append('/');
}
sb.append(path);
return sb.toString();
}
public static void joinMulticastGroup(MulticastSocket multicastSocket, InetAddress multicastAddress) throws IOException {
setInterface(multicastSocket, multicastAddress instanceof Inet6Address);
multicastSocket.setLoopbackMode(false);
multicastSocket.joinGroup(multicastAddress);
}
public static void setInterface(MulticastSocket multicastSocket, boolean preferIpv6) throws IOException {
boolean interfaceSet = false;
Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface i = (NetworkInterface) interfaces.nextElement();
Enumeration addresses = i.getInetAddresses();
while (addresses.hasMoreElements()) {
InetAddress address = (InetAddress) addresses.nextElement();
if (preferIpv6 && address instanceof Inet6Address) {
try {
if (address.isReachable(100)) {
multicastSocket.setInterface(address);
interfaceSet = true;
break;
}
} catch (IOException e) {
// ignore
}
} else if (!preferIpv6 && address instanceof Inet4Address) {
try {
if (address.isReachable(100)) {
multicastSocket.setInterface(address);
interfaceSet = true;
break;
}
} catch (IOException e) {
// ignore
}
}
}
if (interfaceSet) {
break;
}
}
}
// public static boolean matchIpExpression(String pattern, String host, int port) throws UnknownHostException {
//
// // if the pattern is subnet format, it will not be allowed to config port param in pattern.
// if (pattern.contains("/")) {
// CIDRUtils utils = new CIDRUtils(pattern);
// return utils.isInRange(host);
// }
//
//
// return matchIpRange(pattern, host, port);
// }
/**
* @param pattern
* @param host
* @param port
* @return
* @throws UnknownHostException
*/
public static boolean matchIpRange(String pattern, String host, int port) throws UnknownHostException {
if (pattern == null || host == null) {
throw new IllegalArgumentException("Illegal Argument pattern or hostName. Pattern:" + pattern + ", Host:" + host);
}
pattern = pattern.trim();
if ("*.*.*.*".equals(pattern) || "*".equals(pattern)) {
return true;
}
InetAddress inetAddress = InetAddress.getByName(host);
boolean isIpv4 = isValidV4Address(inetAddress) ? true : false;
String[] hostAndPort = getPatternHostAndPort(pattern, isIpv4);
if (hostAndPort[1] != null && !hostAndPort[1].equals(String.valueOf(port))) {
return false;
}
pattern = hostAndPort[0];
String splitCharacter = SPLIT_IPV4_CHARECTER;
if (!isIpv4) {
splitCharacter = SPLIT_IPV6_CHARECTER;
}
String[] mask = pattern.split(splitCharacter);
//check format of pattern
checkHostPattern(pattern, mask, isIpv4);
host = inetAddress.getHostAddress();
String[] ipAddress = host.split(splitCharacter);
if (pattern.equals(host)) {
return true;
}
// short name condition
if (!ipPatternContainExpression(pattern)) {
InetAddress patternAddress = InetAddress.getByName(pattern);
if (patternAddress.getHostAddress().equals(host)) {
return true;
} else {
return false;
}
}
for (int i = 0; i < mask.length; i++) {
if ("*".equals(mask[i]) || mask[i].equals(ipAddress[i])) {
continue;
} else if (mask[i].contains("-")) {
String[] rangeNumStrs = mask[i].split("-");
if (rangeNumStrs.length != 2) {
throw new IllegalArgumentException("There is wrong format of ip Address: " + mask[i]);
}
Integer min = getNumOfIpSegment(rangeNumStrs[0], isIpv4);
Integer max = getNumOfIpSegment(rangeNumStrs[1], isIpv4);
Integer ip = getNumOfIpSegment(ipAddress[i], isIpv4);
if (ip < min || ip > max) {
return false;
}
} else if ("0".equals(ipAddress[i]) && ("0".equals(mask[i]) || "00".equals(mask[i]) || "000".equals(mask[i]) || "0000".equals(mask[i]))) {
continue;
} else if (!mask[i].equals(ipAddress[i])) {
return false;
}
}
return true;
}
private static boolean ipPatternContainExpression(String pattern) {
return pattern.contains("*") || pattern.contains("-");
}
private static void checkHostPattern(String pattern, String[] mask, boolean isIpv4) {
if (!isIpv4) {
if (mask.length != 8 && ipPatternContainExpression(pattern)) {
throw new IllegalArgumentException("If you config ip expression that contains '*' or '-', please fill qulified ip pattern like 234e:0:4567:0:0:0:3d:*. ");
}
if (mask.length != 8 && !pattern.contains("::")) {
throw new IllegalArgumentException("The host is ipv6, but the pattern is not ipv6 pattern : " + pattern);
}
} else {
if (mask.length != 4) {
throw new IllegalArgumentException("The host is ipv4, but the pattern is not ipv4 pattern : " + pattern);
}
}
}
private static String[] getPatternHostAndPort(String pattern, boolean isIpv4) {
String[] result = new String[2];
if (pattern.startsWith("[") && pattern.contains("]:")) {
int end = pattern.indexOf("]:");
result[0] = pattern.substring(1, end);
result[1] = pattern.substring(end + 2);
return result;
} else if (pattern.startsWith("[") && pattern.endsWith("]")) {
result[0] = pattern.substring(1, pattern.length() - 1);
result[1] = null;
return result;
} else if (isIpv4 && pattern.contains(":")) {
int end = pattern.indexOf(":");
result[0] = pattern.substring(0, end);
result[1] = pattern.substring(end + 1);
return result;
} else {
result[0] = pattern;
return result;
}
}
private static Integer getNumOfIpSegment(String ipSegment, boolean isIpv4) {
if (isIpv4) {
return Integer.parseInt(ipSegment);
}
return Integer.parseInt(ipSegment, 16);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/ThreadPoolUtil.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/ThreadPoolUtil.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.utils;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class ThreadPoolUtil {
public static ThreadPoolExecutor newThreadPoolExecutor() {
int processors = Runtime.getRuntime().availableProcessors();
ThreadPoolExecutor executor = new ThreadPoolExecutor(processors, Integer.MAX_VALUE,
0, TimeUnit.MILLISECONDS, new SynchronousQueue<>());
return executor;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/JsonUtil.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/utils/JsonUtil.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.utils;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.MessageOrBuilder;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
public class JsonUtil {
private static ObjectMapper mapper = new ObjectMapper();
static {
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
}
public static String object2Json(Object o) {
if (o == null) {
return null;
}
String s = "";
try {
s = mapper.writeValueAsString(o);
} catch (IOException e) {
e.printStackTrace();
}
return s;
}
public static <T> T json2Object(String json, Class<T> c) {
if (StringUtils.isBlank(json)) {
return null;
}
T t = null;
try {
t = mapper.readValue(json, c);
} catch (IOException e) {
e.printStackTrace();
}
return t;
}
public static <T> T json2Object(byte[] json, Class<T> c) {
T t = null;
try {
t = mapper.readValue(json, c);
} catch (IOException e) {
e.printStackTrace();
}
return t;
}
public static <T> T json2List(String json, TypeReference<T> typeReference) {
if (StringUtils.isBlank(json)) {
return null;
}
T result = null;
try {
result = mapper.readValue(json, typeReference);
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
@SuppressWarnings("unchecked")
public static <T> T json2Object(String json, TypeReference<T> tr) {
if (StringUtils.isBlank(json)) {
return null;
}
T t = null;
try {
t = (T) mapper.readValue(json, tr);
} catch (IOException e) {
e.printStackTrace();
}
return (T) t;
}
public static JsonObject object2JsonObject(Object source){
String json = object2Json(source);
return JsonParser.parseString(json).getAsJsonObject();
}
public static <T> T json2Object(JsonObject source,Class<T> clazz){
String json = source.toString();
return json2Object(json,clazz);
}
public static <T> T object2Objcet(Object source,Class<T> clazz){
String json = object2Json(source);
return json2Object(json,clazz);
}
public static <T> T object2Objcet(Object source,TypeReference<T> tr){
String json = object2Json(source);
return json2Object(json,tr);
}
public static String formatJson(String jsonStr) {
return formatJson(jsonStr," ");
}
/***
* format json string
*/
public static String formatJson(String jsonStr,String formatChar) {
if (null == jsonStr || "".equals(jsonStr)) return "";
jsonStr = jsonStr.replace("\\n", "");
StringBuilder sb = new StringBuilder();
char last;
char current = '\0';
int indent = 0;
boolean isInQuotationMarks = false;
for (int i = 0; i < jsonStr.length(); i++) {
last = current;
current = jsonStr.charAt(i);
switch (current) {
case '"':
if (last != '\\') {
isInQuotationMarks = !isInQuotationMarks;
}
sb.append(current);
break;
case '{':
case '[':
sb.append(current);
if (!isInQuotationMarks) {
sb.append('\n');
indent++;
addIndentTab(sb, indent,formatChar);
}
break;
case '}':
case ']':
if (!isInQuotationMarks) {
sb.append('\n');
indent--;
addIndentTab(sb, indent,formatChar);
}
sb.append(current);
break;
case ',':
sb.append(current);
if (last != '\\' && !isInQuotationMarks) {
sb.append('\n');
addIndentTab(sb, indent,formatChar);
}
break;
case ' ':
if (',' != jsonStr.charAt(i - 1)) {
sb.append(current);
}
break;
case '\\':
sb.append("\\");
break;
default:
sb.append(current);
}
}
return sb.toString();
}
private static void addIndentTab(StringBuilder sb, int indent,String formatChar) {
for (int i = 0; i < indent; i++) {
sb.append(formatChar);
}
}
public static String pbToJson(MessageOrBuilder message){
try {
return com.google.protobuf.util.JsonFormat.printer().print(message);
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
return "";
}
public static void main(String[] args) {
String s = JsonUtil.formatJson("{\"route_table\":{\"default\":{\"default\":[{\"ip\":\"127.0.0.1\",\"port\":9999,\"useSSL\":false}]},\"10000\":{\"default\":[{\"ip\":\"127.0.0.1\",\"port\":8889}],\"serving\":[{\"ip\":\"127.0.0.1\",\"port\":8080}]},\"123\":[{\"host\":\"127.0.0.1\",\"port\":8888,\"useSSL\":false,\"negotiationType\":\"\",\"certChainFile\":\"\",\"privateKeyFile\":\"\",\"caFile\":\"\"}]},\"permission\":{\"default_allow\":true}}");
System.out.println(s);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/timer/Timer.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/timer/Timer.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.timer;
import java.util.Set;
import java.util.concurrent.TimeUnit;
public interface Timer {
Timeout newTimeout(TimerTask task, long delay, TimeUnit unit);
Set<Timeout> stop();
boolean isStop();
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/timer/Timeout.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/timer/Timeout.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.timer;
public interface Timeout {
Timer timer();
TimerTask task();
boolean isExpired();
boolean isCancelled();
boolean cancel();
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/timer/TimerTask.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/timer/TimerTask.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.timer;
public interface TimerTask {
void run(Timeout timeout) throws Exception;
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/timer/HashedWheelTimer.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/timer/HashedWheelTimer.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.timer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicLong;
public class HashedWheelTimer implements Timer {
public static final String NAME = "hased";
static final String OS_NAME = "os.name";
static final String USER_HOME = "user.home";
static final String OS_NAME_WIN = "win";
private static final Logger logger = LoggerFactory.getLogger(HashedWheelTimer.class);
private static final AtomicInteger INSTANCE_COUNTER = new AtomicInteger();
private static final AtomicBoolean WARNED_TOO_MANY_INSTANCES = new AtomicBoolean();
private static final int INSTANCE_COUNT_LIMIT = 64;
private static final AtomicIntegerFieldUpdater<HashedWheelTimer> WORKER_STATE_UPDATER =
AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimer.class, "workerState");
private static final int WORKER_STATE_INIT = 0;
private static final int WORKER_STATE_STARTED = 1;
private static final int WORKER_STATE_SHUTDOWN = 2;
private final Worker worker = new Worker();
private final Thread workerThread;
private final long tickDuration;
private final HashedWheelBucket[] wheel;
private final int mask;
private final CountDownLatch startTimeInitialized = new CountDownLatch(1);
private final Queue<HashedWheelTimeout> timeouts = new LinkedBlockingQueue<>();
private final Queue<HashedWheelTimeout> cancelledTimeouts = new LinkedBlockingQueue<>();
private final AtomicLong pendingTimeouts = new AtomicLong(0);
private final long maxPendingTimeouts;
/**
* 0 - init, 1 - started, 2 - shut down
*/
@SuppressWarnings({"unused", "FieldMayBeFinal"})
private volatile int workerState;
private volatile long startTime;
public HashedWheelTimer() {
this(Executors.defaultThreadFactory());
}
public HashedWheelTimer(long tickDuration, TimeUnit unit) {
this(Executors.defaultThreadFactory(), tickDuration, unit);
}
public HashedWheelTimer(long tickDuration, TimeUnit unit, int ticksPerWheel) {
this(Executors.defaultThreadFactory(), tickDuration, unit, ticksPerWheel);
}
public HashedWheelTimer(ThreadFactory threadFactory) {
this(threadFactory, 100, TimeUnit.MILLISECONDS);
}
public HashedWheelTimer(
ThreadFactory threadFactory, long tickDuration, TimeUnit unit) {
this(threadFactory, tickDuration, unit, 512);
}
public HashedWheelTimer(
ThreadFactory threadFactory,
long tickDuration, TimeUnit unit, int ticksPerWheel) {
this(threadFactory, tickDuration, unit, ticksPerWheel, -1);
}
public HashedWheelTimer(
ThreadFactory threadFactory,
long tickDuration, TimeUnit unit, int ticksPerWheel,
long maxPendingTimeouts) {
if (threadFactory == null) {
throw new NullPointerException("threadFactory");
}
if (unit == null) {
throw new NullPointerException("unit");
}
if (tickDuration <= 0) {
throw new IllegalArgumentException("tickDuration must be greater than 0: " + tickDuration);
}
if (ticksPerWheel <= 0) {
throw new IllegalArgumentException("ticksPerWheel must be greater than 0: " + ticksPerWheel);
}
// Normalize ticksPerWheel to power of two and initialize the wheel.
wheel = createWheel(ticksPerWheel);
mask = wheel.length - 1;
// Convert tickDuration to nanos.
this.tickDuration = unit.toNanos(tickDuration);
// Prevent overflow.
if (this.tickDuration >= Long.MAX_VALUE / wheel.length) {
throw new IllegalArgumentException(String.format(
"tickDuration: %d (expected: 0 < tickDuration in nanos < %d",
tickDuration, Long.MAX_VALUE / wheel.length));
}
workerThread = threadFactory.newThread(worker);
this.maxPendingTimeouts = maxPendingTimeouts;
if (INSTANCE_COUNTER.incrementAndGet() > INSTANCE_COUNT_LIMIT &&
WARNED_TOO_MANY_INSTANCES.compareAndSet(false, true)) {
reportTooManyInstances();
}
}
private static HashedWheelBucket[] createWheel(int ticksPerWheel) {
if (ticksPerWheel <= 0) {
throw new IllegalArgumentException(
"ticksPerWheel must be greater than 0: " + ticksPerWheel);
}
if (ticksPerWheel > 1073741824) {
throw new IllegalArgumentException(
"ticksPerWheel may not be greater than 2^30: " + ticksPerWheel);
}
ticksPerWheel = normalizeTicksPerWheel(ticksPerWheel);
HashedWheelBucket[] wheel = new HashedWheelBucket[ticksPerWheel];
for (int i = 0; i < wheel.length; i++) {
wheel[i] = new HashedWheelBucket();
}
return wheel;
}
private static int normalizeTicksPerWheel(int ticksPerWheel) {
int normalizedTicksPerWheel = ticksPerWheel - 1;
normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 1;
normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 2;
normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 4;
normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 8;
normalizedTicksPerWheel |= normalizedTicksPerWheel >>> 16;
return normalizedTicksPerWheel + 1;
}
private static void reportTooManyInstances() {
String resourceType = HashedWheelTimer.class.getName();
logger.error("You are creating too many " + resourceType + " instances. " +
resourceType + " is a shared resource that must be reused across the JVM," +
"so that only a few instances are created.");
}
@Override
protected void finalize() throws Throwable {
try {
super.finalize();
} finally {
// This object is going to be GCed and it is assumed the ship has sailed to do a proper shutdown. If
// we have not yet shutdown then we want to make sure we decrement the active instance count.
if (WORKER_STATE_UPDATER.getAndSet(this, WORKER_STATE_SHUTDOWN) != WORKER_STATE_SHUTDOWN) {
INSTANCE_COUNTER.decrementAndGet();
}
}
}
public void start() {
switch (WORKER_STATE_UPDATER.get(this)) {
case WORKER_STATE_INIT:
if (WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_INIT, WORKER_STATE_STARTED)) {
workerThread.start();
}
break;
case WORKER_STATE_STARTED:
break;
case WORKER_STATE_SHUTDOWN:
throw new IllegalStateException("cannot be started once stopped");
default:
throw new Error("Invalid WorkerState");
}
// Wait until the startTime is initialized by the worker.
while (startTime == 0) {
try {
startTimeInitialized.await();
} catch (InterruptedException ignore) {
// Ignore - it will be ready very soon.
}
}
}
@Override
public Set<Timeout> stop() {
if (Thread.currentThread() == workerThread) {
throw new IllegalStateException(
HashedWheelTimer.class.getSimpleName() +
".stop() cannot be called from " +
TimerTask.class.getSimpleName());
}
if (!WORKER_STATE_UPDATER.compareAndSet(this, WORKER_STATE_STARTED, WORKER_STATE_SHUTDOWN)) {
// workerState can be 0 or 2 at this moment - let it always be 2.
if (WORKER_STATE_UPDATER.getAndSet(this, WORKER_STATE_SHUTDOWN) != WORKER_STATE_SHUTDOWN) {
INSTANCE_COUNTER.decrementAndGet();
}
return Collections.emptySet();
}
try {
boolean interrupted = false;
while (workerThread.isAlive()) {
workerThread.interrupt();
try {
workerThread.join(100);
} catch (InterruptedException ignored) {
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
} finally {
INSTANCE_COUNTER.decrementAndGet();
}
return worker.unprocessedTimeouts();
}
@Override
public boolean isStop() {
return WORKER_STATE_SHUTDOWN == WORKER_STATE_UPDATER.get(this);
}
@Override
public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) {
if (task == null) {
throw new NullPointerException("task");
}
if (unit == null) {
throw new NullPointerException("unit");
}
long pendingTimeoutsCount = pendingTimeouts.incrementAndGet();
if (maxPendingTimeouts > 0 && pendingTimeoutsCount > maxPendingTimeouts) {
pendingTimeouts.decrementAndGet();
throw new RejectedExecutionException("Number of pending timeouts ("
+ pendingTimeoutsCount + ") is greater than or equal to maximum allowed pending "
+ "timeouts (" + maxPendingTimeouts + ")");
}
start();
// Add the timeout to the timeout queue which will be processed on the next tick.
// During processing all the queued HashedWheelTimeouts will be added to the correct HashedWheelBucket.
long deadline = System.nanoTime() + unit.toNanos(delay) - startTime;
// Guard against overflow.
if (delay > 0 && deadline < 0) {
deadline = Long.MAX_VALUE;
}
HashedWheelTimeout timeout = new HashedWheelTimeout(this, task, deadline);
timeouts.add(timeout);
return timeout;
}
public long pendingTimeouts() {
return pendingTimeouts.get();
}
private boolean isWindows() {
return System.getProperty(OS_NAME, "").toLowerCase(Locale.US).contains(OS_NAME_WIN);
}
private static final class HashedWheelTimeout implements Timeout {
private static final int ST_INIT = 0;
private static final int ST_CANCELLED = 1;
private static final int ST_EXPIRED = 2;
private static final AtomicIntegerFieldUpdater<HashedWheelTimeout> STATE_UPDATER =
AtomicIntegerFieldUpdater.newUpdater(HashedWheelTimeout.class, "state");
private final HashedWheelTimer timer;
private final TimerTask task;
private final long deadline;
/**
* RemainingRounds will be calculated and set by Worker.transferTimeoutsToBuckets() before the
* HashedWheelTimeout will be added to the correct HashedWheelBucket.
*/
long remainingRounds;
/**
* This will be used to chain timeouts in HashedWheelTimerBucket via a double-linked-list.
* As only the workerThread will act on it there is no need for synchronization / volatile.
*/
HashedWheelTimeout next;
HashedWheelTimeout prev;
/**
* The bucket to which the timeout was added
*/
HashedWheelBucket bucket;
@SuppressWarnings({"unused", "FieldMayBeFinal", "RedundantFieldInitialization"})
private volatile int state = ST_INIT;
HashedWheelTimeout(HashedWheelTimer timer, TimerTask task, long deadline) {
this.timer = timer;
this.task = task;
this.deadline = deadline;
}
@Override
public Timer timer() {
return timer;
}
@Override
public TimerTask task() {
return task;
}
@Override
public boolean cancel() {
// only update the state it will be removed from HashedWheelBucket on next tick.
if (!compareAndSetState(ST_INIT, ST_CANCELLED)) {
return false;
}
// If a task should be canceled we put this to another queue which will be processed on each tick.
// So this means that we will have a GC latency of max. 1 tick duration which is good enough. This way
// we can make again use of our MpscLinkedQueue and so minimize the locking / overhead as much as possible.
timer.cancelledTimeouts.add(this);
return true;
}
void remove() {
HashedWheelBucket bucket = this.bucket;
if (bucket != null) {
bucket.remove(this);
} else {
timer.pendingTimeouts.decrementAndGet();
}
}
public boolean compareAndSetState(int expected, int state) {
return STATE_UPDATER.compareAndSet(this, expected, state);
}
public int state() {
return state;
}
@Override
public boolean isCancelled() {
return state() == ST_CANCELLED;
}
@Override
public boolean isExpired() {
return state() == ST_EXPIRED;
}
public void expire() {
if (!compareAndSetState(ST_INIT, ST_EXPIRED)) {
return;
}
try {
task.run(this);
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn("An exception was thrown by " + TimerTask.class.getSimpleName() + '.', t);
}
}
}
@Override
public String toString() {
final long currentTime = System.nanoTime();
long remaining = deadline - currentTime + timer.startTime;
// String simpleClassName = ClassUtils.simpleClassName(this.getClass());
StringBuilder buf = new StringBuilder(192)
.append('(')
.append("deadline: ");
if (remaining > 0) {
buf.append(remaining)
.append(" ns later");
} else if (remaining < 0) {
buf.append(-remaining)
.append(" ns ago");
} else {
buf.append("now");
}
if (isCancelled()) {
buf.append(", cancelled");
}
return buf.append(", task: ")
.append(task())
.append(')')
.toString();
}
}
/**
* Bucket that stores HashedWheelTimeouts. These are stored in a linked-list like datastructure to allow easy
* removal of HashedWheelTimeouts in the middle. Also the HashedWheelTimeout act as nodes themself and so no
* extra object creation is needed.
*/
private static final class HashedWheelBucket {
/**
* Used for the linked-list datastructure
*/
private HashedWheelTimeout head;
private HashedWheelTimeout tail;
/**
* Add {@link HashedWheelTimeout} to this bucket.
*/
void addTimeout(HashedWheelTimeout timeout) {
assert timeout.bucket == null;
timeout.bucket = this;
if (head == null) {
head = tail = timeout;
} else {
tail.next = timeout;
timeout.prev = tail;
tail = timeout;
}
}
/**
* Expire all {@link HashedWheelTimeout}s for the given {@code deadline}.
*/
void expireTimeouts(long deadline) {
HashedWheelTimeout timeout = head;
// process all timeouts
while (timeout != null) {
HashedWheelTimeout next = timeout.next;
if (timeout.remainingRounds <= 0) {
next = remove(timeout);
if (timeout.deadline <= deadline) {
timeout.expire();
} else {
// The timeout was placed into a wrong slot. This should never happen.
throw new IllegalStateException(String.format(
"timeout.deadline (%d) > deadline (%d)", timeout.deadline, deadline));
}
} else if (timeout.isCancelled()) {
next = remove(timeout);
} else {
timeout.remainingRounds--;
}
timeout = next;
}
}
public HashedWheelTimeout remove(HashedWheelTimeout timeout) {
HashedWheelTimeout next = timeout.next;
// remove timeout that was either processed or cancelled by updating the linked-list
if (timeout.prev != null) {
timeout.prev.next = next;
}
if (timeout.next != null) {
timeout.next.prev = timeout.prev;
}
if (timeout == head) {
// if timeout is also the tail we need to adjust the entry too
if (timeout == tail) {
tail = null;
head = null;
} else {
head = next;
}
} else if (timeout == tail) {
// if the timeout is the tail modify the tail to be the prev node.
tail = timeout.prev;
}
// null out prev, next and bucket to allow for GC.
timeout.prev = null;
timeout.next = null;
timeout.bucket = null;
timeout.timer.pendingTimeouts.decrementAndGet();
return next;
}
/**
* Clear this bucket and return all not expired / cancelled {@link Timeout}s.
*/
void clearTimeouts(Set<Timeout> set) {
for (; ; ) {
HashedWheelTimeout timeout = pollTimeout();
if (timeout == null) {
return;
}
if (timeout.isExpired() || timeout.isCancelled()) {
continue;
}
set.add(timeout);
}
}
private HashedWheelTimeout pollTimeout() {
HashedWheelTimeout head = this.head;
if (head == null) {
return null;
}
HashedWheelTimeout next = head.next;
if (next == null) {
tail = this.head = null;
} else {
this.head = next;
next.prev = null;
}
// null out prev and next to allow for GC.
head.next = null;
head.prev = null;
head.bucket = null;
return head;
}
}
private final class Worker implements Runnable {
private final Set<Timeout> unprocessedTimeouts = new HashSet<Timeout>();
private long tick;
@Override
public void run() {
// Initialize the startTime.
startTime = System.nanoTime();
if (startTime == 0) {
// We use 0 as an indicator for the uninitialized value here, so make sure it's not 0 when initialized.
startTime = 1;
}
// Notify the other threads waiting for the initialization at start().
startTimeInitialized.countDown();
do {
final long deadline = waitForNextTick();
if (deadline > 0) {
int idx = (int) (tick & mask);
processCancelledTasks();
HashedWheelBucket bucket =
wheel[idx];
transferTimeoutsToBuckets();
bucket.expireTimeouts(deadline);
tick++;
}
} while (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_STARTED);
// Fill the unprocessedTimeouts so we can return them from stop() method.
for (HashedWheelBucket bucket : wheel) {
bucket.clearTimeouts(unprocessedTimeouts);
}
for (; ; ) {
HashedWheelTimeout timeout = timeouts.poll();
if (timeout == null) {
break;
}
if (!timeout.isCancelled()) {
unprocessedTimeouts.add(timeout);
}
}
processCancelledTasks();
}
private void transferTimeoutsToBuckets() {
// transfer only max. 100000 timeouts per tick to prevent a thread to stale the workerThread when it just
// adds new timeouts in a loop.
for (int i = 0; i < 100000; i++) {
HashedWheelTimeout timeout = timeouts.poll();
if (timeout == null) {
// all processed
break;
}
if (timeout.state() == HashedWheelTimeout.ST_CANCELLED) {
// Was cancelled in the meantime.
continue;
}
long calculated = timeout.deadline / tickDuration;
timeout.remainingRounds = (calculated - tick) / wheel.length;
// Ensure we don't schedule for past.
final long ticks = Math.max(calculated, tick);
int stopIndex = (int) (ticks & mask);
HashedWheelBucket bucket = wheel[stopIndex];
bucket.addTimeout(timeout);
}
}
private void processCancelledTasks() {
for (; ; ) {
HashedWheelTimeout timeout = cancelledTimeouts.poll();
if (timeout == null) {
// all processed
break;
}
try {
timeout.remove();
} catch (Throwable t) {
if (logger.isWarnEnabled()) {
logger.warn("An exception was thrown while process a cancellation task", t);
}
}
}
}
/**
* calculate goal nanoTime from startTime and current tick number,
* then wait until that goal has been reached.
*
* @return Long.MIN_VALUE if received a shutdown request,
* current time otherwise (with Long.MIN_VALUE changed by +1)
*/
private long waitForNextTick() {
long deadline = tickDuration * (tick + 1);
for (; ; ) {
final long currentTime = System.nanoTime() - startTime;
long sleepTimeMs = (deadline - currentTime + 999999) / 1000000;
if (sleepTimeMs <= 0) {
if (currentTime == Long.MIN_VALUE) {
return -Long.MAX_VALUE;
} else {
return currentTime;
}
}
if (isWindows()) {
sleepTimeMs = sleepTimeMs / 10 * 10;
}
try {
Thread.sleep(sleepTimeMs);
} catch (InterruptedException ignored) {
if (WORKER_STATE_UPDATER.get(HashedWheelTimer.this) == WORKER_STATE_SHUTDOWN) {
return Long.MIN_VALUE;
}
}
}
}
Set<Timeout> unprocessedTimeouts() {
return Collections.unmodifiableSet(unprocessedTimeouts);
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/HttpAdapterResponseCodeEnum.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/HttpAdapterResponseCodeEnum.java | package com.webank.ai.fate.serving.core.bean;
/**
* @author hcy
*/
public class HttpAdapterResponseCodeEnum{
// 通用http响应成功码
public static final int COMMON_HTTP_SUCCESS_CODE = 0;
//正常
public static final int SUCCESS_CODE = 200;
//查询无果
public static final int ERROR_CODE = 404;
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/MergedInferenceResult.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/MergedInferenceResult.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
/**
* @Description TODO
* @Author kaideng
**/
public class MergedInferenceResult {
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/BatchInferenceRequest.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/BatchInferenceRequest.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import com.google.common.collect.Maps;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import java.util.List;
import java.util.Map;
public class BatchInferenceRequest extends InferenceRequest {
private String serviceId;
private List<SingleInferenceData> batchDataList;
public List<SingleInferenceData> getBatchDataList() {
return batchDataList;
}
public void setBatchDataList(List<SingleInferenceData> batchDataList) {
this.batchDataList = batchDataList;
}
@Override
public void setCaseId(String caseId) {
this.caseId = caseId;
}
@Override
public String getApplyId() {
return applyId;
}
@Override
public void setApplyId(String applyId) {
this.applyId = applyId;
}
@Override
public String getServiceId() {
return serviceId;
}
@Override
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
@Override
public String toString() {
String result = "";
try {
result = JsonUtil.object2Json(this);
} catch (Throwable e) {
}
return result;
}
public static class SingleInferenceData {
int index;
Map<String, Object> featureData = Maps.newHashMap();
Map<String, Object> sendToRemoteFeatureData = Maps.newHashMap();
boolean needCheckFeature = false;
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public Map<String, Object> getFeatureData() {
return featureData;
}
public void setFeatureData(Map<String, Object> featureData) {
this.featureData = featureData;
}
public Map<String, Object> getSendToRemoteFeatureData() {
return sendToRemoteFeatureData;
}
public void setSendToRemoteFeatureData(Map<String, Object> sendToRemoteFeatureData) {
this.sendToRemoteFeatureData = sendToRemoteFeatureData;
}
public boolean isNeedCheckFeature() {
return needCheckFeature;
}
public void setNeedCheckFeature(boolean needCheckFeature) {
this.needCheckFeature = needCheckFeature;
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/FederatedRoles.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/FederatedRoles.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FederatedRoles {
private Map<String, List<String>> roleMap;
public FederatedRoles() {
this.roleMap = new HashMap<>();
}
public Map<String, List<String>> getRoleMap() {
return roleMap;
}
public void setRoleMap(Map<String, List<String>> roleMap) {
this.roleMap = roleMap;
}
public List<String> getRole(String role) {
return this.roleMap.get(role);
}
public void setRole(String role, List<String> partyIds) {
this.roleMap.put(role, partyIds);
}
public void addParty(String role, String partyId) {
this.roleMap.get(role).add(partyId);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/RouterTableRequest.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/RouterTableRequest.java | package com.webank.ai.fate.serving.core.bean;
import java.util.List;
/**
* @auther Xiong li
* @date 2021/6/29
* @remark
*/
public class RouterTableRequest {
String serverHost;
Integer serverPort;
public Object getRouterTableList() {
return routerTableList;
}
public void setRouterTableList(Object routerTableList) {
this.routerTableList = routerTableList;
}
Object routerTableList;
Integer page;
Integer pageSize;
public String getServerHost() {
return serverHost;
}
public void setServerHost(String serverHost) {
this.serverHost = serverHost;
}
public Integer getServerPort() {
return serverPort;
}
public void setServerPort(Integer serverPort) {
this.serverPort = serverPort;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.page = page;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public static class RouterTable {
String partyId;
String ip;
Integer port;
boolean useSSL;
String negotiationType;
String certChainFile;
String privateKeyFile;
String caFile;
String serverType;
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public boolean isUseSSL() {
return useSSL;
}
public void setUseSSL(boolean useSSL) {
this.useSSL = useSSL;
}
public String getNegotiationType() {
return negotiationType;
}
public void setNegotiationType(String negotiationType) {
this.negotiationType = negotiationType;
}
public String getCertChainFile() {
return certChainFile;
}
public void setCertChainFile(String certChainFile) {
this.certChainFile = certChainFile;
}
public String getPrivateKeyFile() {
return privateKeyFile;
}
public void setPrivateKeyFile(String privateKeyFile) {
this.privateKeyFile = privateKeyFile;
}
public String getCaFile() {
return caFile;
}
public void setCaFile(String caFile) {
this.caFile = caFile;
}
public String getServerType() {
return serverType;
}
public void setServerType(String serverType) {
this.serverType = serverType;
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/MetaInfo.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/MetaInfo.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import com.google.common.collect.Maps;
import com.webank.ai.fate.serving.core.adaptor.AdaptorDescriptor;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
public class MetaInfo {
public static final long CURRENT_VERSION = 216;
public static List<AdaptorDescriptor.ParamDescriptor> inferenceParamDescriptorList;
public static List<AdaptorDescriptor.ParamDescriptor> batchInferenceParamDescriptorList;
public static Boolean PROPERTY_REMOTE_MODEL_INFERENCE_RESULT_CACHE_SWITCH;
public static Integer PROPERTY_PORT;
public static String PROPERTY_ZK_URL;
public static String PROPERTY_PROXY_ADDRESS;
public static Integer PROPERTY_SERVING_CORE_POOL_SIZE;
public static Integer PROPERTY_SERVING_MAX_POOL_SIZE;
public static Integer PROPERTY_SERVING_POOL_ALIVE_TIME;
public static Integer PROPERTY_SERVING_POOL_QUEUE_SIZE;
public static Boolean PROPERTY_USE_REGISTER;
public static Boolean PROPERTY_USE_ZK_ROUTER;
public static String PROPERTY_FEATURE_BATCH_ADAPTOR;
public static String PROPERTY_FETTURE_BATCH_SINGLE_ADAPTOR;
public static Integer PROPERTY_BATCH_INFERENCE_MAX;
public static String PROPERTY_FEATURE_SINGLE_ADAPTOR;
public static Integer PROPERTY_SINGLE_INFERENCE_RPC_TIMEOUT;
public static Integer PROPERTY_BATCH_INFERENCE_RPC_TIMEOUT;
public static String PROXY_ROUTER_TABLE;
public static String PROPERTY_REDIS_IP;
public static String PROPERTY_REDIS_PASSWORD;
public static Integer PROPERTY_REDIS_PORT;
public static Integer PROPERTY_REDIS_TIMEOUT;
public static Integer PROPERTY_REDIS_MAX_TOTAL;
public static Integer PROPERTY_REDIS_MAX_IDLE;
public static Integer PROPERTY_REDIS_EXPIRE;
public static String PROPERTY_REDIS_CLUSTER_NODES;
public static String PROPERTY_CACHE_TYPE;
public static Integer PROPERTY_LOCAL_CACHE_MAXSIZE;
public static Integer PROPERTY_LOCAL_CACHE_EXPIRE;
public static Integer PROPERTY_LOCAL_CACHE_INTERVAL;
public static Integer PROPERTY_BATCH_SPLIT_SIZE;
public static Integer PROPERTY_LR_SPLIT_SIZE;
public static String PROPERTY_SERVICE_ROLE_NAME;
public static String PROPERTY_MODEL_TRANSFER_URL;
public static boolean PROPERTY_MODEL_SYNC;
public static Integer PROPERTY_COORDINATOR;
public static Integer PROPERTY_SERVER_PORT;
public static String PROPERTY_INFERENCE_SERVICE_NAME;
public static String PROPERTY_ROUTE_TYPE;
public static String PROPERTY_ROUTE_TABLE;
public static String PROPERTY_AUTH_FILE;
public static Integer PROPERTY_PROXY_GRPC_INTRA_PORT;
public static Integer PROPERTY_PROXY_GRPC_INTER_PORT;
public static Integer PROPERTY_PROXY_GRPC_INFERENCE_TIMEOUT;
public static Integer PROPERTY_PROXY_GRPC_INFERENCE_ASYNC_TIMEOUT;
public static Integer PROPERTY_PROXY_GRPC_UNARYCALL_TIMEOUT;
public static Integer PROPERTY_PROXY_GRPC_THREADPOOL_CORESIZE;
public static Integer PROPERTY_PROXY_GRPC_THREADPOOL_MAXSIZE;
public static Integer PROPERTY_PROXY_GRPC_THREADPOOL_QUEUESIZE;
public static Integer PROPERTY_PROXY_ASYNC_TIMEOUT;
public static Integer PROPERTY_PROXY_ASYNC_CORESIZE;
public static Integer PROPERTY_PROXY_ASYNC_MAXSIZE;
public static Integer PROPERTY_PROXY_GRPC_BATCH_INFERENCE_TIMEOUT;
public static String PROPERTY_MODEL_CACHE_PATH;
public static String PROPERTY_FATEFLOW_LOAD_URL;
public static String PROPERTY_FATEFLOW_BIND_URL;
public static Integer PROPERTY_GRPC_TIMEOUT;
public static Boolean PROPERTY_ACL_ENABLE;
public static String PROPERTY_ACL_USERNAME;
public static String PROPERTY_ACL_PASSWORD;
public static String PROPERTY_ROOT_PATH;
public static Boolean PROPERTY_PRINT_INPUT_DATA;
public static Boolean PROPERTY_PRINT_OUTPUT_DATA;
public static Boolean PROPERTY_LR_USE_PARALLEL;
public static Boolean PROPERTY_AUTH_OPEN;
public static String PROPERTY_PROXY_GRPC_INTER_NEGOTIATIONTYPE;
public static String PROPERTY_PROXY_GRPC_INTER_CA_FILE;
public static String PROPERTY_PROXY_GRPC_INTER_CLIENT_CERTCHAIN_FILE;
public static String PROPERTY_PROXY_GRPC_INTER_CLIENT_PRIVATEKEY_FILE;
public static String PROPERTY_PROXY_GRPC_INTER_SERVER_CERTCHAIN_FILE;
public static String PROPERTY_PROXY_GRPC_INTER_SERVER_PRIVATEKEY_FILE;
public static Integer PROPERTY_ADMIN_HEALTH_CHECK_TIME;
public static Boolean PROPERTY_ALLOW_HEALTH_CHECK;
public static Integer HTTP_CLIENT_CONFIG_CONN_REQ_TIME_OUT;
public static Integer HTTP_CLIENT_CONFIG_CONN_TIME_OUT;
public static Integer HTTP_CLIENT_CONFIG_SOCK_TIME_OUT;
public static Integer HTTP_CLIENT_INIT_POOL_MAX_TOTAL;
public static Integer HTTP_CLIENT_INIT_POOL_DEF_MAX_PER_ROUTE;
public static Integer HTTP_CLIENT_INIT_POOL_SOCK_TIME_OUT;
public static Integer HTTP_CLIENT_INIT_POOL_CONN_TIME_OUT;
public static Integer HTTP_CLIENT_INIT_POOL_CONN_REQ_TIME_OUT;
public static Integer HTTP_CLIENT_TRAN_CONN_REQ_TIME_OUT;
public static Integer HTTP_CLIENT_TRAN_CONN_TIME_OUT;
public static Integer HTTP_CLIENT_TRAN_SOCK_TIME_OUT;
public static int PROPERTY_HTTP_CONNECT_REQUEST_TIMEOUT;
public static int PROPERTY_HTTP_CONNECT_TIMEOUT;
public static int PROPERTY_HTTP_SOCKET_TIMEOUT;
public static int PROPERTY_HTTP_MAX_POOL_SIZE;
public static String PROPERTY_HTTP_ADAPTER_URL;
public static Map toMap() {
Map result = Maps.newHashMap();
Field[] fields = MetaInfo.class.getFields();
for (Field field : fields) {
try {
if (field.get(MetaInfo.class) != null) {
String key = Dict.class.getField(field.getName()) != null ? String.valueOf(Dict.class.getField(field.getName()).get(Dict.class)) : field.getName();
result.put(key, field.get(MetaInfo.class));
}
} catch (IllegalAccessException | NoSuchFieldException e) {
}
}
return result;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/LocalInferenceParam.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/LocalInferenceParam.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
/**
* @Description TODO
* @Author kaideng
**/
public class LocalInferenceParam {
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/Context.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/Context.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import com.google.common.util.concurrent.ListenableFuture;
import com.webank.ai.fate.serving.core.rpc.grpc.GrpcType;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
public interface Context<Req, Resp> {
static final String LOGGER_NAME = "flow";
public void preProcess();
public Object getData(Object key);
public Object getDataOrDefault(Object key, Object defaultValue);
public void putData(Object key, Object data);
public String getCaseId();
public void setCaseId(String caseId);
public long getTimeStamp();
public default void postProcess(Req req, Resp resp) {
}
public ReturnResult getFederatedResult();
public void setFederatedResult(ReturnResult returnResult);
public boolean isHitCache();
public void hitCache(boolean hitCache);
public Context subContext();
public String getInterfaceName();
public void setInterfaceName(String interfaceName);
public String getActionType();
public void setActionType(String actionType);
public String getSeqNo();
public long getCostTime();
/**
* proxy
*/
public GrpcType getGrpcType();
public void setGrpcType(GrpcType grpcType);
public String getVersion();
public void setVersion(String version);
public String getGuestAppId();
public void setGuestAppId(String guestAppId);
public String getHostAppid();
public void setHostAppid(String hostAppid);
public RouterInfo getRouterInfo();
public void setRouterInfo(RouterInfo routerInfo);
public Object getResultData();
public void setResultData(Object resultData);
public int getReturnCode();
public void setReturnCode(int returnCode);
public long getDownstreamCost();
public void setDownstreamCost(long downstreamCost);
public long getDownstreamBegin();
public void setDownstreamBegin(long downstreamBegin);
public long getRouteBasis();
public void setRouteBasis(long routeBasis);
public String getSourceIp();
public void setSourceIp(String sourceIp);
public String getServiceName();
public void setServiceName(String serviceName);
public String getCallName();
public void setCallName(String callName);
public String getServiceId();
public void setServiceId(String serviceId);
public String getApplyId();
public void setApplyId(String applyId);
public ListenableFuture getRemoteFuture();
public void setRemoteFuture(ListenableFuture future);
public String getResourceName();
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/FederatedParams.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/FederatedParams.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.builder.ToStringBuilder;
import java.util.List;
import java.util.Map;
public class FederatedParams {
String caseId;
String seqNo;
boolean isBatch;
FederatedParty local;
ModelInfo modelInfo;
FederatedRoles role;
Map<String, Object> featureIdMap = Maps.newHashMap();
List<Map<String, Object>> batchFeatureIdMapList = Lists.newArrayList();
Map<String, Object> data = Maps.newHashMap();
public boolean isBatch() {
return isBatch;
}
public void setBatch(boolean batch) {
isBatch = batch;
}
public List<Map<String, Object>> getBatchFeatureIdMapList() {
return batchFeatureIdMapList;
}
public void setBatchFeatureIdMapList(List<Map<String, Object>> batchFeatureIdMapList) {
this.batchFeatureIdMapList = batchFeatureIdMapList;
}
public ModelInfo getModelInfo() {
return modelInfo;
}
public void setModelInfo(ModelInfo modelInfo) {
this.modelInfo = modelInfo;
}
public String getCaseId() {
return caseId;
}
public void setCaseId(String caseId) {
this.caseId = caseId;
}
public String getSeqNo() {
return seqNo;
}
public void setSeqNo(String seqNo) {
this.seqNo = seqNo;
}
public FederatedParty getLocal() {
return local;
}
public void setLocal(FederatedParty local) {
this.local = local;
}
public FederatedRoles getRole() {
return role;
}
public void setRole(FederatedRoles role) {
this.role = role;
}
public Map<String, Object> getFeatureIdMap() {
return featureIdMap;
}
public Map<String, Object> getData() {
return data;
}
public void setData(Map<String, Object> data) {
this.data = data;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/BatchHostFederatedParams.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/BatchHostFederatedParams.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
public class BatchHostFederatedParams extends BatchInferenceRequest {
String hostTableName;
String hostNamespace;
String guestPartyId;
String hostPartyId;
String caseId;
public String getHostTableName() {
return hostTableName;
}
public void setHostTableName(String hostTableName) {
this.hostTableName = hostTableName;
}
public String getHostNamespace() {
return hostNamespace;
}
public void setHostNamespace(String hostNamespace) {
this.hostNamespace = hostNamespace;
}
public String getGuestPartyId() {
return guestPartyId;
}
public void setGuestPartyId(String guestPartyId) {
this.guestPartyId = guestPartyId;
}
public String getHostPartyId() {
return hostPartyId;
}
public void setHostPartyId(String hostPartyId) {
this.hostPartyId = hostPartyId;
}
@Override
public void setCaseId(String caseId) {
this.caseId = caseId;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/Dict.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/Dict.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
public class Dict {
public static final String ORIGIN_REQUEST = "origin_request";
public static final String CASEID = "caseid";
public static final String SCORE = "score";
public static final String SEQNO = "seqno";
public static final String NONE = "NONE";
public static final String PIPLELINE_IN_MODEL = "pipeline.pipeline:Pipeline";
public static final String POST_PROCESSING_CONFIG = "InferencePostProcessingAdapter";
public static final String PRE_PROCESSING_CONFIG = "InferencePreProcessingAdapter";
public static final String GET_REMOTE_PARTY_RESULT = "getRemotePartyResult";
public static final String FEDERATED_RESULT = "federatedResult";
public static final String PORT = "port";
public static final String INSTANCE_ID = "instanceId";
public static final String ORIGINAL_PREDICT_DATA = "originalPredictData";
public static final String HIT_CACHE = "hitCache";
public static final String REQUEST_SEQNO = "REQUEST_SEQNO";
public static final String MODEL_KEYS = "model_keys";
public static final String MODEL_NANESPACE_DATA = "model_namespace_data";
public static final String APPID_NANESPACE_DATA = "appid_namespace_data";
public static final String PARTNER_MODEL_DATA = "partner_model_index";
public static final String MODEL_FEDERATED_PARTY = "model_federated_party";
public static final String MODEL_FEDERATED_ROLES = "model_federated_roles";
public static final String MODEL = "model";
public static final String VERSION = "version";
public static final String GRPC_TYPE = "grpcType";
public static final String ROUTER_INFO = "routerInfo";
public static final String RESULT_DATA = "resultData";
public static final String RETURN_CODE = "returnCode";
public static final String DOWN_STREAM_COST = "downstreamCost";
public static final String DOWN_STREAM_BEGIN = "downstreamBegin";
public static final String ROUTE_BASIS = "routeBasis";
public static final String SOURCE_IP = "sourceIp";
public static final String PROPERTY_SERVING_CORE_POOL_SIZE = "serving.core.pool.size";
public static final String SERVING_MAX_POOL_ZIE = "serving.max.pool.size";
public static final String PROPERTY_SERVING_POOL_ALIVE_TIME = "serving.pool.alive.time";
public static final String PROPERTY_SERVING_POOL_QUEUE_SIZE = "serving.pool.queue.size";
public static final String PROPERTY_SINGLE_INFERENCE_RPC_TIMEOUT = "single.inference.rpc.timeout";
public static final String PROPERTY_BATCH_INFERENCE_RPC_TIMEOUT = "batch.inference.rpc.timeout";
public static final String PROPERTY_FEATURE_SINGLE_ADAPTOR = "feature.single.adaptor";
public static final String PROPERTY_BATCH_SPLIT_SIZE = "batch.split.size";
public static final String PROPERTY_LR_SPLIT_SIZE = "lr.split.size";
public static final String CACHE_TYPE_REDIS = "redis";
public static final String DEFAULT_FATE_ROOT = "FATE-SERVICES";
/**
* configuration property key
*/
public static final String PROPERTY_REMOTE_MODEL_INFERENCE_RESULT_CACHE_TTL = "remoteModelInferenceResultCacheTTL";
public static final String PROPERTY_REMOTE_MODEL_INFERENCE_RESULT_CACHE_MAX_SIZE = "remoteModelInferenceResultCacheMaxSize";
public static final String PROPERTY_INFERENCE_RESULT_CACHE_TTL = "inferenceResultCacheTTL";
public static final String PROPERTY_INFERENCE_RESULT_CACHE_CACHE_MAX_SIZE = "inferenceResultCacheCacheMaxSize";
public static final String PROPERTY_CACHE_TYPE = "cache.type";
public static final String PROPERTY_REDIS_MAX_TOTAL = "redis.maxTotal";
public static final String PROPERTY_REDIS_MAX_IDLE = "redis.maxIdle";
public static final String PROPERTY_REDIS_IP = "redis.ip";
public static final String PROPERTY_REDIS_PORT = "redis.port";
public static final String PROPERTY_REDIS_TIMEOUT = "redis.timeout";
public static final String PROPERTY_REDIS_PASSWORD = "redis.password";
public static final String PROPERTY_REDIS_EXPIRE = "redis.expire";
public static final String PROPERTY_REDIS_CLUSTER_NODES = "redis.cluster.nodes";
public static final String PROPERTY_LOCAL_CACHE_MAXSIZE = "local.cache.maxsize";
public static final String PROPERTY_LOCAL_CACHE_EXPIRE = "local.cache.expire";
public static final String PROPERTY_LOCAL_CACHE_INTERVAL = "local.cache.interval";
public static final String PROPERTY_FATEFLOW_LOAD_URL = "fateflow.load.url";
public static final String PROPERTY_FATEFLOW_BIND_URL = "fateflow.bind.url";
public static final String PROPERTY_GRPC_TIMEOUT = "grpc.timeout";
public static final String PROPERTY_EXTERNAL_INFERENCE_RESULT_CACHE_DB_INDEX = "external.inferenceResultCacheDBIndex";
public static final String PROPERTY_EXTERNAL_INFERENCE_RESULT_CACHE_TTL = "external.inferenceResultCacheTTL";
public static final String PROPERTY_EXTERNAL_REMOTE_MODEL_INFERENCE_RESULT_CACHE_DB_INDEX = "external.remoteModelInferenceResultCacheDBIndex";
public static final String PROPERTY_EXTERNAL_PROCESS_CACHE_DB_INDEX = "external.processCacheDBIndex";
public static final String PROPERTY_EXTERNAL_REMOTE_MODEL_INFERENCE_RESULT_CACHE_TTL = "external.remoteModelInferenceResultCacheTTL";
public static final String PROPERTY_REMOTE_MODEL_INFERENCE_RESULT_CACHE_SWITCH = "remoteModelInferenceResultCacheSwitch";
public static final String PROPERTY_CAN_CACHE_RET_CODE = "canCacheRetcode";
public static final String PROPERTY_SERVICE_ROLE_NAME = "serviceRoleName";
public static final String PROPERTY_SERVICE_ROLE_NAME_DEFAULT_VALUE = "serving";
public static final String PROPERTY_ONLINE_DATA_ACCESS_ADAPTER = "OnlineDataAccessAdapter";
public static final String PROPERTY_ONLINE_DATA_BATCH_ACCESS_ADAPTER = "OnlineDataBatchAccessAdapter";
public static final String PROPERTY_MODEL_CACHE_ACCESS_TTL = "modelCacheAccessTTL";
public static final String PROPERTY_MODEL_CACHE_MAX_SIZE = "modelCacheMaxSize";
public static final String PROPERTY_INFERENCE_WORKER_THREAD_NUM = "inferenceWorkerThreadNum";
public static final String PROPERTY_PROXY_ADDRESS = "proxy";
public static final String ONLINE_ENVIRONMENT = "online";
public static final String PROPERTY_ROLL_ADDRESS = "roll";
public static final String PROPERTY_FLOW_ADDRESS = "flow";
public static final String PROPERTY_SERVING_ADDRESS = "serving";
public static final String PROPERTY_USE_ZOOKEEPER = "useZookeeper";
public static final String PROPERTY_PORT = "port";
public static final String PROPERTY_USER_DIR = "user.dir";
public static final String PROPERTY_USER_HOME = "user.home";
public static final String PROPERTY_FILE_SEPARATOR = "file.separator";
public static final String PROPERTY_ZK_URL = "zk.url";
public static final String PROPERTY_USE_ZK_ROUTER = "useZkRouter";
public static final String PROPERTY_USE_REGISTER = "useRegister";
public static final String PROPERTY_MODEL_TRANSFER_URL = "model.transfer.url";
public static final String PROPERTY_MODEL_SYNC = "model.synchronize";
public static final String PROPERTY_SERVING_MAX_POOL_SIZE = "serving.max.pool.size";
public static final String PROPERTY_FEATURE_BATCH_ADAPTOR = "feature.batch.adaptor";
public static final String PROPERTY_FEATURE_BATCH_SINGLE_ADAPTOR = "feature.batch.single.adaptor";
public static final String PROPERTY_ACL_ENABLE = "acl.enable";
public static final String PROPERTY_ACL_USERNAME = "acl.username";
public static final String PROPERTY_ACL_PASSWORD = "acl.password";
public static final String PROXY_ROUTER_TABLE = "proxy.router.table";
public static final String PROPERTY_BATCH_INFERENCE_MAX = "batch.inference.max";
public static final String PROPERTY_PRINT_INPUT_DATA = "print.input.data";
public static final String PROPERTY_PRINT_OUTPUT_DATA = "print.output.data";
public static final String PROPERTY_PROXY_GRPC_INTER_NEGOTIATIONTYPE = "proxy.grpc.inter.negotiationType";
public static final String PROPERTY_PROXY_GRPC_INTER_CA_FILE = "proxy.grpc.inter.CA.file";
public static final String PROPERTY_PROXY_GRPC_INTER_CLIENT_CERTCHAIN_FILE = "proxy.grpc.inter.client.certChain.file";
public static final String PROPERTY_PROXY_GRPC_INTER_CLIENT_PRIVATEKEY_FILE = "proxy.grpc.inter.client.privateKey.file";
public static final String PROPERTY_PROXY_GRPC_INTER_SERVER_CERTCHAIN_FILE = "proxy.grpc.inter.server.certChain.file";
public static final String PROPERTY_PROXY_GRPC_INTER_SERVER_PRIVATEKEY_FILE = "proxy.grpc.inter.server.privateKey.file";
public static final String CURRENT_VERSION = "currentVersion";
public static final String PROPERTY_COORDINATOR = "coordinator";
public static final String PROPERTY_SERVER_PORT = "server.port";
public static final String PROPERTY_INFERENCE_SERVICE_NAME = "inference.service.name";
public static final String PROPERTY_ROUTE_TYPE = "routeType";
public static final String PROPERTY_ROUTE_TABLE = "route.table";
public static final String PROPERTY_AUTH_FILE = "auth.file";
public static final String PROPERTY_AUTH_OPEN = "auth.open";
public static final String PROPERTY_PROXY_GRPC_INTRA_PORT = "proxy.grpc.intra.port";
public static final String PROPERTY_PROXY_GRPC_INTER_PORT = "proxy.grpc.inter.port";
public static final String PROPERTY_PROXY_GRPC_INFERENCE_TIMEOUT = "proxy.grpc.inference.timeout";
public static final String PROPERTY_PROXY_GRPC_INFERENCE_ASYNC_TIMEOUT = "proxy.grpc.inference.async.timeout";
public static final String PROPERTY_PROXY_GRPC_UNARYCALL_TIMEOUT = "proxy.grpc.unaryCall.timeout";
public static final String PROPERTY_PROXY_GRPC_THREADPOOL_CORESIZE = "proxy.grpc.threadpool.coresize";
public static final String PROPERTY_PROXY_GRPC_THREADPOOL_MAXSIZE = "proxy.grpc.threadpool.maxsize";
public static final String PROPERTY_PROXY_GRPC_THREADPOOL_QUEUESIZE = "proxy.grpc.threadpool.queuesize";
public static final String PROPERTY_PROXY_ASYNC_TIMEOUT = "proxy.async.timeout";
public static final String PROPERTY_PROXY_ASYNC_CORESIZE = "proxy.async.coresize";
public static final String PROPERTY_PROXY_ASYNC_MAXSIZE = "proxy.async.maxsize";
public static final String PROPERTY_PROXY_GRPC_BATCH_INFERENCE_TIMEOUT = "proxy.grpc.batch.inference.timeout";
public static final String PROPERTY_MODEL_CACHE_PATH = "model.cache.path";
public static final String PROPERTY_LR_USE_PARALLEL="lr.use.parallel";
public static final String PROPERTY_ALLOW_HEALTH_CHECK = "health.check.allow";
public static final String ACTION_TYPE_ASYNC_EXECUTE = "ASYNC_EXECUTE";
public static final String RET_CODE = "retcode";
public static final String RET_MSG = "retmsg";
public static final String DATA = "data";
public static final String STATUS = "status";
public static final String SUCCESS = "success";
public static final String PROB = "prob";
public static final String ACCESS = "access";
public static final String MODEL_WRIGHT_HIT_RATE = "modelWrightHitRate";
public static final String INPUT_DATA_HIT_RATE = "inputDataHitRate";
public static final String MODELING_FEATURE_HIT_RATE = "modelingFeatureHitRate";
public static final String GUEST_MODEL_WEIGHT_HIT_RATE = "guestModelWeightHitRate";
public static final String GUEST_INPUT_DATA_HIT_RATE = "guestInputDataHitRate";
public static final String TAG_INPUT_FORMAT = "tag";
public static final String SPARSE_INPUT_FORMAT = "sparse";
public static final String MIN_MAX_SCALE = "min_max_scale";
public static final String STANDARD_SCALE = "standard_scale";
public static final String DSL_COMPONENTS = "components";
public static final String DSL_CODE_PATH = "CodePath";
public static final String DSL_INPUT = "input";
public static final String DSL_DATA = "data";
public static final String DSL_ARGS = "args";
public static final String HOST = "host";
public static final String GUEST = "guest";
public static final String PARTNER_PARTY_NAME = "partnerPartyName";
public static final String PARTY_NAME = "partyName";
public static final String MY_PARTY_NAME = "myPartyName";
public static final String FEDERATED_INFERENCE = "federatedInference";
public static final String FEDERATED_INFERENCE_FOR_TREE = "federatedInference4Tree";
public static final String ID = "id";
public static final String DEVICE_ID = "device_id";
public static final String PHONE_NUM = "phone_num";
public static final String FEDERATED_PARAMS = "federatedParams";
public static final String COMMIT_ID = "commitId";
public static final String BRANCH_MASTER = "master";
public static final String INFERENCE_AUDIT = "inferenceAudit";
public static final String INFERENCE = "inference";
public static final String INFERENCE_REQUEST = "inferenceRequest";
public static final String INFERENCE_RESULT = "inferenceResult";
public static final String FM_CROSS = "fm_cross";
public static final String CONTENT_TYPE = "Content-Type";
public static final String CONTENT_TYPE_JSON_UTF8 = "application/json;charset=UTF-8";
public static final String CHARSET_UTF8 = "UTF-8";
public static final String HTTP = "http";
public static final String HTTPS = "https";
public static final String TAG = "tag";
public static final String INPUT_DATA = "input_data";
public static final String OUTPUT_DATA = "output_data";
public static final String COMPONENT_NAME = "componentName";
public static final String TREE_COMPUTE_ROUND = "treeComputeRound";
public static final String SERVICE_NAME = "serviceName";
public static final String CALL_NAME = "callName";
public static final String TREE_LOCATION = "treeLocation";
public static final String UNARYCALL = "unaryCall";
public static final String GUEST_APP_ID = "guestAppId";
public static final String HOST_APP_ID = "hostAppId";
public static final String SERVICE_ID = "serviceId";
public static final String APPLY_ID = "applyId";
public static final String FUTURE = "future";
public static final String AUTH_FILE = "authFile";
public static final String ENCRYPT_TYPE = "encrypt_type";
public static final String MD5_SALT = "$1$ML";
public static final String USER_CACHE_KEY_PREFIX = "admin_user_";
public static final String CASE_ID = "caseid";
public static final String CODE = "code";
public static final String MESSAGE = "message";
public static final String MODEL_ID = "modelId";
public static final String MODEL_VERSION = "modelVersion";
public static final String TIMESTAMP = "timestamp";
public static final String APP_ID = "appid";
public static final String PARTY_ID = "partyId";
public static final String ROLE = "role";
public static final String PART_ID = "partId";
public static final String FEATURE_DATA = "featureData";
public static final String SESSION_TOKEN = "sessionToken";
public static final String DEFAULT_VERSION = "1.0";
public static final String SELF_PROJECT_NAME = "proxy";
public static final String SELF_ENVIRONMENT = "online";
public static final String HEAD = "head";
public static final String BODY = "body";
public static final String SERVICENAME_INFERENCE = "inference";
public static final String SERVICENAME_BATCH_INFERENCE = "batchInference";
public static final String SERVICENAME_START_INFERENCE_JOB = "startInferenceJob";
public static final String SERVICENAME_GET_INFERENCE_RESULT = "getInferenceResult";
// event
public static final String EVENT_INFERENCE = "inference";
public static final String EVENT_UNARYCALL = "unaryCall";
public static final String EVENT_ERROR = "error";
public static final String EVENT_SET_INFERENCE_CACHE = "setInferenceCache";
public static final String EVENT_SET_BATCH_INFERENCE_CACHE = "setBatchInferenceCache";
public static final String LOCAL_INFERENCE_DATA = "localInferenceData";
public static final String REMOTE_INFERENCE_DATA = "remoteInferenceData";
public static final String SBT_TREE_NODE_ID_ARRAY = "sbtTreeNodeIdArray";
public static final String REMOTE_METHOD_BATCH = "batch";
public static final String MODEL_NAME_SPACE = "modelNameSpace";
public static final String MODEL_TABLE_NAME = "modelTableName";
public static final String REGISTER_ENVIRONMENT = "online";
public static final String SERVICE_SERVING = "serving";
public static final String SERVICE_PROXY = "proxy";
public static final String SERVICE_ADMIN = "admin";
public static final String FAILED = "failed";
public static final String BATCH_PRC_TIMEOUT = "batch.rpc.timeout";
public static final String PASS_QPS = "passQps";
// parameters
public static final String PARAMS_INITIATOR = "initiator";
public static final String PARAMS_ROLE = "role";
public static final String PARAMS_JOB_PARAMETERS = "job_parameters";
public static final String PARAMS_SERVICE_ID = "service_id";
public static final String BATCH_INFERENCE_SPLIT_SIZE = "batch.inference.split.size";
public static final String WARN_LIST = "warnList";
public static final String ERROR_LIST = "errorList";
public static final String HEALTH_INFO = "healthInfo";
public static final String PROPERTY_ADMIN_HEALTH_CHECK_TIME = "health.check.time";
public static final String HTTP_CLIENT_CONFIG_CONN_REQ_TIME_OUT = "httpclinet.config.connection.req.timeout";
public static final String HTTP_CLIENT_CONFIG_CONN_TIME_OUT = "httpclient.config.connection.timeout";
public static final String HTTP_CLIENT_CONFIG_SOCK_TIME_OUT = "httpclient.config.sockect.timeout";
public static final String HTTP_CLIENT_INIT_POOL_MAX_TOTAL = "httpclient.init.pool.maxtotal";
public static final String HTTP_CLIENT_INIT_POOL_DEF_MAX_PER_ROUTE = "httpclient.init.pool.def.max.pre.route";
public static final String HTTP_CLIENT_INIT_POOL_SOCK_TIME_OUT = "httpclient.init.pool.sockect.timeout";
public static final String HTTP_CLIENT_INIT_POOL_CONN_TIME_OUT = "httpclient.init.pool.connection.timeout";
public static final String HTTP_CLIENT_INIT_POOL_CONN_REQ_TIME_OUT = "httpclient.init.pool.connection.req.timeout";
public static final String HTTP_CLIENT_TRAN_CONN_REQ_TIME_OUT = "httpclient.tran.connection.req.timeout";
public static final String HTTP_CLIENT_TRAN_CONN_TIME_OUT = "httpclient.tran.connection.timeout";
public static final String HTTP_CLIENT_TRAN_SOCK_TIME_OUT = "httpclient.tran.sockect.timeout";
public static final String PROPERTY_HTTP_CONNECT_TIMEOUT = "http.connect.timeout";
public static final String PROPERTY_HTTP_SOCKET_TIMEOUT = "http.socket.timeout";
public static final String PROPERTY_HTTP_MAX_POOL_SIZE = "http.max.pool.size";
public static final String PROPERTY_HTTP_CONNECT_REQUEST_TIMEOUT = "http.connect.request.timeout";
public static final String PROPERTY_HTTP_ADAPTER_URL = "http.adapter.url";
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/FederatedInferenceType.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/FederatedInferenceType.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
public enum FederatedInferenceType {
/**
* INITIATED
*/
INITIATED,
/**
* FEDERATED
*/
FEDERATED,
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/EncryptMethod.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/EncryptMethod.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
public enum EncryptMethod {
/**
* type MD5
*/
MD5,
/**
* type SHA256
*/
SHA256,
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/FederatedParty.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/FederatedParty.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
public class FederatedParty {
private String role;
private String partyId;
public FederatedParty() {
}
public FederatedParty(String role, String partyId) {
this.role = role;
this.partyId = partyId;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/ServiceDataWrapper.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/ServiceDataWrapper.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
public class ServiceDataWrapper {
private String url;
private String project;
private String environment;
private String name;
private String callName;
private String host;
private Integer port;
private String routerMode;
private Long version;
private Integer weight;
private int index;
private boolean needVerify;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getProject() {
return project;
}
public void setProject(String project) {
this.project = project;
}
public String getEnvironment() {
return environment;
}
public void setEnvironment(String environment) {
this.environment = environment;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getRouterMode() {
return routerMode;
}
public void setRouterMode(String routerMode) {
this.routerMode = routerMode;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public String getCallName() {
return callName;
}
public void setCallName(String callName) {
this.callName = callName;
}
public boolean isNeedVerify() {
return needVerify;
}
public void setNeedVerify(boolean needVerify) {
this.needVerify = needVerify;
}
@Override
public String toString() {
return JsonUtil.object2Json(this);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/GrpcConnectionPool.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/GrpcConnectionPool.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import io.grpc.ConnectivityState;
import io.grpc.ManagedChannel;
import io.grpc.netty.shaded.io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.shaded.io.grpc.netty.NegotiationType;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import io.grpc.netty.shaded.io.netty.handler.ssl.SslContextBuilder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLException;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
public class GrpcConnectionPool {
private static final Logger logger = LoggerFactory.getLogger(GrpcConnectionPool.class);
static private GrpcConnectionPool pool = new GrpcConnectionPool();
public ConcurrentHashMap<String, ChannelResource> poolMap = new ConcurrentHashMap<String, ChannelResource>();
Random r = new Random();
private int maxTotalPerAddress = Runtime.getRuntime().availableProcessors();
private long defaultLoadFactor = 10;
private ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor(1);
private GrpcConnectionPool() {
scheduledExecutorService.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
poolMap.forEach((k, v) -> {
try {
//logger.info("grpc pool {} channel size {} req count {}", k, v.getChannels().size(), v.getRequestCount().get() - v.getPreCheckCount());
if (needAddChannel(v)) {
String[] ipPort = k.split(":");
String ip = ipPort[0];
int port = Integer.parseInt(ipPort[1]);
ManagedChannel managedChannel = createManagedChannel(ip, port, v.getNettyServerInfo());
v.getChannels().add(managedChannel);
}
v.getChannels().forEach(e -> {
try {
ConnectivityState state = e.getState(true);
if (state.equals(ConnectivityState.TRANSIENT_FAILURE) || state.equals(ConnectivityState.SHUTDOWN)) {
fireChannelError(k, state);
}
} catch (Exception ex) {
ex.printStackTrace();
logger.error("channel {} check status error", k);
}
});
} catch (Exception e) {
logger.error("channel {} check status error", k);
}
});
}
},
1000,
10000,
TimeUnit.MILLISECONDS);
}
static public GrpcConnectionPool getPool() {
return pool;
}
private void fireChannelError(String k, ConnectivityState status) {
logger.error("grpc channel {} status is {}", k, status);
}
private boolean needAddChannel(ChannelResource channelResource) {
long requestCount = channelResource.getRequestCount().longValue();
long preCount = channelResource.getPreCheckCount();
long latestTimestamp = channelResource.getLatestChecktimestamp();
int channelSize = channelResource.getChannels().size();
long now = System.currentTimeMillis();
long loadFactor = ((requestCount - preCount) * 1000) / (channelSize * (now - latestTimestamp));
channelResource.setLatestChecktimestamp(now);
channelResource.setPreCheckCount(requestCount);
if (channelSize > maxTotalPerAddress) {
return false;
}
if (latestTimestamp == 0) {
return false;
}
if (channelSize > 0) {
if (loadFactor > defaultLoadFactor) {
return true;
} else {
return false;
}
} else {
return true;
}
}
public ManagedChannel getManagedChannel(String key) {
return getAManagedChannel(key, new NettyServerInfo());
}
private ManagedChannel getAManagedChannel(String key, NettyServerInfo nettyServerInfo) {
ChannelResource channelResource = poolMap.get(key);
if (channelResource == null) {
return createInner(key, nettyServerInfo);
} else {
return getRandomManagedChannel(channelResource);
}
}
public ManagedChannel getManagedChannel(String ip,int port, NettyServerInfo nettyServerInfo) {
String key = new StringBuilder().append(ip).append(":").append(port).toString();
return this.getAManagedChannel(key, nettyServerInfo);
}
public ManagedChannel getManagedChannel(String ip, int port) {
String key = new StringBuilder().append(ip).append(":").append(port).toString();
return this.getManagedChannel(key);
}
private ManagedChannel getRandomManagedChannel(ChannelResource channelResource) {
List<ManagedChannel> list = channelResource.getChannels();
Preconditions.checkArgument(list != null && list.size() > 0);
int index = r.nextInt(list.size());
ManagedChannel result = list.get(index);
channelResource.getRequestCount().addAndGet(1);
return result;
}
private synchronized ManagedChannel createInner(String key, NettyServerInfo nettyServerInfo) {
ChannelResource channelResource = poolMap.get(key);
if (channelResource == null) {
String[] ipPort = key.split(":");
String ip = ipPort[0];
int port = Integer.parseInt(ipPort[1]);
ManagedChannel managedChannel = createManagedChannel(ip, port, nettyServerInfo);
List<ManagedChannel> managedChannelList = new ArrayList<ManagedChannel>();
managedChannelList.add(managedChannel);
channelResource = new ChannelResource(key, nettyServerInfo);
channelResource.setChannels(managedChannelList);
channelResource.getRequestCount().addAndGet(1);
poolMap.put(key, channelResource);
return managedChannel;
} else {
return getRandomManagedChannel(channelResource);
}
}
public synchronized ManagedChannel createManagedChannel(String ip, int port, NettyServerInfo nettyServerInfo) {
try {
if (logger.isDebugEnabled()) {
logger.debug("create ManagedChannel");
}
NettyChannelBuilder channelBuilder = NettyChannelBuilder
.forAddress(ip, port)
.keepAliveTime(60, TimeUnit.SECONDS)
.keepAliveTimeout(60, TimeUnit.SECONDS)
.keepAliveWithoutCalls(true)
.idleTimeout(60, TimeUnit.SECONDS)
.perRpcBufferLimit(128 << 20)
.flowControlWindow(32 << 20)
.maxInboundMessageSize(32 << 20)
.enableRetry()
.retryBufferSize(16 << 20)
.maxRetryAttempts(20);
if (nettyServerInfo != null && nettyServerInfo.getNegotiationType() == NegotiationType.TLS
&& StringUtils.isNotBlank(nettyServerInfo.getCertChainFilePath())
&& StringUtils.isNotBlank(nettyServerInfo.getPrivateKeyFilePath())
&& StringUtils.isNotBlank(nettyServerInfo.getTrustCertCollectionFilePath())) {
SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient()
.keyManager(new File(nettyServerInfo.getCertChainFilePath()), new File(nettyServerInfo.getPrivateKeyFilePath()))
.trustManager(new File(nettyServerInfo.getTrustCertCollectionFilePath()))
.sessionTimeout(3600 << 4)
.sessionCacheSize(65536);
channelBuilder.sslContext(sslContextBuilder.build()).useTransportSecurity();
logger.info("running in secure mode for endpoint {}:{}, client crt path: {}, client key path: {}, ca crt path: {}.",
ip, port, nettyServerInfo.getCertChainFilePath(), nettyServerInfo.getPrivateKeyFilePath(),
nettyServerInfo.getTrustCertCollectionFilePath());
} else {
channelBuilder.usePlaintext();
}
return channelBuilder.build();
}
catch (Exception e) {
logger.error("create channel error : " ,e);
//e.printStackTrace();
}
return null;
}
class ChannelResource {
String address;
List<ManagedChannel> channels = Lists.newArrayList();
AtomicLong requestCount = new AtomicLong(0);
long latestChecktimestamp = 0;
long preCheckCount = 0;
NettyServerInfo nettyServerInfo;
public ChannelResource(String address) {
this(address, null);
}
public NettyServerInfo getNettyServerInfo() {
return nettyServerInfo;
}
public ChannelResource(String address, NettyServerInfo nettyServerInfo) {
this.address = address;
this.nettyServerInfo = nettyServerInfo;
}
public List<ManagedChannel> getChannels() {
return channels;
}
public void setChannels(List<ManagedChannel> channels) {
this.channels = channels;
}
public AtomicLong getRequestCount() {
return requestCount;
}
public void setRequestCount(AtomicLong requestCount) {
this.requestCount = requestCount;
}
public long getLatestChecktimestamp() {
return latestChecktimestamp;
}
public void setLatestChecktimestamp(long latestChecktimestamp) {
this.latestChecktimestamp = latestChecktimestamp;
}
public long getPreCheckCount() {
return preCheckCount;
}
public void setPreCheckCount(long preCheckCount) {
this.preCheckCount = preCheckCount;
}
}
} | java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/RequestParamWrapper.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/RequestParamWrapper.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import java.util.List;
public class RequestParamWrapper {
String host;
Integer port;
public String getTargetHost() {
return targetHost;
}
public void setTargetHost(String targetHost) {
this.targetHost = targetHost;
}
public Integer getTargetPort() {
return targetPort;
}
public void setTargetPort(Integer targetPort) {
this.targetPort = targetPort;
}
String targetHost;
Integer targetPort;
/**
* /admin/login
*/
String username;
String password;
/**
* /model/unbind
*/
String tableName;
String namespace;
List<String> serviceIds;
/**
* /service/update
*/
String url;
String routerMode;
Integer weight;
Long version;
/**
* /service/updateFlowRule
*/
String source;
Integer allowQps;
/**
* /component/updateConfig
*/
String filePath;
String data;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public Integer getAllowQps() {
return allowQps;
}
public void setAllowQps(Integer allowQps) {
this.allowQps = allowQps;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public List<String> getServiceIds() {
return serviceIds;
}
public void setServiceIds(List<String> serviceIds) {
this.serviceIds = serviceIds;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getRouterMode() {
return routerMode;
}
public void setRouterMode(String routerMode) {
this.routerMode = routerMode;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/ModelInfo.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/ModelInfo.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
public class ModelInfo {
private String name;
private String namespace;
public ModelInfo() {
}
public ModelInfo(String name, String namespace) {
this.name = name;
this.namespace = namespace;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/HttpAdapterResponse.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/HttpAdapterResponse.java | package com.webank.ai.fate.serving.core.bean;
import java.util.Map;
public class HttpAdapterResponse {
private int code;
private Map<String,Object> data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Map<String, Object> getData() {
return data;
}
public void setData(Map<String, Object> data) {
this.data = data;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/InferenceActionType.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/InferenceActionType.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
public enum InferenceActionType {
/**
* SYNC_RUN
*/
SYNC_RUN,
/**
* ASYNC_RUN
*/
ASYNC_RUN,
/**
* GET_RESULT
*/
GET_RESULT,
/**
*
*/
BATCH
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/CommonActionType.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/CommonActionType.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
public enum CommonActionType {
QUERY_METRICS,
UPDATE_FLOW_RULE,
LIST_PROPS,
QUERY_JVM,
UPDATE_SERVICE,
UPDATE_CONFIG,
CHECK_HEALTH,
QUERY_ROUTER,
ADD_ROUTER,
UPDATE_ROUTER,
DELETE_ROUTER,
SAVE_ROUTER
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/InferenceRequest.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/InferenceRequest.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import com.webank.ai.fate.serving.core.utils.InferenceUtils;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import java.util.HashMap;
import java.util.Map;
public class InferenceRequest implements Request {
protected String appid;
protected String partyId;
protected String modelVersion;
protected String modelId;
protected String seqno;
protected String caseId;
protected String serviceId;
public void setFeatureData(Map<String, Object> featureData) {
this.featureData = featureData;
}
protected Map<String, Object> featureData;
protected String applyId;
protected Map<String, Object> sendToRemoteFeatureData;
public InferenceRequest() {
seqno = InferenceUtils.generateSeqno();
caseId = InferenceUtils.generateCaseid();
featureData = new HashMap<>();
sendToRemoteFeatureData = new HashMap<>();
}
public String getApplyId() {
return applyId;
}
public void setApplyId(String applyId) {
this.applyId = applyId;
}
public String getServiceId() {
return serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public Map<String, Object> getSendToRemoteFeatureData() {
return sendToRemoteFeatureData;
}
public void setSendToRemoteFeatureData(Map<String, Object> sendToRemoteFeatureData) {
this.sendToRemoteFeatureData = sendToRemoteFeatureData;
}
public void setCaseId(String caseId) {
this.caseId = caseId;
}
@Override
public String getSeqno() {
return seqno;
}
@Override
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
this.partyId = appid;
}
@Override
public String getCaseId() {
return caseId;
}
@Override
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
this.appid = partyId;
}
@Override
public String getModelVersion() {
return modelVersion;
}
public void setModelVersion(String modelVersion) {
this.modelVersion = modelVersion;
}
@Override
public String getModelId() {
return modelId;
}
public void setModelId(String modelId) {
this.modelId = modelId;
}
@Override
public Map<String, Object> getFeatureData() {
return featureData;
}
public boolean haveAppId() {
return (!StringUtils.isEmpty(appid) || !StringUtils.isEmpty(partyId));
}
@Override
public String toString() {
String result = "";
try {
result = JsonUtil.object2Json(this);
} catch (Throwable e) {
}
return result;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/NettyServerInfo.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/NettyServerInfo.java | package com.webank.ai.fate.serving.core.bean;
import io.grpc.netty.shaded.io.grpc.netty.NegotiationType;
public class NettyServerInfo {
public NettyServerInfo() {
this.negotiationType = NegotiationType.PLAINTEXT;
}
public NettyServerInfo(String negotiationType, String certChainFilePath, String privateKeyFilePath, String trustCertCollectionFilePath) {
this.negotiationType = NegotiationType.valueOf(negotiationType);
this.certChainFilePath = certChainFilePath;
this.privateKeyFilePath = privateKeyFilePath;
this.trustCertCollectionFilePath = trustCertCollectionFilePath;
}
private NegotiationType negotiationType;
private String certChainFilePath;
private String privateKeyFilePath;
private String trustCertCollectionFilePath;
public NegotiationType getNegotiationType() {
return negotiationType;
}
public void setNegotiationType(NegotiationType negotiationType) {
this.negotiationType = negotiationType;
}
public String getCertChainFilePath() {
return certChainFilePath;
}
public void setCertChainFilePath(String certChainFilePath) {
this.certChainFilePath = certChainFilePath;
}
public String getPrivateKeyFilePath() {
return privateKeyFilePath;
}
public void setPrivateKeyFilePath(String privateKeyFilePath) {
this.privateKeyFilePath = privateKeyFilePath;
}
public String getTrustCertCollectionFilePath() {
return trustCertCollectionFilePath;
}
public void setTrustCertCollectionFilePath(String trustCertCollectionFilePath) {
this.trustCertCollectionFilePath = trustCertCollectionFilePath;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/ModelActionType.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/ModelActionType.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
public enum ModelActionType {
/**
* MODEL_LOAD
*/
MODEL_LOAD,
/**
* MODEL_PUBLISH_ONLINE
*/
MODEL_PUBLISH_ONLINE,
UNLOAD,
UNBIND,
QUERY_MODEL,
FETCH_MODEL,
MODEL_TRANSFER
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/ReturnResult.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/ReturnResult.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
public class ReturnResult {
private static final Logger logger = LoggerFactory.getLogger(ReturnResult.class);
private int retcode;
private String retmsg = "";
private String caseid = "";
private Map<String, Object> data;
private Map<String, Object> log;
private Map<String, Object> warn;
private int flag;
public ReturnResult() {
this.data = new HashMap<>();
this.log = new HashMap<>();
this.warn = new HashMap<>();
}
public static ReturnResult build(int retcode, String retmsg, Map<String, Object> data) {
ReturnResult returnResult = new ReturnResult();
returnResult.setRetcode(retcode);
returnResult.setRetmsg(retmsg);
returnResult.setData(data);
return returnResult;
}
public static ReturnResult build(int retcode, String retmsg) {
ReturnResult returnResult = new ReturnResult();
returnResult.setRetcode(retcode);
returnResult.setRetmsg(retmsg);
return returnResult;
}
public static ReturnResult build(int retcode, Map<String, Object> data) {
ReturnResult returnResult = new ReturnResult();
returnResult.setRetcode(retcode);
returnResult.setData(data);
return returnResult;
}
public int getFlag() {
return flag;
}
public void setFlag(int flag) {
this.flag = flag;
}
public int getRetcode() {
return retcode;
}
public void setRetcode(int retcode) {
this.retcode = retcode;
}
public String getRetmsg() {
return retmsg != null ? retmsg : "";
}
public void setRetmsg(String retmsg) {
this.retmsg = retmsg;
}
public Map<String, Object> getData() {
return data;
}
public void setData(Map<String, Object> data) {
this.data = data;
}
public Map<String, Object> getLog() {
return log;
}
public void setLog(Map<String, Object> log) {
this.log = log;
}
public Map<String, Object> getWarn() {
return warn;
}
public void setWarn(Map<String, Object> warn) {
this.warn = warn;
}
public String getCaseid() {
return caseid;
}
public void setCaseid(String caseid) {
this.caseid = caseid;
}
@Override
public String toString() {
String result = JsonUtil.object2Json(this);
return result;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/Request.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/Request.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import java.util.Map;
public interface Request {
public String getSeqno();
public String getAppid();
public String getCaseId();
public String getPartyId();
public String getModelVersion();
public String getModelId();
public Map<String, Object> getFeatureData();
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/RouterTableResponseRecord.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/RouterTableResponseRecord.java | package com.webank.ai.fate.serving.core.bean;
import com.google.gson.JsonArray;
import java.util.List;
/**
* @auther Xiongli
* @date 2021/6/29
* @remark
*/
public class RouterTableResponseRecord {
String partyId;
Long createTime;
Long updateTime;
List<RouterTable> routerList;
int count;
public static class RouterTable {
String ip;
Integer port;
boolean useSSL;
String negotiationType;
String certChainFile;
String privateKeyFile;
String caFile;
String serverType;
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public boolean isUseSSL() {
return useSSL;
}
public void setUseSSL(boolean useSSL) {
this.useSSL = useSSL;
}
public String getNegotiationType() {
return negotiationType;
}
public void setNegotiationType(String negotiationType) {
this.negotiationType = negotiationType;
}
public String getCertChainFile() {
return certChainFile;
}
public void setCertChainFile(String certChainFile) {
this.certChainFile = certChainFile;
}
public String getPrivateKeyFile() {
return privateKeyFile;
}
public void setPrivateKeyFile(String privateKeyFile) {
this.privateKeyFile = privateKeyFile;
}
public String getCaFile() {
return caFile;
}
public void setCaFile(String caFile) {
this.caFile = caFile;
}
public String getServerType() {
return serverType;
}
public void setServerType(String serverType) {
this.serverType = serverType;
}
}
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
}
public Long getCreateTime() {
return createTime;
}
public void setCreateTime(Long createTime) {
this.createTime = createTime;
}
public Long getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Long updateTime) {
this.updateTime = updateTime;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<RouterTable> getRouterList() {
return routerList;
}
public void setRouterList(List<RouterTable> routerList) {
this.routerList = routerList;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/BatchHostFeatureAdaptorResult.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/BatchHostFeatureAdaptorResult.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import com.google.common.collect.Maps;
import java.util.Map;
/**
* adaptor 专用
*/
public class BatchHostFeatureAdaptorResult {
int retcode;
String caseId;
/**
* key 为请求中的index
*/
Map<Integer, SingleBatchHostFeatureAdaptorResult> indexResultMap = Maps.newHashMap();
public int getRetcode() {
return retcode;
}
public void setRetcode(int retcode) {
this.retcode = retcode;
}
public String getCaseId() {
return caseId;
}
public void setCaseId(String caseId) {
this.caseId = caseId;
}
public Map<Integer, SingleBatchHostFeatureAdaptorResult> getIndexResultMap() {
return indexResultMap;
}
public void setIndexResultMap(Map<Integer, SingleBatchHostFeatureAdaptorResult> indexResultMap) {
this.indexResultMap = indexResultMap;
}
public static class SingleBatchHostFeatureAdaptorResult {
int index;
int retcode;
String msg;
Map<String, Object> features;
public Map<String, Object> getFeatures() {
return features;
}
public void setFeatures(Map<String, Object> features) {
this.features = features;
}
public Integer getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getRetcode() {
return retcode;
}
public void setRetcode(int retcode) {
this.retcode = retcode;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/BatchInferenceResult.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/BatchInferenceResult.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
import com.google.common.collect.Maps;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class BatchInferenceResult extends ReturnResult {
List<SingleInferenceResult> batchDataList;
private Map<Integer, SingleInferenceResult> singleInferenceResultMap;
public List<SingleInferenceResult> getBatchDataList() {
if (batchDataList == null) {
batchDataList = new ArrayList<>();
}
return batchDataList;
}
public void setBatchDataList(List<SingleInferenceResult> batchDataList) {
this.batchDataList = batchDataList;
}
public void rebuild() {
Map result = Maps.newHashMap();
List<BatchInferenceResult.SingleInferenceResult> batchInferences = this.getBatchDataList();
for (BatchInferenceResult.SingleInferenceResult singleInferenceResult : batchInferences) {
result.put(singleInferenceResult.getIndex(), singleInferenceResult);
}
singleInferenceResultMap = result;
}
public Map<Integer, SingleInferenceResult> getSingleInferenceResultMap() {
if (singleInferenceResultMap == null) {
rebuild();
}
return singleInferenceResultMap;
}
static public class SingleInferenceResult {
Integer index;
int retcode;
String retmsg;
Map<String, Object> data;
public SingleInferenceResult() {
}
public SingleInferenceResult(Integer index, int retcode, String msg, Map<String, Object> data) {
this.index = index;
this.retcode = retcode;
this.retmsg = msg;
this.data = data;
}
public int getRetcode() {
return retcode;
}
public void setRetcode(int retcode) {
this.retcode = retcode;
}
public Map<String, Object> getData() {
return data;
}
public void setData(Map<String, Object> data) {
this.data = data;
}
public Integer getIndex() {
return index;
}
public void setIndex(Integer index) {
this.index = index;
}
public String getRetmsg() {
return retmsg;
}
public void setRetmsg(String retmsg) {
this.retmsg = retmsg;
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/MergeRemoteInferenceParam.java | fate-serving-core/src/main/java/com/webank/ai/fate/serving/core/bean/MergeRemoteInferenceParam.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.core.bean;
/**
* @Description TODO
* @Author kaideng
**/
public class MergeRemoteInferenceParam {
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/Bootstrap.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/Bootstrap.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.admin;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.common.flow.JvmInfoCounter;
import com.webank.ai.fate.serving.common.rpc.core.AbstractServiceAdaptor;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;
import java.io.*;
import java.util.Properties;
@SpringBootApplication
@PropertySource("classpath:application.properties")
public class Bootstrap {
private static Logger logger = LoggerFactory.getLogger(Bootstrap.class);
private static ApplicationContext applicationContext;
public static void main(String[] args) {
try {
parseConfig();
Bootstrap bootstrap = new Bootstrap();
bootstrap.start(args);
Runtime.getRuntime().addShutdownHook(new Thread(() -> bootstrap.stop()));
} catch (Exception ex) {
logger.error("serving-admin start error", ex);
System.exit(1);
}
}
public static void parseConfig() {
ClassPathResource classPathResource = new ClassPathResource("application.properties");
try {
File file = classPathResource.getFile();
Properties environment = new Properties();
try (InputStream inputStream = new BufferedInputStream(new FileInputStream(file))) {
environment.load(inputStream);
} catch (FileNotFoundException e) {
logger.error("profile application.properties not found");
} catch (IOException e) {
logger.error("parse config error, {}", e.getMessage());
}
// serving-admin must open the zookeeper registry
MetaInfo.PROPERTY_USE_ZK_ROUTER = true;
MetaInfo.PROPERTY_SERVER_PORT = environment.getProperty(Dict.PROPERTY_SERVER_PORT) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_SERVER_PORT)) : 8350;
MetaInfo.PROPERTY_ZK_URL = environment.getProperty(Dict.PROPERTY_ZK_URL);
MetaInfo.PROPERTY_CACHE_TYPE = environment.getProperty(Dict.PROPERTY_CACHE_TYPE, "local");
MetaInfo.PROPERTY_REDIS_IP = environment.getProperty(Dict.PROPERTY_REDIS_IP);
MetaInfo.PROPERTY_REDIS_PASSWORD = environment.getProperty(Dict.PROPERTY_REDIS_PASSWORD);
MetaInfo.PROPERTY_REDIS_PORT = environment.getProperty(Dict.PROPERTY_REDIS_PORT) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_REDIS_PORT)) : 6379;
MetaInfo.PROPERTY_REDIS_TIMEOUT = environment.getProperty(Dict.PROPERTY_REDIS_TIMEOUT) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_REDIS_TIMEOUT)) : 2000;
MetaInfo.PROPERTY_REDIS_MAX_TOTAL = environment.getProperty(Dict.PROPERTY_REDIS_MAX_TOTAL) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_REDIS_MAX_TOTAL)) : 20;
MetaInfo.PROPERTY_REDIS_MAX_IDLE = environment.getProperty(Dict.PROPERTY_REDIS_MAX_IDLE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_REDIS_MAX_IDLE)) : 2;
MetaInfo.PROPERTY_REDIS_EXPIRE = environment.getProperty(Dict.PROPERTY_REDIS_EXPIRE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_REDIS_EXPIRE)) : 3000;
MetaInfo.PROPERTY_LOCAL_CACHE_MAXSIZE = environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_MAXSIZE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_MAXSIZE)) : 10000;
MetaInfo.PROPERTY_LOCAL_CACHE_EXPIRE = environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_EXPIRE) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_EXPIRE)) : 300;
MetaInfo.PROPERTY_LOCAL_CACHE_INTERVAL = environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_INTERVAL) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_LOCAL_CACHE_INTERVAL)) : 3;
MetaInfo.PROPERTY_FATEFLOW_LOAD_URL = environment.getProperty(Dict.PROPERTY_FATEFLOW_LOAD_URL);
MetaInfo.PROPERTY_FATEFLOW_BIND_URL = environment.getProperty(Dict.PROPERTY_FATEFLOW_LOAD_URL);
MetaInfo.PROPERTY_GRPC_TIMEOUT = Integer.valueOf(environment.getProperty(Dict.PROPERTY_GRPC_TIMEOUT, "5000"));
MetaInfo.PROPERTY_ACL_ENABLE = Boolean.valueOf(environment.getProperty(Dict.PROPERTY_ACL_ENABLE, "false"));
MetaInfo.PROPERTY_ACL_USERNAME = environment.getProperty(Dict.PROPERTY_ACL_USERNAME);
MetaInfo.PROPERTY_ACL_PASSWORD = environment.getProperty(Dict.PROPERTY_ACL_PASSWORD);
MetaInfo.PROPERTY_PRINT_INPUT_DATA = environment.getProperty(Dict.PROPERTY_PRINT_INPUT_DATA) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_PRINT_INPUT_DATA)) : false;
MetaInfo.PROPERTY_PRINT_OUTPUT_DATA = environment.getProperty(Dict.PROPERTY_PRINT_OUTPUT_DATA) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_PRINT_OUTPUT_DATA)) : false;
MetaInfo.PROPERTY_ADMIN_HEALTH_CHECK_TIME = environment.getProperty(Dict.PROPERTY_ADMIN_HEALTH_CHECK_TIME) != null ? Integer.valueOf(environment.getProperty(Dict.PROPERTY_ADMIN_HEALTH_CHECK_TIME)) : 30;
MetaInfo.PROPERTY_ALLOW_HEALTH_CHECK = environment.getProperty(Dict.PROPERTY_ALLOW_HEALTH_CHECK) != null ? Boolean.valueOf(environment.getProperty(Dict.PROPERTY_ALLOW_HEALTH_CHECK)) : true;
} catch (Exception e) {
e.printStackTrace();
logger.error("init meta info error", e);
}
}
public void start(String[] args) {
SpringApplication springApplication = new SpringApplication(Bootstrap.class);
applicationContext = springApplication.run(args);
JvmInfoCounter.start();
}
public void stop() {
logger.info("try to shutdown server ...");
AbstractServiceAdaptor.isOpen = false;
boolean useZkRouter = MetaInfo.PROPERTY_USE_ZK_ROUTER;
if (useZkRouter) {
ZookeeperRegistry zookeeperRegistry = applicationContext.getBean(ZookeeperRegistry.class);
zookeeperRegistry.destroy();
}
int tryNum = 0;
while (AbstractServiceAdaptor.requestInHandle.get() > 0 && tryNum < 30) {
logger.info("try to shutdown,try count {}, remain {}", tryNum, AbstractServiceAdaptor.requestInHandle.get());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
tryNum++;
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/LoginController.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/LoginController.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.admin.controller;
import com.google.common.base.Preconditions;
import com.webank.ai.fate.serving.common.cache.Cache;
import com.webank.ai.fate.serving.core.bean.*;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.utils.EncryptUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* @Description User management
* @Date: 2020/3/25 11:13
* @Author: v_dylanxu
*/
@RequestMapping("/api")
@RestController
public class LoginController {
private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
@Value("${admin.username}")
private String username;
@Value("${admin.password}")
private String hashedPassword;
@Value("${admin.isEncrypt}")
private Boolean isEncrypt;
@Autowired
private Cache cache;
@PostMapping("/admin/login")
public ReturnResult login(@RequestBody RequestParamWrapper requestParams) {
String username = requestParams.getUsername();
String password = requestParams.getPassword();
boolean passwordIfCorrect;
Preconditions.checkArgument(StringUtils.isNotBlank(username), "parameter username is blank");
Preconditions.checkArgument(StringUtils.isNotBlank(password), "parameter password is blank");
ReturnResult result = new ReturnResult();
if (isEncrypt) {
passwordIfCorrect = new BCryptPasswordEncoder().matches(password, this.hashedPassword);
} else {
passwordIfCorrect = password.equals(this.hashedPassword);
}
if (username.equals(this.username) && passwordIfCorrect) {
String userInfo = StringUtils.join(Arrays.asList(username, password), "_");
String token = EncryptUtils.encrypt(Dict.USER_CACHE_KEY_PREFIX + userInfo, EncryptMethod.MD5);
cache.put(token, userInfo, MetaInfo.PROPERTY_CACHE_TYPE.equalsIgnoreCase("local") ? MetaInfo.PROPERTY_LOCAL_CACHE_EXPIRE : MetaInfo.PROPERTY_REDIS_EXPIRE);
logger.info("user {} login success.", username);
Map data = new HashMap<>();
data.put("timestamp", System.currentTimeMillis());
data.put(Dict.SESSION_TOKEN, token);
result.setRetcode(StatusCode.SUCCESS);
result.setData(data);
} else {
logger.error("user {} login failure, username or password {} is wrong.", username,password);
result.setRetcode(StatusCode.PARAM_ERROR);
result.setRetmsg("username or password is wrong");
}
return result;
}
@PostMapping("/admin/logout")
public ReturnResult logout(HttpServletRequest request) {
ReturnResult result = new ReturnResult();
String sessionToken = request.getHeader(Dict.SESSION_TOKEN);
String userInfo = (String) cache.get(sessionToken);
if (StringUtils.isNotBlank(userInfo)) {
cache.delete(sessionToken);
result.setRetcode(StatusCode.SUCCESS);
} else {
logger.error("Session token unavailable");
result.setRetcode(StatusCode.PARAM_ERROR);
result.setRetmsg("Session token unavailable");
}
return result;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/RouterController.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/RouterController.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.admin.controller;
import com.google.common.collect.Maps;
import com.webank.ai.fate.api.networking.common.CommonServiceGrpc;
import com.webank.ai.fate.api.networking.common.CommonServiceProto;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.admin.services.ComponentService;
import com.webank.ai.fate.serving.admin.utils.NetAddressChecker;
import com.webank.ai.fate.serving.core.bean.*;
import com.webank.ai.fate.serving.core.exceptions.RemoteRpcException;
import com.webank.ai.fate.serving.core.exceptions.SysException;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.core.utils.NetUtils;
import com.webank.ai.fate.serving.core.utils.ParameterUtils;
import com.webank.ai.fate.serving.proxy.rpc.grpc.RouterTableServiceGrpc;
import com.webank.ai.fate.serving.proxy.rpc.grpc.RouterTableServiceProto;
import io.grpc.ManagedChannel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@RequestMapping("/api")
@RestController
public class RouterController {
private static final Logger logger = LoggerFactory.getLogger(RouterController.class);
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
@Autowired
ZookeeperRegistry zookeeperRegistry;
@Autowired
ComponentService componentService;
static final String ROUTER_URL = "proxy/online/queryRouter";
@PostMapping("/router/query")
public ReturnResult queryRouter(@RequestBody RouterTableRequest routerTable) {
List<URL> urls = zookeeperRegistry.getCacheUrls(URL.valueOf(ROUTER_URL));
if (urls == null || urls.size() == 0) {
return new ReturnResult();
}
Map<String, Object> data = Maps.newHashMap();
String serverHost = routerTable.getServerHost();
Integer serverPort = routerTable.getServerPort();
checkAddress(serverHost, serverPort);
String routerTableInfo = "";
boolean matched = false;
for (URL url : urls) {
logger.info("url {} {} {} {}", url.getHost(), url.getPort(), serverHost, serverPort);
if (serverHost.equals(url.getHost()) && serverPort.intValue() == serverPort) { // todo-wcy
matched = true;
}
}
int statusCode;
String retMsg;
if (!matched) {
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(serverHost, serverPort);
CommonServiceGrpc.CommonServiceBlockingStub blockingStub = CommonServiceGrpc.newBlockingStub(managedChannel);
blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
CommonServiceProto.QueryPropsRequest.Builder builder = CommonServiceProto.QueryPropsRequest.newBuilder();
CommonServiceProto.CommonResponse response = blockingStub.listProps(builder.build());
Map<String, Object> propMap = JsonUtil.json2Object(response.getData().toStringUtf8(), Map.class);
routerTableInfo = propMap.get(Dict.PROXY_ROUTER_TABLE) != null ? propMap.get(Dict.PROXY_ROUTER_TABLE).toString() : "";
statusCode = response.getStatusCode();
retMsg = response.getMessage();
} else {
if (logger.isDebugEnabled()) {
logger.debug("query router, host: {}, port: {}", serverHost, serverPort);
}
RouterTableServiceGrpc.RouterTableServiceBlockingStub blockingStub = getRouterTableServiceBlockingStub(serverHost, serverPort);
RouterTableServiceProto.RouterOperatetRequest.Builder queryRouterRequestBuilder = RouterTableServiceProto.RouterOperatetRequest.newBuilder();
RouterTableServiceProto.RouterOperatetResponse response = blockingStub.queryRouter(queryRouterRequestBuilder.build());
routerTableInfo = response.getData().toStringUtf8();
statusCode = response.getStatusCode();
retMsg = response.getMessage();
}
data.put("routerTable", routerTableInfo);
data.put("changeAble", matched);
return ReturnResult.build(statusCode, retMsg, data);
}
private RouterTableServiceGrpc.RouterTableServiceBlockingStub getRouterTableServiceBlockingStub(String host, Integer port) {
ParameterUtils.checkArgument(StringUtils.isNotBlank(host), "parameter host is blank");
ParameterUtils.checkArgument(port != null && port != 0, "parameter port was wrong");
NetAddressChecker.check(host, port);
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
RouterTableServiceGrpc.RouterTableServiceBlockingStub blockingStub = RouterTableServiceGrpc.newBlockingStub(managedChannel);
blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
return blockingStub;
}
@PostMapping("/router/save")
public ReturnResult saveRouter(@RequestBody RouterTableRequest routerTables) {
logger.info("save router table {}", routerTables.getRouterTableList());
checkAddress(routerTables.getServerHost(), routerTables.getServerPort());
String content = JsonUtil.object2Json(routerTables.getRouterTableList());
// for (Map routerTable : parseRouterInfo(routerTables.getRouterTableList())) {
// checkParameter(routerTable);
// }
RouterTableServiceGrpc.RouterTableServiceBlockingStub blockingStub = getRouterTableServiceBlockingStub(routerTables.getServerHost(), routerTables.getServerPort());
RouterTableServiceProto.RouterOperatetRequest.Builder addRouterBuilder = RouterTableServiceProto.RouterOperatetRequest.newBuilder();
addRouterBuilder.setRouterInfo(content);
RouterTableServiceProto.RouterOperatetResponse response = blockingStub.saveRouter(addRouterBuilder.build());
if (logger.isDebugEnabled()) {
logger.debug("response: {}", response);
}
if (response == null) {
throw new RemoteRpcException("Remote rpc error ,target: " + routerTables.getServerHost() + ":" + routerTables.getServerPort());
}
return ReturnResult.build(response.getStatusCode(), response.getMessage());
}
// private void checkParameter(RouterTableServiceProto.RouterTableInfo routerTable) {
// ParameterUtils.checkArgument(checkPartyId(routerTable.getPartyId()), "parameter partyId:{" + routerTable.getPartyId() + "} must be default or number");
// ParameterUtils.checkArgument(NetUtils.isValidAddress(routerTable.getHost() + ":" + routerTable.getPort()), "parameter Network Access : {" + routerTable.getHost() + ":" + routerTable.getPort() + "} format error");
// ParameterUtils.checkArgument(StringUtils.isNotBlank(routerTable.getServerType()), "parameter serverType must is blank");
// if (routerTable.getUseSSL()) {
// ParameterUtils.checkArgument(StringUtils.isBlank(routerTable.getCertChainFile()), "parameter certificatePath is blank");
// }
// }
private void checkAddress(String serverHost, Integer serverPort) {
ParameterUtils.checkArgument(StringUtils.isNotBlank(serverHost), "parameter serverHost is blank");
ParameterUtils.checkArgument(serverPort != 0, "parameter serverPort is blank");
if (logger.isDebugEnabled()) {
logger.debug("add router, host: {}, port: {}", serverHost, serverPort);
}
}
// private void checkAddress(RouterTableRequest routerTables) {
// ParameterUtils.checkArgument(StringUtils.isNotBlank(routerTables.getServerHost()), "parameter serverHost is blank");
// ParameterUtils.checkArgument(routerTables.getServerPort() != 0, "parameter serverPort is blank");
//
// List<RouterTableRequest.RouterTable> routerTableList = routerTables.getRouterTableList();
// if(routerTableList != null){
// for (RouterTableRequest.RouterTable routerTable : routerTableList) {
// ParameterUtils.checkArgument(NetUtils.isValidAddress(routerTable.getIp() + ":" + routerTable.getPort()), "parameter Network Access : {" + routerTable.getIp() + ":" + routerTable.getPort() + "} format error");
// }
// }
// }
public boolean checkPartyId(String partyId) {
return "default".equals(partyId) || partyId.matches("^\\d{1,5}$");
}
// public List<RouterTableServiceProto.RouterTableInfo> parseRouterInfo(List<RouterTableRequest.RouterTable> routerTableList) {
// List<RouterTableServiceProto.RouterTableInfo> routerTableInfoList = new ArrayList<>();
// if (routerTableList == null) {
// return routerTableInfoList;
// }
// for (RouterTableRequest.RouterTable routerTable : routerTableList) {
// if (routerTable == null) continue;
// RouterTableServiceProto.RouterTableInfo.Builder builder = RouterTableServiceProto.RouterTableInfo.newBuilder();
// builder.setPartyId(routerTable.getPartyId())
// .setHost(routerTable.getIp())
// .setPort(routerTable.getPort())
// .setUseSSL(routerTable.isUseSSL())
// .setNegotiationType(routerTable.getNegotiationType())
// .setCertChainFile(routerTable.getCertChainFile())
// .setPrivateKeyFile(routerTable.getPrivateKeyFile())
// .setCaFile(routerTable.getCaFile())
// .setServerType(routerTable.getServerType());
// routerTableInfoList.add(builder.build());
// }
// return routerTableInfoList;
// }
public static int comparePartyId(String prev, String next) {
String numberReg = "^\\d{1,9}$";
Integer prevInt = prev.matches(numberReg) ? Integer.parseInt(prev) : 0;
Integer nextInt = next.matches(numberReg) ? Integer.parseInt(next) : 0;
return prevInt - nextInt;
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/MonitorController.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/MonitorController.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.admin.controller;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.protobuf.ByteString;
import com.webank.ai.fate.api.networking.common.CommonServiceGrpc;
import com.webank.ai.fate.api.networking.common.CommonServiceProto;
import com.webank.ai.fate.api.serving.InferenceServiceGrpc;
import com.webank.ai.fate.api.serving.InferenceServiceProto;
import com.webank.ai.fate.serving.admin.services.ComponentService;
import com.webank.ai.fate.serving.admin.services.HealthCheckService;
import com.webank.ai.fate.serving.admin.utils.NetAddressChecker;
import com.webank.ai.fate.serving.common.flow.JvmInfo;
import com.webank.ai.fate.serving.common.flow.MetricNode;
import com.webank.ai.fate.serving.common.health.HealthCheckRecord;
import com.webank.ai.fate.serving.common.health.HealthCheckStatus;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.GrpcConnectionPool;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.exceptions.RemoteRpcException;
import com.webank.ai.fate.serving.core.exceptions.SysException;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.core.utils.NetUtils;
import com.webank.ai.fate.serving.core.utils.ThreadPoolUtil;
import io.grpc.ManagedChannel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
@RequestMapping("/api")
@RestController
public class MonitorController {
Logger logger = LoggerFactory.getLogger(MonitorController.class);
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
@Autowired
ComponentService componentService;
@Autowired
HealthCheckService healthCheckService;
@GetMapping("/monitor/queryJvm")
public ReturnResult queryJvmData(String host, int port) {
CommonServiceGrpc.CommonServiceBlockingStub blockingStub = getMonitorServiceBlockStub(host, port);
blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
CommonServiceProto.QueryJvmInfoRequest.Builder builder = CommonServiceProto.QueryJvmInfoRequest.newBuilder();
CommonServiceProto.CommonResponse commonResponse = blockingStub.queryJvmInfo(builder.build());
List<JvmInfo> resultList = Lists.newArrayList();
if (commonResponse.getData() != null && !commonResponse.getData().toStringUtf8().equals("null")) {
List<JvmInfo> resultData = JsonUtil.json2List(commonResponse.getData().toStringUtf8(), new TypeReference<List<JvmInfo>>() {
});
if (resultData != null) {
resultList = resultData;
}
resultList = resultList.stream()
.sorted(((o1, o2) -> o1.getTimestamp() == o2.getTimestamp() ? 0 : ((o1.getTimestamp() - o2.getTimestamp()) > 0 ? 1 : -1)))
.collect(Collectors.toList());
}
Map map = Maps.newHashMap();
map.put("total", resultList.size());
map.put("rows", resultList);
return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, map);
}
@GetMapping("/monitor/query")
public ReturnResult queryMonitorData(String host, int port, String source) {
CommonServiceGrpc.CommonServiceBlockingStub blockingStub = getMonitorServiceBlockStub(host, port);
blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
CommonServiceProto.QueryMetricRequest.Builder builder = CommonServiceProto.QueryMetricRequest.newBuilder();
long now = System.currentTimeMillis();
builder.setBeginMs(now - 15000);
builder.setEndMs(now);
if (StringUtils.isNotBlank(source)) {
builder.setSource(source);
}
builder.setType(CommonServiceProto.MetricType.INTERFACE);
CommonServiceProto.CommonResponse commonResponse = blockingStub.queryMetrics(builder.build());
List<MetricNode> metricNodes = Lists.newArrayList();
if (commonResponse.getData() != null && !commonResponse.getData().toStringUtf8().equals("null")) {
List<MetricNode> resultData = JsonUtil.json2List(commonResponse.getData().toStringUtf8(), new TypeReference<List<MetricNode>>() {
});
if (resultData != null) {
metricNodes = resultData;
}
}
metricNodes = metricNodes.stream()
.sorted(((o1, o2) -> o1.getTimestamp() == o2.getTimestamp() ? 0 : ((o1.getTimestamp() - o2.getTimestamp()) > 0 ? 1 : -1)))
.collect(Collectors.toList());
Map<String, Object> dataMap = Maps.newHashMap();
if (metricNodes != null) {
metricNodes.forEach(metricNode -> {
List<MetricNode> nodes = (List<MetricNode>) dataMap.get(metricNode.getResource());
if (nodes == null) {
nodes = Lists.newArrayList();
}
nodes.add(metricNode);
dataMap.put(metricNode.getResource(), nodes);
});
}
return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, dataMap);
}
@GetMapping("/monitor/queryModel")
public ReturnResult queryModelMonitorData(String host, int port, String source) {
Preconditions.checkArgument(StringUtils.isNotBlank(source), "parameter source is blank");
CommonServiceGrpc.CommonServiceBlockingStub blockingStub = getMonitorServiceBlockStub(host, port);
blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
CommonServiceProto.QueryMetricRequest.Builder builder = CommonServiceProto.QueryMetricRequest.newBuilder();
long now = System.currentTimeMillis();
builder.setBeginMs(now - 15000);
builder.setEndMs(now);
if (StringUtils.isNotBlank(source)) {
builder.setSource(source);
}
builder.setType(CommonServiceProto.MetricType.MODEL);
CommonServiceProto.CommonResponse commonResponse = blockingStub.queryMetrics(builder.build());
List<MetricNode> metricNodes = Lists.newArrayList();
if (commonResponse.getData() != null && !commonResponse.getData().toStringUtf8().equals("null")) {
List<MetricNode> resultData = JsonUtil.json2List(commonResponse.getData().toStringUtf8(), new TypeReference<List<MetricNode>>() {
});
if (resultData != null) {
metricNodes = resultData;
}
}
metricNodes = metricNodes.stream()
.sorted(((o1, o2) -> o1.getTimestamp() == o2.getTimestamp() ? 0 : ((o1.getTimestamp() - o2.getTimestamp()) > 0 ? 1 : -1)))
.collect(Collectors.toList());
Map<String, Object> dataMap = Maps.newHashMap();
if (metricNodes != null) {
metricNodes.forEach(metricNode -> {
List<MetricNode> nodes = (List<MetricNode>) dataMap.get(metricNode.getResource());
if (nodes == null) {
nodes = Lists.newArrayList();
}
nodes.add(metricNode);
dataMap.put(metricNode.getResource(), nodes);
});
}
return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, dataMap);
}
@GetMapping("monitor/checkHealth")
public ReturnResult checkHealthService() {
Map data = healthCheckService.getHealthCheckInfo();
Map resultData = Maps.newHashMap();
resultData.putAll(data);
Map<String, Set<String>> componentData = componentService.getProjectNodes();
if(componentData.get("proxy")==null||((Set)componentData.get("proxy")).size()==0){
Map proxyInfo = new HashMap();
Map emptyProxyResult = new HashMap();
proxyInfo.put("No instance founded",emptyProxyResult);
List<HealthCheckRecord> okList = Lists.newArrayList();
List<HealthCheckRecord> warnList = Lists.newArrayList();
List<HealthCheckRecord> errorList = Lists.newArrayList();
HealthCheckRecord healthCheckRecord= new HealthCheckRecord();
healthCheckRecord.setCheckItemName(" ");
healthCheckRecord.setMsg(" " );
emptyProxyResult.put("okList",okList);
emptyProxyResult.put("warnList",warnList);
warnList.add(healthCheckRecord);
emptyProxyResult.put("errorList",errorList);
resultData.put("proxy",proxyInfo);
}
if(componentData.get("serving")==null||((Set)componentData.get("serving")).size()==0){
Map servingInfo = new HashMap();
Map emptyResult = new HashMap();
servingInfo.put("No instance founded",emptyResult);
List<HealthCheckRecord> okList = Lists.newArrayList();
List<HealthCheckRecord> warnList = Lists.newArrayList();
List<HealthCheckRecord> errorList = Lists.newArrayList();
HealthCheckRecord healthCheckRecord= new HealthCheckRecord();
healthCheckRecord.setCheckItemName(" ");
healthCheckRecord.setMsg(" " );
emptyResult.put("okList",okList);
emptyResult.put("warnList",warnList);
warnList.add(healthCheckRecord);
emptyResult.put("errorList",errorList);
resultData.put("serving",servingInfo);
}
return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, resultData);
}
@GetMapping("monitor/selfCheck")
public ReturnResult selfCheckService() {
long currentTimestamp = System.currentTimeMillis();
Map data = healthCheckService.getHealthCheckInfo();
if(data!=null&&data.get(Dict.TIMESTAMP)!=null){
long timestamp = ((Number)data.get(Dict.TIMESTAMP)).longValue();
if(currentTimestamp-timestamp>10000){
data = healthCheckService.check();
}
}
Map resultData = Maps.newHashMap();
resultData.putAll(data);
Map<String, Set<String>> componentData = componentService.getProjectNodes();
if(componentData.get("proxy")==null||((Set)componentData.get("proxy")).size()==0){
Map proxyInfo = new HashMap();
Map emptyProxyResult = new HashMap();
proxyInfo.put("No instance founded",emptyProxyResult);
List<HealthCheckRecord> okList = Lists.newArrayList();
List<HealthCheckRecord> warnList = Lists.newArrayList();
List<HealthCheckRecord> errorList = Lists.newArrayList();
HealthCheckRecord healthCheckRecord= new HealthCheckRecord();
healthCheckRecord.setCheckItemName(" ");
healthCheckRecord.setMsg(" " );
emptyProxyResult.put("okList",okList);
emptyProxyResult.put("warnList",warnList);
warnList.add(healthCheckRecord);
emptyProxyResult.put("errorList",errorList);
resultData.put("proxy",proxyInfo);
}
if(componentData.get("serving")==null||((Set)componentData.get("serving")).size()==0){
Map servingInfo = new HashMap();
Map emptyResult = new HashMap();
servingInfo.put("No instance founded",emptyResult);
List<HealthCheckRecord> okList = Lists.newArrayList();
List<HealthCheckRecord> warnList = Lists.newArrayList();
List<HealthCheckRecord> errorList = Lists.newArrayList();
HealthCheckRecord healthCheckRecord= new HealthCheckRecord();
healthCheckRecord.setCheckItemName(" ");
healthCheckRecord.setMsg(" " );
emptyResult.put("okList",okList);
emptyResult.put("warnList",warnList);
warnList.add(healthCheckRecord);
emptyResult.put("errorList",errorList);
resultData.put("serving",servingInfo);
}
return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, resultData);
}
private CommonServiceGrpc.CommonServiceBlockingStub getMonitorServiceBlockStub(String host, int port) {
Preconditions.checkArgument(StringUtils.isNotBlank(host), "parameter host is blank");
Preconditions.checkArgument(port != 0, "parameter port was wrong");
NetAddressChecker.check(host, port);
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
return CommonServiceGrpc.newBlockingStub(managedChannel);
}
private InferenceServiceGrpc.InferenceServiceBlockingStub getInferenceServiceBlockingStub(String host, int port, int timeout) throws Exception {
Preconditions.checkArgument(StringUtils.isNotBlank(host), "host is blank");
NetAddressChecker.check(host, port);
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
InferenceServiceGrpc.InferenceServiceBlockingStub blockingStub = InferenceServiceGrpc.newBlockingStub(managedChannel);
return blockingStub.withDeadlineAfter(timeout, TimeUnit.MILLISECONDS);
}
private void checkInferenceService(Map<String,Map> componentMap, ComponentService.ServiceInfo serviceInfo) throws Exception{
InferenceServiceProto.InferenceMessage.Builder inferenceMessageBuilder = InferenceServiceProto.InferenceMessage.newBuilder();
ClassPathResource inferenceTest;
if (serviceInfo.getName().equals(Dict.SERVICENAME_BATCH_INFERENCE)) {
inferenceTest = new ClassPathResource("batchInferenceTest.json");
} else {
inferenceTest = new ClassPathResource("inferenceTest.json");
}
try {
File jsonFile = inferenceTest.getFile();
ObjectMapper objectMapper = new ObjectMapper();
Map map = objectMapper.readValue(jsonFile, Map.class);
map.put("serviceId", serviceInfo.getServiceId());
String host = serviceInfo.getHost();
int port = serviceInfo.getPort();
inferenceMessageBuilder.setBody(ByteString.copyFrom(JsonUtil.object2Json(map), "UTF-8"));
InferenceServiceProto.InferenceMessage inferenceMessage = inferenceMessageBuilder.build();
InferenceServiceGrpc.InferenceServiceBlockingStub blockingStub =
this.getInferenceServiceBlockingStub(host, port, 3000);
InferenceServiceProto.InferenceMessage result;
if (serviceInfo.getName().equals(Dict.SERVICENAME_BATCH_INFERENCE)) {
result = blockingStub.batchInference(inferenceMessage);
}
else {
result = blockingStub.inference(inferenceMessage);
}
Map<String,List> currentComponentMap = componentMap.get("serving");
if (!currentComponentMap.containsKey(serviceInfo.getHost() + ":" + port)) {
currentComponentMap.put(serviceInfo.getHost() + ":" + port, new Vector<>());
}
List currentList = currentComponentMap.get(serviceInfo.getHost() + ":" + port);
Map<String,Object> currentInfoMap = new HashMap<>();
currentInfoMap.put("type","inference");
if (result.getBody() == null || "null".equals(result.getBody().toStringUtf8())) {
currentInfoMap.put("data", null);
}
else{
Map resultMap = JsonUtil.json2Object(result.getBody().toStringUtf8(),Map.class);
Object returnCode = resultMap.get("retcode");
Object returnMessage = resultMap.get("retmsg");
resultMap.clear();
resultMap.put("serviceId",serviceInfo.getServiceId());
resultMap.put("retcode",returnCode);
resultMap.put("retmsg",returnMessage);
currentInfoMap.put("data",resultMap);
currentList.add(currentInfoMap);
}
} catch (IOException e) {
} catch (Exception e) {
e.printStackTrace();
}
return;
}
//@Scheduled(cron = "5/10 * * * * ? ")
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/DynamicLogController.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/DynamicLogController.java | package com.webank.ai.fate.serving.admin.controller;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
/**
* @author hcy
*/
@RequestMapping("/admin")
@RestController
public class DynamicLogController {
private static final Logger logger = LoggerFactory.getLogger(DynamicLogController.class);
@GetMapping("/alterSysLogLevel/{level}")
public String alterSysLogLevel(@PathVariable String level){
try {
LoggerContext context = (LoggerContext) LogManager.getContext(false);
context.getLogger("ROOT").setLevel(Level.valueOf(level));
return "ok";
} catch (Exception ex) {
logger.error("admin alterSysLogLevel failed : " + ex);
return "failed";
}
}
@GetMapping("/alterPkgLogLevel")
public String alterPkgLogLevel(@RequestParam String level, @RequestParam String pkgName){
try {
LoggerContext context = (LoggerContext) LogManager.getContext(false);
context.getLogger(pkgName).setLevel(Level.valueOf(level));
return "ok";
} catch (Exception ex) {
logger.error("admin alterPkgLogLevel failed : " + ex);
return "failed";
}
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/ServiceController.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/ServiceController.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.admin.controller;
import com.google.common.base.Preconditions;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ListenableFuture;
import com.webank.ai.fate.api.networking.common.CommonServiceGrpc;
import com.webank.ai.fate.api.networking.common.CommonServiceProto;
import com.webank.ai.fate.register.common.Constants;
import com.webank.ai.fate.register.url.URL;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.admin.bean.VerifyService;
import com.webank.ai.fate.serving.admin.services.ComponentService;
import com.webank.ai.fate.serving.admin.utils.NetAddressChecker;
import com.webank.ai.fate.serving.core.bean.*;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.exceptions.RemoteRpcException;
import com.webank.ai.fate.serving.core.exceptions.SysException;
import com.webank.ai.fate.serving.core.utils.NetUtils;
import io.grpc.ManagedChannel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* @Description Service management
* @Date: 2020/3/25 11:13
* @Author: v_dylanxu
*/
@RequestMapping("/api")
@RestController
public class ServiceController {
private static final Logger logger = LoggerFactory.getLogger(ServiceController.class);
@Autowired
private ZookeeperRegistry zookeeperRegistry;
@Autowired
ComponentService componentService;
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
Set<String> filterSet = Sets.newHashSet("batchInference","inference","unaryCall");
/**
* 列出集群中所注册的所有接口
* @param page
* @param pageSize
* @return
*/
@GetMapping("/service/list")
public ReturnResult listRegistered(Integer page, Integer pageSize) {
int defaultPage = 1;
int defaultPageSize = 10;
if (page == null || page <= 0) {
page = defaultPage;
}
if (pageSize == null || pageSize <= 0) {
pageSize = defaultPageSize;
}
if (logger.isDebugEnabled()) {
logger.debug("try to query all registered service");
}
Properties properties = zookeeperRegistry.getCacheProperties();
List<ServiceDataWrapper> resultList = new ArrayList<>();
int totalSize = 0;
int index = 0;
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
// serving/9999/batchInference
String key = (String) entry.getKey();
String value = (String) entry.getValue();
if (StringUtils.isNotBlank(value)) {
String[] arr = value.trim().split("\\s+");
for (String u : arr) {
URL url = URL.valueOf(u);
if (!Constants.EMPTY_PROTOCOL.equals(url.getProtocol())) {
String[] split = key.split("/");
if (!filterSet.contains(split[2])) {
continue;
}
ServiceDataWrapper wrapper = new ServiceDataWrapper();
wrapper.setUrl(url.toFullString());
wrapper.setProject(split[0]);
wrapper.setEnvironment(split[1]);
wrapper.setName(key);
wrapper.setCallName(split[2]);
wrapper.setHost(url.getHost());
wrapper.setPort(url.getPort());
wrapper.setRouterMode(String.valueOf(url.getParameter("router_mode")));
wrapper.setVersion(Long.parseLong(url.getParameter("version", "100")));
wrapper.setWeight(Integer.parseInt(url.getParameter("weight", "100")));
wrapper.setIndex(index);
wrapper.setNeedVerify(VerifyService.contains(wrapper.getCallName()));
resultList.add(wrapper);
index++;
}
}
}
}
totalSize = resultList.size();
resultList = resultList.stream().sorted((Comparator.comparing(o -> (o.getProject() + o.getEnvironment())))).collect(Collectors.toList());
int totalPage = (resultList.size() + pageSize - 1) / pageSize;
if (page <= totalPage) {
resultList = resultList.subList((page - 1) * pageSize, Math.min(page * pageSize, resultList.size()));
}
if (logger.isDebugEnabled()) {
logger.info("registered services: {}", resultList);
}
Map data = Maps.newHashMap();
data.put("total", totalSize);
data.put("rows", resultList);
return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, data);
}
/**
* 修改每个接口中的路由信息,权重信息
* @param requestParams
* @return
* @throws Exception
*/
@PostMapping("/service/update")
public ReturnResult updateService(@RequestBody RequestParamWrapper requestParams) throws Exception {
String host = requestParams.getHost();
int port = requestParams.getPort();
String url = requestParams.getUrl();
String routerMode = requestParams.getRouterMode();
Integer weight = requestParams.getWeight();
Long version = requestParams.getVersion();
if (logger.isDebugEnabled()) {
logger.debug("try to update service");
}
Preconditions.checkArgument(StringUtils.isNotBlank(url), "parameter url is blank");
logger.info("update url: {}, routerMode: {}, weight: {}, version: {}", url, routerMode, weight, version);
CommonServiceGrpc.CommonServiceFutureStub commonServiceFutureStub = getCommonServiceFutureStub(host, port);
CommonServiceProto.UpdateServiceRequest.Builder builder = CommonServiceProto.UpdateServiceRequest.newBuilder();
builder.setUrl(url);
if (StringUtils.isNotBlank(routerMode)) {
builder.setRouterMode(routerMode);
}
if (weight != null) {
builder.setWeight(weight);
} else {
builder.setWeight(-1);
}
if (version != null) {
builder.setVersion(version);
} else {
builder.setVersion(-1);
}
ListenableFuture<CommonServiceProto.CommonResponse> future = commonServiceFutureStub.updateService(builder.build());
CommonServiceProto.CommonResponse response = future.get(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
ReturnResult result = new ReturnResult();
result.setRetcode(response.getStatusCode());
result.setRetmsg(response.getMessage());
return result;
}
@PostMapping("/service/updateFlowRule")
public ReturnResult updateFlowRule(@RequestBody RequestParamWrapper requestParams) throws Exception {
String source = requestParams.getSource();
Integer allowQps = requestParams.getAllowQps();
Preconditions.checkArgument(StringUtils.isNotBlank(source), "parameter source is blank");
Preconditions.checkArgument(allowQps != null, "parameter allowQps is null");
logger.info("update source: {}, allowQps: {}", source, allowQps);
CommonServiceGrpc.CommonServiceFutureStub commonServiceFutureStub = getCommonServiceFutureStub(requestParams.getHost(), requestParams.getPort());
CommonServiceProto.UpdateFlowRuleRequest.Builder builder = CommonServiceProto.UpdateFlowRuleRequest.newBuilder();
builder.setSource(source);
builder.setAllowQps(allowQps);
ListenableFuture<CommonServiceProto.CommonResponse> future = commonServiceFutureStub.updateFlowRule(builder.build());
CommonServiceProto.CommonResponse response = future.get(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
ReturnResult result = new ReturnResult();
result.setRetcode(response.getStatusCode());
result.setRetmsg(response.getMessage());
return result;
}
private CommonServiceGrpc.CommonServiceFutureStub getCommonServiceFutureStub(String host, Integer port) throws Exception {
Preconditions.checkArgument(StringUtils.isNotBlank(host), "parameter host is blank");
Preconditions.checkArgument(port != null && port.intValue() != 0, "parameter port was wrong");
NetAddressChecker.check(host, port);
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
return CommonServiceGrpc.newFutureStub(managedChannel);
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
FederatedAI/FATE-Serving | https://github.com/FederatedAI/FATE-Serving/blob/a25807586a960051b9acd4e0114f94a13ddc90ef/fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/ModelController.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/ModelController.java | /*
* Copyright 2019 The FATE Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.webank.ai.fate.serving.admin.controller;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ListenableFuture;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceGrpc;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceProto;
import com.webank.ai.fate.serving.admin.services.ComponentService;
import com.webank.ai.fate.serving.admin.utils.NetAddressChecker;
import com.webank.ai.fate.serving.core.bean.GrpcConnectionPool;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.bean.RequestParamWrapper;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.core.exceptions.RemoteRpcException;
import com.webank.ai.fate.serving.core.exceptions.SysException;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import com.webank.ai.fate.serving.core.utils.NetUtils;
import io.grpc.ManagedChannel;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
/**
* @Description Model management
* @Date: 2020/3/25 11:13
* @Author: v_dylanxu
*/
@RequestMapping("/api")
@RestController
public class ModelController {
private static final Logger logger = LoggerFactory.getLogger(ModelController.class);
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
@Autowired
private ComponentService componentService;
@GetMapping("/model/query")
public ReturnResult queryModel(String host, Integer port, String serviceId,String tableName, String namespace, Integer page, Integer pageSize) throws Exception {
Preconditions.checkArgument(StringUtils.isNotBlank(host), "parameter host is blank");
Preconditions.checkArgument(port != 0, "parameter port is blank");
int defaultPage = 1;
int defaultPageSize = 10;
if (page == null || page <= 0) {
page = defaultPage;
}
if (pageSize == null || pageSize <= 0) {
pageSize = defaultPageSize;
}
if (logger.isDebugEnabled()) {
logger.debug("query model, host: {}, port: {}, serviceId: {}", host, port, serviceId);
}
ModelServiceGrpc.ModelServiceBlockingStub blockingStub = getModelServiceBlockingStub(host, port);
ModelServiceProto.QueryModelRequest.Builder queryModelRequestBuilder = ModelServiceProto.QueryModelRequest.newBuilder();
if (StringUtils.isNotBlank(serviceId)) {
// by service id
queryModelRequestBuilder.setQueryType(1);
queryModelRequestBuilder.setServiceId(serviceId);
} else if (StringUtils.isNotBlank(namespace) && StringUtils.isNotBlank(tableName)) {
// query model by tableName and namespace
queryModelRequestBuilder.setTableName(tableName);
queryModelRequestBuilder.setNamespace(namespace);
queryModelRequestBuilder.setQueryType(2);
} else {
// list all
queryModelRequestBuilder.setQueryType(0);
}
ModelServiceProto.QueryModelResponse response = blockingStub.queryModel(queryModelRequestBuilder.build());
parseComponentInfo(response);
if (logger.isDebugEnabled()) {
logger.debug("response: {}", response);
}
//logger.info("response: {}", response);
Map data = Maps.newHashMap();
List rows = Lists.newArrayList();
List<ModelServiceProto.ModelInfoEx> modelInfosList = response.getModelInfosList();
int totalSize = 0;
if (modelInfosList != null) {
totalSize = modelInfosList.size();
modelInfosList = modelInfosList.stream().sorted(Comparator.comparing(ModelServiceProto.ModelInfoEx::getTableName).reversed()).collect(Collectors.toList());
// Pagination
int totalPage = (modelInfosList.size() + pageSize - 1) / pageSize;
if (page <= totalPage) {
modelInfosList = modelInfosList.subList((page - 1) * pageSize, Math.min(page * pageSize, modelInfosList.size()));
}
for (ModelServiceProto.ModelInfoEx modelInfoEx : modelInfosList) {
ModelServiceProto.ModelProcessorExt modelProcessorExt = modelInfoEx.getModelProcessorExt();
Map modelData = JsonUtil.json2Object(modelInfoEx.getContent(), Map.class);
List<Map> componentList = Lists.newArrayList();
if(modelProcessorExt!=null) {
List<ModelServiceProto.PipelineNode> nodes = modelProcessorExt.getNodesList();
if(nodes!=null){
nodes.forEach(node ->{
Map paramMap = JsonUtil.json2Object(node.getParams(),Map.class) ;
Map compnentMap =new HashMap();
compnentMap.put("name",node.getName());
compnentMap.put("params",paramMap);
componentList.add(compnentMap);
});
}
modelData.put("components",componentList);
}
rows.add(modelData);
}
}
data.put("total", totalSize);
data.put("rows", rows);
// logger.info("=============={}",data);
return ReturnResult.build(response.getRetcode(), response.getMessage(), data);
}
@PostMapping("/model/transfer")
public Callable<ReturnResult> transfer(@RequestBody RequestParamWrapper requestParams) throws Exception {
return () -> {
String host = requestParams.getHost();
Integer port = requestParams.getPort();
String tableName = requestParams.getTableName();
String namespace = requestParams.getNamespace();
String targetHost = requestParams.getTargetHost();
Integer targetPort = requestParams.getTargetPort();
Preconditions.checkArgument(StringUtils.isNotBlank(tableName), "parameter tableName is blank");
Preconditions.checkArgument(StringUtils.isNotBlank(namespace), "parameter namespace is blank");
ReturnResult result = new ReturnResult();
if (logger.isDebugEnabled()) {
logger.debug("unload model by tableName and namespace, host: {}, port: {}, tableName: {}, namespace: {}", host, port, tableName, namespace);
}
ModelServiceGrpc.ModelServiceFutureStub futureStub = getModelServiceFutureStub(targetHost, targetPort);
ModelServiceProto.FetchModelRequest fetchModelRequest = ModelServiceProto.FetchModelRequest.newBuilder()
//.setServiceId()
.setNamespace(namespace).setTableName(tableName).setSourceIp(host).setSourcePort(port).build();
ListenableFuture<ModelServiceProto.FetchModelResponse> future = futureStub.fetchModel(fetchModelRequest);
ModelServiceProto.FetchModelResponse response = future.get(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
if (logger.isDebugEnabled()) {
logger.debug("response: {}", response);
}
result.setRetcode(response.getStatusCode());
// result.setData(JSONObject.parseObject(response.getData().toStringUtf8()));
result.setRetmsg(response.getMessage());
return result;
};
}
@PostMapping("/model/unload")
public Callable<ReturnResult> unload(@RequestBody RequestParamWrapper requestParams) throws Exception {
return () -> {
String host = requestParams.getHost();
Integer port = requestParams.getPort();
String tableName = requestParams.getTableName();
String namespace = requestParams.getNamespace();
Preconditions.checkArgument(StringUtils.isNotBlank(tableName), "parameter tableName is blank");
Preconditions.checkArgument(StringUtils.isNotBlank(namespace), "parameter namespace is blank");
ReturnResult result = new ReturnResult();
if (logger.isDebugEnabled()) {
logger.debug("unload model by tableName and namespace, host: {}, port: {}, tableName: {}, namespace: {}", host, port, tableName, namespace);
}
ModelServiceGrpc.ModelServiceFutureStub futureStub = getModelServiceFutureStub(host, port);
ModelServiceProto.UnloadRequest unloadRequest = ModelServiceProto.UnloadRequest.newBuilder()
.setTableName(tableName)
.setNamespace(namespace)
.build();
ListenableFuture<ModelServiceProto.UnloadResponse> future = futureStub.unload(unloadRequest);
ModelServiceProto.UnloadResponse response = future.get(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
if (logger.isDebugEnabled()) {
logger.debug("response: {}", response);
}
result.setRetcode(response.getStatusCode());
// result.setData(JSONObject.parseObject(response.getData().toStringUtf8()));
result.setRetmsg(response.getMessage());
return result;
};
}
@PostMapping("/model/unbind")
public Callable<ReturnResult> unbind(@RequestBody RequestParamWrapper requestParams) throws Exception {
return () -> {
String host = requestParams.getHost();
Integer port = requestParams.getPort();
String tableName = requestParams.getTableName();
String namespace = requestParams.getNamespace();
List<String> serviceIds = requestParams.getServiceIds();
Preconditions.checkArgument(StringUtils.isNotBlank(tableName), "parameter tableName is blank");
Preconditions.checkArgument(StringUtils.isNotBlank(namespace), "parameter namespace is blank");
Preconditions.checkArgument(serviceIds != null && serviceIds.size() != 0, "parameter serviceId is blank");
ReturnResult result = new ReturnResult();
if (logger.isDebugEnabled()) {
logger.debug("unload model by tableName and namespace, host: {}, port: {}, tableName: {}, namespace: {}", host, port, tableName, namespace);
}
ModelServiceGrpc.ModelServiceFutureStub futureStub = getModelServiceFutureStub(host, port);
ModelServiceProto.UnbindRequest unbindRequest = ModelServiceProto.UnbindRequest.newBuilder()
.setTableName(tableName)
.setNamespace(namespace)
.addAllServiceIds(serviceIds)
.build();
ListenableFuture<ModelServiceProto.UnbindResponse> future = futureStub.unbind(unbindRequest);
ModelServiceProto.UnbindResponse response = future.get(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
if (logger.isDebugEnabled()) {
logger.debug("response: {}", response);
}
result.setRetcode(response.getStatusCode());
result.setRetmsg(response.getMessage());
return result;
};
}
private ModelServiceGrpc.ModelServiceBlockingStub getModelServiceBlockingStub(String host, Integer port) throws Exception {
Preconditions.checkArgument(StringUtils.isNotBlank(host), "parameter host is blank");
Preconditions.checkArgument(port != null && port.intValue() != 0, "parameter port was wrong");
NetAddressChecker.check(host, port);
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
ModelServiceGrpc.ModelServiceBlockingStub blockingStub = ModelServiceGrpc.newBlockingStub(managedChannel);
blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
return blockingStub;
}
private ModelServiceGrpc.ModelServiceFutureStub getModelServiceFutureStub(String host, Integer port) throws Exception {
Preconditions.checkArgument(StringUtils.isNotBlank(host), "parameter host is blank");
Preconditions.checkArgument(port != null && port.intValue() != 0, "parameter port was wrong");
NetAddressChecker.check(host, port);
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
return ModelServiceGrpc.newFutureStub(managedChannel);
}
public void parseComponentInfo(ModelServiceProto.QueryModelResponse response){
}
}
| java | Apache-2.0 | a25807586a960051b9acd4e0114f94a13ddc90ef | 2026-01-05T02:38:33.335296Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.