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-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/ComponentController.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/ComponentController.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.databind.ObjectMapper;
import com.google.common.base.Preconditions;
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.serving.admin.bean.ServiceConfiguration;
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.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.io.File;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
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 ComponentController {
private static final Logger logger = LoggerFactory.getLogger(ComponentController.class);
private final ObjectMapper objectMapper = new ObjectMapper();
@Autowired
ComponentService componentServices;
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
@GetMapping("/component/list")
public ReturnResult list() {
ComponentService.NodeData cachedNodeData = componentServices.getCachedNodeData();
Map<String, Object> cachedNodeDataMap = objectMapper.convertValue(cachedNodeData, Map.class);
return ReturnResult.build(StatusCode.SUCCESS, Dict.SUCCESS, cachedNodeDataMap);
}
@GetMapping("/component/listProps")
public ReturnResult listProps(String host, int port, String keyword) {
NetAddressChecker.check(host, port);
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
CommonServiceGrpc.CommonServiceBlockingStub blockingStub = CommonServiceGrpc.newBlockingStub(managedChannel);
blockingStub = blockingStub.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
CommonServiceProto.QueryPropsRequest.Builder builder = CommonServiceProto.QueryPropsRequest.newBuilder();
if (StringUtils.isNotBlank(keyword)) {
builder.setKeyword(keyword);
}
CommonServiceProto.CommonResponse response = blockingStub.listProps(builder.build());
Map<String, Object> propMap = JsonUtil.json2Object(response.getData().toStringUtf8(), Map.class);
List<Map> list = propMap.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getKey))
.map(entry -> {
Map map = Maps.newHashMap();
map.put("key", entry.getKey());
map.put("value", entry.getValue());
return map;
})
.collect(Collectors.toList());
Map data = Maps.newHashMap();
data.put("total", list.size());
data.put("rows", list);
return ReturnResult.build(response.getStatusCode(), response.getMessage(), data);
}
@PostMapping("/component/updateConfig")
public ReturnResult updateConfig(@RequestBody RequestParamWrapper requestParams) {
String filePath = requestParams.getFilePath();
String data = requestParams.getData();
Preconditions.checkArgument(StringUtils.isNotBlank(filePath), "file path is blank");
Preconditions.checkArgument(StringUtils.isNotBlank(data), "data is blank");
String host = requestParams.getHost();
int port = requestParams.getPort();
NetAddressChecker.check(host, port);
String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
String project = componentServices.getProject(host, port);
if (project != null && !ServiceConfiguration.isAllowModify(project, fileName)) {
throw new SysException("the file is not allowed to be modified");
}
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
CommonServiceGrpc.CommonServiceBlockingStub blockingStub = CommonServiceGrpc.newBlockingStub(managedChannel)
.withDeadlineAfter(MetaInfo.PROPERTY_GRPC_TIMEOUT, TimeUnit.MILLISECONDS);
CommonServiceProto.UpdateConfigRequest.Builder builder = CommonServiceProto.UpdateConfigRequest.newBuilder();
builder.setFilePath(filePath);
builder.setData(data);
CommonServiceProto.CommonResponse response = blockingStub.updateConfig(builder.build());
return ReturnResult.build(response.getStatusCode(), response.getMessage());
}
}
| 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/ValidateController.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/controller/ValidateController.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.webank.ai.fate.serving.admin.services.provider.ValidateServiceProvider;
import com.webank.ai.fate.serving.common.bean.BaseContext;
import com.webank.ai.fate.serving.common.rpc.core.InboundPackage;
import com.webank.ai.fate.serving.common.rpc.core.OutboundPackage;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RequestMapping("/api")
@RestController
public class ValidateController {
private static final Logger logger = LoggerFactory.getLogger(ValidateController.class);
@Autowired
ValidateServiceProvider validateServiceProvider;
/**
* 列出集群中所注册的所有接口
* @param callName
* @param params
* @return
*/
@PostMapping("/validate/{callName}")
public ReturnResult validate(@PathVariable String callName, @RequestBody Map params) {
ReturnResult result = new ReturnResult();
try {
if (logger.isDebugEnabled()) {
logger.debug("try to validate {}, receive params: {}", callName, params);
}
BaseContext context = new BaseContext();
context.setActionType(callName);
InboundPackage inboundPackage = new InboundPackage();
inboundPackage.setBody(params);
OutboundPackage outboundPackage = validateServiceProvider.service(context, inboundPackage);
Map resultMap = (Map) outboundPackage.getData();
if (resultMap != null && resultMap.get(Dict.RET_CODE) != null && (int) resultMap.get(Dict.RET_CODE) == StatusCode.SUCCESS) {
logger.info("validate {} success", callName);
}
result.setRetcode(StatusCode.SUCCESS);
result.setData(resultMap);
} catch (Exception e) {
logger.error(e.getMessage());
result.setRetcode(StatusCode.SYSTEM_ERROR);
result.setRetmsg(e.getMessage());
}
return result;
}
/*
* Request parameter example
================== publishLoad/ publishBind ==================
{
"host": "127.0.0.1",
"port": 8000,
"serviceId": "666666",
"local": {
"role": "guest",
"partyId": "9999"
},
"role": {
"guest": {
"partyId": "9999"
},
"host": {
"partyId": "10000"
},
"arbiter": {
"partyId": "10000"
}
},
"model": {
"guest": {
"9999": {
"tableName": "2020040111152695637611",
"namespace": "guest#9999#arbiter-10000#guest-9999#host-10000#model"
}
},
"host": {
"10000": {
"tableName": "2020040111152695637611",
"namespace": "host#10000#arbiter-10000#guest-9999#host-10000#model"
}
},
"arbiter": {
"10000": {
"tableName": "2020040111152695637611",
"namespace": "arbiter#10000#arbiter-10000#guest-9999#host-10000#model"
}
}
},
"loadType": "FILE",
"filePath": "D:/git/FATE-Serving-2.0/fate-serving-server/target/classes/model_2020040111152695637611_guest#9999#arbiter-10000#guest-9999#host-10000#model_cache"
}
================== inference ==================
{
"host": "127.0.0.1",
"port": 8000,
"serviceId": "666666",
"featureData": {
"x0": 0.100016,
"x1": -1.359293,
"x2": 2.303601,
"x3": 2.00137,
"x4": 1.307686,
"x7": 0.102345
},
"sendToRemoteFeatureData": {
"device_id": "aaaaa",
"phone_num": "122222222"
}
}
================== batchInference ==================
{
"host": "127.0.0.1",
"port": 8000,
"serviceId": "666666",
"batchDataList": [
{
"featureData": {
"x0": 1.88669,
"x1": -1.359293,
"x2": 2.303601,
"x3": 2.00137,
"x4": 1.307686
},
"sendToRemoteFeatureData": {
"device_id": "aaaaa",
"phone_num": "122222222"
}
},
{
"featureData": {
"x0": 1.88669,
"x1": -1.359293,
"x2": 2.303601,
"x3": 2.00137,
"x4": 1.307686
},
"sendToRemoteFeatureData": {
"device_id": "aaaaa",
"phone_num": "122222222"
}
}
]
}
*/
}
| 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/services/HealthCheckService.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/services/HealthCheckService.java | package com.webank.ai.fate.serving.admin.services;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
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.utils.NetAddressChecker;
import com.webank.ai.fate.serving.common.health.HealthCheckRecord;
import com.webank.ai.fate.serving.common.health.HealthCheckResult;
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.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.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
@Service
public class HealthCheckService implements InitializingBean {
Logger logger = LoggerFactory.getLogger(HealthCheckService.class);
@Autowired
ComponentService componentService;
private static final String SERVING_CHECK_HEALTH = "serving/online/checkHealth";
private static final String PROXY_CHECK_HEALTH = "proxy/online/checkHealth";
@Autowired
private ZookeeperRegistry zookeeperRegistry;
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
Map<String,Object> healthRecord = new ConcurrentHashMap<>();
public Map getHealthCheckInfo(){
return healthRecord;
}
private void checkRemoteHealth(Map<String,Map> componentMap, String address, String component) {
if (StringUtils.isBlank(address)) {
return ;
}
Map<String,Map> currentComponentMap = componentMap.get(component);
String host = address.substring(0,address.indexOf(':'));
int port = Integer.parseInt(address.substring(address.indexOf(':') + 1));
CommonServiceGrpc.CommonServiceBlockingStub blockingStub = getMonitorServiceBlockStub(host, port);
CommonServiceProto.HealthCheckRequest.Builder builder = CommonServiceProto.HealthCheckRequest.newBuilder();
CommonServiceProto.CommonResponse commonResponse = blockingStub.checkHealthService(builder.build());
HealthCheckResult healthCheckResult = JsonUtil.json2Object(commonResponse.getData().toStringUtf8(), HealthCheckResult.class);
//currentList.add(healthInfo);
//logger.info("healthCheckResult {}",healthCheckResult);
Map result = new HashMap();
List<HealthCheckRecord> okList = Lists.newArrayList();
List<HealthCheckRecord> warnList = Lists.newArrayList();
List<HealthCheckRecord> errorList = Lists.newArrayList();
if(healthCheckResult!=null){
List<HealthCheckRecord> records = healthCheckResult.getRecords();
for (HealthCheckRecord record : records) {
if(record.getHealthCheckStatus().equals(HealthCheckStatus.ok)){
okList.add(record);
}else if(record.getHealthCheckStatus().equals(HealthCheckStatus.warn)){
warnList.add(record);
}else{
errorList.add(record);
}
}
}
result.put("okList",okList);
result.put("warnList",warnList);
result.put("errorList",errorList);
// logger.info("health check {} component {} result {}",address,component,result);
currentComponentMap.put(address,result);
}
public Map check() {
try {
List<URL> servingList = zookeeperRegistry.getCacheUrls(URL.valueOf(SERVING_CHECK_HEALTH));
List<URL> proxyList = zookeeperRegistry.getCacheUrls(URL.valueOf(PROXY_CHECK_HEALTH));
// logger.info("serving urls {}",servingList);
// logger.info("proxy urls {}",proxyList);
Map<String, Map> componentHearthMap = new ConcurrentHashMap<>();
int size =(servingList!=null?servingList.size():0)+(proxyList!=null?proxyList.size():0);
final CountDownLatch countDownLatch = new CountDownLatch(size);
componentHearthMap.put("proxy", new ConcurrentHashMap());
componentHearthMap.put("serving", new ConcurrentHashMap());
if(servingList!=null){
servingList.forEach(url ->{
try {
if(StringUtils.isNotBlank(url.getAddress())) {
checkRemoteHealth(componentHearthMap, url.getAddress(), "serving");
}
} catch (Exception e){
logger.error("serving-server health check error",e);
}finally {
countDownLatch.countDown();
}
});
}
if(proxyList!=null){
proxyList.forEach(url->{
try {
checkRemoteHealth(componentHearthMap, url.getAddress(), "proxy");
} catch (Exception e){
logger.error("serving-proxy health check error",e);
}finally {
countDownLatch.countDown();
}
});
}
Map<String, Object> newHealthRecord = new ConcurrentHashMap<>();
countDownLatch.await();
newHealthRecord.put(Dict.TIMESTAMP, System.currentTimeMillis());
newHealthRecord.putAll(componentHearthMap);
healthRecord = newHealthRecord;
}catch(Exception e){
logger.error("schedule health check error ",e );
}
return healthRecord;
}
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);
}
@Override
public void afterPropertiesSet() throws Exception {
if(MetaInfo.PROPERTY_ALLOW_HEALTH_CHECK) {
ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();
scheduledExecutorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
check();
}
}, 0, MetaInfo.PROPERTY_ADMIN_HEALTH_CHECK_TIME, TimeUnit.SECONDS);
}
}
}
| 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/services/FateServiceRegister.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/services/FateServiceRegister.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.services;
import com.webank.ai.fate.serving.common.rpc.core.*;
import com.webank.ai.fate.serving.core.bean.GrpcConnectionPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
@Component
public class FateServiceRegister implements ServiceRegister, ApplicationContextAware, ApplicationListener<ApplicationReadyEvent> {
Logger logger = LoggerFactory.getLogger(FateServiceRegister.class);
Map<String, ServiceAdaptor> serviceAdaptorMap = new HashMap<String, ServiceAdaptor>();
ApplicationContext applicationContext;
@Override
public ServiceAdaptor getServiceAdaptor(String name) {
if (serviceAdaptorMap.get(name) != null) {
return serviceAdaptorMap.get(name);
} else {
return serviceAdaptorMap.get("NotFound");
}
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.applicationContext = context;
}
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationEvent) {
String[] beans = applicationContext.getBeanNamesForType(AbstractServiceAdaptor.class);
for (String beanName : beans) {
AbstractServiceAdaptor serviceAdaptor = applicationContext.getBean(beanName, AbstractServiceAdaptor.class);
FateService proxyService = serviceAdaptor.getClass().getAnnotation(FateService.class);
Method[] methods = serviceAdaptor.getClass().getMethods();
for (Method method : methods) {
FateServiceMethod fateServiceMethod = method.getAnnotation(FateServiceMethod.class);
if (fateServiceMethod != null) {
String[] names = fateServiceMethod.name();
for (String name : names) {
serviceAdaptor.getMethodMap().put(name, method);
}
}
}
if (proxyService != null) {
serviceAdaptor.setServiceName(proxyService.name());
String[] postChain = proxyService.postChain();
String[] preChain = proxyService.preChain();
for (String post : postChain) {
Interceptor postInterceptor = applicationContext.getBean(post, Interceptor.class);
serviceAdaptor.addPostProcessor(postInterceptor);
}
for (String pre : preChain) {
Interceptor preInterceptor = applicationContext.getBean(pre, Interceptor.class);
serviceAdaptor.addPreProcessor(preInterceptor);
}
this.serviceAdaptorMap.put(proxyService.name(), serviceAdaptor);
}
}
logger.info("service register info {}", this.serviceAdaptorMap.keySet());
}
}
| 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/services/ComponentService.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/services/ComponentService.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.services;
import com.google.common.collect.Lists;
import com.webank.ai.fate.register.common.Constants;
import com.webank.ai.fate.register.url.CollectionUtils;
import com.webank.ai.fate.register.zookeeper.ZookeeperClient;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.util.*;
@Service
public class ComponentService {
private static final String PATH_SEPARATOR = "/";
private static final String DEFAULT_COMPONENT_ROOT = "FATE-COMPONENTS";
Logger logger = LoggerFactory.getLogger(ComponentService.class);
@Autowired
ZookeeperRegistry zookeeperRegistry;
NodeData cachedNodeData;
List<ServiceInfo> serviceInfos;
public Map<String, Set<String>> getProjectNodes() {
return projectNodes;
}
public void setProjectNodes(Map<String, Set<String>> projectNodes) {
this.projectNodes = projectNodes;
}
/**
* project -> nodes mapping
*/
Map<String, Set<String>> projectNodes = new HashMap<>();
public NodeData getCachedNodeData() {
return cachedNodeData;
}
public List<ServiceInfo> getServiceInfos() {
return serviceInfos;
}
public Set<String> getWhitelist() {
if (projectNodes == null || projectNodes.size() == 0) {
return null;
}
Set<String> list = new HashSet<>();
for (Set<String> value : this.projectNodes.values()) {
list.addAll(value);
}
return list;
}
public String getProject(String host, int port) {
if (projectNodes == null || projectNodes.size() == 0) {
return null;
}
Optional<String> project = this.projectNodes.entrySet().stream().filter(entry -> {
if (entry.getValue() != null) {
return entry.getValue().contains(host + ":" + port);
}
return false;
}).map(Map.Entry::getKey).findFirst();
return project.orElse("");
}
public boolean isAllowAccess(String host, int port) {
Set<String> whitelist = getWhitelist();
return whitelist != null && whitelist.contains(host + ":" + port);
}
@Scheduled(cron = "0/5 * * * * ?")
public void schedulePullComponent() {
try {
ZookeeperClient zkClient = zookeeperRegistry.getZkClient();
NodeData root = new NodeData();
root.setName("cluster");
root.setLabel(root.getName());
List<String> componentLists = zkClient.getChildren(PATH_SEPARATOR + DEFAULT_COMPONENT_ROOT);
if (componentLists != null) {
componentLists.forEach(name -> {
List<String> nodes = zkClient.getChildren(PATH_SEPARATOR + DEFAULT_COMPONENT_ROOT + PATH_SEPARATOR + name);
if (nodes != null) {
Set<String> set = projectNodes.computeIfAbsent(name, k -> new HashSet<>());
set.clear();
set.addAll(nodes);
}
NodeData componentData = new NodeData();
componentData.setName(name);
componentData.setLabel(root.getLabel() + "-" + componentData.getName());
root.getChildren().add(componentData);
if (CollectionUtils.isNotEmpty(nodes)) {
nodes.forEach(nodeName -> {
String content = zkClient.getContent(PATH_SEPARATOR + DEFAULT_COMPONENT_ROOT + PATH_SEPARATOR + name + PATH_SEPARATOR + nodeName);
Map contentMap = JsonUtil.json2Object(content, Map.class);
NodeData nodeData = new NodeData();
nodeData.setName(nodeName);
nodeData.setLeaf(true);
nodeData.setLabel(componentData.getLabel() + "-" + nodeData.getName());
nodeData.setTimestamp((Long) contentMap.get(Constants.TIMESTAMP_KEY));
componentData.getChildren().add(nodeData);
});
}
});
}
cachedNodeData = root;
if (logger.isDebugEnabled()) {
logger.debug("refresh component info ");
}
}catch(Exception e){
logger.error("get component from zk error",e);
cachedNodeData = null;
projectNodes.clear();
}
}
public Map<String,List<String>> getComponentAddresses() {
Map<String,List<String>> addresses= new HashMap<>();
ZookeeperClient zkClient = zookeeperRegistry.getZkClient();
List<String> componentLists = zkClient.getChildren(PATH_SEPARATOR + DEFAULT_COMPONENT_ROOT);
if(componentLists!=null) {
for (String component : componentLists) {
addresses.put(component, new ArrayList<>());
List<String> nodes = zkClient.getChildren(PATH_SEPARATOR + DEFAULT_COMPONENT_ROOT + PATH_SEPARATOR + component);
for (String node : nodes) {
addresses.get(component).add(node);
}
}
}
return addresses;
}
public void pullService() {
serviceInfos = new ArrayList<>();
Properties properties = zookeeperRegistry.getCacheProperties();
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String key = (String) entry.getKey();
String serviceName = key.substring(key.lastIndexOf('/')+1);
if (serviceName.equals(Dict.SERVICENAME_BATCH_INFERENCE) || serviceName.equals(Dict.SERVICENAME_INFERENCE)) {
String value = (String) entry.getValue();
if (value.startsWith("empty")) {
continue;
}
String address = value.substring(value.indexOf("//")+2);
String host = address.substring(0, address.indexOf(':'));
int port = Integer.valueOf(address.substring(address.indexOf(':') + 1, address.indexOf('/')));
String serviceId = key.substring(key.indexOf('/')+1,key.lastIndexOf('/'));
ServiceInfo serviceInfo = new ServiceInfo();
serviceInfo.setHost(host);
serviceInfo.setName(serviceName);
serviceInfo.setPort(port);
serviceInfo.setServiceId(serviceId);
serviceInfos.add(serviceInfo);
}
}
}
public class NodeData {
String name;
boolean leaf;
String label;
long timestamp;
List<NodeData> children = Lists.newArrayList();
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public boolean isLeaf() {
return leaf;
}
public void setLeaf(boolean leaf) {
this.leaf = leaf;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<NodeData> getChildren() {
return children;
}
public void setChildren(List<NodeData> children) {
this.children = children;
}
}
public class ServiceInfo {
String name;
String host;
int port;
String serviceId;
public void setName(String name) {
this.name = name;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
}
public void setHost(String host) {
this.host = host;
}
public void setPort(int port) {
this.port = port;
}
public String getHost() {
return host;
}
public String getName() {
return name;
}
public int getPort() {
return port;
}
public String getServiceId() {
return serviceId;
}
}
}
| 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/services/AbstractAdminServiceProvider.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/services/AbstractAdminServiceProvider.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.services;
import com.webank.ai.fate.serving.common.rpc.core.AbstractServiceAdaptor;
import com.webank.ai.fate.serving.common.rpc.core.InboundPackage;
import com.webank.ai.fate.serving.common.rpc.core.OutboundPackage;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.exceptions.BaseException;
import com.webank.ai.fate.serving.core.exceptions.SysException;
import com.webank.ai.fate.serving.core.exceptions.UnSupportMethodException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
public abstract class AbstractAdminServiceProvider<req, resp> extends AbstractServiceAdaptor<req, resp> {
@Override
protected resp doService(Context context, InboundPackage<req> data, OutboundPackage<resp> outboundPackage) {
Map<String, Method> methodMap = this.getMethodMap();
String actionType = context.getActionType();
resp result;
try {
Method method = methodMap.get(actionType);
if (method == null) {
throw new UnSupportMethodException();
}
result = (resp) method.invoke(this, context, data);
} catch (Throwable e) {
e.printStackTrace();
if (e.getCause() != null && e.getCause() instanceof BaseException) {
throw (BaseException) e.getCause();
} else if (e instanceof InvocationTargetException) {
InvocationTargetException ex = (InvocationTargetException) e;
throw new SysException(ex.getTargetException().getMessage());
} else {
throw new SysException(e.getMessage());
}
}
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/services/provider/ValidateServiceProvider.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/services/provider/ValidateServiceProvider.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.services.provider;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.protobuf.ByteString;
import com.webank.ai.fate.api.mlmodel.manager.ModelServiceGrpc;
import com.webank.ai.fate.api.serving.InferenceServiceGrpc;
import com.webank.ai.fate.api.serving.InferenceServiceProto;
import com.webank.ai.fate.serving.admin.controller.ValidateController;
import com.webank.ai.fate.serving.admin.services.AbstractAdminServiceProvider;
import com.webank.ai.fate.serving.admin.services.ComponentService;
import com.webank.ai.fate.serving.admin.utils.NetAddressChecker;
import com.webank.ai.fate.serving.common.rpc.core.FateService;
import com.webank.ai.fate.serving.common.rpc.core.FateServiceMethod;
import com.webank.ai.fate.serving.common.rpc.core.InboundPackage;
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.BaseException;
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.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
@FateService(name = "validateService", preChain = {
"validateParamInterceptor"
})
@Service
public class ValidateServiceProvider extends AbstractAdminServiceProvider {
private static final Logger logger = LoggerFactory.getLogger(ValidateController.class);
GrpcConnectionPool grpcConnectionPool = GrpcConnectionPool.getPool();
@Autowired
ComponentService componentService;
/*@FateServiceMethod(name = "publishLoad")
public Object publishLoad(Context context, InboundPackage data) throws Exception {
Map params = (Map) data.getBody();
String host = (String) params.get(Dict.HOST);
int port = (int) params.get(Dict.PORT);
ModelServiceProto.PublishRequest publishRequest = buildPublishRequest(params);
ModelServiceGrpc.ModelServiceFutureStub modelServiceFutureStub = getModelServiceFutureStub(host, port);
ListenableFuture<ModelServiceProto.PublishResponse> future = modelServiceFutureStub.publishLoad(publishRequest);
ModelServiceProto.PublishResponse response = future.get(timeout * 2, TimeUnit.MILLISECONDS);
Map returnResult = new HashMap();
returnResult.put(Dict.RET_CODE, response.getStatusCode());
returnResult.put(Dict.RET_MSG, response.getMessage());
return returnResult;
}
@FateServiceMethod(name = {"publishBind", "publishOnline"})
public Object publishBind(Context context, InboundPackage data) throws Exception {
Map params = (Map) data.getBody();
String host = (String) params.get(Dict.HOST);
int port = (int) params.get(Dict.PORT);
Preconditions.checkArgument(StringUtils.isNotBlank((String) params.get("serviceId")), "parameter serviceId is required");
ModelServiceProto.PublishRequest publishRequest = buildPublishRequest(params);
ModelServiceGrpc.ModelServiceFutureStub modelServiceFutureStub = getModelServiceFutureStub(host, port);
ListenableFuture<ModelServiceProto.PublishResponse> future = modelServiceFutureStub.publishBind(publishRequest);
ModelServiceProto.PublishResponse response = future.get(timeout * 2, TimeUnit.MILLISECONDS);
Map returnResult = new HashMap();
returnResult.put(Dict.RET_CODE, response.getStatusCode());
returnResult.put(Dict.RET_MSG, response.getMessage());
return returnResult;
}*/
@FateServiceMethod(name = "inference")
public Object inference(Context context, InboundPackage data) throws Exception {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String caseId = request.getHeader("caseId");
Map params = (Map) data.getBody();
String host = (String) params.get(Dict.HOST);
int port = (int) params.get(Dict.PORT);
String serviceId = (String) params.get("serviceId");
Map<String, Object> featureData = (Map<String, Object>) params.get("featureData");
Map<String, Object> sendToRemoteFeatureData = (Map<String, Object>) params.get("sendToRemoteFeatureData");
try {
Preconditions.checkArgument(StringUtils.isNotBlank(serviceId), "parameter serviceId is required");
Preconditions.checkArgument(featureData != null, "parameter featureData is required");
Preconditions.checkArgument(sendToRemoteFeatureData != null, "parameter sendToRemoteFeatureData is required");
}
catch(Exception e){
throw new BaseException(StatusCode.GUEST_PARAM_ERROR, e.getMessage());
}
InferenceRequest inferenceRequest = new InferenceRequest();
if (StringUtils.isNotBlank(serviceId)) {
inferenceRequest.setServiceId(serviceId);
}
if(params.get("applyId")!=null){
inferenceRequest.setApplyId(params.get("applyId").toString());
}
if(caseId != null && !caseId.isEmpty()) {
inferenceRequest.setCaseId(caseId);
}
for (Map.Entry<String, Object> entry : featureData.entrySet()) {
inferenceRequest.getFeatureData().put(entry.getKey(), entry.getValue());
}
for (Map.Entry<String, Object> entry : sendToRemoteFeatureData.entrySet()) {
inferenceRequest.getSendToRemoteFeatureData().put(entry.getKey(), entry.getValue());
}
InferenceServiceProto.InferenceMessage.Builder builder = InferenceServiceProto.InferenceMessage.newBuilder();
builder.setBody(ByteString.copyFrom(JsonUtil.object2Json(inferenceRequest), Charset.forName("UTF-8")));
InferenceServiceGrpc.InferenceServiceFutureStub inferenceServiceFutureStub = getInferenceServiceFutureStub(host, port);
ListenableFuture<InferenceServiceProto.InferenceMessage> future = inferenceServiceFutureStub.inference(builder.build());
InferenceServiceProto.InferenceMessage response = future.get(MetaInfo.PROPERTY_GRPC_TIMEOUT * 2, TimeUnit.MILLISECONDS);
return JsonUtil.json2Object(response.getBody().toStringUtf8(), Map.class);
}
@FateServiceMethod(name = "batchInference")
public Object batchInference(Context context, InboundPackage data) throws Exception {
Map params = (Map) data.getBody();
String host = (String) params.get(Dict.HOST);
int port = (int) params.get(Dict.PORT);
String serviceId = (String) params.get("serviceId");
List<Map> batchDataList = (List<Map>) params.get("batchDataList");
Preconditions.checkArgument(StringUtils.isNotBlank(serviceId), "parameter serviceId is required");
Preconditions.checkArgument(batchDataList != null, "parameter batchDataList is required");
BatchInferenceRequest batchInferenceRequest = new BatchInferenceRequest();
if (StringUtils.isNotBlank(serviceId)) {
batchInferenceRequest.setServiceId(serviceId);
}
List<BatchInferenceRequest.SingleInferenceData> singleInferenceDataList = Lists.newArrayList();
for (int i = 0; i < batchDataList.size(); i++) {
BatchInferenceRequest.SingleInferenceData singleInferenceData = new BatchInferenceRequest.SingleInferenceData();
Map map = batchDataList.get(i);
Map<String, Object> featureData = (Map<String, Object>) map.get("featureData");
Map<String, Object> sendToRemoteFeatureData = (Map<String, Object>) map.get("sendToRemoteFeatureData");
Preconditions.checkArgument(featureData != null, "parameter featureData is required");
Preconditions.checkArgument(sendToRemoteFeatureData != null, "parameter sendToRemoteFeatureData is required");
for (Map.Entry<String, Object> entry : featureData.entrySet()) {
singleInferenceData.getFeatureData().put(entry.getKey(), entry.getValue());
}
for (Map.Entry<String, Object> entry : sendToRemoteFeatureData.entrySet()) {
singleInferenceData.getSendToRemoteFeatureData().put(entry.getKey(), entry.getValue());
}
singleInferenceData.setIndex(i);
singleInferenceDataList.add(singleInferenceData);
}
batchInferenceRequest.setBatchDataList(singleInferenceDataList);
InferenceServiceProto.InferenceMessage.Builder builder = InferenceServiceProto.InferenceMessage.newBuilder();
builder.setBody(ByteString.copyFrom(JsonUtil.object2Json(batchInferenceRequest), Charset.forName("UTF-8")));
InferenceServiceGrpc.InferenceServiceFutureStub inferenceServiceFutureStub = getInferenceServiceFutureStub(host, port);
ListenableFuture<InferenceServiceProto.InferenceMessage> future = inferenceServiceFutureStub.batchInference(builder.build());
InferenceServiceProto.InferenceMessage response = future.get(MetaInfo.PROPERTY_GRPC_TIMEOUT * 2, TimeUnit.MILLISECONDS);
return JsonUtil.json2Object(response.getBody().toStringUtf8(), Map.class);
}
/*private ModelServiceProto.PublishRequest buildPublishRequest(Map params) {
Map<String, String> local = (Map<String, String>) params.get("local");
Map<String, Map> roleMap = (Map<String, Map>) params.get("role");
Map<String, Map> modelMap = (Map<String, Map>) params.get("model");
String serviceId = (String) params.get("serviceId");
String tableName = (String) params.get("tableName");
String namespace = (String) params.get("namespace");
String loadType = (String) params.get("loadType");
String filePath = (String) params.get("filePath");
Preconditions.checkArgument(local != null, "parameter local is required");
Preconditions.checkArgument(roleMap != null, "parameter roleMap is required");
Preconditions.checkArgument(modelMap != null, "parameter modelMap is required");
ModelServiceProto.PublishRequest.Builder builder = ModelServiceProto.PublishRequest.newBuilder();
builder.setLocal(ModelServiceProto.LocalInfo.newBuilder().setRole(local.get(Dict.ROLE)).setPartyId(local.get(Dict.PARTY_ID)).build());
for (Map.Entry<String, Map> entry : roleMap.entrySet()) {
Map value = entry.getValue();
Preconditions.checkArgument(value != null);
builder.putRole(entry.getKey(), ModelServiceProto.Party.newBuilder().addPartyId((String) value.get(Dict.PARTY_ID)).build());
}
for (Map.Entry<String, Map> entry : modelMap.entrySet()) {
Map roleModelInfoMap = entry.getValue();
Preconditions.checkArgument(roleModelInfoMap != null);
if (roleModelInfoMap.size() == 1) {
ModelServiceProto.RoleModelInfo roleModelInfo = null;
Map.Entry<String, Map> roleModelInfoEntry = (Map.Entry<String, Map>) roleModelInfoMap.entrySet().iterator().next();
Preconditions.checkArgument(roleModelInfoEntry != null);
Map modelInfo = roleModelInfoEntry.getValue();
roleModelInfo = ModelServiceProto.RoleModelInfo.newBuilder().putRoleModelInfo(roleModelInfoEntry.getKey(),
ModelServiceProto.ModelInfo.newBuilder().setTableName((String) modelInfo.get("tableName"))
.setNamespace((String) modelInfo.get("namespace")).build()).build();
builder.putModel(entry.getKey(), roleModelInfo);
}
}
if (StringUtils.isNotBlank(loadType)) {
builder.setLoadType(loadType);
}
if (StringUtils.isNotBlank(filePath)) {
builder.setFilePath(filePath);
}
if (StringUtils.isNotBlank(serviceId)) {
builder.setServiceId(StringUtils.trim(serviceId));
}
return builder.build();
}*/
@Override
protected Object transformExceptionInfo(Context context, ExceptionInfo data) {
Map returnResult = new HashMap();
if (data != null) {
int code = data.getCode();
String msg = data.getMessage() != null ? data.getMessage() : "";
returnResult.put(Dict.RET_CODE, code);
returnResult.put(Dict.RET_MSG, msg);
return returnResult;
}
return null;
}
private ModelServiceGrpc.ModelServiceBlockingStub getModelServiceBlockingStub(String host, Integer port) throws Exception {
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 {
NetAddressChecker.check(host, port);
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
return ModelServiceGrpc.newFutureStub(managedChannel);
}
private InferenceServiceGrpc.InferenceServiceFutureStub getInferenceServiceFutureStub(String host, Integer port) throws Exception {
NetAddressChecker.check(host, port);
ManagedChannel managedChannel = grpcConnectionPool.getManagedChannel(host, port);
return InferenceServiceGrpc.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/services/interceptors/ValidateParamInterceptor.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/services/interceptors/ValidateParamInterceptor.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.services.interceptors;
import com.google.common.base.Preconditions;
import com.webank.ai.fate.serving.common.rpc.core.InboundPackage;
import com.webank.ai.fate.serving.common.rpc.core.Interceptor;
import com.webank.ai.fate.serving.common.rpc.core.OutboundPackage;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.exceptions.BaseException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class ValidateParamInterceptor implements Interceptor {
@Override
public void doPreProcess(Context context, InboundPackage inboundPackage, OutboundPackage outboundPackage) throws Exception {
try {
Map params = (Map) inboundPackage.getBody();
String host = (String) params.get(Dict.HOST);
Integer port = (Integer) params.get(Dict.PORT);
Preconditions.checkArgument(StringUtils.isNotBlank(host), "parameter host is required");
Preconditions.checkArgument(port != null && port.intValue() != 0, "parameter port is required");
} catch (Exception e) {
throw new BaseException(StatusCode.PARAM_ERROR, e.getMessage());
}
}
}
| 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/filter/SecurityFilter.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/filter/SecurityFilter.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.filter;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
@WebFilter(urlPatterns={"/**"}, filterName="PotentialClickjackingFilter")
public class SecurityFilter implements Filter {
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain) throws IOException, ServletException {
((HttpServletResponse) resp).addHeader("X-Frame-Options", "DENY");
((HttpServletResponse) resp).addHeader("X-XSS-Protection", "1; mode=block");
filterChain.doFilter(req, resp);
}
} | 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/utils/NetAddressChecker.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/utils/NetAddressChecker.java | package com.webank.ai.fate.serving.admin.utils;
import com.webank.ai.fate.serving.admin.services.ComponentService;
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;
/**
* @author hcy
*/
public class NetAddressChecker {
private static final ComponentService componentService = new ComponentService();
public static void check(String host, Integer port) {
if (!NetUtils.isValidAddress(host + ":" + port)) {
throw new SysException("invalid address");
}
if (!componentService.isAllowAccess(host, port)) {
throw new RemoteRpcException("no allow access, target: " + host + ":" + port);
}
}
}
| 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/bean/VerifyService.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/bean/VerifyService.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.bean;
public enum VerifyService {
// PUBLISH_LOAD("publishLoad"),
// PUBLISH_BIND("publishBind"),
// PUBLISH_ONLINE("publishOnline"),
INFERENCE("inference"),
BATCH_INFERENCE("batchInference");
private String callName;
public String getCallName() {
return callName;
}
public void setCallName(String callName) {
this.callName = callName;
}
VerifyService(String callName) {
this.callName = callName;
}
public static boolean contains(String callName) {
VerifyService[] values = VerifyService.values();
for (VerifyService value : values) {
if (value.getCallName().equals(callName)) {
return true;
}
}
return false;
}
}
| 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/bean/ServiceConfiguration.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/bean/ServiceConfiguration.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.bean;
import java.util.Arrays;
public enum ServiceConfiguration {
/**
* name equal Dict.SERVICE_PROXY
*/
PROXY("route_table.json"),
/**
* name equal Dict.SERVICE_SERVING
*/
SERVING();
/**
* support multiple
* @param config configuration file name
*/
ServiceConfiguration(String... config) {
this.config = config;
}
private String[] config;
public static boolean isAllowModify(String project, String config) {
ServiceConfiguration value = ServiceConfiguration.valueOf(project.toUpperCase());
if (value == null) {
return Boolean.FALSE;
}
return Arrays.asList(value.config).contains(config);
}
}
| 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/config/WebConfig.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/config/WebConfig.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.config;
import com.webank.ai.fate.serving.admin.interceptors.LoginInterceptor;
import com.webank.ai.fate.serving.common.cache.Cache;
import com.webank.ai.fate.serving.common.cache.ExpiringLRUCache;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@EnableScheduling
public class WebConfig implements WebMvcConfigurer {
private static final Logger logger = LoggerFactory.getLogger(WebConfig.class);
@Bean
public LoginInterceptor loginInterceptor() {
return new LoginInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginInterceptor())
.addPathPatterns("/api/**")
.excludePathPatterns("/api/admin/login");
}
/*@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}*/
/*@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("*")
.allowedHeaders("*")
.allowCredentials(true)
.maxAge(86400);
}*/
@Bean
public Cache cache() {
String cacheType = MetaInfo.PROPERTY_CACHE_TYPE;
logger.info("cache type is {},prepare to build cache", cacheType);
Integer maxSize = MetaInfo.PROPERTY_LOCAL_CACHE_MAXSIZE;
Integer expireTime = MetaInfo.PROPERTY_LOCAL_CACHE_EXPIRE;
Integer interval = MetaInfo.PROPERTY_LOCAL_CACHE_INTERVAL;
return new ExpiringLRUCache(maxSize, expireTime, interval);
}
}
| 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/config/RegistryConfig.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/config/RegistryConfig.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.config;
import com.webank.ai.fate.register.zookeeper.ZookeeperRegistry;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.exceptions.SysException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RegistryConfig {
private static final Logger logger = LoggerFactory.getLogger(RegistryConfig.class);
@Bean(destroyMethod = "destroy")
public ZookeeperRegistry zookeeperRegistry() {
if (logger.isDebugEnabled()) {
logger.info("prepare to create zookeeper registry ,use zk {}", MetaInfo.PROPERTY_USE_ZK_ROUTER);
}
if (MetaInfo.PROPERTY_USE_ZK_ROUTER) {
if (StringUtils.isEmpty(MetaInfo.PROPERTY_ZK_URL)) {
logger.error("useZkRouter is true,but zkUrl is empty,please check zk.url in the config file");
throw new RuntimeException("wrong zk url");
}
ZookeeperRegistry zookeeperRegistry = ZookeeperRegistry.createRegistry(MetaInfo.PROPERTY_ZK_URL, Dict.SERVICE_ADMIN, Dict.ONLINE_ENVIRONMENT, MetaInfo.PROPERTY_SERVER_PORT);
zookeeperRegistry.registerComponent();
zookeeperRegistry.subProject(Dict.SERVICE_SERVING);
zookeeperRegistry.subProject(Dict.SERVICE_PROXY);
if (!zookeeperRegistry.isAvailable()) {
logger.error("zookeeper registry connection is not available");
throw new SysException("zookeeper registry connection loss");
}
return zookeeperRegistry;
}
return null;
}
/*@Bean
@ConditionalOnBean(ZookeeperRegistry.class)
public RouterService routerService(ZookeeperRegistry zookeeperRegistry) {
DefaultRouterService defaultRouterService = new DefaultRouterService();
defaultRouterService.setRegistry(zookeeperRegistry);
return defaultRouterService;
}*/
}
| 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/interceptors/LoginInterceptor.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/interceptors/LoginInterceptor.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.interceptors;
import com.google.common.base.Preconditions;
import com.webank.ai.fate.serving.common.cache.Cache;
import com.webank.ai.fate.serving.core.bean.Dict;
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.utils.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
public class LoginInterceptor implements HandlerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
@Autowired
private Cache cache;
private static final List<String> EXCLUDES = Arrays.asList("/api/component/list", "/api/monitor/queryJvm", "/api/monitor/query", "/api/monitor/queryModel");
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
response.setStatus(HttpStatus.OK.value());
return true;
}
String token = request.getHeader(Dict.SESSION_TOKEN);
Preconditions.checkArgument(StringUtils.isNotBlank(token), "parameter sessionToken is required");
String userInfo = (String) cache.get(token);
if (StringUtils.isNotBlank(userInfo)) {
if (!EXCLUDES.contains(request.getRequestURI())) {
cache.put(token, userInfo, "local".equalsIgnoreCase(MetaInfo.PROPERTY_CACHE_TYPE) ? MetaInfo.PROPERTY_LOCAL_CACHE_EXPIRE : MetaInfo.PROPERTY_REDIS_EXPIRE);
}
return true;
} else {
if (logger.isDebugEnabled()) {
logger.debug("session token unavailable");
}
response.getWriter().write(JsonUtil.object2Json(ReturnResult.build(StatusCode.INVALID_TOKEN, "session token unavailable")));
response.flushBuffer();
return false;
}
}
}
| 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/handler/GlobalExceptionHandler.java | fate-serving-admin/src/main/java/com/webank/ai/fate/serving/admin/handler/GlobalExceptionHandler.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.handler;
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.ParameterException;
import com.webank.ai.fate.serving.core.exceptions.RemoteRpcException;
import io.grpc.StatusRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
/**
* @Description Global exceptions management
* @Date: 2020/3/25 11:11
* @Author: v_dylanxu
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(value = {MethodArgumentTypeMismatchException.class, IllegalArgumentException.class})
public ReturnResult paramValidationExceptionHandle(Exception e) {
logger.error("[ParamValidationException]Exception:", e);
return ReturnResult.build(StatusCode.PARAM_ERROR, "request parameter error");
}
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(value = {StatusRuntimeException.class, RemoteRpcException.class})
public ReturnResult statusRuntimeExceptionHandle(Exception e) {
logger.error("[RemoteRpcException]Exception:", e);
return ReturnResult.build(StatusCode.NET_ERROR, "remote rpc request exception");
}
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(value = {ParameterException.class})
public ReturnResult statusRuntimeExceptionHandle(ParameterException e) {
logger.error("[RemoteRpcException]Exception:", e);
return ReturnResult.build(e.getRetcode(), e.getMessage());
}
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(value = Exception.class)
public ReturnResult commonExceptionHandle(Exception e) {
logger.error("[SystemException]Exception:", e);
return ReturnResult.build(StatusCode.SYSTEM_ERROR, "system error, please check the log for detail");
}
} | 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-common/src/main/java/com/webank/ai/fate/serving/common/cache/LRUCache.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/cache/LRUCache.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.common.cache;
import java.util.LinkedHashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LRUCache<K, V> extends LinkedHashMap<K, V> {
private static final long serialVersionUID = -5167631809472116969L;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private static final int DEFAULT_MAX_CAPACITY = 1000;
private final Lock lock = new ReentrantLock();
private volatile int maxCapacity;
public LRUCache() {
this(DEFAULT_MAX_CAPACITY);
}
public LRUCache(int maxCapacity) {
super(16, DEFAULT_LOAD_FACTOR, true);
this.maxCapacity = maxCapacity;
}
@Override
protected boolean removeEldestEntry(java.util.Map.Entry<K, V> eldest) {
return size() > maxCapacity;
}
@Override
public boolean containsKey(Object key) {
lock.lock();
try {
return super.containsKey(key);
} finally {
lock.unlock();
}
}
@Override
public V get(Object key) {
lock.lock();
try {
return super.get(key);
} finally {
lock.unlock();
}
}
@Override
public V put(K key, V value) {
lock.lock();
try {
return super.put(key, value);
} finally {
lock.unlock();
}
}
@Override
public V remove(Object key) {
lock.lock();
try {
return super.remove(key);
} finally {
lock.unlock();
}
}
@Override
public int size() {
lock.lock();
try {
return super.size();
} finally {
lock.unlock();
}
}
@Override
public void clear() {
lock.lock();
try {
super.clear();
} finally {
lock.unlock();
}
}
public int getMaxCapacity() {
return maxCapacity;
}
public void setMaxCapacity(int maxCapacity) {
this.maxCapacity = maxCapacity;
}
} | 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-common/src/main/java/com/webank/ai/fate/serving/common/cache/RedisCache.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/cache/RedisCache.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.common.cache;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Pipeline;
import java.util.List;
public class RedisCache implements Cache {
private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);
int expireTime;
String host;
int port;
int timeout;
String password;
int maxTotal;
int maxIdel;
JedisPool jedisPool;
synchronized public void init() {
initStandaloneConfiguration();
}
private void initStandaloneConfiguration() {
if (logger.isDebugEnabled()) {
logger.debug("redis cache init, mode: standalone");
}
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxTotal(maxTotal);
jedisPoolConfig.setMaxIdle(maxIdel);
jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
}
@Override
public void put(Object key, Object value) {
this.put(key, value, expireTime);
}
@Override
public void put(Object key, Object value, int expire) {
if (logger.isDebugEnabled()) {
logger.debug("put cache key: {} value: {} expire: {}", key, value, expire);
}
try (Jedis jedis = jedisPool.getResource()) {
Pipeline redisPipeline = jedis.pipelined();
redisPipeline.set(key.toString(), value.toString());
if (expire > 0) {
redisPipeline.expire(key.toString(), expire);
}
redisPipeline.sync();
}
}
@Override
public Object get(Object key) {
if (logger.isDebugEnabled()) {
logger.debug("get cache key: {}", key);
}
try (Jedis jedis = jedisPool.getResource()) {
return jedis.get(key.toString());
}
}
@Override
public List get(Object[] keys) {
List<DataWrapper> result = Lists.newArrayList();
for (Object key : keys) {
Object singleResult = this.get(key);
if (singleResult != null) {
DataWrapper dataWrapper = new DataWrapper(key, singleResult);
result.add(dataWrapper);
}
}
return result;
}
@Override
public void delete(Object key) {
if (logger.isDebugEnabled()) {
logger.debug("remove cache key: {}", key);
}
try (Jedis jedis = jedisPool.getResource()) {
jedis.del(key.toString());
}
}
@Override
public void put(List list) {
for (Object object : list) {
DataWrapper dataWrapper = (DataWrapper) object;
this.put(dataWrapper.getKey(), dataWrapper.getValue());
}
}
public int getExpireTime() {
return expireTime;
}
public void setExpireTime(int expireTime) {
this.expireTime = expireTime;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getMaxTotal() {
return maxTotal;
}
public void setMaxTotal(int maxTotal) {
this.maxTotal = maxTotal;
}
public int getMaxIdel() {
return maxIdel;
}
public void setMaxIdel(int maxIdel) {
this.maxIdel = maxIdel;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/cache/Cache.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/cache/Cache.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.common.cache;
import java.util.List;
public interface Cache<K, V> {
void put(K key, V value);
void put(K key, V value, int expire);
V get(K key);
List<DataWrapper> get(K... keys);
void put(List<DataWrapper> dataWrappers);
void delete(K key);
public static class DataWrapper<K, V> {
K key;
V value;
public DataWrapper(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/cache/RedisClusterCache.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/cache/RedisClusterCache.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.common.cache;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class RedisClusterCache extends RedisCache {
private static final Logger logger = LoggerFactory.getLogger(RedisClusterCache.class);
String clusterNodes;
JedisCluster jedisCluster;
public RedisClusterCache(String clusterNodes) {
this.clusterNodes = clusterNodes;
}
@Override
public synchronized void init() {
initClusterConfiguration();
}
private void initClusterConfiguration() {
if (logger.isDebugEnabled()) {
logger.debug("redis cache init, mode: cluster");
}
if (StringUtils.isNotBlank(clusterNodes)) {
Set<HostAndPort> nodeSet = new HashSet<>();
try {
String[] nodes = clusterNodes.split(",");
if (nodes.length > 0) {
for (String node : nodes) {
String[] hostAndPost = node.split(":");
nodeSet.add(new HostAndPort(hostAndPost[0], Integer.valueOf(hostAndPost[1])));
}
}
} catch (Exception e) {
logger.error("redis.cluster.nodes is invalid format");
e.printStackTrace();
}
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdel);
jedisPoolConfig.setMaxTotal(maxTotal);
jedisPoolConfig.setMaxWaitMillis(timeout);
jedisPoolConfig.setTestOnBorrow(true);
jedisCluster = new JedisCluster(nodeSet, timeout, timeout, 3, password, jedisPoolConfig);
}
}
@Override
public void put(Object key, Object value) {
this.put(key, value, expireTime);
}
@Override
public void put(Object key, Object value, int expire) {
if (logger.isDebugEnabled()) {
logger.debug("put cache key: {} value: {} expire: {}", key, value, expire);
}
jedisCluster.set(key.toString(), value.toString());
if (expire > 0) {
jedisCluster.expire(key.toString(), expire);
}
}
@Override
public Object get(Object key) {
if (logger.isDebugEnabled()) {
logger.debug("get cache key: {}", key);
}
return jedisCluster.get(key.toString());
}
@Override
public List get(Object[] keys) {
return super.get(keys);
}
@Override
public void delete(Object key) {
if (logger.isDebugEnabled()) {
logger.debug("remove cache key: {}", key);
}
jedisCluster.del(key.toString());
}
@Override
public void put(List list) {
super.put(list);
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/cache/ExpiringMap.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/cache/ExpiringMap.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.common.cache;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ExpiringMap<K, V> extends LinkedHashMap<K, V> {
private static final int DEFAULT_TIME_TO_LIVE = 180;
private static final int DEFAULT_MAX_CAPACITY = 1000;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
private static final int DEFAULT_EXPIRATION_INTERVAL = 1;
private static AtomicInteger expireCount = new AtomicInteger(1);
private final ConcurrentHashMap<K, ExpiryObject> delegateMap;
private final ExpireThread expireThread;
private volatile int maxCapacity;
public ExpiringMap() {
this(DEFAULT_MAX_CAPACITY, DEFAULT_TIME_TO_LIVE, DEFAULT_EXPIRATION_INTERVAL);
}
public ExpiringMap(int maxCapacity, int timeToLive, int expirationInterval) {
this.maxCapacity = maxCapacity;
this.delegateMap = new ConcurrentHashMap<>();
this.expireThread = new ExpireThread();
expireThread.setTimeToLive(timeToLive);
expireThread.setExpirationInterval(expirationInterval);
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > maxCapacity;
}
@Override
public V put(K key, V value) {
ExpiryObject answer = delegateMap.put(key, new ExpiryObject(key, value, System.currentTimeMillis()));
if (answer == null) {
return null;
}
return answer.getValue();
}
@Override
public V get(Object key) {
ExpiryObject object = delegateMap.get(key);
if (object != null) {
object.setLastAccessTime(System.currentTimeMillis());
return object.getValue();
}
return null;
}
@Override
public V remove(Object key) {
ExpiryObject answer = delegateMap.remove(key);
if (answer == null) {
return null;
}
return answer.getValue();
}
@Override
public boolean containsKey(Object key) {
return delegateMap.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return delegateMap.containsValue(value);
}
@Override
public int size() {
return delegateMap.size();
}
@Override
public boolean isEmpty() {
return delegateMap.isEmpty();
}
@Override
public void clear() {
delegateMap.clear();
expireThread.stopExpiring();
}
@Override
public int hashCode() {
return delegateMap.hashCode();
}
@Override
public Set<K> keySet() {
return delegateMap.keySet();
}
@Override
public boolean equals(Object obj) {
return delegateMap.equals(obj);
}
@Override
public void putAll(Map<? extends K, ? extends V> inMap) {
throw new UnsupportedOperationException();
}
// @Override
// public Collection<V> values() {
// List<V> list = new ArrayList<V>();
// Set<Entry<K, ExpiryObject>> delegatedSet = delegateMap.entrySet();
// for (Entry<K, ExpiryObject> entry : delegatedSet) {
// ExpiryObject value = entry.getValue();
// list.add(value.getValue());
// }
// return list;
// }
// @Override
// public Set<Entry<K, V>> entrySet() {
// throw new UnsupportedOperationException();
// }
public ExpireThread getExpireThread() {
return expireThread;
}
public int getExpirationInterval() {
return expireThread.getExpirationInterval();
}
public void setExpirationInterval(int expirationInterval) {
expireThread.setExpirationInterval(expirationInterval);
}
public int getTimeToLive() {
return expireThread.getTimeToLive();
}
public void setTimeToLive(int timeToLive) {
expireThread.setTimeToLive(timeToLive);
}
@Override
public String toString() {
return "ExpiringMap{" +
"delegateMap=" + delegateMap.toString() +
", expireThread=" + expireThread.toString() +
'}';
}
/**
* can be expired object
*/
private class ExpiryObject {
private K key;
private V value;
private AtomicLong lastAccessTime;
ExpiryObject(K key, V value, long lastAccessTime) {
if (value == null) {
throw new IllegalArgumentException("An expiring object cannot be null.");
}
this.key = key;
this.value = value;
this.lastAccessTime = new AtomicLong(lastAccessTime);
}
public long getLastAccessTime() {
return lastAccessTime.get();
}
public void setLastAccessTime(long lastAccessTime) {
this.lastAccessTime.set(lastAccessTime);
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
@Override
public boolean equals(Object obj) {
return value.equals(obj);
}
@Override
public int hashCode() {
return value.hashCode();
}
@Override
public String toString() {
return "ExpiryObject{" +
"key=" + key +
", value=" + value +
", lastAccessTime=" + lastAccessTime +
'}';
}
}
/**
* Background thread, periodically checking if the data is out of date
*/
public class ExpireThread implements Runnable {
private final Thread expirerThread;
private long timeToLiveMillis;
private long expirationIntervalMillis;
private volatile boolean running = false;
public ExpireThread() {
expirerThread = new Thread(this, "ExpiryMapExpire-" + expireCount.getAndIncrement());
expirerThread.setDaemon(true);
}
@Override
public String toString() {
return "ExpireThread{" +
", timeToLiveMillis=" + timeToLiveMillis +
", expirationIntervalMillis=" + expirationIntervalMillis +
", running=" + running +
", expirerThread=" + expirerThread +
'}';
}
@Override
public void run() {
while (running) {
processExpires();
try {
Thread.sleep(expirationIntervalMillis);
} catch (InterruptedException e) {
running = false;
}
}
}
private void processExpires() {
long timeNow = System.currentTimeMillis();
for (ExpiryObject o : delegateMap.values()) {
if (timeToLiveMillis <= 0) {
continue;
}
long timeIdle = timeNow - o.getLastAccessTime();
if (timeIdle >= timeToLiveMillis) {
delegateMap.remove(o.getKey());
}
}
}
/**
* start expiring Thread
*/
public void startExpiring() {
if (!running) {
running = true;
expirerThread.start();
}
}
/**
* start thread
*/
public void startExpiryIfNotStarted() {
if (running) {
return;
}
startExpiring();
}
/**
* stop thread
*/
public void stopExpiring() {
if (running) {
running = false;
expirerThread.interrupt();
}
}
/**
* get thread state
*
* @return thread state
*/
public boolean isRunning() {
return running;
}
/**
* get time to live
*
* @return time to live
*/
public int getTimeToLive() {
return (int) timeToLiveMillis / 1000;
}
/**
* update time to live
*
* @param timeToLive time to live
*/
public void setTimeToLive(long timeToLive) {
this.timeToLiveMillis = timeToLive * 1000;
}
/**
* get expiration interval
*
* @return expiration interval (second)
*/
public int getExpirationInterval() {
return (int) expirationIntervalMillis / 1000;
}
/**
* set expiration interval
*
* @param expirationInterval expiration interval (second)
*/
public void setExpirationInterval(long expirationInterval) {
this.expirationIntervalMillis = expirationInterval * 1000;
}
}
} | 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-common/src/main/java/com/webank/ai/fate/serving/common/cache/ExpiringLRUCache.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/cache/ExpiringLRUCache.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.common.cache;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Map;
public class ExpiringLRUCache implements Cache {
private static final Logger logger = LoggerFactory.getLogger(ExpiringLRUCache.class);
private final Map<Object, Object> store;
public ExpiringLRUCache(int maxSize, int liveTimeSeconds, int intervalSeconds) {
if (logger.isDebugEnabled()) {
logger.debug("expiring lru cache init");
}
ExpiringMap<Object, Object> expiringMap = new ExpiringMap<>(maxSize, liveTimeSeconds, intervalSeconds);
expiringMap.getExpireThread().startExpiryIfNotStarted();
this.store = expiringMap;
}
@Override
public void put(Object key, Object value) {
if (logger.isDebugEnabled()) {
logger.debug("put cache key: {} value: {}", key, value);
}
store.put(key, value);
}
@Override
public void put(Object key, Object value, int expire) {
this.put(key, value);
}
@Override
public Object get(Object key) {
if (logger.isDebugEnabled()) {
logger.debug("get cache key: {}", key);
}
return store.get(key);
}
@Override
public List<DataWrapper> get(Object[] keys) {
List<DataWrapper> result = Lists.newArrayList();
for (Object key : keys) {
Object singleResult = this.get(key);
if (singleResult != null) {
DataWrapper dataWrapper = new DataWrapper(key, singleResult);
result.add(dataWrapper);
}
}
return result;
}
@Override
public void delete(Object key) {
if (logger.isDebugEnabled()) {
logger.debug("remove cache key: {}", key);
}
store.remove(key);
}
@Override
public void put(List list) {
for (Object object : list) {
DataWrapper dataWrapper = (DataWrapper) object;
this.put(dataWrapper.getKey(), dataWrapper.getValue());
}
}
// @Override
// public void put(List<DataWrapper> dataWrappers) {
// for(DataWrapper dataWrapper: dataWrappers ) {
// this.store.put(dataWrapper.getKey(),dataWrapper.getValue());
// }
//
// }
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckConstant.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckConstant.java | package com.webank.ai.fate.serving.common.health;
public class HealthCheckConstant {
public static final String CHECK_ROUTER="check router info";
public static final String CHECK_ZOOKEEPER_IS_CONFIGED ="check zookeeper url is configed";
public static final String CHECK_CERT_FILE= "check cert file";
public static final String CHECK_MEMORY_USAGE="check memory usage";
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckStatus.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckStatus.java | package com.webank.ai.fate.serving.common.health;
public enum HealthCheckStatus {
/**
* 健康
*/
ok("状态健康"),
/**
* 异常
*/
warn("状态异常"),
/**
* 错误
*/
error("状态错误");
private final String desc;
HealthCheckStatus(String desc) {
this.desc = desc;
}
public String getDesc() {
return desc;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckUtil.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckUtil.java | package com.webank.ai.fate.serving.common.health;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.GlobalMemory;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;
public class HealthCheckUtil {
public static void memoryCheck(HealthCheckResult healthCheckResult){
try {
SystemInfo systemInfo = new SystemInfo();
CentralProcessor processor = systemInfo.getHardware().getProcessor();
long[] prevTicks = processor.getSystemCpuLoadTicks();
long[] ticks = processor.getSystemCpuLoadTicks();
long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()];
long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()];
long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()];
long steal = ticks[CentralProcessor.TickType.STEAL.getIndex()] - prevTicks[CentralProcessor.TickType.STEAL.getIndex()];
long cSys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()];
long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()];
long ioWait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()];
long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()];
long totalCpu = user + nice + cSys + idle + ioWait + irq + softirq + steal;
Map<String,String> CPUInfo = new HashMap<>();
CPUInfo.put("Total CPU Processors", String.valueOf(processor.getLogicalProcessorCount()));
CPUInfo.put("CPU Usage", new DecimalFormat("#.##%").format(1.0-(idle * 1.0 / totalCpu)));
GlobalMemory memory = systemInfo.getHardware().getMemory();
long totalByte = memory.getTotal();
long callableByte = memory.getAvailable();
Map<String,String> memoryInfo= new HashMap<>();
memoryInfo.put("Total Memory",new DecimalFormat("#.##GB").format(totalByte/1024.0/1024.0/1024.0));
memoryInfo.put("Memory Usage", new DecimalFormat("#.##%").format((totalByte-callableByte)*1.0/totalByte));
double useRate = (totalByte-callableByte)*1.0/totalByte;
String useRateString= getPercentFormat(useRate,1,2);
if(useRate>0.8) {
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_MEMORY_USAGE.getItemName()," usage:"+useRateString ,HealthCheckStatus.error));
}else{
healthCheckResult.getRecords().add(new HealthCheckRecord(HealthCheckItemEnum.CHECK_MEMORY_USAGE.getItemName(),"usage:"+useRateString ,HealthCheckStatus.ok));
}
} catch (Exception e) {
}
}
public static String getPercentFormat(double d,int IntegerDigits,int FractionDigits){
NumberFormat nf = java.text.NumberFormat.getPercentInstance();
nf.setMaximumIntegerDigits(IntegerDigits);//小数点前保留几位
nf.setMinimumFractionDigits(FractionDigits);// 小数点后保留几位
return nf.format(d);
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckResult.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckResult.java | package com.webank.ai.fate.serving.common.health;
import com.google.common.collect.Lists;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import java.util.List;
public class HealthCheckResult {
public List<HealthCheckRecord> getRecords() {
return records;
}
public void setRecords(List<HealthCheckRecord> records) {
this.records = records;
}
List<HealthCheckRecord> records = Lists.newArrayList();
@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-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckAware.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckAware.java | package com.webank.ai.fate.serving.common.health;
import com.webank.ai.fate.serving.core.bean.Context;
public interface HealthCheckAware {
public HealthCheckResult check(Context context );
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckRecord.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckRecord.java | package com.webank.ai.fate.serving.common.health;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
public class HealthCheckRecord{
String checkItemName;
String msg;
public String getCheckItemName() {
return checkItemName;
}
public void setCheckItemName(String checkItemName) {
this.checkItemName = checkItemName;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public HealthCheckStatus getHealthCheckStatus() {
return healthCheckStatus;
}
public void setHealthCheckStatus(HealthCheckStatus healthCheckStatus) {
this.healthCheckStatus = healthCheckStatus;
}
HealthCheckStatus healthCheckStatus;
public HealthCheckRecord(){
}
public HealthCheckRecord(String checkItemName, String msg, HealthCheckStatus healthCheckStatus) {
this.checkItemName = checkItemName;
this.msg = msg;
this.healthCheckStatus = healthCheckStatus;
}
@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-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckItemEnum.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckItemEnum.java | package com.webank.ai.fate.serving.common.health;
public enum HealthCheckItemEnum {
CHECK_ROUTER_FILE("check route_table.json exist",HealthCheckComponent.SERVINGPROXY),
CHECK_ZOOKEEPER_CONFIG("check zk config",HealthCheckComponent.ALL),
CHECK_ROUTER_NET("check router",HealthCheckComponent.SERVINGPROXY),
CHECK_MEMORY_USAGE("check memory usage",HealthCheckComponent.ALL),
CHECK_CERT_FILE("check cert file",HealthCheckComponent.SERVINGPROXY),
CHECK_DEFAULT_FATEFLOW("check default fateflow config",HealthCheckComponent.SERVINGSERVER),
CHECK_FATEFLOW_IN_ZK("check fateflow in zookeeper",HealthCheckComponent.SERVINGSERVER),
CHECK_MODEL_LOADED("check model loaded",HealthCheckComponent.SERVINGSERVER);
private String itemName;
private HealthCheckComponent component;
HealthCheckItemEnum(String name, HealthCheckComponent healthCheckComponent){
this.component = healthCheckComponent;
this.itemName= name;
}
public String getItemName(){
return itemName;
}
public HealthCheckComponent getComponent(){
return this.component;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckComponent.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/health/HealthCheckComponent.java | package com.webank.ai.fate.serving.common.health;
public enum HealthCheckComponent {
ALL,SERVINGPROXY,SERVINGSERVER
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/TimeUtil.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/TimeUtil.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.common.flow;
import java.util.concurrent.TimeUnit;
public final class TimeUtil {
private static volatile long currentTimeMillis = System.currentTimeMillis();
static {
Thread daemon = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
TimeUtil.currentTimeMillis = System.currentTimeMillis();
try {
TimeUnit.MILLISECONDS.sleep(1L);
} catch (Throwable var2) {
;
}
}
}
});
daemon.setDaemon(true);
daemon.setName("time-tick-thread");
daemon.start();
}
public TimeUtil() {
}
public static long currentTimeMillis() {
return currentTimeMillis;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/LeapArray.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/LeapArray.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.common.flow;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicReferenceArray;
import java.util.concurrent.locks.ReentrantLock;
public abstract class LeapArray<T> {
protected final AtomicReferenceArray<WindowWrap<T>> array;
/**
* The conditional (predicate) update lock is used only when current bucket is deprecated.
*/
private final ReentrantLock updateLock = new ReentrantLock();
protected int windowLengthInMs;
protected int sampleCount;
protected int intervalInMs;
/**
* The total bucket count is: {@code sampleCount = intervalInMs / windowLengthInMs}.
*
* @param sampleCount bucket count of the sliding window
* @param intervalInMs the total time interval of this {@link LeapArray} in milliseconds
*/
public LeapArray(int sampleCount, int intervalInMs) {
// AssertUtil.isTrue(sampleCount > 0, "bucket count is invalid: " + sampleCount);
// AssertUtil.isTrue(intervalInMs > 0, "total time interval of the sliding window should be positive");
// AssertUtil.isTrue(intervalInMs % sampleCount == 0, "time span needs to be evenly divided");
this.windowLengthInMs = intervalInMs / sampleCount;
this.intervalInMs = intervalInMs;
this.sampleCount = sampleCount;
this.array = new AtomicReferenceArray<>(sampleCount);
}
/**
* Get the bucket at current timestamp.
*
* @return the bucket at current timestamp
*/
public WindowWrap<T> currentWindow() {
return currentWindow(TimeUtil.currentTimeMillis());
}
/**
* Create a new statistic value for bucket.
*
* @param timeMillis current time in milliseconds
* @return the new empty bucket
*/
public abstract T newEmptyBucket(long timeMillis);
/**
* Reset given bucket to provided start time and reset the value.
*
* @param startTime the start time of the bucket in milliseconds
* @param windowWrap current bucket
* @return new clean bucket at given start time
*/
protected abstract WindowWrap<T> resetWindowTo(WindowWrap<T> windowWrap, long startTime);
private int calculateTimeIdx(/*@Valid*/ long timeMillis) {
long timeId = timeMillis / windowLengthInMs;
// System.err.println(timeMillis +" "+windowLengthInMs +" timeId "+timeId );
// Calculate current index so we can map the timestamp to the leap array.
return (int) (timeId % array.length());
}
protected long calculateWindowStart(/*@Valid*/ long timeMillis) {
return timeMillis - timeMillis % windowLengthInMs;
}
/**
* Get bucket item at provided timestamp.
*
* @param timeMillis a valid timestamp in milliseconds
* @return current bucket item at provided timestamp if the time is valid; null if time is invalid
*/
public WindowWrap<T> currentWindow(long timeMillis) {
if (timeMillis < 0) {
return null;
}
int idx = calculateTimeIdx(timeMillis);
//System.err.println(timeMillis + " "+idx);
// Calculate current bucket start time.
long windowStart = calculateWindowStart(timeMillis);
/*
* Get bucket item at given time from the array.
*
* (1) Bucket is absent, then just create a new bucket and CAS update to circular array.
* (2) Bucket is up-to-date, then just return the bucket.
* (3) Bucket is deprecated, then reset current bucket and clean all deprecated buckets.
*/
while (true) {
WindowWrap<T> old = array.get(idx);
if (old == null) {
/*
* B0 B1 B2 NULL B4
* ||_______|_______|_______|_______|_______||___
* 200 400 600 800 1000 1200 timestamp
* ^
* time=888
* bucket is empty, so create new and update
*
* If the old bucket is absent, then we create a new bucket at {@code windowStart},
* then try to update circular array via a CAS operation. Only one thread can
* succeed to update, while other threads yield its time slice.
*/
WindowWrap<T> window = new WindowWrap<T>(windowLengthInMs, windowStart, newEmptyBucket(timeMillis));
if (array.compareAndSet(idx, null, window)) {
// Successfully updated, return the created bucket.
return window;
} else {
// Contention failed, the thread will yield its time slice to wait for bucket available.
Thread.yield();
}
} else if (windowStart == old.windowStart()) {
/*
* B0 B1 B2 B3 B4
* ||_______|_______|_______|_______|_______||___
* 200 400 600 800 1000 1200 timestamp
* ^
* time=888
* startTime of Bucket 3: 800, so it's up-to-date
*
* If current {@code windowStart} is equal to the start timestamp of old bucket,
* that means the time is within the bucket, so directly return the bucket.
*/
return old;
} else if (windowStart > old.windowStart()) {
/*
* (old)
* B0 B1 B2 NULL B4
* |_______||_______|_______|_______|_______|_______||___
* ... 1200 1400 1600 1800 2000 2200 timestamp
* ^
* time=1676
* startTime of Bucket 2: 400, deprecated, should be reset
*
* If the start timestamp of old bucket is behind provided time, that means
* the bucket is deprecated. We have to reset the bucket to current {@code windowStart}.
* Note that the reset and clean-up operations are hard to be atomic,
* so we need a update lock to guarantee the correctness of bucket update.
*
* The update lock is conditional (tiny scope) and will take effect only when
* bucket is deprecated, so in most cases it won't lead to performance loss.
*/
if (updateLock.tryLock()) {
try {
// Successfully get the update lock, now we reset the bucket.
return resetWindowTo(old, windowStart);
} finally {
updateLock.unlock();
}
} else {
// Contention failed, the thread will yield its time slice to wait for bucket available.
Thread.yield();
}
} else if (windowStart < old.windowStart()) {
// Should not go through here, as the provided time is already behind.
return new WindowWrap<T>(windowLengthInMs, windowStart, newEmptyBucket(timeMillis));
}
}
}
/**
* Get the previous bucket item before provided timestamp.
*
* @param timeMillis a valid timestamp in milliseconds
* @return the previous bucket item before provided timestamp
*/
public WindowWrap<T> getPreviousWindow(long timeMillis) {
if (timeMillis < 0) {
return null;
}
int idx = calculateTimeIdx(timeMillis - windowLengthInMs);
timeMillis = timeMillis - windowLengthInMs;
WindowWrap<T> wrap = array.get(idx);
if (wrap == null || isWindowDeprecated(wrap)) {
return null;
}
if (wrap.windowStart() + windowLengthInMs < (timeMillis)) {
return null;
}
return wrap;
}
/**
* Get the previous bucket item for current timestamp.
*
* @return the previous bucket item for current timestamp
*/
public WindowWrap<T> getPreviousWindow() {
return getPreviousWindow(TimeUtil.currentTimeMillis());
}
/**
* Get statistic value from bucket for provided timestamp.
*
* @param timeMillis a valid timestamp in milliseconds
* @return the statistic value if bucket for provided timestamp is up-to-date; otherwise null
*/
public T getWindowValue(long timeMillis) {
if (timeMillis < 0) {
return null;
}
int idx = calculateTimeIdx(timeMillis);
WindowWrap<T> bucket = array.get(idx);
if (bucket == null || !bucket.isTimeInWindow(timeMillis)) {
return null;
}
return bucket.value();
}
/**
* Check if a bucket is deprecated, which means that the bucket
* has been behind for at least an entire window time span.
*
* @param windowWrap a non-null bucket
* @return true if the bucket is deprecated; otherwise false
*/
public boolean isWindowDeprecated(/*@NonNull*/ WindowWrap<T> windowWrap) {
return isWindowDeprecated(TimeUtil.currentTimeMillis(), windowWrap);
}
public boolean isWindowDeprecated(long time, WindowWrap<T> windowWrap) {
return time - windowWrap.windowStart() > intervalInMs;
}
/**
* Get valid bucket list for entire sliding window.
* The list will only contain "valid" buckets.
*
* @return valid bucket list for entire sliding window.
*/
public List<WindowWrap<T>> list() {
return list(TimeUtil.currentTimeMillis());
}
public List<WindowWrap<T>> list(long validTime) {
int size = array.length();
List<WindowWrap<T>> result = new ArrayList<WindowWrap<T>>(size);
for (int i = 0; i < size; i++) {
WindowWrap<T> windowWrap = array.get(i);
if (windowWrap == null || isWindowDeprecated(validTime, windowWrap)) {
continue;
}
result.add(windowWrap);
}
return result;
}
/**
* Get all buckets for entire sliding window including deprecated buckets.
*
* @return all buckets for entire sliding window
*/
public List<WindowWrap<T>> listAll() {
int size = array.length();
List<WindowWrap<T>> result = new ArrayList<WindowWrap<T>>(size);
for (int i = 0; i < size; i++) {
WindowWrap<T> windowWrap = array.get(i);
if (windowWrap == null) {
continue;
}
result.add(windowWrap);
}
return result;
}
/**
* Get aggregated value list for entire sliding window.
* The list will only contain value from "valid" buckets.
*
* @return aggregated value list for entire sliding window
*/
public List<T> values() {
return values(TimeUtil.currentTimeMillis());
}
public List<T> values(long timeMillis) {
if (timeMillis < 0) {
return new ArrayList<T>();
}
int size = array.length();
List<T> result = new ArrayList<T>(size);
for (int i = 0; i < size; i++) {
WindowWrap<T> windowWrap = array.get(i);
if (windowWrap == null || isWindowDeprecated(timeMillis, windowWrap)) {
continue;
}
result.add(windowWrap.value());
}
return result;
}
/**
* Get the valid "head" bucket of the sliding window for provided timestamp.
* Package-private for test.
*
* @param timeMillis a valid timestamp in milliseconds
* @return the "head" bucket if it exists and is valid; otherwise null
*/
WindowWrap<T> getValidHead(long timeMillis) {
// Calculate index for expected head time.
int idx = calculateTimeIdx(timeMillis + windowLengthInMs);
WindowWrap<T> wrap = array.get(idx);
if (wrap == null || isWindowDeprecated(wrap)) {
return null;
}
return wrap;
}
/**
* Get the valid "head" bucket of the sliding window at current timestamp.
*
* @return the "head" bucket if it exists and is valid; otherwise null
*/
public WindowWrap<T> getValidHead() {
return getValidHead(TimeUtil.currentTimeMillis());
}
/**
* Get sample count (total amount of buckets).
*
* @return sample count
*/
public int getSampleCount() {
return sampleCount;
}
/**
* Get total interval length of the sliding window in milliseconds.
*
* @return interval in second
*/
public int getIntervalInMs() {
return intervalInMs;
}
/**
* Get total interval length of the sliding window.
*
* @return interval in second
*/
public double getIntervalInSecond() {
return intervalInMs / 1000.0;
}
public void debug(long time) {
StringBuilder sb = new StringBuilder();
List<WindowWrap<T>> lists = list(time);
sb.append("Thread_").append(Thread.currentThread().getId()).append("_");
for (WindowWrap<T> window : lists) {
sb.append(window.windowStart()).append(":").append(window.value().toString());
}
// System.out.println(sb.toString());
}
public long currentWaiting() {
// TODO: default method. Should remove this later.
return 0;
}
public void addWaiting(long time, int acquireCount) {
// Do nothing by default.
throw new UnsupportedOperationException();
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/MetricWriter.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/MetricWriter.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.common.flow;
import com.webank.ai.fate.serving.common.utils.GetSystemInfo;
import com.webank.ai.fate.serving.core.bean.Dict;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
public class MetricWriter {
public static final String METRIC_BASE_DIR = System.getProperty(Dict.PROPERTY_USER_HOME) + "/.fate/metric/";
public static final String METRIC_FILE = "metrics.log";
public static final String METRIC_FILE_INDEX_SUFFIX = ".idx";
public static final Comparator<String> METRIC_FILE_NAME_CMP = new MetricFileNameComparator();
private static final String CHARSET = "UTF-8";
private final static int pid = GetSystemInfo.getPid();
private final static boolean usePid = FlowCounterManager.USE_PID;
private final DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Logger logger = LoggerFactory.getLogger(MetricWriter.class);
String appName;
private long timeSecondBase;
private String baseDir;
private String baseFileName;
private File curMetricFile;
private File curMetricIndexFile;
private FileOutputStream outMetric;
private DataOutputStream outIndex;
private BufferedOutputStream outMetricBuf;
private long singleFileSize;
private int totalFileCount;
private boolean append = false;
/**
* 秒级统计,忽略毫秒数。
*/
private long lastSecond = -1;
public MetricWriter(String appName, long singleFileSize) {
this(appName, singleFileSize, 6);
}
public MetricWriter(String appName, long singleFileSize, int totalFileCount) {
this.appName = appName;
if (singleFileSize <= 0 || totalFileCount <= 0) {
throw new IllegalArgumentException();
}
this.baseDir = METRIC_BASE_DIR;
File dir = new File(baseDir);
if (!dir.exists()) {
dir.mkdirs();
}
long time = System.currentTimeMillis();
this.lastSecond = time / 1000;
this.singleFileSize = singleFileSize;
this.totalFileCount = totalFileCount;
try {
this.timeSecondBase = df.parse("1970-01-01 00:00:00").getTime() / 1000;
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Get all metric files' name in {@code baseDir}. The file name must like
* <pre>
* baseFileName + ".yyyy-MM-dd.number"
* </pre>
* and not endsWith {@link #METRIC_FILE_INDEX_SUFFIX} or ".lck".
*
* @param baseDir the directory to search.
* @param baseFileName the file name pattern.
* @return the metric files' absolute path({@link File#getAbsolutePath()})
* @throws Exception
*/
static List<String> listMetricFiles(String baseDir, String baseFileName) throws Exception {
List<String> list = new ArrayList<String>();
File baseFile = new File(baseDir);
File[] files = baseFile.listFiles();
if (files == null) {
return list;
}
for (File file : files) {
String fileName = file.getName();
if (file.isFile()
&& fileNameMatches(fileName, baseFileName)
&& !fileName.endsWith(METRIC_FILE_INDEX_SUFFIX)
&& !fileName.endsWith(".lck")) {
list.add(file.getAbsolutePath());
}
}
Collections.sort(list, METRIC_FILE_NAME_CMP);
return list;
}
/**
* Test whether fileName matches baseFileName. fileName matches baseFileName when
* <pre>
* fileName = baseFileName + ".yyyy-MM-dd.number"
* </pre>
*
* @param fileName file name
* @param baseFileName base file name.
* @return if fileName matches baseFileName return true, else return false.
*/
public static boolean fileNameMatches(String fileName, String baseFileName) {
String matchFileName = baseFileName;
String part = "";
if (usePid) {
matchFileName = matchFileName.substring(0, matchFileName.indexOf(String.valueOf(pid)));
// System.err.println(matchFileName);
// fileName: serving-metrics.log.pid71860.2020-06-12
// baseFileName: serving-metrics.log.pid71860
if (fileName.startsWith(matchFileName) && !fileName.startsWith(matchFileName + ".")) {
part = fileName.substring(matchFileName.length()); // 71860.2020-06-12
String[] split = part.split("\\.");
if (!split[0].equals(String.valueOf(pid))) {
return false;
}
part = part.substring(part.indexOf(".")); // .2020-06-12
}
} else {
if (fileName.startsWith(matchFileName)) {
part = fileName.substring(matchFileName.length());
}
}
// part is like: ".yyyy-MM-dd.number", eg. ".2018-12-24.11"
return part.matches("\\.[0-9]{4}-[0-9]{2}-[0-9]{2}(\\.[0-9]*)?");
}
public static boolean fileNameAllMatches(String fileName, String baseFileName) {
String matchFileName = baseFileName;
String part = "";
if (usePid) {
matchFileName = matchFileName.substring(0, matchFileName.indexOf(String.valueOf(pid)));
// System.err.println(matchFileName);
if (fileName.startsWith(matchFileName) && !fileName.startsWith(matchFileName + ".")) {
part = fileName.substring(matchFileName.length());
part = part.substring(part.indexOf("."));
}
} else {
if (fileName.startsWith(matchFileName)) {
part = fileName.substring(matchFileName.length());
}
}
// part is like: ".yyyy-MM-dd.number", eg. ".2018-12-24.11"
System.err.println("======" + part);
return part.matches("\\.[0-9]{4}-[0-9]{2}-[0-9]{2}");
}
/**
* Form metric file name use the specific appName and pid. Note that only
* form the file name, not include path.
* <p>
* Note: {@link MetricFileNameComparator}'s implementation relays on the metric file name,
* we should be careful when changing the metric file name.
*
* @param appName
* @param pid
* @return metric file name.
*/
public static String formMetricFileName(String appName, int pid) {
if (appName == null) {
appName = "";
}
// dot is special char that should be replaced.
final String dot = ".";
final String separator = "-";
if (appName.contains(dot)) {
appName = appName.replace(dot, separator);
}
String name = appName + separator + METRIC_FILE;
if (usePid) {
name += ".pid" + pid;
}
return name;
}
/**
* Form index file name of the {@code metricFileName}
*
* @param metricFileName
* @return the index file name of the metricFileName
*/
public static String formIndexFileName(String metricFileName) {
return metricFileName + METRIC_FILE_INDEX_SUFFIX;
}
/**
* 如果传入了time,就认为nodes中所有的时间时间戳都是time.
*
* @param time
* @param nodes
*/
public synchronized void write(long time, List<MetricNode> nodes) throws Exception {
if (nodes == null) {
return;
}
for (MetricNode node : nodes) {
node.setTimestamp(time);
}
// first write, should create file
if (curMetricFile == null) {
baseFileName = formMetricFileName(appName, pid);
closeAndNewFile(nextFileNameOfDay(time));
}
if (!(curMetricFile.exists() && curMetricIndexFile.exists())) {
closeAndNewFile(nextFileNameOfDay(time));
}
long second = time / 1000;
if (second < lastSecond) {
// 时间靠前的直接忽略,不应该发生。
} else if (second == lastSecond) {
for (MetricNode node : nodes) {
outMetricBuf.write(node.toFatString().getBytes(CHARSET));
}
outMetricBuf.flush();
if (!validSize()) {
closeAndNewFile(nextFileNameOfDay(time));
}
} else {
writeIndex(second, outMetric.getChannel().position());
if (isNewDay(lastSecond, second)) {
closeAndNewFile(nextFileNameOfDay(time));
for (MetricNode node : nodes) {
outMetricBuf.write(node.toFatString().getBytes(CHARSET));
}
outMetricBuf.flush();
if (!validSize()) {
closeAndNewFile(nextFileNameOfDay(time));
}
} else {
for (MetricNode node : nodes) {
outMetricBuf.write(node.toFatString().getBytes(CHARSET));
}
outMetricBuf.flush();
if (!validSize()) {
closeAndNewFile(nextFileNameOfDay(time));
}
}
lastSecond = second;
}
}
public synchronized void close() throws Exception {
if (outMetricBuf != null) {
outMetricBuf.close();
}
if (outIndex != null) {
outIndex.close();
}
}
private void writeIndex(long time, long offset) throws Exception {
outIndex.writeLong(time);
outIndex.writeLong(offset);
outIndex.flush();
}
private String nextFileNameOfDay(long time) {
List<String> list = new ArrayList<String>();
File baseFile = new File(baseDir);
DateFormat fileNameDf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = fileNameDf.format(new Date(time));
String fileNameModel = baseFileName + "." + dateStr;
for (File file : baseFile.listFiles()) {
String fileName = file.getName();
if (fileName.contains(fileNameModel)
&& !fileName.endsWith(METRIC_FILE_INDEX_SUFFIX)
&& !fileName.endsWith(".lck")) {
list.add(file.getAbsolutePath());
}
}
Collections.sort(list, METRIC_FILE_NAME_CMP);
if (list.isEmpty()) {
return baseDir + fileNameModel;
}
String last = list.get(list.size() - 1);
int n = 0;
String[] strs = last.split("\\.");
if (strs.length > 0 && strs[strs.length - 1].matches("[0-9]{1,10}")) {
n = Integer.parseInt(strs[strs.length - 1]);
}
return baseDir + fileNameModel + "." + (n + 1);
}
public void removeMoreFiles() throws Exception {
List<String> list = listMetricFiles(baseDir, baseFileName);
if (list == null || list.isEmpty()) {
return;
}
for (int i = 0; i < list.size() - totalFileCount + 1; i++) {
String fileName = list.get(i);
String indexFile = formIndexFileName(fileName);
new File(fileName).delete();
logger.info("removing metric file: " + fileName);
new File(indexFile).delete();
// RecordLog.info("[MetricWriter] Removing metric index file: " + indexFile);
}
}
public void removeAllFiles() throws Exception {
List<String> list = listMetricFiles(baseDir, baseFileName);
if (list == null || list.isEmpty()) {
return;
}
for (int i = 0; i < list.size(); i++) {
String fileName = list.get(i);
if (fileName.indexOf("pid" + pid + ".") > 0) {
String indexFile = formIndexFileName(fileName);
try {
new File(fileName).delete();
} catch (Exception e) {
}
System.err.println("removing metric file: " + fileName);
try {
new File(indexFile).delete();
} catch (Exception e) {
}
System.err.println("removing metric file: " + indexFile);
} else {
System.err.println("metric file " + fileName + " is not match");
}
}
}
private void closeAndNewFile(String fileName) throws Exception {
removeMoreFiles();
if (outMetricBuf != null) {
outMetricBuf.close();
}
if (outIndex != null) {
outIndex.close();
}
outMetric = new FileOutputStream(fileName, append);
outMetricBuf = new BufferedOutputStream(outMetric);
curMetricFile = new File(fileName);
String idxFile = formIndexFileName(fileName);
curMetricIndexFile = new File(idxFile);
outIndex = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(idxFile, append)));
//RecordLog.info("[MetricWriter] New metric file created: " + fileName);
//RecordLog.info("[MetricWriter] New metric index file created: " + idxFile);
}
private boolean validSize() throws Exception {
long size = outMetric.getChannel().size();
return size < singleFileSize;
}
private boolean isNewDay(long lastSecond, long second) {
long lastDay = (lastSecond - timeSecondBase) / 86400;
long newDay = (second - timeSecondBase) / 86400;
return newDay > lastDay;
}
/**
* A comparator for metric file name. Metric file name is like: <br/>
* <pre>
* metrics.log.2018-03-06
* metrics.log.2018-03-07
* metrics.log.2018-03-07.10
* metrics.log.2018-03-06.100
* </pre>
* <p>
* File name with the early date is smaller, if date is same, the one with the small file number is smaller.
* Note that if the name is an absolute path, only the fileName({@link File#getName()}) part will be considered.
* So the above file names should be sorted as: <br/>
* <pre>
* metrics.log.2018-03-06
* metrics.log.2018-03-06.100
* metrics.log.2018-03-07
* metrics.log.2018-03-07.10
*
* </pre>
* </p>
*/
private static final class MetricFileNameComparator implements Comparator<String> {
private final String pid = "pid";
@Override
public int compare(String o1, String o2) {
String name1 = new File(o1).getName();
String name2 = new File(o2).getName();
String dateStr1 = name1.split("\\.")[2];
String dateStr2 = name2.split("\\.")[2];
// in case of file name contains pid, skip it, like Sentinel-Admin-metrics.log.pid22568.2018-12-24
if (dateStr1.startsWith(pid)) {
dateStr1 = name1.split("\\.")[3];
dateStr2 = name2.split("\\.")[3];
}
// compare date first
int t = dateStr1.compareTo(dateStr2);
if (t != 0) {
return t;
}
// same date, compare file number
t = name1.length() - name2.length();
if (t != 0) {
return t;
}
return name1.compareTo(name2);
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/FlowCounter.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/FlowCounter.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.common.flow;
import java.util.List;
import java.util.concurrent.atomic.LongAdder;
public class FlowCounter {
private final LeapArray<LongAdder> data;
private double qpsAllowed;
public FlowCounter(double qpsAllowed) {
this(new UnaryLeapArray(10, 1000), qpsAllowed);
}
FlowCounter(LeapArray<LongAdder> data, double qpsAllowed) {
this.data = data;
this.qpsAllowed = qpsAllowed;
}
public void increment() {
data.currentWindow().value().increment();
}
public void add(int x) {
data.currentWindow().value().add(x);
}
public QpsData getQpsData() {
long success = 0;
WindowWrap windowWrap = data.currentWindow();
List<LongAdder> list = data.values();
for (LongAdder window : list) {
success += window.sum();
}
double qps = success / data.getIntervalInSecond();
return new QpsData(windowWrap.windowStart(), getSum());
}
public long getSum() {
data.currentWindow();
long success = 0;
List<LongAdder> list = data.values();
for (LongAdder window : list) {
success += window.sum();
}
return success;
}
public double getQps() {
return getSum() / data.getIntervalInSecond();
}
public double getQpsAllowed() {
return qpsAllowed;
}
public FlowCounter setQpsAllowed(double qpsAllowed) {
this.qpsAllowed = qpsAllowed;
return this;
}
public boolean canPass(int times) {
return getQps() + times <= qpsAllowed;
}
public boolean tryPass(int times) {
if (canPass(times)) {
add(times);
return true;
}
return false;
}
public class QpsData {
long current;
long sum;
public QpsData(long current, long sum) {
this.current = current;
this.sum = sum;
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/MetricReport.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/MetricReport.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.common.flow;
import java.util.List;
public interface MetricReport {
public void report(List<MetricNode> metricNodes);
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/WindowWrap.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/WindowWrap.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.common.flow;
public class WindowWrap<T> {
/**
* Time length of a single window bucket in milliseconds.
*/
private final long windowLengthInMs;
/**
* Start timestamp of the window in milliseconds.
*/
private long windowStart;
/**
* Statistic data.
*/
private T value;
/**
* @param windowLengthInMs a single window bucket's time length in milliseconds.
* @param windowStart the start timestamp of the window
* @param value statistic data
*/
public WindowWrap(long windowLengthInMs, long windowStart, T value) {
this.windowLengthInMs = windowLengthInMs;
this.windowStart = windowStart;
this.value = value;
}
public long windowLength() {
return windowLengthInMs;
}
public long windowStart() {
return windowStart;
}
public T value() {
return value;
}
public void setValue(T value) {
this.value = value;
}
/**
* Reset start timestamp of current bucket to provided time.
*
* @param startTime valid start timestamp
* @return bucket after reset
*/
public WindowWrap<T> resetTo(long startTime) {
this.windowStart = startTime;
return this;
}
/**
* Check whether given timestamp is in current bucket.
*
* @param timeMillis valid timestamp in ms
* @return true if the given time is in current bucket, otherwise false
* @since 1.5.0
*/
public boolean isTimeInWindow(long timeMillis) {
return windowStart <= timeMillis && timeMillis < windowStart + windowLengthInMs;
}
@Override
public String toString() {
return "WindowWrap{" +
"windowLengthInMs=" + windowLengthInMs +
", windowStart=" + windowStart +
", value=" + value +
'}';
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/MetricSearcher.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/MetricSearcher.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.common.flow;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.nio.charset.Charset;
import java.util.List;
public class MetricSearcher {
private static final Charset defaultCharset = Charset.forName("UTF-8");
private final MetricsReader metricsReader;
private String baseDir;
private String baseFileName;
private Position lastPosition = new Position();
/**
* @param baseDir metric文件所在目录
* @param baseFileName metric文件名的关键字,比如 alihot-metrics.log
*/
public MetricSearcher(String baseDir, String baseFileName) {
this(baseDir, baseFileName, defaultCharset);
}
/**
* @param baseDir metric文件所在目录
* @param baseFileName metric文件名的关键字,比如 alihot-metrics.log
* @param charset
*/
public MetricSearcher(String baseDir, String baseFileName, Charset charset) {
if (baseDir == null) {
throw new IllegalArgumentException("baseDir can't be null");
}
if (baseFileName == null) {
throw new IllegalArgumentException("baseFileName can't be null");
}
if (charset == null) {
throw new IllegalArgumentException("charset can't be null");
}
this.baseDir = baseDir;
if (!baseDir.endsWith(File.separator)) {
this.baseDir += File.separator;
}
this.baseFileName = baseFileName;
metricsReader = new MetricsReader(charset);
}
/**
* 从beginTime开始,检索recommendLines条(大概)记录。同一秒中的数据是原子的,不能分割成多次查询。
*
* @param beginTimeMs 检索的最小时间戳
* @param recommendLines 查询最多想得到的记录条数,返回条数会尽可能不超过这个数字。但是为保证每一秒的数据不被分割,有时候
* 返回的记录条数会大于该数字。
* @return
* @throws Exception
*/
public synchronized List<MetricNode> find(long beginTimeMs, int recommendLines) throws Exception {
List<String> fileNames = MetricWriter.listMetricFiles(baseDir, baseFileName);
int i = 0;
long offsetInIndex = 0;
if (validPosition(beginTimeMs)) {
i = fileNames.indexOf(lastPosition.metricFileName);
if (i == -1) {
i = 0;
} else {
offsetInIndex = lastPosition.offsetInIndex;
}
}
for (; i < fileNames.size(); i++) {
String fileName = fileNames.get(i);
long offset = findOffset(beginTimeMs, fileName,
MetricWriter.formIndexFileName(fileName), offsetInIndex);
offsetInIndex = 0;
if (offset != -1) {
return metricsReader.readMetrics(fileNames, i, offset, recommendLines);
}
}
return null;
}
/**
* Find metric between [beginTimeMs, endTimeMs], both side inclusive.
* When identity is null, all metric between the time intervalMs will be read, otherwise, only the specific
* identity will be read.
*/
public synchronized List<MetricNode> findByTimeAndResource(long beginTimeMs, long endTimeMs, String identity)
throws Exception {
List<String> fileNames = MetricWriter.listMetricFiles(baseDir, baseFileName);
//RecordLog.info("pid=" + pid + ", findByTimeAndResource([" + beginTimeMs + ", " + endTimeMs
// + "], " + identity + ")");
int i = 0;
long offsetInIndex = 0;
if (validPosition(beginTimeMs)) {
i = fileNames.indexOf(lastPosition.metricFileName);
if (i == -1) {
i = 0;
} else {
offsetInIndex = lastPosition.offsetInIndex;
}
} else {
//RecordLog.info("lastPosition is invalidate, will re iterate all files, pid = " + pid);
}
for (; i < fileNames.size(); i++) {
String fileName = fileNames.get(i);
long offset = findOffset(beginTimeMs, fileName,
MetricWriter.formIndexFileName(fileName), offsetInIndex);
offsetInIndex = 0;
if (offset != -1) {
return metricsReader.readMetricsByEndTime(fileNames, i, offset, beginTimeMs, endTimeMs, identity);
}
}
return null;
}
/**
* The position we cached is useful only when {@code beginTimeMs} is >= {@code lastPosition.second}
* and the index file exists and the second we cached is same as in the index file.
*/
private boolean validPosition(long beginTimeMs) {
if (beginTimeMs / 1000 < lastPosition.second) {
return false;
}
if (lastPosition.indexFileName == null) {
return false;
}
// index file dose not exits
if (!new File(lastPosition.indexFileName).exists()) {
return false;
}
FileInputStream in = null;
try {
in = new FileInputStream(lastPosition.indexFileName);
in.getChannel().position(lastPosition.offsetInIndex);
DataInputStream indexIn = new DataInputStream(in);
try { // timestamp(second) in the specific position == that we cached
return indexIn.readLong() == lastPosition.second;
}finally {
indexIn.close();
}
} catch (Exception e) {
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ignore) {
}
}
}
}
private long findOffset(long beginTime, String metricFileName,
String idxFileName, long offsetInIndex) throws Exception {
lastPosition.metricFileName = null;
lastPosition.indexFileName = null;
if (!new File(idxFileName).exists()) {
return -1;
}
long beginSecond = beginTime / 1000;
FileInputStream in = new FileInputStream(idxFileName);
in.getChannel().position(offsetInIndex);
DataInputStream indexIn = new DataInputStream(in);
try {
long offset;
long second;
lastPosition.offsetInIndex = in.getChannel().position();
while ((second = indexIn.readLong()) < beginSecond) {
offset = indexIn.readLong();
lastPosition.offsetInIndex = in.getChannel().position();
}
offset = indexIn.readLong();
lastPosition.metricFileName = metricFileName;
lastPosition.indexFileName = idxFileName;
lastPosition.second = second;
return offset;
} catch (EOFException ignore) {
return -1;
} finally {
try {
in.close();
indexIn.close();
}catch(Exception igore){
}
}
}
/**
* 记录上一次读取的index文件位置和数值
*/
private static final class Position {
String metricFileName;
String indexFileName;
/**
* 索引文件内的偏移
*/
long offsetInIndex;
/**
* 索引文件中offsetInIndex位置上的数字,秒数。
*/
long second;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/LimitQueue.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/LimitQueue.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.common.flow;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
public class LimitQueue<E> implements Queue<E> {
Queue<E> queue = new LinkedList<E>();
private int limit;
public LimitQueue(int limit) {
this.limit = limit;
}
@Override
public boolean offer(E e) {
if (queue.size() >= limit) {
//如果超出长度,入队时,先出队
queue.poll();
}
return queue.offer(e);
}
@Override
public E poll() {
return queue.poll();
}
public Queue<E> getQueue() {
return queue;
}
public int getLimit() {
return limit;
}
@Override
public boolean add(E e) {
return queue.add(e);
}
@Override
public E element() {
return queue.element();
}
@Override
public E peek() {
return queue.peek();
}
@Override
public boolean isEmpty() {
return queue.size() == 0 ? true : false;
}
@Override
public int size() {
return queue.size();
}
@Override
public E remove() {
return queue.remove();
}
@Override
public boolean addAll(Collection<? extends E> c) {
return queue.addAll(c);
}
@Override
public void clear() {
queue.clear();
}
@Override
public boolean contains(Object o) {
return queue.contains(o);
}
@Override
public boolean containsAll(Collection<?> c) {
return queue.containsAll(c);
}
@Override
public Iterator<E> iterator() {
return queue.iterator();
}
@Override
public boolean remove(Object o) {
return queue.remove(o);
}
@Override
public boolean removeAll(Collection<?> c) {
return queue.removeAll(c);
}
@Override
public boolean retainAll(Collection<?> c) {
return queue.retainAll(c);
}
@Override
public Object[] toArray() {
return queue.toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return queue.toArray(a);
}
} | 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/FlowCounterManager.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/FlowCounterManager.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.common.flow;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.webank.ai.fate.serving.common.utils.GetSystemInfo;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.exceptions.SysException;
import com.webank.ai.fate.serving.core.timer.HashedWheelTimer;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
public class FlowCounterManager {
public static final boolean USE_PID = true;
private static final String DEFAULT_CONFIG_FILE = MetaInfo.PROPERTY_ROOT_PATH + File.separator + ".fate" + File.separator + "flowRules.json";
Logger logger = LoggerFactory.getLogger(FlowCounterManager.class);
String appName;
MetricSearcher metricSearcher;
MetricSearcher modelMetricSearcher;
boolean countModelRequest;
LimitQueue<MetricNode> modelLimitQueue = new LimitQueue<MetricNode>(10);
HashedWheelTimer hashedWheelTimer = new HashedWheelTimer();
MetricReport metricReport;
MetricReport modelMetricReport;
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
Map<String, Double> sourceQpsAllowMap = new HashMap<>();
File file = new File(DEFAULT_CONFIG_FILE);
private ConcurrentHashMap<String, FlowCounter> passMap = new ConcurrentHashMap<>();
private ConcurrentHashMap<String, FlowCounter> successMap = new ConcurrentHashMap<>();
private ConcurrentHashMap<String, FlowCounter> blockMap = new ConcurrentHashMap<>();
private ConcurrentHashMap<String, FlowCounter> exceptionMap = new ConcurrentHashMap<>();
public FlowCounterManager(String appName) {
this(appName, false);
}
public FlowCounterManager(String appName, Boolean countModelRequest) {
this.appName = appName;
String baseFileName = appName + "-metrics.log";
String modelFileName = "model-metrics.log";
if (USE_PID) {
baseFileName += ".pid" + GetSystemInfo.getPid();
modelFileName += ".pid" + GetSystemInfo.getPid();
}
metricSearcher = new MetricSearcher(MetricWriter.METRIC_BASE_DIR, baseFileName);
metricReport = new FileMetricReport(appName);
if (countModelRequest) {
modelMetricReport = new FileMetricReport("model");
modelMetricSearcher = new MetricSearcher(MetricWriter.METRIC_BASE_DIR, modelFileName);
}
}
public MetricSearcher getMetricSearcher() {
return metricSearcher;
}
public void setMetricSearcher(MetricSearcher metricSearcher) {
this.metricSearcher = metricSearcher;
}
public List<MetricNode> queryMetrics(long beginTimeMs, long endTimeMs, String identity) {
try {
return metricSearcher.findByTimeAndResource(beginTimeMs, endTimeMs, identity);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public List<MetricNode> queryAllMetrics(long beginTimeMs, int size) {
try {
return metricSearcher.find(beginTimeMs, size);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public List<MetricNode> queryModelMetrics(long beginTimeMs, long endTimeMs, String identity) {
try {
return modelMetricSearcher.findByTimeAndResource(beginTimeMs, endTimeMs, identity);
} catch (Exception e) {
logger.error("find model metric error", e);
throw new SysException("find model metric error");
}
}
public List<MetricNode> queryAllModelMetrics(long beginTimeMs, int size) {
try {
return modelMetricSearcher.find(beginTimeMs, size);
} catch (Exception e) {
logger.error("find mode metric error", e);
throw new SysException("find mode metric error");
}
}
public MetricReport getMetricReport() {
return metricReport;
}
public void setMetricReport(MetricReport metricReport) {
this.metricReport = metricReport;
}
public boolean pass(String sourceName, int times) {
FlowCounter flowCounter = passMap.get(sourceName);
if (flowCounter == null) {
Double allowedQps = getAllowedQps(sourceName);
flowCounter = passMap.putIfAbsent(sourceName, new FlowCounter(allowedQps != null ? allowedQps : Integer.MAX_VALUE));
if (flowCounter == null) {
flowCounter = passMap.get(sourceName);
}
}
return flowCounter.tryPass(times);
}
public boolean success(String sourceName, int times) {
FlowCounter flowCounter = successMap.get(sourceName);
if (flowCounter == null) {
flowCounter = successMap.putIfAbsent(sourceName, new FlowCounter(Integer.MAX_VALUE));
if (flowCounter == null) {
flowCounter = successMap.get(sourceName);
}
}
return flowCounter.tryPass(times);
}
public boolean block(String sourceName, int times) {
FlowCounter flowCounter = blockMap.get(sourceName);
if (flowCounter == null) {
flowCounter = blockMap.putIfAbsent(sourceName, new FlowCounter(Integer.MAX_VALUE));
if (flowCounter == null) {
flowCounter = blockMap.get(sourceName);
}
}
return flowCounter.tryPass(times);
}
public boolean exception(String sourceName, int times) {
FlowCounter flowCounter = exceptionMap.get(sourceName);
if (flowCounter == null) {
flowCounter = exceptionMap.putIfAbsent(sourceName, new FlowCounter(Integer.MAX_VALUE));
if (flowCounter == null) {
flowCounter = exceptionMap.get(sourceName);
}
}
return flowCounter.tryPass(times);
}
public void startReport() {
// init();
executor.scheduleAtFixedRate(() -> {
long current = TimeUtil.currentTimeMillis();
List<MetricNode> reportList = Lists.newArrayList();
List<MetricNode> modelReportList = Lists.newArrayList();
passMap.forEach((sourceName, flowCounter) -> {
FlowCounter successCounter = successMap.get(sourceName);
FlowCounter blockCounter = blockMap.get(sourceName);
FlowCounter exceptionCounter = exceptionMap.get(sourceName);
MetricNode metricNode = new MetricNode();
metricNode.setTimestamp(current);
metricNode.setResource(sourceName);
metricNode.setPassQps(flowCounter.getSum());
metricNode.setBlockQps(blockCounter != null ? new Double(blockCounter.getQps()).longValue() : 0);
metricNode.setExceptionQps(exceptionCounter != null ? new Double(exceptionCounter.getQps()).longValue() : 0);
metricNode.setSuccessQps(successCounter != null ? new Double(successCounter.getQps()).longValue() : 0);
if (sourceName.startsWith("I_")) {
reportList.add(metricNode);
}
if (sourceName.startsWith("M_")) {
modelReportList.add(metricNode);
}
});
// logger.info("try to report {}",reportList);
metricReport.report(reportList);
if (modelMetricReport != null) {
modelMetricReport.report(modelReportList);
}
}, 0, 1, TimeUnit.SECONDS);
}
public void rmAllFiles() {
try {
if (modelMetricReport instanceof FileMetricReport) {
FileMetricReport fileMetricReport = (FileMetricReport) modelMetricReport;
fileMetricReport.rmAllFile();
}
if (metricReport instanceof FileMetricReport) {
FileMetricReport fileMetricReport = (FileMetricReport) metricReport;
fileMetricReport.rmAllFile();
}
} catch (Exception e) {
logger.error("remove metric file error");
}
}
/**
* init rules
*/
private void initialize() throws IOException {
logger.info("try to load flow counter rules, {}", file.getAbsolutePath());
if (file.exists()) {
String result = "";
try (
FileInputStream fileInputStream = new FileInputStream(file);
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
BufferedReader reader = new BufferedReader(inputStreamReader)
) {
String tempString;
while ((tempString = reader.readLine()) != null) {
result += tempString;
}
List<Map> list = JsonUtil.json2Object(result, new TypeReference<List<Map>>() {});
if (list != null) {
list.forEach(map -> {
sourceQpsAllowMap.put((String) map.get("source"), Double.valueOf(String.valueOf(map.get("allow_qps"))));
});
}
} catch (IOException e) {
logger.error("load flow counter rules failed, use default setting, cause by: {}", e.getMessage());
}
logger.info("load flow counter rules success");
}
}
private void store(File file, byte[] data) {
try {
if (!file.exists() && file.getParentFile() != null && !file.getParentFile().exists()) {
if (!file.getParentFile().mkdirs()) {
throw new IllegalArgumentException("invalid flow control cache file " + file + ", cause: Failed to create directory " + file.getParentFile() + "!");
}
}
if (!file.exists()) {
file.createNewFile();
}
try (FileOutputStream outputFile = new FileOutputStream(file)) {
outputFile.write(data);
}
} catch (Throwable e) {
logger.error("store rules file failed, cause: {}", e.getMessage());
}
}
public Double getAllowedQps(String sourceName) {
return sourceQpsAllowMap.get(sourceName);
}
public void setAllowQps(String sourceName, double allowQps) {
logger.info("update {} allowed qps to {}", sourceName, allowQps);
sourceQpsAllowMap.put(sourceName, allowQps);
List<Map> list = sourceQpsAllowMap.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getKey))
.map(entry -> {
Map map = Maps.newHashMap();
map.put("source", entry.getKey());
map.put("allow_qps", entry.getValue());
return map;
})
.collect(Collectors.toList());
this.store(file, JsonUtil.object2Json(list).getBytes());
// 更新FlowCounter
FlowCounter flowCounter = passMap.get(sourceName);
if (flowCounter != null) {
flowCounter.setQpsAllowed(allowQps);
}
}
public void destroy() {
System.err.println("try to destroy flow counter");
if (this != null) {
this.rmAllFiles();
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/MetricNode.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/MetricNode.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.common.flow;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MetricNode {
private long timestamp;
private long passQps;
private long blockQps;
private long successQps;
private long exceptionQps;
private long rt;
private long occupiedPassQps;
private String resource;
/**
* Parse {@link MetricNode} from thin string, see {@link #toThinString()}
*
* @param line
* @return
*/
public static MetricNode fromThinString(String line) {
MetricNode node = new MetricNode();
String[] strs = line.split("\\|");
node.setTimestamp(Long.parseLong(strs[0]));
node.setResource(strs[1]);
node.setPassQps(Long.parseLong(strs[2]));
node.setBlockQps(Long.parseLong(strs[3]));
node.setSuccessQps(Long.parseLong(strs[4]));
node.setExceptionQps(Long.parseLong(strs[5]));
node.setRt(Long.parseLong(strs[6]));
if (strs.length == 8) {
node.setOccupiedPassQps(Long.parseLong(strs[7]));
}
return node;
}
/**
* Parse {@link MetricNode} from fat string, see {@link #toFatString()}
*
* @param line
* @return the {@link MetricNode} parsed.
*/
public static MetricNode fromFatString(String line) {
String[] strs = line.split("\\|");
Long time = Long.parseLong(strs[0]);
MetricNode node = new MetricNode();
node.setTimestamp(time);
node.setResource(strs[2]);
node.setPassQps(Long.parseLong(strs[3]));
node.setBlockQps(Long.parseLong(strs[4]));
node.setSuccessQps(Long.parseLong(strs[5]));
node.setExceptionQps(Long.parseLong(strs[6]));
node.setRt(Long.parseLong(strs[7]));
if (strs.length == 9) {
node.setOccupiedPassQps(Long.parseLong(strs[8]));
}
return node;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public long getOccupiedPassQps() {
return occupiedPassQps;
}
public void setOccupiedPassQps(long occupiedPassQps) {
this.occupiedPassQps = occupiedPassQps;
}
public long getSuccessQps() {
return successQps;
}
public void setSuccessQps(long successQps) {
this.successQps = successQps;
}
public long getPassQps() {
return passQps;
}
public void setPassQps(long passQps) {
this.passQps = passQps;
}
public long getExceptionQps() {
return exceptionQps;
}
public void setExceptionQps(long exceptionQps) {
this.exceptionQps = exceptionQps;
}
public long getBlockQps() {
return blockQps;
}
public void setBlockQps(long blockQps) {
this.blockQps = blockQps;
}
public long getRt() {
return rt;
}
public void setRt(long rt) {
this.rt = rt;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
@Override
public String toString() {
return "MetricNode{" + "timestamp=" + timestamp + ", passQps=" + passQps + ", blockQps=" + blockQps
+ ", successQps=" + successQps + ", exceptionQps=" + exceptionQps + ", rt=" + rt
+ ", occupiedPassQps=" + occupiedPassQps + ", resource='"
+ resource + '\'' + '}';
}
/**
* To formatting string. All "|" in {@link #resource} will be replaced with
* "_", format is: <br/>
* <code>
* timestamp|resource|passQps|blockQps|successQps|exceptionQps|rt|occupiedPassQps
* </code>
*
* @return string format of this.
*/
public String toThinString() {
StringBuilder sb = new StringBuilder();
sb.append(timestamp).append("|");
String legalName = resource.replaceAll("\\|", "_");
sb.append(legalName).append("|");
sb.append(passQps).append("|");
sb.append(blockQps).append("|");
sb.append(successQps).append("|");
sb.append(exceptionQps).append("|");
sb.append(rt).append("|");
sb.append(occupiedPassQps);
return sb.toString();
}
/**
* To formatting string. All "|" in {@link MetricNode#resource} will be
* replaced with "_", format is: <br/>
* <code>
* timestamp|yyyy-MM-dd HH:mm:ss|resource|passQps|blockQps|successQps|exceptionQps|rt|occupiedPassQps\n
* </code>
*
* @return string format of this.
*/
public String toFatString() {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
StringBuilder sb = new StringBuilder(32);
sb.delete(0, sb.length());
sb.append(getTimestamp()).append("|");
sb.append(df.format(new Date(getTimestamp()))).append("|");
String legalName = getResource().replaceAll("\\|", "_");
sb.append(legalName).append("|");
sb.append(getPassQps()).append("|");
sb.append(getBlockQps()).append("|");
sb.append(getSuccessQps()).append("|");
sb.append(getExceptionQps()).append("|");
sb.append(getRt()).append("|");
sb.append(getOccupiedPassQps());
sb.append('\n');
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-common/src/main/java/com/webank/ai/fate/serving/common/flow/JvmInfoCounter.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/JvmInfoCounter.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.common.flow;
import com.google.common.collect.Lists;
import com.webank.ai.fate.serving.common.utils.JVMGCUtils;
import com.webank.ai.fate.serving.common.utils.JVMMemoryUtils;
import com.webank.ai.fate.serving.common.utils.JVMThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class JvmInfoCounter {
static boolean started = false;
static ScheduledThreadPoolExecutor executorService = new ScheduledThreadPoolExecutor(1);
private static LeapArray<JvmInfo> data = new JvmInfoLeapArray(10, 10000);
private static Logger logger = LoggerFactory.getLogger(JvmInfoCounter.class);
public static List<JvmInfo> getMemInfos() {
List<JvmInfo> result = Lists.newArrayList();
if (data.listAll() != null) {
data.listAll().forEach(window -> {
result.add(window.value());
});
}
return result;
}
public static synchronized void start() {
if (!started) {
executorService.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
long timestamp = TimeUtil.currentTimeMillis();
JvmInfo memInfo = data.currentWindow().value();
memInfo.heap = JVMMemoryUtils.getHeapMemoryUsage();
memInfo.old = JVMMemoryUtils.getOldGenMemoryUsage();
memInfo.eden = JVMMemoryUtils.getEdenSpaceMemoryUsage();
memInfo.nonHeap = JVMMemoryUtils.getNonHeapMemoryUsage();
memInfo.survivor = JVMMemoryUtils.getSurvivorSpaceMemoryUsage();
memInfo.yongGcCount = JVMGCUtils.getYoungGCCollectionCount();
memInfo.yongGcTime = JVMGCUtils.getYoungGCCollectionTime();
memInfo.fullGcCount = JVMGCUtils.getFullGCCollectionCount();
memInfo.fullGcTime = JVMGCUtils.getFullGCCollectionTime();
memInfo.threadCount = JVMThreadUtils.getThreadCount();
memInfo.timestamp = timestamp;
}
}, 0, 1000, TimeUnit.MILLISECONDS);
started = true;
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/JvmInfo.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/JvmInfo.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.common.flow;
import com.webank.ai.fate.serving.common.utils.JVMMemoryUtils;
public class JvmInfo {
long timestamp;
JVMMemoryUtils.JVMMemoryUsage heap;
JVMMemoryUtils.JVMMemoryUsage eden;
JVMMemoryUtils.JVMMemoryUsage old;
long yongGcCount;
long yongGcTime;
long fullGcCount;
long threadCount;
long fullGcTime;
JVMMemoryUtils.JVMMemoryUsage nonHeap;
JVMMemoryUtils.JVMMemoryUsage survivor;
public JvmInfo() {
}
public JvmInfo(long timestamp) {
this.timestamp = timestamp;
}
@Override
public String toString() {
return Long.toString(this.timestamp);
}
public long getThreadCount() {
return threadCount;
}
public void setThreadCount(long threadCount) {
this.threadCount = threadCount;
}
public long getYongGcCount() {
return yongGcCount;
}
public void setYongGcCount(long yongGcCount) {
this.yongGcCount = yongGcCount;
}
public long getYongGcTime() {
return yongGcTime;
}
public void setYongGcTime(long yongGcTime) {
this.yongGcTime = yongGcTime;
}
public long getFullGcCount() {
return fullGcCount;
}
public void setFullGcCount(long fullGcCount) {
this.fullGcCount = fullGcCount;
}
public long getFullGcTime() {
return fullGcTime;
}
public void setFullGcTime(long fullGcTime) {
this.fullGcTime = fullGcTime;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public JVMMemoryUtils.JVMMemoryUsage getHeap() {
return heap;
}
public void setHeap(JVMMemoryUtils.JVMMemoryUsage heap) {
this.heap = heap;
}
public JVMMemoryUtils.JVMMemoryUsage getEden() {
return eden;
}
public void setEden(JVMMemoryUtils.JVMMemoryUsage eden) {
this.eden = eden;
}
public JVMMemoryUtils.JVMMemoryUsage getOld() {
return old;
}
public void setOld(JVMMemoryUtils.JVMMemoryUsage old) {
this.old = old;
}
public JVMMemoryUtils.JVMMemoryUsage getNonHeap() {
return nonHeap;
}
public void setNonHeap(JVMMemoryUtils.JVMMemoryUsage nonHeap) {
this.nonHeap = nonHeap;
}
public JVMMemoryUtils.JVMMemoryUsage getSurvivor() {
return survivor;
}
public void setSurvivor(JVMMemoryUtils.JVMMemoryUsage survivor) {
this.survivor = survivor;
}
public void reset() {
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/MetricsReader.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/MetricsReader.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.common.flow;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Reads metrics data from log file.
*/
class MetricsReader {
/**
* Avoid OOM in any cases.
*/
private static final int MAX_LINES_RETURN = 100000;
private final Charset charset;
public MetricsReader(Charset charset) {
this.charset = charset;
}
/**
* @return if should continue read, return true, else false.
*/
boolean readMetricsInOneFileByEndTime(List<MetricNode> list, String fileName, long offset,
long beginTimeMs, long endTimeMs, String identity) throws Exception {
FileInputStream in = null;
long beginSecond = beginTimeMs / 1000;
long endSecond = endTimeMs / 1000;
BufferedReader reader = null;
try {
in = new FileInputStream(fileName);
in.getChannel().position(offset);
reader = new BufferedReader(new InputStreamReader(in, charset));
String line;
while ((line = reader.readLine()) != null) {
MetricNode node = MetricNode.fromFatString(line);
long currentSecond = node.getTimestamp() / 1000;
// currentSecond should >= beginSecond, otherwise a wrong metric file must occur
if (currentSecond < beginSecond) {
return false;
}
if (currentSecond <= endSecond) {
// read all
if (identity == null) {
list.add(node);
} else if (node.getResource().equals(identity)) {
list.add(node);
}
} else {
return false;
}
if (list.size() >= MAX_LINES_RETURN) {
return false;
}
}
} finally {
try {
if (in != null) {
in.close();
}
if(reader!=null){
reader.close();
}
}catch (Exception igore){
}
}
return true;
}
void readMetricsInOneFile(List<MetricNode> list, String fileName,
long offset, int recommendLines) throws Exception {
//if(list.size() >= recommendLines){
// return;
//}
long lastSecond = -1;
if (list.size() > 0) {
lastSecond = list.get(list.size() - 1).getTimestamp() / 1000;
}
FileInputStream in = null;
BufferedReader reader = null;
try {
in = new FileInputStream(fileName);
in.getChannel().position(offset);
reader = new BufferedReader(new InputStreamReader(in, charset));
String line;
while ((line = reader.readLine()) != null) {
MetricNode node = MetricNode.fromFatString(line);
long currentSecond = node.getTimestamp() / 1000;
if (list.size() < recommendLines) {
list.add(node);
} else if (currentSecond == lastSecond) {
list.add(node);
} else {
break;
}
lastSecond = currentSecond;
}
} finally {
try {
if (in != null) {
in.close();
}
if (reader != null) {
reader.close();
}
}catch(Exception igore){
}
}
}
/**
* When identity is null, all metric between the time intervalMs will be read, otherwise, only the specific
* identity will be read.
*/
List<MetricNode> readMetricsByEndTime(List<String> fileNames, int pos, long offset,
long beginTimeMs, long endTimeMs, String identity) throws Exception {
List<MetricNode> list = new ArrayList<MetricNode>(1024);
if (readMetricsInOneFileByEndTime(list, fileNames.get(pos++), offset, beginTimeMs, endTimeMs, identity)) {
while (pos < fileNames.size()
&& readMetricsInOneFileByEndTime(list, fileNames.get(pos++), 0, beginTimeMs, endTimeMs, identity)) {
}
}
return list;
}
List<MetricNode> readMetrics(List<String> fileNames, int pos,
long offset, int recommendLines) throws Exception {
List<MetricNode> list = new ArrayList<MetricNode>(recommendLines);
readMetricsInOneFile(list, fileNames.get(pos++), offset, recommendLines);
while (list.size() < recommendLines && pos < fileNames.size()) {
readMetricsInOneFile(list, fileNames.get(pos++), 0, recommendLines);
}
return list;
}
} | 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/FileMetricReport.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/FileMetricReport.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.common.flow;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
public class FileMetricReport implements MetricReport {
private static final long DEFAULT_FILE_SIZE = 1048576L;
MetricWriter metricWriter;
Logger logger = LoggerFactory.getLogger(FileMetricReport.class);
public FileMetricReport(String appName) {
this.metricWriter = new MetricWriter(appName, DEFAULT_FILE_SIZE);
}
public void rmAllFile() throws Exception {
metricWriter.removeAllFiles();
}
@Override
public void report(List<MetricNode> data) {
try {
metricWriter.write(TimeUtil.currentTimeMillis(), data);
} catch (Exception e) {
logger.error("metric writer error",e);
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/UnaryLeapArray.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/UnaryLeapArray.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.common.flow;
import java.util.concurrent.atomic.LongAdder;
public class UnaryLeapArray extends LeapArray<LongAdder> {
public UnaryLeapArray(int sampleCount, int intervalInMs) {
super(sampleCount, intervalInMs);
}
@Override
public LongAdder newEmptyBucket(long time) {
return new LongAdder();
}
@Override
protected WindowWrap<LongAdder> resetWindowTo(WindowWrap<LongAdder> windowWrap, long startTime) {
windowWrap.resetTo(startTime);
windowWrap.value().reset();
return windowWrap;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/flow/JvmInfoLeapArray.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/flow/JvmInfoLeapArray.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.common.flow;
public class JvmInfoLeapArray extends LeapArray<JvmInfo> {
public JvmInfoLeapArray(int sampleCount, int intervalInMs) {
super(sampleCount, intervalInMs);
}
@Override
public JvmInfo newEmptyBucket(long timeMillis) {
return new JvmInfo(timeMillis);
}
@Override
protected WindowWrap<JvmInfo> resetWindowTo(WindowWrap<JvmInfo> windowWrap, long startTime) {
windowWrap.resetTo(startTime);
windowWrap.value().reset();
return windowWrap;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/model/Model.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/model/Model.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.common.model;
import com.google.common.collect.Maps;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.apache.commons.lang3.SerializationUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class Model implements Comparable<Model>, Serializable, Cloneable {
private static final long serialVersionUID = 1L;
String resourceName;
private long timestamp;
private String tableName;
private String namespace;
/**
* guest or host
*/
private String role;
private String partId;
/**
* 对端模型信息,因为需要支持多方,所以设计成Map
*/
private Map<String, Model> federationModelMap = Maps.newHashMap();
/**
* 实例化好的模型处理类
*/
private transient ModelProcessor modelProcessor;
private List<String> serviceIds = new ArrayList<>();
private List<Map> rolePartyMapList;
private Double allowQps;
private String resourceAdress;
public String getResourceAdress() {
return resourceAdress;
}
public void setResourceAdress(String resourceAdress) {
this.resourceAdress = resourceAdress;
}
public Double getAllowQps() {
return allowQps;
}
public void setAllowQps(Double allowQps) {
this.allowQps = allowQps;
}
public Model() {
this.timestamp = System.currentTimeMillis();
}
public List<Map> getRolePartyMapList() {
return rolePartyMapList;
}
public void setRolePartyMapList(List<Map> rolePartyMapList) {
this.rolePartyMapList = rolePartyMapList;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getPartId() {
return partId;
}
public void setPartId(String partId) {
this.partId = partId;
}
public ModelProcessor getModelProcessor() {
return modelProcessor;
}
public void setModelProcessor(ModelProcessor modelProcessor) {
this.modelProcessor = modelProcessor;
}
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 Map<String, Model> getFederationModelMap() {
return federationModelMap;
}
public void setFederationModelMap(Map<String, Model> federationModelMap) {
this.federationModelMap = federationModelMap;
}
@Override
public int compareTo(Model o) {
if (this.timestamp > o.timestamp) {
return 1;
} else {
return -1;
}
}
@Override
public int hashCode() {
return (tableName + namespace).intern().hashCode();
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Model) {
Model model = (Model) obj;
if(this.namespace != null && this.tableName != null) {
return this.namespace.equals(model.namespace) && this.tableName.equals(model.tableName);
} else {
return false;
}
} else {
return false;
}
}
@Override
public Object clone() {
return SerializationUtils.clone(this);
}
@Override
public String toString() {
return JsonUtil.object2Json(this);
}
public String getResourceName() {
if (StringUtils.isBlank(resourceName)) {
resourceName = "M_" + tableName + "_" + namespace;
}
return resourceName;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/model/ComponentSimpleInfo.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/model/ComponentSimpleInfo.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.common.model;
public class ComponentSimpleInfo {
String componentName;
} | 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-common/src/main/java/com/webank/ai/fate/serving/common/model/LocalInferenceAware.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/model/LocalInferenceAware.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.common.model;
import com.webank.ai.fate.serving.core.bean.Context;
import java.util.List;
import java.util.Map;
public interface LocalInferenceAware {
public Map<String, Object> localInference(Context context, List<Map<String, Object>> input);
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/model/MergeInferenceAware.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/model/MergeInferenceAware.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.common.model;
import com.webank.ai.fate.serving.core.bean.Context;
import java.util.List;
import java.util.Map;
public interface MergeInferenceAware {
public Map<String, Object> mergeRemoteInference(Context context, List<Map<String, Object>> localData,
Map<String, Object> remoteData);
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/model/ModelProcessor.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/model/ModelProcessor.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.common.model;
import com.webank.ai.fate.serving.core.bean.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Future;
public interface ModelProcessor {
public BatchInferenceResult guestBatchInference(Context context, BatchInferenceRequest batchInferenceRequest, Map<String, Future> remoteFutureMap, long timeout);
public BatchInferenceResult hostBatchInference(Context context, BatchHostFederatedParams batchHostFederatedParams);
public ReturnResult guestInference(Context context, InferenceRequest inferenceRequest, Map<String, Future> remoteFutureMap, long timeout);
public ReturnResult hostInference(Context context, InferenceRequest inferenceRequest);
public Object getComponent(String name);
public void setModel(Model model);
// public ModelProcessor initComponentParmasMap();
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/ServiceAdaptor.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/ServiceAdaptor.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.common.rpc.core;
import com.webank.ai.fate.serving.core.bean.Context;
import java.util.List;
public interface ServiceAdaptor<req, rsp> {
public OutboundPackage<rsp> service(Context context, InboundPackage<req> inboundPackage);
public OutboundPackage<rsp> serviceFail(Context context, InboundPackage<req> data, List<Throwable> e);
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/FateServiceMethod.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/FateServiceMethod.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.common.rpc.core;
import java.lang.annotation.*;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface FateServiceMethod {
String[] name();
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/InterceptorChain.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/InterceptorChain.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.common.rpc.core;
/**
* @Description
* @Author
**/
public interface InterceptorChain<req, resp> extends Interceptor<req, resp> {
public void addInterceptor(Interceptor<req, resp> interceptor);
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/OutboundPackage.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/OutboundPackage.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.common.rpc.core;
/**
* @Description TODO
* @Author
**/
public class OutboundPackage<T> {
public boolean hitCache = false;
T data;
public boolean isHitCache() {
return hitCache;
}
public void setHitCache(boolean hitCache) {
this.hitCache = hitCache;
}
public T getData() {
return data;
}
public void setData(T 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/AbstractServiceAdaptor.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/AbstractServiceAdaptor.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.common.rpc.core;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.webank.ai.fate.serving.common.async.AsyncMessageEvent;
import com.webank.ai.fate.serving.common.bean.ServingServerContext;
import com.webank.ai.fate.serving.common.flow.FlowCounterManager;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.common.utils.DisruptorUtil;
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.ShowDownRejectException;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import io.grpc.stub.AbstractStub;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Description 默认的服务适配器
* @Author
**/
public abstract class AbstractServiceAdaptor<req, resp> implements ServiceAdaptor<req, resp> {
static public AtomicInteger requestInHandle = new AtomicInteger(0);
public static boolean isOpen = true;
protected FlowCounterManager flowCounterManager;
protected Logger flowLogger = LoggerFactory.getLogger("flow");
protected String serviceName;
Logger logger = LoggerFactory.getLogger(this.getClass().getName());
ServiceAdaptor serviceAdaptor;
InterceptorChain preChain = new DefaultInterceptorChain();
InterceptorChain postChain = new DefaultInterceptorChain();
private Map<String, Method> methodMap = Maps.newHashMap();
private AbstractStub serviceStub;
public AbstractServiceAdaptor() {
}
public FlowCounterManager getFlowCounterManager() {
return flowCounterManager;
}
public void setFlowCounterManager(FlowCounterManager flowCounterManager) {
this.flowCounterManager = flowCounterManager;
}
public Map<String, Method> getMethodMap() {
return methodMap;
}
public void setMethodMap(Map<String, Method> methodMap) {
this.methodMap = methodMap;
}
public void addPreProcessor(Interceptor interceptor) {
preChain.addInterceptor(interceptor);
}
public void addPostProcessor(Interceptor interceptor) {
postChain.addInterceptor(interceptor);
}
public ServiceAdaptor getServiceAdaptor() {
return serviceAdaptor;
}
public void setServiceAdaptor(ServiceAdaptor serviceAdaptor) {
this.serviceAdaptor = serviceAdaptor;
}
public AbstractStub getServiceStub() {
return serviceStub;
}
public void setServiceStub(AbstractStub serviceStub) {
this.serviceStub = serviceStub;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
protected abstract resp doService(Context context, InboundPackage<req> data, OutboundPackage<resp> outboundPackage);
/**
* @param context
* @param data
* @return
* @throws Exception
*/
@Override
public OutboundPackage<resp> service(Context context, InboundPackage<req> data) throws RuntimeException {
OutboundPackage<resp> outboundPackage = new OutboundPackage<resp>();
context.preProcess();
List<Throwable> exceptions = Lists.newArrayList();
context.setReturnCode(StatusCode.SUCCESS);
if (!isOpen) {
return this.serviceFailInner(context, data, new ShowDownRejectException());
}
if(data.getBody()!=null) {
context.putData(Dict.INPUT_DATA, data.getBody());
}
try {
requestInHandle.addAndGet(1);
resp result = null;
context.setServiceName(this.serviceName);
try {
preChain.doPreProcess(context, data, outboundPackage);
result = doService(context, data, outboundPackage);
if (logger.isDebugEnabled()) {
logger.debug("do service, router info: {}, service name: {}, result: {}", JsonUtil.object2Json(data.getRouterInfo()), serviceName, result);
}
} catch (Throwable e) {
exceptions.add(e);
logger.error("do service fail, cause by: {}", e.getMessage());
}
outboundPackage.setData(result);
postChain.doPostProcess(context, data, outboundPackage);
} catch (Throwable e) {
exceptions.add(e);
logger.error("service error",e);
} finally {
requestInHandle.decrementAndGet();
if (exceptions.size() != 0) {
try {
outboundPackage = this.serviceFail(context, data, exceptions);
AsyncMessageEvent messageEvent = new AsyncMessageEvent();
long end = System.currentTimeMillis();
messageEvent.setName(Dict.EVENT_ERROR);
messageEvent.setTimestamp(end);
messageEvent.setAction(context.getActionType());
messageEvent.setData(exceptions);
messageEvent.setContext(context);
DisruptorUtil.producer(messageEvent);
if (flowCounterManager != null) {
flowCounterManager.exception(context.getResourceName(), 1);
if (context instanceof ServingServerContext) {
ServingServerContext servingServerContext = (ServingServerContext) context;
Model model = servingServerContext.getModel();
if (model != null) {
flowCounterManager.exception(model.getResourceName(), 1);
}
}
}
} catch (Throwable e) {
logger.error("error ", e);
}
}
int returnCode = context.getReturnCode();
if (StatusCode.SUCCESS == returnCode) {
if (flowCounterManager != null) {
if (context instanceof ServingServerContext) {
Model model = ((ServingServerContext) context).getModel();
if (model != null) {
// batch exceptions
if (context.getServiceName().equalsIgnoreCase(Dict.SERVICENAME_BATCH_INFERENCE)) {
BatchInferenceResult batchInferenceResult = (BatchInferenceResult) outboundPackage.getData();
if (batchInferenceResult != null && batchInferenceResult.getBatchDataList() != null) {
int successCount = 0;
int failedConunt = 0;
for (BatchInferenceResult.SingleInferenceResult singleInferenceResult : batchInferenceResult.getBatchDataList()) {
if (singleInferenceResult.getRetcode() != StatusCode.SUCCESS) {
failedConunt++;
} else {
successCount++;
}
}
flowCounterManager.success(model.getResourceName(), successCount);
flowCounterManager.exception(model.getResourceName(), failedConunt);
}
} else {
flowCounterManager.success(model.getResourceName(), 1);
}
}
}
flowCounterManager.success(context.getResourceName(), 1);
}
}
if(outboundPackage.getData()!=null) {
context.putData(Dict.OUTPUT_DATA, outboundPackage.getData());
}
context.postProcess(data, outboundPackage);
printFlowLog(context);
}
return outboundPackage;
}
protected void printFlowLog(Context context) {
flowLogger.info("{}|{}|{}|{}|" +
"{}|{}|{}|{}|" +
"{}|{}|{}",
context.getSourceIp(), context.getCaseId(), context.getGuestAppId(),
context.getHostAppid(), context.getReturnCode(), context.getCostTime(),
context.getDownstreamCost(), serviceName, context.getRouterInfo() != null ? context.getRouterInfo() : "",
MetaInfo.PROPERTY_PRINT_INPUT_DATA?context.getData(Dict.INPUT_DATA):"",
MetaInfo.PROPERTY_PRINT_OUTPUT_DATA?context.getData(Dict.OUTPUT_DATA):"");
}
protected OutboundPackage<resp> serviceFailInner(Context context, InboundPackage<req> data, Throwable e) {
OutboundPackage<resp> outboundPackage = new OutboundPackage<resp>();
ExceptionInfo exceptionInfo = ErrorMessageUtil.handleExceptionExceptionInfo(e);
context.setReturnCode(exceptionInfo.getCode());
resp rsp = transformExceptionInfo(context, exceptionInfo);
outboundPackage.setData(rsp);
return outboundPackage;
}
@Override
public OutboundPackage<resp> serviceFail(Context context, InboundPackage<req> data, List<Throwable> errors) throws RuntimeException {
Throwable e = errors.get(0);
logger.error("service fail ", e);
return serviceFailInner(context, data, e);
}
abstract protected resp transformExceptionInfo(Context context, ExceptionInfo exceptionInfo);
/**
* 需要支持多方host
*
* @param context
* @param batchInferenceRequest
* @return
*/
protected BatchHostFederatedParams buildBatchHostFederatedParams(Context context, BatchInferenceRequest batchInferenceRequest, Model guestModel, Model hostModel) {
BatchHostFederatedParams batchHostFederatedParams = new BatchHostFederatedParams();
String seqNo = batchInferenceRequest.getSeqno();
batchHostFederatedParams.setGuestPartyId(guestModel.getPartId());
batchHostFederatedParams.setHostPartyId(hostModel.getPartId());
List<BatchHostFederatedParams.SingleInferenceData> sendToHostDataList = Lists.newArrayList();
List<BatchInferenceRequest.SingleInferenceData> guestDataList = batchInferenceRequest.getBatchDataList();
for (BatchInferenceRequest.SingleInferenceData singleInferenceData : guestDataList) {
BatchHostFederatedParams.SingleInferenceData singleBatchHostFederatedParam = new BatchHostFederatedParams.SingleInferenceData();
singleBatchHostFederatedParam.setSendToRemoteFeatureData(singleInferenceData.getSendToRemoteFeatureData());
singleBatchHostFederatedParam.setIndex(singleInferenceData.getIndex());
sendToHostDataList.add(singleBatchHostFederatedParam);
}
batchHostFederatedParams.setBatchDataList(sendToHostDataList);
batchHostFederatedParams.setHostTableName(hostModel.getTableName());
batchHostFederatedParams.setHostNamespace(hostModel.getNamespace());
batchHostFederatedParams.setCaseId(batchInferenceRequest.getCaseId());
return batchHostFederatedParams;
}
public static class ExceptionInfo {
int code;
String message;
public ExceptionInfo() {
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message != null ? message : "";
}
public void setMessage(String message) {
this.message = 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/FederatedRpcInvoker.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/FederatedRpcInvoker.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.common.rpc.core;
import com.google.common.collect.Lists;
import com.google.common.util.concurrent.ListenableFuture;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.core.bean.BatchInferenceResult;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import java.util.List;
import java.util.Map;
public interface FederatedRpcInvoker<T> {
public ListenableFuture<BatchInferenceResult> batchInferenceRpcWithCache(Context context,
RpcDataWraper rpcDataWraper, boolean useCache);
public T sync(Context context, RpcDataWraper rpcDataWraper, long timeout);
public ListenableFuture<T> async(Context context, RpcDataWraper rpcDataWraper);
public ListenableFuture<ReturnResult> singleInferenceRpcWithCache(Context context,
FederatedRpcInvoker.RpcDataWraper rpcDataWraper, boolean useCache);
public class RpcDataWraper {
Object data;
Model guestModel;
Model hostModel;
String remoteMethodName;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Model getGuestModel() {
return guestModel;
}
public void setGuestModel(Model guestModel) {
this.guestModel = guestModel;
}
public Model getHostModel() {
if (hostModel != null) {
return hostModel;
} else if (this.guestModel != null) {
Map<String, Model> modelMap = this.getGuestModel().getFederationModelMap();
List<String> keys = Lists.newArrayList(modelMap.keySet());
return modelMap.get(keys.get(0));
}
return null;
}
public void setHostModel(Model hostModel) {
this.hostModel = hostModel;
}
public String getRemoteMethodName() {
return remoteMethodName;
}
public void setRemoteMethodName(String remoteMethodName) {
this.remoteMethodName = remoteMethodName;
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/DefaultInterceptorChain.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/DefaultInterceptorChain.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.common.rpc.core;
import com.google.common.collect.Lists;
import com.webank.ai.fate.serving.core.bean.Context;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* @Description TODO
* @Author
**/
public class DefaultInterceptorChain<req, resp> implements InterceptorChain<req, resp> {
Logger logger = LoggerFactory.getLogger(DefaultInterceptorChain.class);
List<Interceptor<req, resp>> chain = Lists.newArrayList();
@Override
public void addInterceptor(Interceptor<req, resp> interceptor) {
chain.add(interceptor);
}
/**
* 前处理因为多数是校验逻辑 , 在这里抛出异常,将中断流程
*
* @param context
* @param inboundPackage
* @param outboundPackage
* @throws Exception
*/
@Override
public void doPreProcess(Context context, InboundPackage<req> inboundPackage, OutboundPackage<resp> outboundPackage) throws Exception {
for (Interceptor<req, resp> interceptor : chain) {
interceptor.doPreProcess(context, inboundPackage, outboundPackage);
}
}
/**
* 后处理即使抛出异常,也将执行完所有
*
* @param context
* @param inboundPackage
* @param outboundPackage
* @throws Exception
*/
@Override
public void doPostProcess(Context context, InboundPackage<req> inboundPackage, OutboundPackage<resp> outboundPackage) throws Exception {
for (Interceptor<req, resp> interceptor : chain) {
try {
interceptor.doPostProcess(context, inboundPackage, outboundPackage);
} catch (Throwable e) {
logger.error("doPostProcess error", e);
}
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/FateService.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/FateService.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.common.rpc.core;
import java.lang.annotation.*;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface FateService {
String name();
String[] preChain() default {};
String[] postChain() default {};
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/ServiceRegister.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/ServiceRegister.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.common.rpc.core;
/**
* @Description TODO
* @Author
**/
public interface ServiceRegister {
public ServiceAdaptor getServiceAdaptor(String name);
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/InboundPackage.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/InboundPackage.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.common.rpc.core;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
import io.grpc.ManagedChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
/**
* @Description TODO
* @Author
**/
public class InboundPackage<T> {
static Logger logger = LoggerFactory.getLogger(InboundPackage.class);
ManagedChannel managedChannel;
RouterInfo routerInfo;
String source;
Map head;
/*public HttpServletRequest getHttpServletRequest() {
return httpServletRequest;
}
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
HttpServletRequest httpServletRequest;*/
T body;
public ManagedChannel getManagedChannel() {
return managedChannel;
}
public void setManagedChannel(ManagedChannel managedChannel) {
this.managedChannel = managedChannel;
}
public RouterInfo getRouterInfo() {
return routerInfo;
}
public void setRouterInfo(RouterInfo routerInfo) {
this.routerInfo = routerInfo;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public Map getHead() {
return head;
}
public void setHead(Map head) {
this.head = head;
}
public T getBody() {
return body;
}
public void setBody(T body) {
this.body = body;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/ErrorMessageUtil.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/ErrorMessageUtil.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.common.rpc.core;
import com.webank.ai.fate.serving.core.bean.Dict;
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.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* @Description TODO
* @Author
**/
public class ErrorMessageUtil {
static Logger logger = LoggerFactory.getLogger(ErrorMessageUtil.class);
public static ReturnResult handleExceptionToReturnResult(Throwable e) {
ReturnResult returnResult = new ReturnResult();
if (e instanceof BaseException) {
BaseException baseException = (BaseException) e;
returnResult.setRetcode(baseException.getRetcode());
returnResult.setRetmsg(e.getMessage());
} else {
returnResult.setRetcode(StatusCode.SYSTEM_ERROR);
}
return returnResult;
}
public static String buildRemoteRpcErrorMsg(int code, String msg) {
return new StringBuilder().append("host return code ").append(code)
.append(" host msg :").append(msg).toString();
}
public static int transformRemoteErrorCode(int code) {
return Integer.valueOf(new StringBuilder().append("2").append(code).toString());
}
public static int getLocalExceptionCode(Exception e) {
int retcode = StatusCode.SYSTEM_ERROR;
if (e instanceof BaseException) {
retcode = ((BaseException) e).getRetcode();
}
return retcode;
}
public static AbstractServiceAdaptor.ExceptionInfo handleExceptionExceptionInfo(Throwable e) {
AbstractServiceAdaptor.ExceptionInfo exceptionInfo = new AbstractServiceAdaptor.ExceptionInfo();
if (e instanceof BaseException) {
BaseException baseException = (BaseException) e;
exceptionInfo.setCode(baseException.getRetcode());
exceptionInfo.setMessage(baseException.getMessage());
} else {
exceptionInfo.setCode(StatusCode.SYSTEM_ERROR);
exceptionInfo.setMessage(e.getMessage());
}
return exceptionInfo;
}
public static Map handleExceptionToMap(Throwable e) {
Map returnResult = new HashMap();
if (e instanceof BaseException) {
BaseException baseException = (BaseException) e;
returnResult.put(Dict.RET_CODE, baseException.getRetcode());
returnResult.put(Dict.MESSAGE, baseException.getMessage());
} else {
returnResult.put(Dict.RET_CODE, StatusCode.SYSTEM_ERROR);
}
return returnResult;
}
public static Map handleException(Map result, Throwable e) {
if (e instanceof IllegalArgumentException) {
result.put(Dict.CODE, StatusCode.PARAM_ERROR);
result.put(Dict.MESSAGE, "PARAM_ERROR");
} else if (e instanceof NoRouterInfoException) {
result.put(Dict.CODE, StatusCode.GUEST_ROUTER_ERROR);
result.put(Dict.MESSAGE, "ROUTER_ERROR");
} else if (e instanceof SysException) {
result.put(Dict.CODE, StatusCode.SYSTEM_ERROR);
result.put(Dict.MESSAGE, "SYSTEM_ERROR");
} else if (e instanceof OverLoadException) {
result.put(Dict.CODE, StatusCode.OVER_LOAD_ERROR);
result.put(Dict.MESSAGE, "OVER_LOAD");
} else if (e instanceof InvalidRoleInfoException) {
result.put(Dict.CODE, StatusCode.INVALID_ROLE_ERROR);
result.put(Dict.MESSAGE, "ROLE_ERROR");
} else if (e instanceof ShowDownRejectException) {
result.put(Dict.CODE, StatusCode.SHUTDOWN_ERROR);
result.put(Dict.MESSAGE, "SHUTDOWN_ERROR");
} else if (e instanceof NoResultException) {
logger.error("NET_ERROR ", e);
result.put(Dict.CODE, StatusCode.NET_ERROR);
result.put(Dict.MESSAGE, "NET_ERROR");
} else {
logger.error("SYSTEM_ERROR ", e);
result.put(Dict.CODE, StatusCode.SYSTEM_ERROR);
result.put(Dict.MESSAGE, "SYSTEM_ERROR");
}
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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/Interceptor.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/Interceptor.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.common.rpc.core;
import com.webank.ai.fate.serving.core.bean.Context;
public interface Interceptor<req, resp> {
default public void doPreProcess(Context context, InboundPackage<req> inboundPackage, OutboundPackage<resp> outboundPackage) throws Exception {
}
default public void doPostProcess(Context context, InboundPackage<req> inboundPackage, OutboundPackage<resp> outboundPackage) 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-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/RouterInterface.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/rpc/core/RouterInterface.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.common.rpc.core;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
public interface RouterInterface extends Interceptor {
RouterInfo route(Context context, InboundPackage inboundPackage);
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/async/AsyncMessageEvent.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/async/AsyncMessageEvent.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.common.async;
import com.lmax.disruptor.EventFactory;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
public class AsyncMessageEvent<T> implements Cloneable {
public static final EventFactory<AsyncMessageEvent> FACTORY = () -> new AsyncMessageEvent();
/**
* event name, e.g. interface name, use to @Subscribe value
*/
private String name;
private String action;
private T data;
private String ip;
private long timestamp;
private Context context;
public Context getContext() {
return context;
}
public void setContext(Context context) {
this.context = context;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
void clear() {
this.name = null;
this.action = null;
this.data = null;
this.ip = null;
this.timestamp = 0;
}
@Override
public String toString() {
return JsonUtil.object2Json(this);
}
@Override
public AsyncMessageEvent clone() {
AsyncMessageEvent stu = null;
try {
stu = (AsyncMessageEvent) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return stu;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/async/DefaultAsyncMessageProcessor.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/async/DefaultAsyncMessageProcessor.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.common.async;
import com.webank.ai.fate.serving.core.bean.Dict;
public class DefaultAsyncMessageProcessor extends AbstractAsyncMessageProcessor {
// private static Logger logger = LoggerFactory.getLogger(DefaultAsyncMessageProcessor.class);
@Subscribe(Dict.EVENT_INFERENCE)
public void processInferenceEvent(AsyncMessageEvent event) {
// logger.info("Process inference event..");
}
@Subscribe(Dict.EVENT_UNARYCALL)
public void processUnaryCallEvent(AsyncMessageEvent event) {
// logger.info("Process unaryCall event..");
}
@Subscribe(Dict.EVENT_ERROR)
public void processErrorEvent(AsyncMessageEvent event) {
// logger.info("Process error event..");
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/async/MockAlertInfoUploader.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/async/MockAlertInfoUploader.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.common.async;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class MockAlertInfoUploader implements AlertInfoUploader {
Logger logger = LoggerFactory.getLogger(MockAlertInfoUploader.class);
@Override
public void upload(AsyncMessageEvent event) {
logger.warn("alert info {}", event);
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/async/ClearingEventHandler.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/async/ClearingEventHandler.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.common.async;
import com.lmax.disruptor.EventHandler;
public class ClearingEventHandler<T> implements EventHandler<AsyncMessageEvent<T>> {
@Override
public void onEvent(AsyncMessageEvent<T> event, long sequence, boolean endOfBatch) throws Exception {
// Failing to call clear here will result in the
// object associated with the event to live until
// it is overwritten once the ring buffer has wrapped
// around to the beginning.
event.clear();
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/async/AsyncMessageEventProducer.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/async/AsyncMessageEventProducer.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.common.async;
import com.lmax.disruptor.EventTranslatorVararg;
import com.lmax.disruptor.RingBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Producer
*/
public class AsyncMessageEventProducer {
public static final EventTranslatorVararg<AsyncMessageEvent> TRANSLATOR =
(event, sequence, args) -> {
if (args[0] instanceof AsyncMessageEvent) {
AsyncMessageEvent argEvent = (AsyncMessageEvent) args[0];
event.setName(argEvent.getName());
event.setAction(argEvent.getAction());
event.setData(argEvent.getData());
event.setTimestamp(argEvent.getTimestamp());
event.setContext(argEvent.getContext());
if (event.getTimestamp() == 0) {
event.setTimestamp(System.currentTimeMillis());
}
}
event.setTimestamp(System.currentTimeMillis());
};
private static Logger logger = LoggerFactory.getLogger(AsyncMessageEventProducer.class);
private final RingBuffer<AsyncMessageEvent> ringBuffer;
public AsyncMessageEventProducer(RingBuffer<AsyncMessageEvent> ringBuffer) {
this.ringBuffer = ringBuffer;
}
public void publishEvent(Object... args) {
if (args != null && args.length > 0) {
ringBuffer.tryPublishEvent(TRANSLATOR, args);
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/async/AlertInfoUploader.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/async/AlertInfoUploader.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.common.async;
public interface AlertInfoUploader {
public void upload(AsyncMessageEvent event);
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/async/AsyncSubscribeRegister.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/async/AsyncSubscribeRegister.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.common.async;
import com.google.common.collect.Maps;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class AsyncSubscribeRegister {
public static final Map<String, Set<Method>> SUBSCRIBE_METHOD_MAP = new HashMap<>();
public static final Map<Method, Object> METHOD_INSTANCE_MAP = Maps.newHashMap();
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/async/AsyncMessageEventHandler.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/async/AsyncMessageEventHandler.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.common.async;
import com.lmax.disruptor.EventHandler;
import com.webank.ai.fate.serving.core.exceptions.AsyncMessageException;
import com.webank.ai.fate.serving.core.utils.ThreadPoolUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.concurrent.ExecutorService;
/**
* Consumer
*/
public class AsyncMessageEventHandler implements EventHandler<AsyncMessageEvent> {
private static Logger logger = LoggerFactory.getLogger(AsyncMessageEventHandler.class);
ExecutorService executorService = null;
public AsyncMessageEventHandler() {
executorService = ThreadPoolUtil.newThreadPoolExecutor();
}
@Override
public void onEvent(AsyncMessageEvent event, long sequence, boolean endOfBatch) throws Exception {
String eventName = event.getName();
logger.info("Async event: {}", eventName);
if (StringUtils.isBlank(eventName)) {
throw new AsyncMessageException("eventName is blank");
}
Set<Method> methods = AsyncSubscribeRegister.SUBSCRIBE_METHOD_MAP.get(eventName);
if (methods == null || methods.size() == 0) {
logger.error("event {} not subscribe {}", eventName, AsyncSubscribeRegister.SUBSCRIBE_METHOD_MAP);
throw new AsyncMessageException(eventName + " event not subscribe {}");
}
AsyncMessageEvent another = event.clone();
for (Method method : methods) {
executorService.submit(() -> {
try {
Object object = AsyncSubscribeRegister.METHOD_INSTANCE_MAP.get(method);
method.invoke(object, another);
} catch (Exception e) {
logger.error("invoke event processor, {}", e.getMessage());
e.printStackTrace();
}
});
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/async/DisruptorExceptionHandler.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/async/DisruptorExceptionHandler.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.common.async;
import com.lmax.disruptor.ExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DisruptorExceptionHandler implements ExceptionHandler {
private static Logger logger = LoggerFactory.getLogger(DisruptorExceptionHandler.class);
@Override
public void handleEventException(Throwable ex, long sequence, Object event) {
logger.error("Disruptor event exception, {}", ex.getMessage());
ex.printStackTrace();
}
@Override
public void handleOnStartException(Throwable ex) {
logger.error("Disruptor start exception, {}", ex.getMessage());
ex.printStackTrace();
}
@Override
public void handleOnShutdownException(Throwable ex) {
logger.error("Disruptor shutdown exception, {}", ex.getMessage());
ex.printStackTrace();
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/async/Subscribe.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/async/Subscribe.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.common.async;
import java.lang.annotation.*;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface Subscribe {
String value() default "";
String name() default "";
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/async/AbstractAsyncMessageProcessor.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/async/AbstractAsyncMessageProcessor.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.common.async;
public abstract class AbstractAsyncMessageProcessor {
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/JVMGCUtils.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/JVMGCUtils.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.common.utils;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
public class JVMGCUtils {
static private GarbageCollectorMXBean youngGC;
static private GarbageCollectorMXBean fullGC;
static {
List<GarbageCollectorMXBean> gcMXBeanList = ManagementFactory.getGarbageCollectorMXBeans();
for (final GarbageCollectorMXBean gcMXBean : gcMXBeanList) {
String gcName = gcMXBean.getName();
if (gcName == null) {
continue;
}
//G1 Old Generation
//Garbage collection optimized for short pausetimes Old Collector
//Garbage collection optimized for throughput Old Collector
//Garbage collection optimized for deterministic pausetimes Old Collector
//G1 Young Generation
//Garbage collection optimized for short pausetimes Young Collector
//Garbage collection optimized for throughput Young Collector
//Garbage collection optimized for deterministic pausetimes Young Collector
if (fullGC == null &&
(gcName.endsWith("Old Collector")
|| "ConcurrentMarkSweep".equals(gcName)
|| "MarkSweepCompact".equals(gcName)
|| "PS MarkSweep".equals(gcName))
) {
fullGC = gcMXBean;
} else if (youngGC == null &&
(gcName.endsWith("Young Generation")
|| "ParNew".equals(gcName)
|| "Copy".equals(gcName)
|| "PS Scavenge".equals(gcName))
) {
youngGC = gcMXBean;
}
}
}//static
//YGC名称
static public String getYoungGCName() {
return youngGC == null ? "" : youngGC.getName();
}
//YGC总次数
static public long getYoungGCCollectionCount() {
return youngGC == null ? 0 : youngGC.getCollectionCount();
}
//YGC总时间
static public long getYoungGCCollectionTime() {
return youngGC == null ? 0 : youngGC.getCollectionTime();
}
//FGC名称
static public String getFullGCName() {
return fullGC == null ? "" : fullGC.getName();
}
//FGC总次数
static public long getFullGCCollectionCount() {
return fullGC == null ? 0 : fullGC.getCollectionCount();
}
//FGC总次数
static public long getFullGCCollectionTime() {
return fullGC == null ? 0 : fullGC.getCollectionTime();
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/HttpAdapterClientPool.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/HttpAdapterClientPool.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.common.utils;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.HttpAdapterResponse;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.utils.JsonUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.Map;
public class HttpAdapterClientPool {
private static final Logger logger = LoggerFactory.getLogger(HttpAdapterClientPool.class);
// private static CloseableHttpClient httpClient;
public static HttpAdapterResponse doPost(String url, Map<String, Object> bodyMap) {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(MetaInfo.PROPERTY_HTTP_CONNECT_REQUEST_TIMEOUT)
.setConnectTimeout(MetaInfo.PROPERTY_HTTP_CONNECT_TIMEOUT)
.setSocketTimeout(MetaInfo.PROPERTY_HTTP_SOCKET_TIMEOUT).build();
httpPost.addHeader(Dict.CONTENT_TYPE, Dict.CONTENT_TYPE_JSON_UTF8);
httpPost.setConfig(requestConfig);
String bodyJson = JsonUtil.object2Json(bodyMap);
StringEntity stringEntity = new StringEntity(bodyJson, Dict.CHARSET_UTF8);
stringEntity.setContentEncoding(Dict.CHARSET_UTF8);
httpPost.setEntity(stringEntity);
logger.info(" postUrl = {"+url+"} body = {"+bodyJson+"} ");
return getResponse(httpPost);
}
private static HttpAdapterResponse getResponse(HttpRequestBase request) {
CloseableHttpResponse response = null;
try {
response = HttpClientPool.getConnection().execute(request,
HttpClientContext.create());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, Dict.CHARSET_UTF8);
return JsonUtil.json2Object(result, HttpAdapterResponse.class);
} catch (IOException ex) {
logger.error("get http response failed:", ex);
return null;
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException ex) {
logger.error("get http response failed:", ex);
}
}
}
public static HttpAdapterResponse doPostgetCodeByHeader(String url, Map<String, Object> bodyMap) {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(MetaInfo.PROPERTY_HTTP_CONNECT_REQUEST_TIMEOUT)
.setConnectTimeout(MetaInfo.PROPERTY_HTTP_CONNECT_TIMEOUT)
.setSocketTimeout(MetaInfo.PROPERTY_HTTP_SOCKET_TIMEOUT).build();
httpPost.addHeader(Dict.CONTENT_TYPE, Dict.CONTENT_TYPE_JSON_UTF8);
httpPost.setConfig(requestConfig);
String bodyJson = JsonUtil.object2Json(bodyMap);
StringEntity stringEntity = new StringEntity(bodyJson, Dict.CHARSET_UTF8);
stringEntity.setContentEncoding(Dict.CHARSET_UTF8);
httpPost.setEntity(stringEntity);
logger.info(" postUrl = {"+url+"} body = {"+bodyJson+"} ");
return getResponseByHeader(httpPost);
}
private static HttpAdapterResponse getResponseByHeader(HttpRequestBase request) {
CloseableHttpResponse response = null;
try {
response = HttpClientPool.getConnection().execute(request,
HttpClientContext.create());
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity, Dict.CHARSET_UTF8);
int statusCode = response.getStatusLine().getStatusCode();
HttpAdapterResponse result = new HttpAdapterResponse();
result.setCode(statusCode);
result.setData(JsonUtil.json2Object(data, Map.class));
return result;
} catch (IOException ex) {
logger.error("get http response failed:", ex);
return null;
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException ex) {
logger.error("get http response failed:", ex);
}
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/JVMThreadUtils.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/JVMThreadUtils.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.common.utils;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
/**
* 类描述:JVM 线程信息工具类
*
**/
public class JVMThreadUtils {
static private ThreadMXBean threadMXBean;
static {
threadMXBean = ManagementFactory.getThreadMXBean();
}
/**
* Daemon线程总量
* @return
*/
static public int getDaemonThreadCount() {
return threadMXBean.getDaemonThreadCount();
}
/**
* 当前线程总量
* @return
*/
static public int getThreadCount() {
return threadMXBean.getThreadCount();
}
/**
* 获取线程数量峰值(从启动或resetPeakThreadCount()方法重置开始统计)
* @return
*/
static public int getPeakThreadCount() {
return threadMXBean.getPeakThreadCount();
}
/**
* 获取线程数量峰值(从启动或resetPeakThreadCount()方法重置开始统计),并重置
* @return
* @Throws java.lang.SecurityException - if a security manager exists and the caller does not have ManagementPermission("control").
*/
static public int getAndResetPeakThreadCount() {
int count = threadMXBean.getPeakThreadCount();
resetPeakThreadCount();
return count;
}
/**
* 重置线程数量峰值
*
* @Throws java.lang.SecurityException - if a security manager exists and the caller does not have ManagementPermission("control").
*/
static public void resetPeakThreadCount() {
threadMXBean.resetPeakThreadCount();
}
/**
* 死锁线程总量
* @return
* @Throws IllegalStateException 没有权限或JVM不支持的操作
*/
static public int getDeadLockedThreadCount() {
try {
long[] deadLockedThreadIds = threadMXBean.findDeadlockedThreads();
if (deadLockedThreadIds == null) {
return 0;
}
return deadLockedThreadIds.length;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/HttpClientPool.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/HttpClientPool.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.common.utils;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.MetaInfo;
import com.webank.ai.fate.serving.core.utils.ObjectTransform;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class HttpClientPool {
private static final Logger logger = LoggerFactory.getLogger(HttpClientPool.class);
private static PoolingHttpClientConnectionManager poolConnManager;
private static RequestConfig requestConfig;
private static CloseableHttpClient httpClient;
private static void config(HttpRequestBase httpRequestBase, Map<String, String> headers) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(MetaInfo.HTTP_CLIENT_CONFIG_CONN_REQ_TIME_OUT)
.setConnectTimeout(MetaInfo.HTTP_CLIENT_CONFIG_CONN_TIME_OUT)
.setSocketTimeout(MetaInfo.HTTP_CLIENT_CONFIG_SOCK_TIME_OUT).build();
httpRequestBase.addHeader(Dict.CONTENT_TYPE, Dict.CONTENT_TYPE_JSON_UTF8);
if (headers != null) {
headers.forEach(httpRequestBase::addHeader);
}
httpRequestBase.setConfig(requestConfig);
}
public static void initPool() {
try {
SSLContextBuilder builder = new SSLContextBuilder();
builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
Dict.HTTP, PlainConnectionSocketFactory.getSocketFactory()).register(
Dict.HTTPS, sslsf).build();
poolConnManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
poolConnManager.setMaxTotal(MetaInfo.HTTP_CLIENT_INIT_POOL_MAX_TOTAL);
poolConnManager.setDefaultMaxPerRoute(MetaInfo.HTTP_CLIENT_INIT_POOL_DEF_MAX_PER_ROUTE);
int socketTimeout = MetaInfo.HTTP_CLIENT_INIT_POOL_SOCK_TIME_OUT;
int connectTimeout = MetaInfo.HTTP_CLIENT_INIT_POOL_CONN_TIME_OUT;
int connectionRequestTimeout = MetaInfo.HTTP_CLIENT_INIT_POOL_CONN_REQ_TIME_OUT;
requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
connectTimeout).build();
httpClient = createConnection();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
logger.error("init http client pool failed:", ex);
}
}
public static CloseableHttpClient getConnection() {
return httpClient;
}
public static CloseableHttpClient createConnection() {
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(poolConnManager)
.setDefaultRequestConfig(requestConfig)
.evictExpiredConnections()
.evictIdleConnections(5, TimeUnit.SECONDS)
.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
.build();
return httpClient;
}
public static String post(String url, Map<String, Object> requestData) {
return sendPost(url, requestData, null);
}
public static String post(String url, Map<String, Object> requestData, Map<String, String> headers) {
return sendPost(url, requestData, headers);
}
public static String sendPost(String url, Map<String, Object> requestData, Map<String, String> headers) {
HttpPost httpPost = new HttpPost(url);
config(httpPost, headers);
StringEntity stringEntity = new StringEntity(ObjectTransform.bean2Json(requestData), Dict.CHARSET_UTF8);
stringEntity.setContentEncoding(Dict.CHARSET_UTF8);
httpPost.setEntity(stringEntity);
return getResponse(httpPost);
}
public static String sendPost(String url, String requestData, Map<String, String> headers) {
HttpPost httpPost = new HttpPost(url);
config(httpPost, headers);
StringEntity stringEntity = new StringEntity(requestData, Dict.CHARSET_UTF8);
stringEntity.setContentEncoding(Dict.CHARSET_UTF8);
httpPost.setEntity(stringEntity);
return getResponse(httpPost);
}
public static String get(String url, Map<String, String> headers) {
return sendGet(url, headers);
}
public static String get(String url) {
return sendGet(url, null);
}
public static String sendGet(String url, Map<String, String> headers) {
HttpGet httpGet = new HttpGet(url);
config(httpGet, headers);
return getResponse(httpGet);
}
private static String getResponse(HttpRequestBase request) {
CloseableHttpResponse response = null;
try {
response = httpClient.execute(request,
HttpClientContext.create());
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity, Dict.CHARSET_UTF8);
EntityUtils.consume(entity);
return result;
} catch (IOException ex) {
logger.error("get http response failed:", ex);
return null;
} finally {
try {
if (response != null) {
response.close();
}
} catch (IOException ex) {
logger.error("get http response failed:", ex);
}
}
}
public static String transferPost(String url, Map<String, Object> requestData) {
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(MetaInfo.HTTP_CLIENT_TRAN_CONN_REQ_TIME_OUT)
.setConnectTimeout(MetaInfo.HTTP_CLIENT_TRAN_CONN_TIME_OUT)
.setSocketTimeout(MetaInfo.HTTP_CLIENT_TRAN_SOCK_TIME_OUT).build();
httpPost.addHeader(Dict.CONTENT_TYPE, Dict.CONTENT_TYPE_JSON_UTF8);
httpPost.setConfig(requestConfig);
StringEntity stringEntity = new StringEntity(ObjectTransform.bean2Json(requestData), Dict.CHARSET_UTF8);
stringEntity.setContentEncoding(Dict.CHARSET_UTF8);
httpPost.setEntity(stringEntity);
return getResponse(httpPost);
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/TelnetUtil.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/TelnetUtil.java | package com.webank.ai.fate.serving.common.utils;
import org.apache.commons.net.telnet.TelnetClient;
public class TelnetUtil {
public static boolean tryTelnet(String host ,int port){
TelnetClient telnetClient = new TelnetClient("vt200");
telnetClient.setDefaultTimeout(5000);
boolean isConnected = false;
try {
telnetClient.connect(host, port);
isConnected = true;
telnetClient.disconnect();
} catch (Exception e) {
throw new RuntimeException(e);
}
return isConnected;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/ThreadUtils.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/ThreadUtils.java | package com.webank.ai.fate.serving.common.utils;
import com.webank.ai.fate.serving.common.bean.ThreadVO;
import java.util.ArrayList;
import java.util.List;
/**
* @author hcy
*/
public class ThreadUtils {
private static ThreadGroup getRoot() {
ThreadGroup group = Thread.currentThread().getThreadGroup();
ThreadGroup parent;
while ((parent = group.getParent()) != null) {
group = parent;
}
return group;
}
public static List<ThreadVO> getThreads() {
ThreadGroup root = getRoot();
Thread[] threads = new Thread[root.activeCount()];
while (root.enumerate(threads, true) == threads.length) {
threads = new Thread[threads.length * 2];
}
List<ThreadVO> list = new ArrayList<ThreadVO>(threads.length);
for (Thread thread : threads) {
if (thread != null) {
ThreadVO threadVO = createThreadVO(thread);
list.add(threadVO);
}
}
return list;
}
private static ThreadVO createThreadVO(Thread thread) {
ThreadGroup group = thread.getThreadGroup();
ThreadVO threadVO = new ThreadVO();
threadVO.setId(thread.getId());
threadVO.setName(thread.getName());
threadVO.setGroup(group == null ? "" : group.getName());
threadVO.setPriority(thread.getPriority());
threadVO.setState(thread.getState());
threadVO.setInterrupted(thread.isInterrupted());
threadVO.setDaemon(thread.isDaemon());
return threadVO;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/TransferUtils.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/TransferUtils.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.common.utils;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.dataformat.yaml.YAMLParser;
import java.io.*;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
public class TransferUtils {
private static final String ENCODING = "utf-8";
public static List<String> yml2Properties(String path) {
final String DOT = ".";
List<String> lines = new LinkedList<>();
try {
YAMLFactory yamlFactory = new YAMLFactory();
YAMLParser parser = yamlFactory.createParser(
new InputStreamReader(new FileInputStream(path), Charset.forName(ENCODING)));
String key = "";
String value = null;
JsonToken token = parser.nextToken();
while (token != null) {
if (JsonToken.START_OBJECT.equals(token)) {
// do nothing
} else if (JsonToken.FIELD_NAME.equals(token)) {
if (key.length() > 0) {
key = key + DOT;
}
key = key + parser.getCurrentName();
token = parser.nextToken();
if (JsonToken.START_OBJECT.equals(token)) {
continue;
}
value = parser.getText();
lines.add(key + "=" + value);
int dotOffset = key.lastIndexOf(DOT);
if (dotOffset > 0) {
key = key.substring(0, dotOffset);
}
value = null;
} else if (JsonToken.END_OBJECT.equals(token)) {
int dotOffset = key.lastIndexOf(DOT);
if (dotOffset > 0) {
key = key.substring(0, dotOffset);
} else {
key = "";
// lines.add("");
}
}
token = parser.nextToken();
}
parser.close();
return lines;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void properties2Yaml(String path) {
JsonParser parser = null;
JavaPropsFactory factory = new JavaPropsFactory();
try {
parser = factory.createParser(
new InputStreamReader(new FileInputStream(path), Charset.forName(ENCODING)));
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
YAMLFactory yamlFactory = new YAMLFactory();
YAMLGenerator generator = yamlFactory.createGenerator(
new OutputStreamWriter(new FileOutputStream(path), Charset.forName(ENCODING)));
try {
JsonToken token = parser.nextToken();
while (token != null) {
if (JsonToken.START_OBJECT.equals(token)) {
generator.writeStartObject();
} else if (JsonToken.FIELD_NAME.equals(token)) {
generator.writeFieldName(parser.getCurrentName());
} else if (JsonToken.VALUE_STRING.equals(token)) {
generator.writeString(parser.getText());
} else if (JsonToken.END_OBJECT.equals(token)) {
generator.writeEndObject();
}
token = parser.nextToken();
}
}finally {
try {
if(parser!=null) {
parser.close();
}
if(generator!=null) {
generator.flush();
generator.close();
}
}catch (Exception igore){
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/JVMMemoryUtils.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/JVMMemoryUtils.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.common.utils;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.ArrayList;
import java.util.List;
/**
* 类描述:JVM内存信息工具类
*
**/
public class JVMMemoryUtils {
static private MemoryMXBean memoryMXBean;
static private MemoryPoolMXBean edenSpaceMxBean;
static private MemoryPoolMXBean survivorSpaceMxBean;
static private MemoryPoolMXBean oldGenMxBean;
static private MemoryPoolMXBean permGenMxBean;
static private MemoryPoolMXBean codeCacheMxBean;
/**
* JVM内存区域使用情况。</br>
* <pre>
* init:初始内存大小(字节)
* used:当前使用内存大小(字节)
* committed:已经申请分配的内存大小(字节)
* max:最大内存大小(字节)
* usedPercent:已经申请分配内存与最大内存大小的百分比
* </pre>
* @author tangjiyu
*/
static public class JVMMemoryUsage {
//初始内存大小(字节)
private long init;
//当前使用内存大小(字节)
private long used;
//已经申请分配的内存大小(字节)
private long committed;
//最大内存大小(字节)
private long max;
//已经申请分配内存与最大内存大小的百分比
private float usedPercent;
public JVMMemoryUsage() {
}
public JVMMemoryUsage(MemoryUsage memoryUsage) {
this.setMemoryUsage(memoryUsage);
//this(memoryUsage.getInit(), memoryUsage.getUsed(), memoryUsage.getCommitted(), memoryUsage.getMax());
}
public JVMMemoryUsage(long init, long used, long committed, long max) {
super();
this.setMemoryUsage(init, used, committed, max);
}
private void setMemoryUsage(MemoryUsage memoryUsage) {
if(memoryUsage!=null) {
this.setMemoryUsage(memoryUsage.getInit(), memoryUsage.getUsed(), memoryUsage.getCommitted(), memoryUsage.getMax());
} else {
this.setMemoryUsage(0, 0, 0, 0);
}
}
private void setMemoryUsage(long init, long used, long committed, long max) {
this.init = init;
this.used = used;
this.committed = committed;
this.max = max;
if(this.used>0 && max>0) {
this.usedPercent = used * Float.valueOf("1.0") / max;
} else {
this.usedPercent = 0;
}
}
public long getInit() {
return init;
}
public long getUsed() {
return used;
}
public long getCommitted() {
return committed;
}
public long getMax() {
return max;
}
public float getUsedPercent() {
return usedPercent;
}
@Override
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("init = " + init + "(" + (init >> 10) + "K) ");
buf.append("used = " + used + "(" + (used >> 10) + "K) ");
buf.append("committed = " + committed + "(" +
(committed >> 10) + "K) " );
buf.append("max = " + max + "(" + (max >> 10) + "K)");
buf.append("usedPercent = " + usedPercent);
return buf.toString();
}
}
static {
memoryMXBean = ManagementFactory.getMemoryMXBean();
List<MemoryPoolMXBean> memoryPoolMXBeanList = ManagementFactory.getMemoryPoolMXBeans();
for (final MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeanList) {
String poolName = memoryPoolMXBean.getName();
if(poolName==null) {
continue;
}
// 官方JVM(HotSpot)提供的MemoryPoolMXBean
// JDK1.7/1.8 Eden区内存池名称: "Eden Space" 或 "PS Eden Space"、 “G1 Eden Space”(和垃圾收集器有关)
// JDK1.7/1.8 Survivor区内存池名称:"Survivor Space" 或 "PS Survivor Space"、“G1 Survivor Space”(和垃圾收集器有关)
// JDK1.7 老区内存池名称: "Tenured Gen"
// JDK1.8 老区内存池名称:"Old Gen" 或 "PS Old Gen"、“G1 Old Gen”(和垃圾收集器有关)
// JDK1.7 方法/永久区内存池名称: "Perm Gen" 或 "PS Perm Gen"(和垃圾收集器有关)
// JDK1.8 方法/永久区内存池名称:"Metaspace"(注意:不在堆内存中)
// JDK1.7/1.8 CodeCache区内存池名称: "Code Cache"
if (edenSpaceMxBean==null && poolName.endsWith("Eden Space")) {
edenSpaceMxBean = memoryPoolMXBean;
} else if (survivorSpaceMxBean==null && poolName.endsWith("Survivor Space")) {
survivorSpaceMxBean = memoryPoolMXBean;
} else if (oldGenMxBean==null && (poolName.endsWith("Tenured Gen") || poolName.endsWith("Old Gen"))) {
oldGenMxBean = memoryPoolMXBean;
} else if (permGenMxBean==null && (poolName.endsWith("Perm Gen") || poolName.endsWith("Metaspace"))) {
permGenMxBean = memoryPoolMXBean;
} else if (codeCacheMxBean==null && poolName.endsWith("Code Cache")) {
codeCacheMxBean = memoryPoolMXBean;
}
}
}// static
/**
* 获取堆内存情况
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getHeapMemoryUsage() {
if(memoryMXBean!=null) {
final MemoryUsage usage =memoryMXBean.getHeapMemoryUsage();
if(usage!=null) {
return new JVMMemoryUsage(usage);
}
}
return null;
}
/**
* 获取堆外内存情况
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getNonHeapMemoryUsage() {
if(memoryMXBean!=null) {
final MemoryUsage usage =memoryMXBean.getNonHeapMemoryUsage();
if(usage!=null) {
return new JVMMemoryUsage(usage);
}
}
return null;
}
/**
* 获取Eden区内存情况
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getEdenSpaceMemoryUsage() {
return getMemoryPoolUsage(edenSpaceMxBean);
}
/**
* 获取Eden区内存峰值(从启动或上一次重置开始统计),并重置
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getAndResetEdenSpaceMemoryPeakUsage() {
return getAndResetMemoryPoolPeakUsage(edenSpaceMxBean);
}
/**
* 获取Survivor区内存情况
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getSurvivorSpaceMemoryUsage() {
return getMemoryPoolUsage(survivorSpaceMxBean);
}
/**
* 获取Survivor区内存峰值(从启动或上一次重置开始统计),并重置
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getAndResetSurvivorSpaceMemoryPeakUsage() {
return getAndResetMemoryPoolPeakUsage(survivorSpaceMxBean);
}
/**
* 获取老区内存情况
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getOldGenMemoryUsage() {
return getMemoryPoolUsage(oldGenMxBean);
}
/**
* 获取老区内存峰值(从启动或上一次重置开始统计),并重置
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getAndResetOldGenMemoryPeakUsage() {
return getAndResetMemoryPoolPeakUsage(oldGenMxBean);
}
/**
* 获取永久区/方法区内存情况
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getPermGenMemoryUsage() {
return getMemoryPoolUsage(permGenMxBean);
}
/**
* 获取永久区/方法区内存峰值(从启动或上一次重置开始统计),并重置
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getAndResetPermGenMemoryPeakUsage() {
return getAndResetMemoryPoolPeakUsage(permGenMxBean);
}
/**
* 获取CodeCache区内存情况
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getCodeCacheMemoryUsage() {
return getMemoryPoolUsage(codeCacheMxBean);
}
/**
* 获取CodeCache区内存峰值(从启动或上一次重置开始统计),并重置
* @return 不能获取到返回null
*/
static public JVMMemoryUsage getAndResetCodeCacheMemoryPeakUsage() {
return getAndResetMemoryPoolPeakUsage(codeCacheMxBean);
}
static private JVMMemoryUsage getMemoryPoolUsage(MemoryPoolMXBean memoryPoolMXBean) {
if(memoryPoolMXBean!=null) {
final MemoryUsage usage = memoryPoolMXBean.getUsage();
if(usage!=null) {
return new JVMMemoryUsage(usage);
}
}
return null;
}
static private JVMMemoryUsage getAndResetMemoryPoolPeakUsage(MemoryPoolMXBean memoryPoolMXBean) {
if(memoryPoolMXBean!=null) {
final MemoryUsage usage = memoryPoolMXBean.getPeakUsage();
if(usage!=null) {
memoryPoolMXBean.resetPeakUsage();
return new JVMMemoryUsage(usage);
}
}
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-common/src/main/java/com/webank/ai/fate/serving/common/utils/ThreadSample.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/ThreadSample.java | package com.webank.ai.fate.serving.common.utils;
import com.webank.ai.fate.serving.common.bean.ThreadVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.management.HotspotThreadMBean;
import sun.management.ManagementFactoryHelper;
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author hcy
*/
class ThreadSampler {
private static Logger logger = LoggerFactory.getLogger(ThreadSampler.class);
private static ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
private static HotspotThreadMBean hotspotThreadMBean;
private static boolean hotspotThreadMBeanEnable = true;
private Map<ThreadVO, Long> lastCpuTimes = new HashMap<ThreadVO, Long>();
private long lastSampleTimeNanos;
private boolean includeInternalThreads = true;
public List<ThreadVO> sample(Collection<ThreadVO> originThreads) {
List<ThreadVO> threads = new ArrayList<ThreadVO>(originThreads);
// Sample CPU
if (lastCpuTimes.isEmpty()) {
lastSampleTimeNanos = System.nanoTime();
for (ThreadVO thread : threads) {
if (thread.getId() > 0) {
long cpu = threadMXBean.getThreadCpuTime(thread.getId());
lastCpuTimes.put(thread, cpu);
thread.setTime(cpu / 1000000);
}
}
// add internal threads
Map<String, Long> internalThreadCpuTimes = getInternalThreadCpuTimes();
if (internalThreadCpuTimes != null) {
for (Map.Entry<String, Long> entry : internalThreadCpuTimes.entrySet()) {
String key = entry.getKey();
ThreadVO thread = createThreadVO(key);
thread.setTime(entry.getValue() / 1000000);
threads.add(thread);
lastCpuTimes.put(thread, entry.getValue());
}
}
//sort by time
Collections.sort(threads, new Comparator<ThreadVO>() {
@Override
public int compare(ThreadVO o1, ThreadVO o2) {
long l1 = o1.getTime();
long l2 = o2.getTime();
if (l1 < l2) {
return 1;
} else if (l1 > l2) {
return -1;
} else {
return 0;
}
}
});
return threads;
}
// Resample
long newSampleTimeNanos = System.nanoTime();
Map<ThreadVO, Long> newCpuTimes = new HashMap<ThreadVO, Long>(threads.size());
for (ThreadVO thread : threads) {
if (thread.getId() > 0) {
long cpu = threadMXBean.getThreadCpuTime(thread.getId());
newCpuTimes.put(thread, cpu);
}
}
// internal threads
Map<String, Long> newInternalThreadCpuTimes = getInternalThreadCpuTimes();
if (newInternalThreadCpuTimes != null) {
for (Map.Entry<String, Long> entry : newInternalThreadCpuTimes.entrySet()) {
ThreadVO threadVO = createThreadVO(entry.getKey());
threads.add(threadVO);
newCpuTimes.put(threadVO, entry.getValue());
}
}
// Compute delta time
final Map<ThreadVO, Long> deltas = new HashMap<ThreadVO, Long>(threads.size());
for (ThreadVO thread : newCpuTimes.keySet()) {
Long t = lastCpuTimes.get(thread);
if (t == null) {
t = 0L;
}
long time1 = t;
long time2 = newCpuTimes.get(thread);
if (time1 == -1) {
time1 = time2;
} else if (time2 == -1) {
time2 = time1;
}
long delta = time2 - time1;
deltas.put(thread, delta);
}
long sampleIntervalNanos = newSampleTimeNanos - lastSampleTimeNanos;
// Compute cpu usage
final HashMap<ThreadVO, Double> cpuUsages = new HashMap<ThreadVO, Double>(threads.size());
for (ThreadVO thread : threads) {
double cpu = sampleIntervalNanos == 0 ? 0 : (Math.rint(deltas.get(thread) * 10000.0 / sampleIntervalNanos) / 100.0);
cpuUsages.put(thread, cpu);
}
// Sort by CPU time : should be a rendering hint...
Collections.sort(threads, new Comparator<ThreadVO>() {
@Override
public int compare(ThreadVO o1, ThreadVO o2) {
long l1 = deltas.get(o1);
long l2 = deltas.get(o2);
if (l1 < l2) {
return 1;
} else if (l1 > l2) {
return -1;
} else {
return 0;
}
}
});
for (ThreadVO thread : threads) {
//nanos to mills
long timeMills = newCpuTimes.get(thread) / 1000000;
long deltaTime = deltas.get(thread) / 1000000;
double cpu = cpuUsages.get(thread);
thread.setCpu(cpu);
thread.setTime(timeMills);
thread.setDeltaTime(deltaTime);
}
lastCpuTimes = newCpuTimes;
lastSampleTimeNanos = newSampleTimeNanos;
return threads;
}
private Map<String, Long> getInternalThreadCpuTimes() {
if (hotspotThreadMBeanEnable && includeInternalThreads) {
try {
if (hotspotThreadMBean == null) {
hotspotThreadMBean = ManagementFactoryHelper.getHotspotThreadMBean();
}
return hotspotThreadMBean.getInternalThreadCpuTimes();
} catch (Exception ex) {
logger.error("getInternalThreadCpuTimes failed Cause : " + ex);
hotspotThreadMBeanEnable = false;
}
}
return null;
}
private ThreadVO createThreadVO(String name) {
ThreadVO threadVO = new ThreadVO();
threadVO.setId(-1);
threadVO.setName(name);
threadVO.setPriority(-1);
threadVO.setDaemon(true);
threadVO.setInterrupted(false);
return threadVO;
}
public void pause(long mills) {
try {
Thread.sleep(mills);
} catch (InterruptedException e) {
logger.error("pause failed Cause : " + e);
}
}
public boolean isIncludeInternalThreads() {
return includeInternalThreads;
}
public void setIncludeInternalThreads(boolean includeInternalThreads) {
this.includeInternalThreads = includeInternalThreads;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/DisruptorUtil.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/DisruptorUtil.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.common.utils;
import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import com.lmax.disruptor.util.DaemonThreadFactory;
import com.webank.ai.fate.serving.common.async.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class DisruptorUtil {
private static Logger logger = LoggerFactory.getLogger(DisruptorUtil.class);
private static Disruptor<AsyncMessageEvent> disruptor = null;
static {
// Construct the Disruptor, use single event publisher
disruptor = new Disruptor(AsyncMessageEvent.FACTORY, 2048, DaemonThreadFactory.INSTANCE,
ProducerType.SINGLE, new BlockingWaitStrategy());
// Connect the handler
disruptor.handleEventsWith(new AsyncMessageEventHandler()).then(new ClearingEventHandler());
// disruptor.handleEventsWithWorkerPool()
// exception handler
disruptor.setDefaultExceptionHandler(new DisruptorExceptionHandler());
// Start the Disruptor, starts all threads running
disruptor.start();
logger.info("disruptor initialized");
}
/**
* event producer
* args[0] event name, e.g. interface name, use to @Subscribe value
* args[1] event action
* args[2] data params
*
* @param args
*/
public static void producer(AsyncMessageEvent... args) {
RingBuffer<AsyncMessageEvent> ringBuffer = disruptor.getRingBuffer();
AsyncMessageEventProducer producer = new AsyncMessageEventProducer(ringBuffer);
producer.publishEvent(args);
}
public void shutdown() {
if (disruptor != null) {
disruptor.shutdown();
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/ZipUtil.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/ZipUtil.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.common.utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class ZipUtil {
private static Logger logger = LoggerFactory.getLogger(ZipUtil.class);
public static String unzip(File zipFile, String outputDirectory) throws Exception {
String suffix = zipFile.getName().substring(zipFile.getName().lastIndexOf("."));
if (!zipFile.isFile() || !suffix.equalsIgnoreCase(".zip")) {
logger.error("{} is not zip file", zipFile.getAbsolutePath());
return null;
}
ZipFile zip = new ZipFile(new File(zipFile.getAbsolutePath()), Charset.forName("UTF-8"));
String uuid = UUID.randomUUID().toString();
File tempDir = new File(outputDirectory + uuid);
String resultPath = "";
try {
if (!tempDir.exists()) {
tempDir.mkdirs();
}
resultPath = tempDir.getAbsolutePath();
Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
File outputFile = new File(outputDirectory + uuid, entry.getName());
if (!outputFile.toPath().normalize().startsWith(outputDirectory + uuid)) {
throw new RuntimeException("Bad zip entry");
}
if (entry.isDirectory()) {
outputFile.mkdirs();
continue;
} else {
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
}
try (InputStream in = zip.getInputStream(entry); FileOutputStream out = new FileOutputStream(outputFile)) {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}finally {
if(zip!=null) {
try {
zip.close();
}catch (Exception igore){
}
}
}
return resultPath;
}
public static void delete(File file) {
if (file != null && file.exists()) {
if (file.isDirectory()) {
for (File listFile : file.listFiles()) {
if (listFile.isDirectory()) {
delete(listFile);
}
listFile.delete();
}
}
file.delete();
}
}
public static void clear(String outputPath) {
logger.info("try to clear {}", outputPath);
if (StringUtils.isNotBlank(outputPath)) {
delete(new File(outputPath));
}
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/GetSystemInfo.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/GetSystemInfo.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.common.utils;
import com.sun.management.OperatingSystemMXBean;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.management.ManagementFactoryHelper;
import java.io.IOException;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
public class GetSystemInfo {
private static final Logger logger = LoggerFactory.getLogger(GetSystemInfo.class);
private static final Pattern ADDRESS_PATTERN = Pattern.compile("^\\d{1,3}(\\.\\d{1,3}){3}\\:\\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 = ":";
public static String localIp;
private static String ANYHOST_KEY = "anyhost";
private static String ANYHOST_VALUE = "0.0.0.0";
private static String LOCALHOST_KEY = "localhost";
private static String LOCALHOST_VALUE = "127.0.0.1";
static {
localIp = getLocalIp();
logger.info("set local ip : {}", localIp);
}
public static int getPid() {
String name = ManagementFactory.getRuntimeMXBean().getName();
return Integer.parseInt(name.split("@")[0]);
}
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 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;
}
public static String getOsName() {
String osName = System.getProperty("os.name");
return osName;
}
static boolean isPreferIpv6Address() {
boolean preferIpv6 = Boolean.getBoolean("java.net.preferIPv6Addresses");
if (!preferIpv6) {
return false;
}
return false;
}
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;
}
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();
}
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;
}
public static double getSystemCpuLoad() {
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactoryHelper
.getOperatingSystemMXBean();
double systemCpuLoad = osmxb.getSystemCpuLoad();
return systemCpuLoad;
}
public static double getProcessCpuLoad() {
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactoryHelper
.getOperatingSystemMXBean();
double processCpuLoad = osmxb.getProcessCpuLoad();
return processCpuLoad;
}
public static long getTotalMemorySize() {
int kb = 1024;
OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactoryHelper
.getOperatingSystemMXBean();
long totalMemorySize = osmxb.getTotalPhysicalMemorySize() / kb;
return totalMemorySize;
}
// public static long getFreePhysicalMemorySize() {
// int kb = 1024;
// OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
// .getOperatingSystemMXBean();
// long freePhysicalMemorySize = osmxb.getFreePhysicalMemorySize() / kb;
// return freePhysicalMemorySize;
// }
// public static long getUsedMemory() {
//// int kb = 1024;
//// OperatingSystemMXBean osmxb = (OperatingSystemMXBean) ManagementFactory
//// .getOperatingSystemMXBean();
//// long usedMemory = (osmxb.getTotalPhysicalMemorySize() - osmxb.getFreePhysicalMemorySize()) / kb;
//// return usedMemory;
//// }
public static void getJVMRuntimeParam(){
// RuntimeMXBean runtimeMXBean = ManagementFactoryHelper.getRuntimeMXBean();
//JVM启动参数
// System.out.println(runtimeMXBean.getInputArguments());
//系统属性
// System.out.println(runtimeMXBean.getSystemProperties());
//JVM名字
// System.out.println(runtimeMXBean.getVmName());
}
public static void getJvmThreadInfo(){
java.lang.management.ThreadMXBean threadMXBean = ManagementFactoryHelper.getThreadMXBean();
threadMXBean.getThreadCount();
threadMXBean.getCurrentThreadCpuTime();
threadMXBean.getCurrentThreadUserTime();
}
private static void reportGC() {
long fullCount = 0, fullTime = 0, youngCount = 0, youngTime = 0;
List<GarbageCollectorMXBean> gcs = ManagementFactory.getGarbageCollectorMXBeans();
for (GarbageCollectorMXBean gc : gcs) {
System.err.println(gc.getName() +"" +gc.getCollectionCount());
}
// switch (GarbageCollectorName.of(gc.getName())) {
// case MarkSweepCompact:
// case PSMarkSweep:
// case ConcurrentMarkSweep:
// fullCount += gc.getCollectionCount();
// fullTime += gc.getCollectionTime();
// break;
// case Copy:
// case ParNew:
// case PSScavenge:
// youngCount += gc.getCollectionCount();
// youngTime += gc.getCollectionTime();
// break;
// }
//todo your deal code, perfcounter report or write log here
}
public static void getSystemLoad(){
java.lang.management.OperatingSystemMXBean operatingSystemMXBean = ManagementFactoryHelper.getOperatingSystemMXBean();
//获取服务器的CPU个数
// System.out.println(operatingSystemMXBean.());
//获取服务器的平均负载。这个指标非常重要,它可以有效的说明当前机器的性能是否正常,如果load过高,说明CPU无法及时处理任务。
// System.out.println(operatingSystemMXBean.getSystemLoadAverage());
}
public static void main(String[] args){
getSystemLoad();
reportGC();
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/utils/JVMCPUUtils.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/utils/JVMCPUUtils.java | package com.webank.ai.fate.serving.common.utils;
import com.webank.ai.fate.serving.common.bean.ThreadVO;
import java.util.*;
/**
* @author hcy
*/
public class JVMCPUUtils {
private static Set<String> states = null;
static {
states = new HashSet<>(Thread.State.values().length);
for (Thread.State state : Thread.State.values()) {
states.add(state.name());
}
}
public static List<ThreadVO> getThreadsState() {
List<ThreadVO> threads = ThreadUtils.getThreads();
Collection<ThreadVO> resultThreads = new ArrayList<>();
for (ThreadVO thread : threads) {
if (thread.getState() != null && states.contains(thread.getState().name())) {
resultThreads.add(thread);
}
}
ThreadSampler threadSampler = new ThreadSampler();
threadSampler.setIncludeInternalThreads(true);
threadSampler.sample(resultThreads);
threadSampler.pause(1000);
return threadSampler.sample(resultThreads);
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/bean/ServingServerContext.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/bean/ServingServerContext.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.common.bean;
import com.webank.ai.fate.serving.common.model.Model;
import com.webank.ai.fate.serving.core.bean.Dict;
public class ServingServerContext extends BaseContext {
String tableName;
String namespace;
public Model getModel() {
return (Model) this.dataMap.get(Dict.MODEL);
}
public void setModel(Model model) {
this.dataMap.put(Dict.MODEL, model);
}
public String getModelTableName() {
return tableName;
}
public void setModelTableName(String tableName) {
this.tableName = tableName;
}
public String getModelNamesapce() {
return namespace;
}
public void setModelNamesapce(String modelNamesapce) {
this.namespace = modelNamesapce;
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/bean/ThreadVO.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/bean/ThreadVO.java | package com.webank.ai.fate.serving.common.bean;
import java.io.Serializable;
import java.util.Objects;
/**
* @author hcy
*/
public class ThreadVO implements Serializable {
private static final long serialVersionUID = 0L;
private long id;
private String name;
private String group;
private int priority;
private Thread.State state;
private double cpu;
private long deltaTime;
private long time;
private boolean interrupted;
private boolean daemon;
public ThreadVO() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public Thread.State getState() {
return state;
}
public void setState(Thread.State state) {
this.state = state;
}
public double getCpu() {
return cpu;
}
public void setCpu(double cpu) {
this.cpu = cpu;
}
public long getDeltaTime() {
return deltaTime;
}
public void setDeltaTime(long deltaTime) {
this.deltaTime = deltaTime;
}
public long getTime() {
return time;
}
public void setTime(long time) {
this.time = time;
}
public boolean isInterrupted() {
return interrupted;
}
public void setInterrupted(boolean interrupted) {
this.interrupted = interrupted;
}
public boolean isDaemon() {
return daemon;
}
public void setDaemon(boolean daemon) {
this.daemon = daemon;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ThreadVO threadVO = (ThreadVO) o;
if (id != threadVO.id) {
return false;
}
return Objects.equals(name, threadVO.name);
}
@Override
public int hashCode() {
int result = (int) (id ^ (id >>> 32));
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ThreadVO{" +
"id=" + id +
", name='" + name + '\'' +
", group='" + group + '\'' +
", priority=" + priority +
", state=" + state +
", cpu=" + cpu +
", deltaTime=" + deltaTime +
", time=" + time +
", interrupted=" + interrupted +
", daemon=" + daemon +
'}';
}
}
| 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-common/src/main/java/com/webank/ai/fate/serving/common/bean/BaseContext.java | fate-serving-common/src/main/java/com/webank/ai/fate/serving/common/bean/BaseContext.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.common.bean;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.ListenableFuture;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.core.rpc.grpc.GrpcType;
import com.webank.ai.fate.serving.core.rpc.router.RouterInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;
public class BaseContext<Req, Resp> implements Context<Req, Resp> {
private static final Logger logger = LoggerFactory.getLogger(LOGGER_NAME);
public static AtomicLong requestInProcess = new AtomicLong(0);
protected long timestamp;
protected String interfaceName;
protected String actionType;
protected Map dataMap = Maps.newHashMap();
long costTime;
String resourceName;
public BaseContext() {
timestamp = System.currentTimeMillis();
}
public BaseContext(String actionType) {
timestamp = System.currentTimeMillis();
this.actionType = actionType;
}
private BaseContext(long timestamp, Map dataMap) {
this.timestamp = timestamp;
this.dataMap = dataMap;
}
@Override
public String getActionType() {
return actionType;
}
@Override
public void setActionType(String actionType) {
this.actionType = actionType;
}
@Override
public void preProcess() {
try {
requestInProcess.addAndGet(1);
} catch (Exception e) {
logger.error("preProcess error", e);
}
}
@Override
public Object getData(Object key) {
return dataMap.get(key);
}
@Override
public Object getDataOrDefault(Object key, Object defaultValue) {
return dataMap.getOrDefault(key, defaultValue);
}
@Override
public void putData(Object key, Object data) {
dataMap.put(key, data);
}
@Override
public String getCaseId() {
if (dataMap.get(Dict.CASEID) != null) {
return dataMap.get(Dict.CASEID).toString();
} else {
return null;
}
}
@Override
public void setCaseId(String caseId) {
dataMap.put(Dict.CASEID, caseId);
}
@Override
public long getTimeStamp() {
return timestamp;
}
@Override
public void postProcess(Req req, Resp resp) {
try {
requestInProcess.decrementAndGet();
costTime = System.currentTimeMillis() - timestamp;
} catch (Throwable e) {
logger.error("postProcess error", e);
}
}
@Override
public ReturnResult getFederatedResult() {
return (ReturnResult) dataMap.get(Dict.FEDERATED_RESULT);
}
@Override
public void setFederatedResult(ReturnResult returnResult) {
dataMap.put(Dict.FEDERATED_RESULT, returnResult);
}
@Override
public boolean isHitCache() {
return (Boolean) dataMap.getOrDefault(Dict.HIT_CACHE, false);
}
@Override
public void hitCache(boolean hitCache) {
dataMap.put(Dict.HIT_CACHE, hitCache);
}
@Override
public Context subContext() {
Map newDataMap = Maps.newHashMap(dataMap);
return new BaseContext(this.timestamp, newDataMap);
}
@Override
public String getInterfaceName() {
return interfaceName;
}
@Override
public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}
@Override
public String getSeqNo() {
return (String) this.dataMap.getOrDefault(Dict.REQUEST_SEQNO, "");
}
@Override
public long getCostTime() {
return costTime;
}
@Override
public GrpcType getGrpcType() {
return (GrpcType) dataMap.get(Dict.GRPC_TYPE);
}
@Override
public void setGrpcType(GrpcType grpcType) {
dataMap.put(Dict.GRPC_TYPE, grpcType);
}
@Override
public String getVersion() {
return (String) dataMap.get(Dict.VERSION);
}
@Override
public void setVersion(String version) {
dataMap.put(Dict.VERSION, version);
}
@Override
public String getGuestAppId() {
return (String) dataMap.get(Dict.GUEST_APP_ID);
}
@Override
public void setGuestAppId(String guestAppId) {
dataMap.put(Dict.GUEST_APP_ID, guestAppId);
}
@Override
public String getHostAppid() {
return (String) dataMap.get(Dict.HOST_APP_ID);
}
@Override
public void setHostAppid(String hostAppid) {
dataMap.put(Dict.HOST_APP_ID, hostAppid);
}
@Override
public RouterInfo getRouterInfo() {
return (RouterInfo) dataMap.get(Dict.ROUTER_INFO);
}
@Override
public void setRouterInfo(RouterInfo routerInfo) {
dataMap.put(Dict.ROUTER_INFO, routerInfo);
}
@Override
public Object getResultData() {
return dataMap.get(Dict.RESULT_DATA);
}
@Override
public void setResultData(Object resultData) {
dataMap.put(Dict.RESULT_DATA, resultData);
}
@Override
public int getReturnCode() {
return (int) dataMap.get(Dict.RETURN_CODE);
}
@Override
public void setReturnCode(int returnCode) {
dataMap.put(Dict.RETURN_CODE, returnCode);
}
@Override
public long getDownstreamCost() {
if (dataMap.get(Dict.DOWN_STREAM_COST) != null) {
return (long) dataMap.get(Dict.DOWN_STREAM_COST);
}
return 0;
}
@Override
public void setDownstreamCost(long downstreamCost) {
dataMap.put(Dict.DOWN_STREAM_COST, downstreamCost);
}
@Override
public long getDownstreamBegin() {
return dataMap.get(Dict.DOWN_STREAM_BEGIN)!=null? (long) dataMap.get(Dict.DOWN_STREAM_BEGIN):0;
}
@Override
public void setDownstreamBegin(long downstreamBegin) {
dataMap.put(Dict.DOWN_STREAM_BEGIN, downstreamBegin);
}
@Override
public long getRouteBasis() {
return dataMap.get(Dict.ROUTE_BASIS)!=null?(long) dataMap.get(Dict.ROUTE_BASIS):0;
}
@Override
public void setRouteBasis(long routeBasis) {
dataMap.put(Dict.ROUTE_BASIS, routeBasis);
}
@Override
public String getSourceIp() {
return (String) dataMap.get(Dict.SOURCE_IP);
}
@Override
public void setSourceIp(String sourceIp) {
dataMap.put(Dict.SOURCE_IP, sourceIp);
}
@Override
public String getServiceName() {
return (String) dataMap.get(Dict.SERVICE_NAME);
}
@Override
public void setServiceName(String serviceName) {
dataMap.put(Dict.SERVICE_NAME, serviceName);
}
@Override
public String getCallName() {
return (String) dataMap.get(Dict.CALL_NAME);
}
@Override
public void setCallName(String callName) {
dataMap.put(Dict.CALL_NAME, callName);
}
@Override
public String getServiceId() {
return (String) this.dataMap.getOrDefault(Dict.SERVICE_ID, "");
}
@Override
public void setServiceId(String serviceId) {
dataMap.put(Dict.SERVICE_ID, serviceId);
}
@Override
public String getApplyId() {
return (String) this.dataMap.getOrDefault(Dict.APPLY_ID, "");
}
@Override
public void setApplyId(String applyId) {
dataMap.put(Dict.APPLY_ID, applyId);
}
@Override
public ListenableFuture getRemoteFuture() {
return (ListenableFuture) this.dataMap.getOrDefault(Dict.FUTURE, null);
}
@Override
public void setRemoteFuture(ListenableFuture future) {
this.dataMap.put(Dict.FUTURE, future);
}
@Override
public String getResourceName() {
if (StringUtils.isNotEmpty(resourceName)) {
return resourceName;
} else {
resourceName = "I_" + (StringUtils.isNotEmpty(this.getActionType()) ? this.getActionType() : this.getServiceName());
}
return resourceName;
}
}
| 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-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/AbstractBatchFeatureDataAdaptor.java | fate-serving-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/AbstractBatchFeatureDataAdaptor.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.adaptor.dataaccess;
import com.webank.ai.fate.serving.core.adaptor.BatchFeatureDataAdaptor;
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 org.springframework.core.env.Environment;
import java.util.List;
public abstract class AbstractBatchFeatureDataAdaptor implements BatchFeatureDataAdaptor {
protected Environment environment;
public Environment getEnvironment() {
return environment;
}
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public abstract void init();
@Override
public abstract BatchHostFeatureAdaptorResult getFeatures(Context context, List<BatchHostFederatedParams.SingleInferenceData> featureIdList);
@Override
public List<ParamDescriptor> desc() {
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-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/DTest.java | fate-serving-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/DTest.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.adaptor.dataaccess;
import com.webank.ai.fate.serving.common.utils.HttpClientPool;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.Dict;
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.utils.ObjectTransform;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class DTest extends AbstractSingleFeatureDataAdaptor {
private static final Logger logger = LoggerFactory.getLogger(DTest.class);
@Override
public void init() {
}
@Override
public ReturnResult getData(Context context, Map<String, Object> featureIds) {
ReturnResult returnResult = new ReturnResult();
Map<String, Object> requestData = new HashMap<>(8);
requestData.putAll(featureIds);
String responseBody = HttpClientPool.post("http://127.0.0.1:1234/feature", requestData);
if (StringUtils.isEmpty(responseBody)) {
return null;
}
Map<String, Object> tmp = (Map<String, Object>) ObjectTransform.json2Bean(responseBody, HashMap.class);
if ((int) Optional.ofNullable(tmp.get(Dict.STATUS)).orElse(1) != 0) {
return null;
}
String[] features = StringUtils.split(((List<String>) tmp.get(Dict.DATA)).get(0), "\t");
Map<String, Object> featureData = new HashMap<>(8);
for (int i = 1; i < features.length; i++) {
featureData.put(features[i], i);
}
returnResult.setData(featureData);
returnResult.setRetcode(StatusCode.SUCCESS);
return returnResult;
}
}
| 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-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/HttpAdapterByHeader.java | fate-serving-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/HttpAdapterByHeader.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.adaptor.dataaccess;
import com.webank.ai.fate.serving.common.utils.HttpAdapterClientPool;
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.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
public class HttpAdapterByHeader extends AbstractSingleFeatureDataAdaptor {
private static final Logger logger = LoggerFactory.getLogger(HttpAdapterByHeader.class);
private final static String HTTP_ADAPTER_URL = MetaInfo.PROPERTY_HTTP_ADAPTER_URL;
@Override
public void init() {
environment.getProperty("port");
}
@Override
public ReturnResult getData(Context context, Map<String, Object> featureIds) {
ReturnResult returnResult = new ReturnResult();
HttpAdapterResponse responseResult ;
try {
//get data by http
responseResult = HttpAdapterClientPool.doPostgetCodeByHeader(HTTP_ADAPTER_URL, featureIds);
int responseCode = responseResult.getCode();
switch (responseCode) {
case HttpAdapterResponseCodeEnum.SUCCESS_CODE:
if (responseResult.getData() == null || responseResult.getData().size() == 0) {
returnResult.setRetcode(StatusCode.FEATURE_DATA_ADAPTOR_ERROR);
returnResult.setRetmsg("responseData is null ");
} else {
returnResult.setRetcode(StatusCode.SUCCESS);
returnResult.setData(responseResult.getData());
}
break;
default:
returnResult.setRetcode(StatusCode.FEATURE_DATA_ADAPTOR_ERROR);
returnResult.setRetmsg("HTTP request failed ,error code :"+responseResult.getCode());
}
if (logger.isDebugEnabled()) {
logger.debug("HttpAdapter result, {}", JsonUtil.object2Json(returnResult));
}
} catch (Exception ex) {
logger.error(ex.getMessage());
returnResult.setRetcode(StatusCode.SYSTEM_ERROR);
}
return returnResult;
}
public static void main(String[] args) {
}
}
| 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-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/TestFilePickAdapter.java | fate-serving-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/TestFilePickAdapter.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.adaptor.dataaccess;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.Dict;
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.FeatureDataAdaptorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestFilePickAdapter extends AbstractSingleFeatureDataAdaptor {
private static final Logger logger = LoggerFactory.getLogger(TestFilePickAdapter.class);
private static final Map<String, Map<String, Object>> featureMaps = new HashMap<>();
@Override
public void init() {
}
@Override
public ReturnResult getData(Context context, Map<String, Object> featureIds) {
ReturnResult returnResult = new ReturnResult();
try {
if (featureMaps.isEmpty()) {
logger.info("user dir {}",System.getProperty(Dict.PROPERTY_USER_DIR));
logger.info("testHost data path = {}", Paths.get(System.getProperty(Dict.PROPERTY_USER_DIR), "host_data.csv"));
List<String> lines = Files.readAllLines(Paths.get(System.getProperty(Dict.PROPERTY_USER_DIR), "host_data.csv"));
for (int i = 0; i < lines.size(); i++) {
String[] idFeats = StringUtils.split(lines.get(i), ",");
if(idFeats.length == 2){
Map<String, Object> data = new HashMap<>();
for (String kv : StringUtils.split(idFeats[1], ";")) {
String[] a = StringUtils.split(kv, ":");
data.put(a[0], Double.valueOf(a[1]));
}
featureMaps.put(idFeats[0], data);
} else {
logger.error("please check the format for line " + (i + 1));
featureMaps.clear();
throw new FeatureDataAdaptorException("please check the host_data.csv format for line " + (i + 1));
}
}
}
Map<String, Object> featureData = featureMaps.get(featureIds.get(Dict.ID).toString());
if (featureData != null) {
Map clone = (Map) ((HashMap) featureData).clone();
returnResult.setData(clone);
returnResult.setRetcode(StatusCode.SUCCESS);
} else {
logger.error("cant not find features for {}.", featureIds.get(Dict.ID).toString());
returnResult.setRetcode(StatusCode.HOST_FEATURE_NOT_EXIST);
returnResult.setRetmsg("cant not find features for " + featureIds.get(Dict.ID).toString());
}
} catch (Exception ex) {
logger.error("test file adaptore error",ex);
returnResult.setRetcode(StatusCode.HOST_FEATURE_ERROR);
}
return returnResult;
}
} | 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-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/ParallelBatchToSingleFeatureAdaptor.java | fate-serving-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/ParallelBatchToSingleFeatureAdaptor.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.adaptor.dataaccess;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.webank.ai.fate.serving.core.adaptor.SingleFeatureDataAdaptor;
import com.webank.ai.fate.serving.core.bean.*;
import com.webank.ai.fate.serving.core.utils.InferenceUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.*;
/**
* 许多host方并未提供批量查询接口,这个类将批量请求拆分成单笔请求发送,再合结果
*/
public class ParallelBatchToSingleFeatureAdaptor extends AbstractBatchFeatureDataAdaptor {
private static final Logger logger = LoggerFactory.getLogger(HttpAdapter.class);
int timeout;
SingleFeatureDataAdaptor singleFeatureDataAdaptor;
ListeningExecutorService listeningExecutorService;
// 自定义Adapter初始化
public ParallelBatchToSingleFeatureAdaptor(int core, int max, int timeout) {
initExecutor(core, max, timeout);
}
// 默认Adapter初始化
public ParallelBatchToSingleFeatureAdaptor() {
// 默认线程池核心线程10
int defaultCore = 10;
// 默认线程池最大线程 100
int defaultMax = 100;
// 默认countDownLatch超时时间永远比grpc超时时间小
timeout = MetaInfo.PROPERTY_GRPC_TIMEOUT.intValue() - 1;
initExecutor(defaultCore, defaultMax, timeout);
}
private void initExecutor(int core, int max, int timeout) {
SingleFeatureDataAdaptor singleFeatureDataAdaptor = null;
String adaptorClass = MetaInfo.PROPERTY_FETTURE_BATCH_SINGLE_ADAPTOR;
if (StringUtils.isNotEmpty(adaptorClass)) {
logger.info("try to load single adaptor for ParallelBatchToSingleFeatureAdaptor {}", adaptorClass);
singleFeatureDataAdaptor = (SingleFeatureDataAdaptor) InferenceUtils.getClassByName(adaptorClass);
}
if (singleFeatureDataAdaptor != null) {
String implementationClass = singleFeatureDataAdaptor.getClass().getName();
logger.info("SingleFeatureDataAdaptor implementation class: " + implementationClass);
} else {
logger.warn("SingleFeatureDataAdaptor is null.");
}
this.singleFeatureDataAdaptor = singleFeatureDataAdaptor;
this.timeout = timeout;
ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(core, max, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1000), new ThreadPoolExecutor.AbortPolicy());
listeningExecutorService = MoreExecutors.listeningDecorator(threadPoolExecutor);
}
@Override
public void init() {
}
@Override
public BatchHostFeatureAdaptorResult getFeatures(Context context, List<BatchHostFederatedParams.SingleInferenceData> featureIdList) {
BatchHostFeatureAdaptorResult result = new BatchHostFeatureAdaptorResult();
CountDownLatch countDownLatch = new CountDownLatch(featureIdList.size());
for (int i = 0; i < featureIdList.size(); i++) {
BatchHostFederatedParams.SingleInferenceData singleInferenceData = featureIdList.get(i);
try {
this.listeningExecutorService.submit(new Runnable() {
@Override
public void run() {
try {
Integer index = singleInferenceData.getIndex();
ReturnResult returnResult = singleFeatureDataAdaptor.getData(context, singleInferenceData.getSendToRemoteFeatureData());
BatchHostFeatureAdaptorResult.SingleBatchHostFeatureAdaptorResult adaptorResult = new BatchHostFeatureAdaptorResult.SingleBatchHostFeatureAdaptorResult();
adaptorResult.setFeatures(returnResult.getData());
result.getIndexResultMap().put(index, adaptorResult);
} finally {
countDownLatch.countDown();
}
}
});
} catch (RejectedExecutionException ree) {
// 处理线程池满后的异常, 等待2s后重新提交
logger.error("The thread pool has exceeded the maximum capacity, sleep 3s and submit again : " + ree.getMessage(), ree);
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
logger.error("Interrupt during thread sleep");
}
this.listeningExecutorService.submit((Runnable) this);
}
}
/**
* 这里的超时时间需要设置比rpc超时时间短,否则没有意义
*/
try {
countDownLatch.await(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
logger.error("Interrupt during countDownLatch thread await", e);
}
/**
* 如果等待超时也需要把已经返回的查询结果返回
*/
return result;
}
@Override
public List<ParamDescriptor> desc() {
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-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/TestFileAdapter.java | fate-serving-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/TestFileAdapter.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.adaptor.dataaccess;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TestFileAdapter extends AbstractSingleFeatureDataAdaptor {
private static final Logger logger = LoggerFactory.getLogger(TestFileAdapter.class);
@Override
public void init() {
}
@Override
public ReturnResult getData(Context context, Map<String, Object> featureIds) {
ReturnResult returnResult = new ReturnResult();
Map<String, Object> data = new HashMap<>();
try {
logger.info("testHost data path = {}", Paths.get(System.getProperty(Dict.PROPERTY_USER_DIR), "host_data.csv"));
List<String> lines = Files.readAllLines(Paths.get(System.getProperty(Dict.PROPERTY_USER_DIR), "host_data.csv"));
lines.forEach(line -> {
for (String kv : StringUtils.split(line, ",")) {
String[] a = StringUtils.split(kv, ":");
data.put(a[0], Double.valueOf(a[1]));
}
});
returnResult.setData(data);
returnResult.setRetcode(StatusCode.SUCCESS);
} catch (Exception ex) {
logger.error(ex.getMessage());
returnResult.setRetcode(StatusCode.HOST_FEATURE_ERROR);
}
return returnResult;
}
}
| 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-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/AbstractSingleFeatureDataAdaptor.java | fate-serving-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/AbstractSingleFeatureDataAdaptor.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.adaptor.dataaccess;
import com.webank.ai.fate.serving.core.adaptor.SingleFeatureDataAdaptor;
import com.webank.ai.fate.serving.core.bean.Context;
import com.webank.ai.fate.serving.core.bean.ReturnResult;
import org.springframework.core.env.Environment;
import java.util.Map;
public abstract class AbstractSingleFeatureDataAdaptor implements SingleFeatureDataAdaptor {
protected Environment environment;
public Environment getEnvironment() {
return environment;
}
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public abstract void init();
@Override
public abstract 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-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/MockAdapter.java | fate-serving-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/MockAdapter.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.adaptor.dataaccess;
import com.webank.ai.fate.serving.core.bean.Context;
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.utils.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
public class MockAdapter extends AbstractSingleFeatureDataAdaptor {
private static final Logger logger = LoggerFactory.getLogger(MockAdapter.class);
@Override
public void init() {
environment.getProperty("port");
}
@Override
public ReturnResult getData(Context context, Map<String, Object> featureIds) {
ReturnResult returnResult = new ReturnResult();
Map<String, Object> data = new HashMap<>();
try {
String mockData = "x0:1,x1:5,x2:13,x3:58,x4:95,x5:352,x6:418,x7:833,x8:888,x9:937,x10:32776";
for (String kv : StringUtils.split(mockData, ",")) {
String[] a = StringUtils.split(kv, ":");
data.put(a[0], Double.valueOf(a[1]));
}
returnResult.setData(data);
returnResult.setRetcode(StatusCode.SUCCESS);
if (logger.isDebugEnabled()) {
logger.debug("MockAdapter result, {}", JsonUtil.object2Json(returnResult));
}
} catch (Exception ex) {
logger.error(ex.getMessage());
returnResult.setRetcode(StatusCode.SYSTEM_ERROR);
}
return returnResult;
}
}
| 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-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/BatchTestFilePickAdapter.java | fate-serving-extension/src/main/java/com/webank/ai/fate/serving/adaptor/dataaccess/BatchTestFilePickAdapter.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.adaptor.dataaccess;
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 com.webank.ai.fate.serving.core.bean.Dict;
import com.webank.ai.fate.serving.core.constant.StatusCode;
import com.webank.ai.fate.serving.core.exceptions.FeatureDataAdaptorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BatchTestFilePickAdapter extends AbstractBatchFeatureDataAdaptor {
private static final Logger logger = LoggerFactory.getLogger(BatchTestFilePickAdapter.class);
private static final Map<String, Map<String, Object>> featureMaps = new HashMap<>();
@Override
public void init() {
try {
if (featureMaps.isEmpty()) {
List<String> lines = Files.readAllLines(Paths.get(System.getProperty(Dict.PROPERTY_USER_DIR), "host_data.csv"));
for (int i = 0; i < lines.size(); i++) {
String[] idFeats = StringUtils.split(lines.get(i), ",");
if(idFeats.length == 2){
Map<String, Object> data = new HashMap<>();
for (String kv : StringUtils.split(idFeats[1], ";")) {
String[] a = StringUtils.split(kv, ":");
data.put(a[0], Double.valueOf(a[1]));
}
featureMaps.put(idFeats[0], data);
} else {
logger.error("please check the format for line " + (i + 1));
throw new FeatureDataAdaptorException("please check the host_data.csv format for line " + (i + 1));
}
}
}
} catch (Exception e) {
logger.error("init BatchTestFilePick error, {}", e.getMessage());
e.printStackTrace();
}
}
@Override
public BatchHostFeatureAdaptorResult getFeatures(Context context, List<BatchHostFederatedParams.SingleInferenceData> featureIdList) {
BatchHostFeatureAdaptorResult batchHostFeatureAdaptorResult = new BatchHostFeatureAdaptorResult();
try {
featureIdList.forEach(singleInferenceData -> {
Map<Integer, BatchHostFeatureAdaptorResult.SingleBatchHostFeatureAdaptorResult> indexMap = batchHostFeatureAdaptorResult.getIndexResultMap();
BatchHostFeatureAdaptorResult.SingleBatchHostFeatureAdaptorResult singleBatchHostFeatureAdaptorResult = new BatchHostFeatureAdaptorResult.SingleBatchHostFeatureAdaptorResult();
if (singleInferenceData.getSendToRemoteFeatureData().containsKey(Dict.DEVICE_ID)) {
Map<String, Object> featureData = featureMaps.get(singleInferenceData.getSendToRemoteFeatureData().get(Dict.DEVICE_ID));
if (featureData != null) {
Map clone = (Map) ((HashMap) featureData).clone();
singleBatchHostFeatureAdaptorResult.setFeatures(clone);
singleBatchHostFeatureAdaptorResult.setRetcode(StatusCode.SUCCESS);
} else {
logger.error("cant not find features for {}.", singleInferenceData.getSendToRemoteFeatureData().get(Dict.DEVICE_ID));
singleBatchHostFeatureAdaptorResult.setRetcode(StatusCode.HOST_FEATURE_NOT_EXIST);
}
indexMap.put(singleInferenceData.getIndex(), singleBatchHostFeatureAdaptorResult);
}
});
batchHostFeatureAdaptorResult.setRetcode(StatusCode.SUCCESS);
} catch (Exception ex) {
logger.error(ex.getMessage());
batchHostFeatureAdaptorResult.setRetcode(StatusCode.HOST_FEATURE_ERROR);
}
return batchHostFeatureAdaptorResult;
}
@Override
public List<ParamDescriptor> desc() {
return null;
}
}
| 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.